id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
245,100
|
dangunter/smoqe
|
smoqe/query.py
|
ConstraintOperator._set_size_code
|
def _set_size_code(self):
"""Set the code for a size operation.
"""
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(self.SIZE):]
self._size_code = self.SZ_MAPPING.get(suffix, None)
if self._size_code is None:
raise ValueError('invalid "{}" suffix "{}"'.format(self.SIZE, suffix))
|
python
|
def _set_size_code(self):
"""Set the code for a size operation.
"""
if not self._op.startswith(self.SIZE):
self._size_code = None
return
if len(self._op) == len(self.SIZE):
self._size_code = self.SZ_EQ
else:
suffix = self._op[len(self.SIZE):]
self._size_code = self.SZ_MAPPING.get(suffix, None)
if self._size_code is None:
raise ValueError('invalid "{}" suffix "{}"'.format(self.SIZE, suffix))
|
[
"def",
"_set_size_code",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_op",
".",
"startswith",
"(",
"self",
".",
"SIZE",
")",
":",
"self",
".",
"_size_code",
"=",
"None",
"return",
"if",
"len",
"(",
"self",
".",
"_op",
")",
"==",
"len",
"(",
"self",
".",
"SIZE",
")",
":",
"self",
".",
"_size_code",
"=",
"self",
".",
"SZ_EQ",
"else",
":",
"suffix",
"=",
"self",
".",
"_op",
"[",
"len",
"(",
"self",
".",
"SIZE",
")",
":",
"]",
"self",
".",
"_size_code",
"=",
"self",
".",
"SZ_MAPPING",
".",
"get",
"(",
"suffix",
",",
"None",
")",
"if",
"self",
".",
"_size_code",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'invalid \"{}\" suffix \"{}\"'",
".",
"format",
"(",
"self",
".",
"SIZE",
",",
"suffix",
")",
")"
] |
Set the code for a size operation.
|
[
"Set",
"the",
"code",
"for",
"a",
"size",
"operation",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L302-L315
|
245,101
|
dangunter/smoqe
|
smoqe/query.py
|
Constraint.passes
|
def passes(self, value):
"""Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple
"""
try:
if self._op.compare(value, self.value):
return True, None
else:
return False, self.value
except ValueError as err:
return False, str(err)
|
python
|
def passes(self, value):
"""Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple
"""
try:
if self._op.compare(value, self.value):
return True, None
else:
return False, self.value
except ValueError as err:
return False, str(err)
|
[
"def",
"passes",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"if",
"self",
".",
"_op",
".",
"compare",
"(",
"value",
",",
"self",
".",
"value",
")",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"self",
".",
"value",
"except",
"ValueError",
"as",
"err",
":",
"return",
"False",
",",
"str",
"(",
"err",
")"
] |
Does the given value pass this constraint?
:return: True,None if so; False,<expected> if not
:rtype: tuple
|
[
"Does",
"the",
"given",
"value",
"pass",
"this",
"constraint?"
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L403-L415
|
245,102
|
dangunter/smoqe
|
smoqe/query.py
|
ConstraintGroup.add_constraint
|
def add_constraint(self, op, val):
"""Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal
"""
if len(self.constraints) > 0:
if op.is_equality():
clist = ', '.join(map(str, self.constraints))
raise ValueError('Field {}: equality operator cannot be combined '
'with others: {}'.format(self._field.name, clist))
elif op.is_exists():
raise ValueError('Field {}: existence is implied '
'by other operators'.format(self._field.name))
constraint = Constraint(self._field, op, val)
self.constraints.append(constraint)
if self._field.has_subfield():
self._array = True
elif op.is_inequality():
self._range = True
|
python
|
def add_constraint(self, op, val):
"""Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal
"""
if len(self.constraints) > 0:
if op.is_equality():
clist = ', '.join(map(str, self.constraints))
raise ValueError('Field {}: equality operator cannot be combined '
'with others: {}'.format(self._field.name, clist))
elif op.is_exists():
raise ValueError('Field {}: existence is implied '
'by other operators'.format(self._field.name))
constraint = Constraint(self._field, op, val)
self.constraints.append(constraint)
if self._field.has_subfield():
self._array = True
elif op.is_inequality():
self._range = True
|
[
"def",
"add_constraint",
"(",
"self",
",",
"op",
",",
"val",
")",
":",
"if",
"len",
"(",
"self",
".",
"constraints",
")",
">",
"0",
":",
"if",
"op",
".",
"is_equality",
"(",
")",
":",
"clist",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"self",
".",
"constraints",
")",
")",
"raise",
"ValueError",
"(",
"'Field {}: equality operator cannot be combined '",
"'with others: {}'",
".",
"format",
"(",
"self",
".",
"_field",
".",
"name",
",",
"clist",
")",
")",
"elif",
"op",
".",
"is_exists",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Field {}: existence is implied '",
"'by other operators'",
".",
"format",
"(",
"self",
".",
"_field",
".",
"name",
")",
")",
"constraint",
"=",
"Constraint",
"(",
"self",
".",
"_field",
",",
"op",
",",
"val",
")",
"self",
".",
"constraints",
".",
"append",
"(",
"constraint",
")",
"if",
"self",
".",
"_field",
".",
"has_subfield",
"(",
")",
":",
"self",
".",
"_array",
"=",
"True",
"elif",
"op",
".",
"is_inequality",
"(",
")",
":",
"self",
".",
"_range",
"=",
"True"
] |
Add new constraint.
:param op: Constraint operator
:type op: ConstraintOperator
:param val: Constraint value
:type val: str,Number
:raise: ValueError if combination of constraints is illegal
|
[
"Add",
"new",
"constraint",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L445-L467
|
245,103
|
dangunter/smoqe
|
smoqe/query.py
|
ConstraintGroup.get_conflicts
|
def get_conflicts(self):
"""Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str)
"""
conflicts = []
if self._array and self._range:
conflicts.append('cannot use range expressions on arrays')
return conflicts
|
python
|
def get_conflicts(self):
"""Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str)
"""
conflicts = []
if self._array and self._range:
conflicts.append('cannot use range expressions on arrays')
return conflicts
|
[
"def",
"get_conflicts",
"(",
"self",
")",
":",
"conflicts",
"=",
"[",
"]",
"if",
"self",
".",
"_array",
"and",
"self",
".",
"_range",
":",
"conflicts",
".",
"append",
"(",
"'cannot use range expressions on arrays'",
")",
"return",
"conflicts"
] |
Get conflicts in constraints, if any.
:return: Description of each conflict, empty if none.
:rtype: list(str)
|
[
"Get",
"conflicts",
"in",
"constraints",
"if",
"any",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L472-L481
|
245,104
|
dangunter/smoqe
|
smoqe/query.py
|
ConstraintGroup.add_existence
|
def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already about existence, nothing is done.
:rtype: None
"""
if len(self.constraints) == 1 and (
# both 'exists' and strict equality don't require the extra clause
self.constraints[0].op.is_exists() or
self.constraints[0].op.is_equality()):
return
value = not rev # value is False if reversed, otherwise True
constraint = Constraint(self._field, ConstraintOperator.EXISTS, value)
self._existence_constraints.append(constraint)
|
python
|
def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already about existence, nothing is done.
:rtype: None
"""
if len(self.constraints) == 1 and (
# both 'exists' and strict equality don't require the extra clause
self.constraints[0].op.is_exists() or
self.constraints[0].op.is_equality()):
return
value = not rev # value is False if reversed, otherwise True
constraint = Constraint(self._field, ConstraintOperator.EXISTS, value)
self._existence_constraints.append(constraint)
|
[
"def",
"add_existence",
"(",
"self",
",",
"rev",
")",
":",
"if",
"len",
"(",
"self",
".",
"constraints",
")",
"==",
"1",
"and",
"(",
"# both 'exists' and strict equality don't require the extra clause",
"self",
".",
"constraints",
"[",
"0",
"]",
".",
"op",
".",
"is_exists",
"(",
")",
"or",
"self",
".",
"constraints",
"[",
"0",
"]",
".",
"op",
".",
"is_equality",
"(",
")",
")",
":",
"return",
"value",
"=",
"not",
"rev",
"# value is False if reversed, otherwise True",
"constraint",
"=",
"Constraint",
"(",
"self",
".",
"_field",
",",
"ConstraintOperator",
".",
"EXISTS",
",",
"value",
")",
"self",
".",
"_existence_constraints",
".",
"append",
"(",
"constraint",
")"
] |
Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already about existence, nothing is done.
:rtype: None
|
[
"Add",
"existence",
"constraint",
"for",
"the",
"field",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L483-L499
|
245,105
|
dangunter/smoqe
|
smoqe/query.py
|
MongoClause._create
|
def _create(self, constraint, exists_main):
"""Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoClause
:raise: ValueError if value doesn't make sense for operator
"""
c = constraint # alias
op = self._reverse_operator(c.op) if self._rev else c.op
mop = self._mongo_op_str(op)
# build the clause parts: location and expression
loc = MongoClause.LOC_MAIN # default location
if op.is_exists():
loc = MongoClause.LOC_MAIN2 if exists_main else MongoClause.LOC_MAIN
assert (isinstance(c.value, bool))
# for exists, reverse the value instead of the operator
not_c_val = not c.value if self._rev else c.value
expr = {c.field.name: {mop: not_c_val}}
elif op.is_size():
if op.is_variable():
# variables only support equality, and need to be in $where
loc = MongoClause.LOC_WHERE
js_op = '!=' if self._rev else '=='
expr = 'this.{}.length {} this.{}'.format(c.field.name, js_op, c.value)
elif op.is_size_eq() and not self._rev:
expr = {c.field.name: {'$size': c.value}}
else:
# inequalities also need to go into $where clause
self._check_size(op, c.value)
loc = MongoClause.LOC_WHERE
szop = ConstraintOperator(op.size_op)
if self._rev:
szop.reverse()
js_op = self._js_op_str(szop)
expr = 'this.{}.length {} {}'.format(c.field.name, js_op, c.value)
elif op.is_type():
loc = MongoClause.LOC_WHERE
type_name = self.JS_TYPES.get(c.value, None)
if type_name is None:
raise RuntimeError('Could not get JS type for {}'.format(c.value))
typeop = '!=' if self._rev else '=='
expr = 'typeof this.{} {} "{}"'.format(c.field.name, typeop, type_name)
elif op.is_regex():
expr = {c.field.name: {mop: c.value.pattern}}
else:
if mop is None:
expr = {c.field.name: c.value}
elif isinstance(c.value, bool):
# can simplify boolean {a: {'$ne': True/False}} to {a: False/True}
not_c_val = not c.value if self._rev else c.value
expr = {c.field.name: not_c_val}
else:
expr = {c.field.name: {mop: c.value}}
return loc, expr
|
python
|
def _create(self, constraint, exists_main):
"""Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoClause
:raise: ValueError if value doesn't make sense for operator
"""
c = constraint # alias
op = self._reverse_operator(c.op) if self._rev else c.op
mop = self._mongo_op_str(op)
# build the clause parts: location and expression
loc = MongoClause.LOC_MAIN # default location
if op.is_exists():
loc = MongoClause.LOC_MAIN2 if exists_main else MongoClause.LOC_MAIN
assert (isinstance(c.value, bool))
# for exists, reverse the value instead of the operator
not_c_val = not c.value if self._rev else c.value
expr = {c.field.name: {mop: not_c_val}}
elif op.is_size():
if op.is_variable():
# variables only support equality, and need to be in $where
loc = MongoClause.LOC_WHERE
js_op = '!=' if self._rev else '=='
expr = 'this.{}.length {} this.{}'.format(c.field.name, js_op, c.value)
elif op.is_size_eq() and not self._rev:
expr = {c.field.name: {'$size': c.value}}
else:
# inequalities also need to go into $where clause
self._check_size(op, c.value)
loc = MongoClause.LOC_WHERE
szop = ConstraintOperator(op.size_op)
if self._rev:
szop.reverse()
js_op = self._js_op_str(szop)
expr = 'this.{}.length {} {}'.format(c.field.name, js_op, c.value)
elif op.is_type():
loc = MongoClause.LOC_WHERE
type_name = self.JS_TYPES.get(c.value, None)
if type_name is None:
raise RuntimeError('Could not get JS type for {}'.format(c.value))
typeop = '!=' if self._rev else '=='
expr = 'typeof this.{} {} "{}"'.format(c.field.name, typeop, type_name)
elif op.is_regex():
expr = {c.field.name: {mop: c.value.pattern}}
else:
if mop is None:
expr = {c.field.name: c.value}
elif isinstance(c.value, bool):
# can simplify boolean {a: {'$ne': True/False}} to {a: False/True}
not_c_val = not c.value if self._rev else c.value
expr = {c.field.name: not_c_val}
else:
expr = {c.field.name: {mop: c.value}}
return loc, expr
|
[
"def",
"_create",
"(",
"self",
",",
"constraint",
",",
"exists_main",
")",
":",
"c",
"=",
"constraint",
"# alias",
"op",
"=",
"self",
".",
"_reverse_operator",
"(",
"c",
".",
"op",
")",
"if",
"self",
".",
"_rev",
"else",
"c",
".",
"op",
"mop",
"=",
"self",
".",
"_mongo_op_str",
"(",
"op",
")",
"# build the clause parts: location and expression",
"loc",
"=",
"MongoClause",
".",
"LOC_MAIN",
"# default location",
"if",
"op",
".",
"is_exists",
"(",
")",
":",
"loc",
"=",
"MongoClause",
".",
"LOC_MAIN2",
"if",
"exists_main",
"else",
"MongoClause",
".",
"LOC_MAIN",
"assert",
"(",
"isinstance",
"(",
"c",
".",
"value",
",",
"bool",
")",
")",
"# for exists, reverse the value instead of the operator",
"not_c_val",
"=",
"not",
"c",
".",
"value",
"if",
"self",
".",
"_rev",
"else",
"c",
".",
"value",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"{",
"mop",
":",
"not_c_val",
"}",
"}",
"elif",
"op",
".",
"is_size",
"(",
")",
":",
"if",
"op",
".",
"is_variable",
"(",
")",
":",
"# variables only support equality, and need to be in $where",
"loc",
"=",
"MongoClause",
".",
"LOC_WHERE",
"js_op",
"=",
"'!='",
"if",
"self",
".",
"_rev",
"else",
"'=='",
"expr",
"=",
"'this.{}.length {} this.{}'",
".",
"format",
"(",
"c",
".",
"field",
".",
"name",
",",
"js_op",
",",
"c",
".",
"value",
")",
"elif",
"op",
".",
"is_size_eq",
"(",
")",
"and",
"not",
"self",
".",
"_rev",
":",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"{",
"'$size'",
":",
"c",
".",
"value",
"}",
"}",
"else",
":",
"# inequalities also need to go into $where clause",
"self",
".",
"_check_size",
"(",
"op",
",",
"c",
".",
"value",
")",
"loc",
"=",
"MongoClause",
".",
"LOC_WHERE",
"szop",
"=",
"ConstraintOperator",
"(",
"op",
".",
"size_op",
")",
"if",
"self",
".",
"_rev",
":",
"szop",
".",
"reverse",
"(",
")",
"js_op",
"=",
"self",
".",
"_js_op_str",
"(",
"szop",
")",
"expr",
"=",
"'this.{}.length {} {}'",
".",
"format",
"(",
"c",
".",
"field",
".",
"name",
",",
"js_op",
",",
"c",
".",
"value",
")",
"elif",
"op",
".",
"is_type",
"(",
")",
":",
"loc",
"=",
"MongoClause",
".",
"LOC_WHERE",
"type_name",
"=",
"self",
".",
"JS_TYPES",
".",
"get",
"(",
"c",
".",
"value",
",",
"None",
")",
"if",
"type_name",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Could not get JS type for {}'",
".",
"format",
"(",
"c",
".",
"value",
")",
")",
"typeop",
"=",
"'!='",
"if",
"self",
".",
"_rev",
"else",
"'=='",
"expr",
"=",
"'typeof this.{} {} \"{}\"'",
".",
"format",
"(",
"c",
".",
"field",
".",
"name",
",",
"typeop",
",",
"type_name",
")",
"elif",
"op",
".",
"is_regex",
"(",
")",
":",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"{",
"mop",
":",
"c",
".",
"value",
".",
"pattern",
"}",
"}",
"else",
":",
"if",
"mop",
"is",
"None",
":",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"c",
".",
"value",
"}",
"elif",
"isinstance",
"(",
"c",
".",
"value",
",",
"bool",
")",
":",
"# can simplify boolean {a: {'$ne': True/False}} to {a: False/True}",
"not_c_val",
"=",
"not",
"c",
".",
"value",
"if",
"self",
".",
"_rev",
"else",
"c",
".",
"value",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"not_c_val",
"}",
"else",
":",
"expr",
"=",
"{",
"c",
".",
"field",
".",
"name",
":",
"{",
"mop",
":",
"c",
".",
"value",
"}",
"}",
"return",
"loc",
",",
"expr"
] |
Create MongoDB query clause for a constraint.
:param constraint: The constraint
:type constraint: Constraint
:param exists_main: Put exists into main clause
:type exists_main: bool
:return: New clause
:rtype: MongoClause
:raise: ValueError if value doesn't make sense for operator
|
[
"Create",
"MongoDB",
"query",
"clause",
"for",
"a",
"constraint",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L578-L635
|
245,106
|
dangunter/smoqe
|
smoqe/query.py
|
MongoQuery.add_clause
|
def add_clause(self, clause):
"""Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
"""
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == MongoClause.LOC_MAIN2:
self._main2.append(clause)
elif clause.query_loc == MongoClause.LOC_WHERE:
self._where.append(clause)
else:
raise RuntimeError('bad clause location: {}'.format(clause.query_loc))
|
python
|
def add_clause(self, clause):
"""Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
"""
if clause.query_loc == MongoClause.LOC_MAIN:
self._main.append(clause)
elif clause.query_loc == MongoClause.LOC_MAIN2:
self._main2.append(clause)
elif clause.query_loc == MongoClause.LOC_WHERE:
self._where.append(clause)
else:
raise RuntimeError('bad clause location: {}'.format(clause.query_loc))
|
[
"def",
"add_clause",
"(",
"self",
",",
"clause",
")",
":",
"if",
"clause",
".",
"query_loc",
"==",
"MongoClause",
".",
"LOC_MAIN",
":",
"self",
".",
"_main",
".",
"append",
"(",
"clause",
")",
"elif",
"clause",
".",
"query_loc",
"==",
"MongoClause",
".",
"LOC_MAIN2",
":",
"self",
".",
"_main2",
".",
"append",
"(",
"clause",
")",
"elif",
"clause",
".",
"query_loc",
"==",
"MongoClause",
".",
"LOC_WHERE",
":",
"self",
".",
"_where",
".",
"append",
"(",
"clause",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'bad clause location: {}'",
".",
"format",
"(",
"clause",
".",
"query_loc",
")",
")"
] |
Add a new clause to the existing query.
:param clause: The clause to add
:type clause: MongoClause
:return: None
|
[
"Add",
"a",
"new",
"clause",
"to",
"the",
"existing",
"query",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L684-L698
|
245,107
|
dangunter/smoqe
|
smoqe/query.py
|
MongoQuery.to_mongo
|
def to_mongo(self, disjunction=True):
"""Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict
"""
q = {}
# add all the main clauses to `q`
clauses = [e.expr for e in self._main]
if clauses:
if disjunction:
if len(clauses) + len(self._where) > 1:
q['$or'] = clauses
else:
# simplify 'or' of one thing
q.update(clauses[0])
else:
for c in clauses:
q.update(c)
# add all the main2 clauses; these are not or'ed
for c in (e.expr for e in self._main2):
# add to existing stuff for the field
for field in c:
if field in q:
q[field].update(c[field])
else:
q.update(c)
# add where clauses, if any, to `q`
if self._where:
wsep = ' || ' if self._where[0].is_reversed else ' && '
where_clause = wsep.join([w.expr for w in self._where])
if disjunction:
if not '$or' in q:
q['$or'] = []
q['$or'].append({'$where': where_clause})
else:
q['$where'] = where_clause
return q
|
python
|
def to_mongo(self, disjunction=True):
"""Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict
"""
q = {}
# add all the main clauses to `q`
clauses = [e.expr for e in self._main]
if clauses:
if disjunction:
if len(clauses) + len(self._where) > 1:
q['$or'] = clauses
else:
# simplify 'or' of one thing
q.update(clauses[0])
else:
for c in clauses:
q.update(c)
# add all the main2 clauses; these are not or'ed
for c in (e.expr for e in self._main2):
# add to existing stuff for the field
for field in c:
if field in q:
q[field].update(c[field])
else:
q.update(c)
# add where clauses, if any, to `q`
if self._where:
wsep = ' || ' if self._where[0].is_reversed else ' && '
where_clause = wsep.join([w.expr for w in self._where])
if disjunction:
if not '$or' in q:
q['$or'] = []
q['$or'].append({'$where': where_clause})
else:
q['$where'] = where_clause
return q
|
[
"def",
"to_mongo",
"(",
"self",
",",
"disjunction",
"=",
"True",
")",
":",
"q",
"=",
"{",
"}",
"# add all the main clauses to `q`",
"clauses",
"=",
"[",
"e",
".",
"expr",
"for",
"e",
"in",
"self",
".",
"_main",
"]",
"if",
"clauses",
":",
"if",
"disjunction",
":",
"if",
"len",
"(",
"clauses",
")",
"+",
"len",
"(",
"self",
".",
"_where",
")",
">",
"1",
":",
"q",
"[",
"'$or'",
"]",
"=",
"clauses",
"else",
":",
"# simplify 'or' of one thing",
"q",
".",
"update",
"(",
"clauses",
"[",
"0",
"]",
")",
"else",
":",
"for",
"c",
"in",
"clauses",
":",
"q",
".",
"update",
"(",
"c",
")",
"# add all the main2 clauses; these are not or'ed",
"for",
"c",
"in",
"(",
"e",
".",
"expr",
"for",
"e",
"in",
"self",
".",
"_main2",
")",
":",
"# add to existing stuff for the field",
"for",
"field",
"in",
"c",
":",
"if",
"field",
"in",
"q",
":",
"q",
"[",
"field",
"]",
".",
"update",
"(",
"c",
"[",
"field",
"]",
")",
"else",
":",
"q",
".",
"update",
"(",
"c",
")",
"# add where clauses, if any, to `q`",
"if",
"self",
".",
"_where",
":",
"wsep",
"=",
"' || '",
"if",
"self",
".",
"_where",
"[",
"0",
"]",
".",
"is_reversed",
"else",
"' && '",
"where_clause",
"=",
"wsep",
".",
"join",
"(",
"[",
"w",
".",
"expr",
"for",
"w",
"in",
"self",
".",
"_where",
"]",
")",
"if",
"disjunction",
":",
"if",
"not",
"'$or'",
"in",
"q",
":",
"q",
"[",
"'$or'",
"]",
"=",
"[",
"]",
"q",
"[",
"'$or'",
"]",
".",
"append",
"(",
"{",
"'$where'",
":",
"where_clause",
"}",
")",
"else",
":",
"q",
"[",
"'$where'",
"]",
"=",
"where_clause",
"return",
"q"
] |
Create from current state a valid MongoDB query expression.
:return: MongoDB query expression
:rtype: dict
|
[
"Create",
"from",
"current",
"state",
"a",
"valid",
"MongoDB",
"query",
"expression",
"."
] |
70aa8ec1e9df875b9d21c71cbded95c595fe2aad
|
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L700-L737
|
245,108
|
maxfischer2781/chainlet
|
chainlet/concurrency/thread.py
|
ThreadPoolExecutor.submit
|
def submit(self, call, *args, **kwargs):
"""
Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture
"""
future = StoredFuture(call, *args, **kwargs)
self._queue.put(future)
self._ensure_worker()
return future
|
python
|
def submit(self, call, *args, **kwargs):
"""
Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture
"""
future = StoredFuture(call, *args, **kwargs)
self._queue.put(future)
self._ensure_worker()
return future
|
[
"def",
"submit",
"(",
"self",
",",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"future",
"=",
"StoredFuture",
"(",
"call",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_queue",
".",
"put",
"(",
"future",
")",
"self",
".",
"_ensure_worker",
"(",
")",
"return",
"future"
] |
Submit a call for future execution
:return: future for the call execution
:rtype: StoredFuture
|
[
"Submit",
"a",
"call",
"for",
"future",
"execution"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L61-L71
|
245,109
|
maxfischer2781/chainlet
|
chainlet/concurrency/thread.py
|
ThreadPoolExecutor._dismiss_worker
|
def _dismiss_worker(self, worker):
"""Dismiss ``worker`` unless it is still required"""
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True
|
python
|
def _dismiss_worker(self, worker):
"""Dismiss ``worker`` unless it is still required"""
self._workers.remove(worker)
if len(self._workers) < self._min_workers:
self._workers.add(worker)
return False
return True
|
[
"def",
"_dismiss_worker",
"(",
"self",
",",
"worker",
")",
":",
"self",
".",
"_workers",
".",
"remove",
"(",
"worker",
")",
"if",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_min_workers",
":",
"self",
".",
"_workers",
".",
"add",
"(",
"worker",
")",
"return",
"False",
"return",
"True"
] |
Dismiss ``worker`` unless it is still required
|
[
"Dismiss",
"worker",
"unless",
"it",
"is",
"still",
"required"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L89-L95
|
245,110
|
maxfischer2781/chainlet
|
chainlet/concurrency/thread.py
|
ThreadPoolExecutor._ensure_worker
|
def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifier + '_%d' % time.time(),
)
worker.daemon = True
self._workers.add(worker)
worker.start()
|
python
|
def _ensure_worker(self):
"""Ensure there are enough workers available"""
while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers:
worker = threading.Thread(
target=self._execute_futures,
name=self.identifier + '_%d' % time.time(),
)
worker.daemon = True
self._workers.add(worker)
worker.start()
|
[
"def",
"_ensure_worker",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_min_workers",
"or",
"len",
"(",
"self",
".",
"_workers",
")",
"<",
"self",
".",
"_queue",
".",
"qsize",
"(",
")",
"<",
"self",
".",
"_max_workers",
":",
"worker",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_execute_futures",
",",
"name",
"=",
"self",
".",
"identifier",
"+",
"'_%d'",
"%",
"time",
".",
"time",
"(",
")",
",",
")",
"worker",
".",
"daemon",
"=",
"True",
"self",
".",
"_workers",
".",
"add",
"(",
"worker",
")",
"worker",
".",
"start",
"(",
")"
] |
Ensure there are enough workers available
|
[
"Ensure",
"there",
"are",
"enough",
"workers",
"available"
] |
4e17f9992b4780bd0d9309202e2847df640bffe8
|
https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/concurrency/thread.py#L97-L106
|
245,111
|
sassoo/goldman
|
goldman/utils/s3_helpers.py
|
s3_upload
|
def s3_upload(acl, bucket, conn, content, content_type, path):
""" Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a string MIMETYPE of the object that S3 should
be informed of
:param path:
an object specific portion of the S3 key name
to be passed to gen_url to generate the the location
in S3 of the new object
:raise:
IOError on any failure
:return:
S3 generated URL of the uploaded object
"""
# obj is the object that will be uploaded
obj = Key(conn.get_bucket(bucket))
obj.content_type = content_type
obj.key = path
obj.set_contents_from_string(content)
obj.set_acl(acl)
return gen_url(bucket, path)
|
python
|
def s3_upload(acl, bucket, conn, content, content_type, path):
""" Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a string MIMETYPE of the object that S3 should
be informed of
:param path:
an object specific portion of the S3 key name
to be passed to gen_url to generate the the location
in S3 of the new object
:raise:
IOError on any failure
:return:
S3 generated URL of the uploaded object
"""
# obj is the object that will be uploaded
obj = Key(conn.get_bucket(bucket))
obj.content_type = content_type
obj.key = path
obj.set_contents_from_string(content)
obj.set_acl(acl)
return gen_url(bucket, path)
|
[
"def",
"s3_upload",
"(",
"acl",
",",
"bucket",
",",
"conn",
",",
"content",
",",
"content_type",
",",
"path",
")",
":",
"# obj is the object that will be uploaded",
"obj",
"=",
"Key",
"(",
"conn",
".",
"get_bucket",
"(",
"bucket",
")",
")",
"obj",
".",
"content_type",
"=",
"content_type",
"obj",
".",
"key",
"=",
"path",
"obj",
".",
"set_contents_from_string",
"(",
"content",
")",
"obj",
".",
"set_acl",
"(",
"acl",
")",
"return",
"gen_url",
"(",
"bucket",
",",
"path",
")"
] |
Store an object in our an S3 bucket.
:param acl:
S3 ACL for the object
:param bucket:
S3 bucket to upload to
:param content:
a string representation of the object to upload
:param content_type:
a string MIMETYPE of the object that S3 should
be informed of
:param path:
an object specific portion of the S3 key name
to be passed to gen_url to generate the the location
in S3 of the new object
:raise:
IOError on any failure
:return:
S3 generated URL of the uploaded object
|
[
"Store",
"an",
"object",
"in",
"our",
"an",
"S3",
"bucket",
"."
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/s3_helpers.py#L39-L70
|
245,112
|
MinchinWeb/colourettu
|
colourettu/_palette.py
|
Palette.to_image
|
def to_image(self, filename='palette.png', band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
"""
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
length(Optional[int]): the length of the overall image in pixels.
This is the dimension orthogonal to ``band_width``. Defaults
to 60 pixels.
max_width(Optional[int]): if ``band_width`` is not set and this is,
this determines how wide the whole image should be.
vertical(Optional[bool]): if the image runs vertical (``True``,
default) or horizontal (``False``).
alpha_channel(Optional[bool]): if ``True``, the created image will
have an Alpha channel. Defaults to ``False``.
"""
# max_width is approximate
# generate output pictures for documentation automatically
if max_width < 1:
pass
else:
band_width = int(max_width/len(self._colours))
image_width = band_width * len(self._colours)
if alpha_channel:
my_image = Image.new('RGBA', (image_width, length))
else:
my_image = Image.new('RGB', (image_width, length))
image_loaded = my_image.load()
x = 0
for my_colour in self._colours:
for x1 in range(band_width):
for y in range(length):
image_loaded[x, y] = my_colour.rgb()
x = x + 1
if vertical:
my_image = my_image.rotate(270)
my_image.save(filename)
|
python
|
def to_image(self, filename='palette.png', band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
"""
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
length(Optional[int]): the length of the overall image in pixels.
This is the dimension orthogonal to ``band_width``. Defaults
to 60 pixels.
max_width(Optional[int]): if ``band_width`` is not set and this is,
this determines how wide the whole image should be.
vertical(Optional[bool]): if the image runs vertical (``True``,
default) or horizontal (``False``).
alpha_channel(Optional[bool]): if ``True``, the created image will
have an Alpha channel. Defaults to ``False``.
"""
# max_width is approximate
# generate output pictures for documentation automatically
if max_width < 1:
pass
else:
band_width = int(max_width/len(self._colours))
image_width = band_width * len(self._colours)
if alpha_channel:
my_image = Image.new('RGBA', (image_width, length))
else:
my_image = Image.new('RGB', (image_width, length))
image_loaded = my_image.load()
x = 0
for my_colour in self._colours:
for x1 in range(band_width):
for y in range(length):
image_loaded[x, y] = my_colour.rgb()
x = x + 1
if vertical:
my_image = my_image.rotate(270)
my_image.save(filename)
|
[
"def",
"to_image",
"(",
"self",
",",
"filename",
"=",
"'palette.png'",
",",
"band_width",
"=",
"1",
",",
"length",
"=",
"60",
",",
"max_width",
"=",
"0",
",",
"vertical",
"=",
"True",
",",
"alpha_channel",
"=",
"False",
")",
":",
"# max_width is approximate",
"# generate output pictures for documentation automatically",
"if",
"max_width",
"<",
"1",
":",
"pass",
"else",
":",
"band_width",
"=",
"int",
"(",
"max_width",
"/",
"len",
"(",
"self",
".",
"_colours",
")",
")",
"image_width",
"=",
"band_width",
"*",
"len",
"(",
"self",
".",
"_colours",
")",
"if",
"alpha_channel",
":",
"my_image",
"=",
"Image",
".",
"new",
"(",
"'RGBA'",
",",
"(",
"image_width",
",",
"length",
")",
")",
"else",
":",
"my_image",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"(",
"image_width",
",",
"length",
")",
")",
"image_loaded",
"=",
"my_image",
".",
"load",
"(",
")",
"x",
"=",
"0",
"for",
"my_colour",
"in",
"self",
".",
"_colours",
":",
"for",
"x1",
"in",
"range",
"(",
"band_width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"length",
")",
":",
"image_loaded",
"[",
"x",
",",
"y",
"]",
"=",
"my_colour",
".",
"rgb",
"(",
")",
"x",
"=",
"x",
"+",
"1",
"if",
"vertical",
":",
"my_image",
"=",
"my_image",
".",
"rotate",
"(",
"270",
")",
"my_image",
".",
"save",
"(",
"filename",
")"
] |
Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
length(Optional[int]): the length of the overall image in pixels.
This is the dimension orthogonal to ``band_width``. Defaults
to 60 pixels.
max_width(Optional[int]): if ``band_width`` is not set and this is,
this determines how wide the whole image should be.
vertical(Optional[bool]): if the image runs vertical (``True``,
default) or horizontal (``False``).
alpha_channel(Optional[bool]): if ``True``, the created image will
have an Alpha channel. Defaults to ``False``.
|
[
"Creates",
"an",
"image",
"from",
"the",
"palette",
"."
] |
f0b2f6b1d44055f3ccee62ac2759829f1e16a252
|
https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_palette.py#L163-L209
|
245,113
|
MinchinWeb/colourettu
|
colourettu/_palette.py
|
Palette.blend
|
def blend(self, cycles=1):
"""
Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
.. code-block:: python
p1.blend()
p1.to_image('p1_blended.png', 60, vertical=False)
.. image:: p1_blended.png
.. code-block:: python
p2.blend()
p2.to_image('p2_blended.png', 60, vertical=False)
.. image:: p2_blended.png
The *blend* functionallity can be applied several times in a sequence
by use of the *cycles* parameter. This may be useful to quickly get a
longer series of intermediate colours.
.. code-block:: python
p3 = Palette(Colour('#fff'), Colour('#7e1e9c'))
p3.blend(cycles=5)
p3.to_image('p3.png', max_width=360, vertical=False)
.. image:: p3.png
.. seealso:: :py:func:`colourettu.blend`
"""
for j in range(int(cycles)):
new_colours = []
for i, c in enumerate(self._colours):
if i != 0:
c2 = blend(c, self._colours[i-1])
new_colours.append(c2)
new_colours.append(c)
self._colours = new_colours
|
python
|
def blend(self, cycles=1):
"""
Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
.. code-block:: python
p1.blend()
p1.to_image('p1_blended.png', 60, vertical=False)
.. image:: p1_blended.png
.. code-block:: python
p2.blend()
p2.to_image('p2_blended.png', 60, vertical=False)
.. image:: p2_blended.png
The *blend* functionallity can be applied several times in a sequence
by use of the *cycles* parameter. This may be useful to quickly get a
longer series of intermediate colours.
.. code-block:: python
p3 = Palette(Colour('#fff'), Colour('#7e1e9c'))
p3.blend(cycles=5)
p3.to_image('p3.png', max_width=360, vertical=False)
.. image:: p3.png
.. seealso:: :py:func:`colourettu.blend`
"""
for j in range(int(cycles)):
new_colours = []
for i, c in enumerate(self._colours):
if i != 0:
c2 = blend(c, self._colours[i-1])
new_colours.append(c2)
new_colours.append(c)
self._colours = new_colours
|
[
"def",
"blend",
"(",
"self",
",",
"cycles",
"=",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"int",
"(",
"cycles",
")",
")",
":",
"new_colours",
"=",
"[",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"self",
".",
"_colours",
")",
":",
"if",
"i",
"!=",
"0",
":",
"c2",
"=",
"blend",
"(",
"c",
",",
"self",
".",
"_colours",
"[",
"i",
"-",
"1",
"]",
")",
"new_colours",
".",
"append",
"(",
"c2",
")",
"new_colours",
".",
"append",
"(",
"c",
")",
"self",
".",
"_colours",
"=",
"new_colours"
] |
Explands the existing Palette by inserting the blending colour
between all Colours already in the Palette.
Changes the Palette in-place.
args:
cycles(int): number of *blend* cycles to apply. (Default is 1)
Example usage:
.. code-block:: python
p1.blend()
p1.to_image('p1_blended.png', 60, vertical=False)
.. image:: p1_blended.png
.. code-block:: python
p2.blend()
p2.to_image('p2_blended.png', 60, vertical=False)
.. image:: p2_blended.png
The *blend* functionallity can be applied several times in a sequence
by use of the *cycles* parameter. This may be useful to quickly get a
longer series of intermediate colours.
.. code-block:: python
p3 = Palette(Colour('#fff'), Colour('#7e1e9c'))
p3.blend(cycles=5)
p3.to_image('p3.png', max_width=360, vertical=False)
.. image:: p3.png
.. seealso:: :py:func:`colourettu.blend`
|
[
"Explands",
"the",
"existing",
"Palette",
"by",
"inserting",
"the",
"blending",
"colour",
"between",
"all",
"Colours",
"already",
"in",
"the",
"Palette",
"."
] |
f0b2f6b1d44055f3ccee62ac2759829f1e16a252
|
https://github.com/MinchinWeb/colourettu/blob/f0b2f6b1d44055f3ccee62ac2759829f1e16a252/colourettu/_palette.py#L211-L260
|
245,114
|
collectiveacuity/labPack
|
utils.py
|
inject_init
|
def inject_init(init_path, readme_path, setup_kwargs):
'''
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup keyword arguments
:return: dictionary with injected keyword arguments
'''
import re
from os import path
from copy import deepcopy
# retrieve init text
init_text = ''
if not path.exists(init_path):
raise ValueError('%s is not a valid path' % init_path)
init_text = open(init_path).read()
# retrieve init settings
init_kwargs = {
'version': '',
'author': '',
'url': '',
'description': '',
'license': '',
}
for key in init_kwargs.keys():
key_regex = re.compile("__%s__\s?\=\s?'(.*?)'" % key)
key_search = key_regex.findall(init_text)
if key_search:
init_kwargs[key] = key_search[0]
# retrieve modifiable settings
mod_kwargs = {
'module': '',
'email': '',
'entry': '',
'authors': ''
}
for key in mod_kwargs.keys():
key_regex = re.compile("__%s__\s?\=\s?'(.*?)'" % key)
key_search = key_regex.findall(init_text)
if key_search:
mod_kwargs[key] = key_search[0]
if mod_kwargs['module']:
init_kwargs['name'] = mod_kwargs['module']
if mod_kwargs['entry']:
init_kwargs['entry_points'] = {"console_scripts": [mod_kwargs['entry']]}
if mod_kwargs['email']:
init_kwargs['author_email'] = mod_kwargs['email']
init_kwargs['maintainer_email'] = mod_kwargs['email']
if mod_kwargs['authors']:
del init_kwargs['author']
init_kwargs['author_list'] = mod_kwargs['authors'].split(' ')
# add readme
if not path.exists(readme_path):
raise ValueError('%s is not a valid path' % readme_path)
try:
readme_text = open(readme_path).read()
init_kwargs['long_description'] = str(readme_text)
except:
raise ValueError('%s is not a valid text file.' % readme_path)
# merge kwargs
setup_kwargs.update(**init_kwargs)
updated_kwargs = deepcopy(setup_kwargs)
for key, value in updated_kwargs.items():
if not value:
del setup_kwargs[key]
return setup_kwargs
|
python
|
def inject_init(init_path, readme_path, setup_kwargs):
'''
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup keyword arguments
:return: dictionary with injected keyword arguments
'''
import re
from os import path
from copy import deepcopy
# retrieve init text
init_text = ''
if not path.exists(init_path):
raise ValueError('%s is not a valid path' % init_path)
init_text = open(init_path).read()
# retrieve init settings
init_kwargs = {
'version': '',
'author': '',
'url': '',
'description': '',
'license': '',
}
for key in init_kwargs.keys():
key_regex = re.compile("__%s__\s?\=\s?'(.*?)'" % key)
key_search = key_regex.findall(init_text)
if key_search:
init_kwargs[key] = key_search[0]
# retrieve modifiable settings
mod_kwargs = {
'module': '',
'email': '',
'entry': '',
'authors': ''
}
for key in mod_kwargs.keys():
key_regex = re.compile("__%s__\s?\=\s?'(.*?)'" % key)
key_search = key_regex.findall(init_text)
if key_search:
mod_kwargs[key] = key_search[0]
if mod_kwargs['module']:
init_kwargs['name'] = mod_kwargs['module']
if mod_kwargs['entry']:
init_kwargs['entry_points'] = {"console_scripts": [mod_kwargs['entry']]}
if mod_kwargs['email']:
init_kwargs['author_email'] = mod_kwargs['email']
init_kwargs['maintainer_email'] = mod_kwargs['email']
if mod_kwargs['authors']:
del init_kwargs['author']
init_kwargs['author_list'] = mod_kwargs['authors'].split(' ')
# add readme
if not path.exists(readme_path):
raise ValueError('%s is not a valid path' % readme_path)
try:
readme_text = open(readme_path).read()
init_kwargs['long_description'] = str(readme_text)
except:
raise ValueError('%s is not a valid text file.' % readme_path)
# merge kwargs
setup_kwargs.update(**init_kwargs)
updated_kwargs = deepcopy(setup_kwargs)
for key, value in updated_kwargs.items():
if not value:
del setup_kwargs[key]
return setup_kwargs
|
[
"def",
"inject_init",
"(",
"init_path",
",",
"readme_path",
",",
"setup_kwargs",
")",
":",
"import",
"re",
"from",
"os",
"import",
"path",
"from",
"copy",
"import",
"deepcopy",
"# retrieve init text",
"init_text",
"=",
"''",
"if",
"not",
"path",
".",
"exists",
"(",
"init_path",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid path'",
"%",
"init_path",
")",
"init_text",
"=",
"open",
"(",
"init_path",
")",
".",
"read",
"(",
")",
"# retrieve init settings",
"init_kwargs",
"=",
"{",
"'version'",
":",
"''",
",",
"'author'",
":",
"''",
",",
"'url'",
":",
"''",
",",
"'description'",
":",
"''",
",",
"'license'",
":",
"''",
",",
"}",
"for",
"key",
"in",
"init_kwargs",
".",
"keys",
"(",
")",
":",
"key_regex",
"=",
"re",
".",
"compile",
"(",
"\"__%s__\\s?\\=\\s?'(.*?)'\"",
"%",
"key",
")",
"key_search",
"=",
"key_regex",
".",
"findall",
"(",
"init_text",
")",
"if",
"key_search",
":",
"init_kwargs",
"[",
"key",
"]",
"=",
"key_search",
"[",
"0",
"]",
"# retrieve modifiable settings",
"mod_kwargs",
"=",
"{",
"'module'",
":",
"''",
",",
"'email'",
":",
"''",
",",
"'entry'",
":",
"''",
",",
"'authors'",
":",
"''",
"}",
"for",
"key",
"in",
"mod_kwargs",
".",
"keys",
"(",
")",
":",
"key_regex",
"=",
"re",
".",
"compile",
"(",
"\"__%s__\\s?\\=\\s?'(.*?)'\"",
"%",
"key",
")",
"key_search",
"=",
"key_regex",
".",
"findall",
"(",
"init_text",
")",
"if",
"key_search",
":",
"mod_kwargs",
"[",
"key",
"]",
"=",
"key_search",
"[",
"0",
"]",
"if",
"mod_kwargs",
"[",
"'module'",
"]",
":",
"init_kwargs",
"[",
"'name'",
"]",
"=",
"mod_kwargs",
"[",
"'module'",
"]",
"if",
"mod_kwargs",
"[",
"'entry'",
"]",
":",
"init_kwargs",
"[",
"'entry_points'",
"]",
"=",
"{",
"\"console_scripts\"",
":",
"[",
"mod_kwargs",
"[",
"'entry'",
"]",
"]",
"}",
"if",
"mod_kwargs",
"[",
"'email'",
"]",
":",
"init_kwargs",
"[",
"'author_email'",
"]",
"=",
"mod_kwargs",
"[",
"'email'",
"]",
"init_kwargs",
"[",
"'maintainer_email'",
"]",
"=",
"mod_kwargs",
"[",
"'email'",
"]",
"if",
"mod_kwargs",
"[",
"'authors'",
"]",
":",
"del",
"init_kwargs",
"[",
"'author'",
"]",
"init_kwargs",
"[",
"'author_list'",
"]",
"=",
"mod_kwargs",
"[",
"'authors'",
"]",
".",
"split",
"(",
"' '",
")",
"# add readme",
"if",
"not",
"path",
".",
"exists",
"(",
"readme_path",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid path'",
"%",
"readme_path",
")",
"try",
":",
"readme_text",
"=",
"open",
"(",
"readme_path",
")",
".",
"read",
"(",
")",
"init_kwargs",
"[",
"'long_description'",
"]",
"=",
"str",
"(",
"readme_text",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid text file.'",
"%",
"readme_path",
")",
"# merge kwargs",
"setup_kwargs",
".",
"update",
"(",
"*",
"*",
"init_kwargs",
")",
"updated_kwargs",
"=",
"deepcopy",
"(",
"setup_kwargs",
")",
"for",
"key",
",",
"value",
"in",
"updated_kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
":",
"del",
"setup_kwargs",
"[",
"key",
"]",
"return",
"setup_kwargs"
] |
a method to add arguments to setup.py from module init file
:param init_path: string with path to module __init__ file
:param readme_path: string with path to module README.rst file
:param setup_kwargs: dictionary with existing setup keyword arguments
:return: dictionary with injected keyword arguments
|
[
"a",
"method",
"to",
"add",
"arguments",
"to",
"setup",
".",
"py",
"from",
"module",
"init",
"file"
] |
52949ece35e72e3cc308f54d9ffa6bfbd96805b8
|
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/utils.py#L6-L79
|
245,115
|
RazerM/bucketcache
|
shovel/version.py
|
bump
|
def bump(dev=False, patch=False, minor=False, major=False, nocommit=False):
"""Bump version number and commit change."""
if sum([int(x) for x in (patch, minor, major)]) > 1:
raise ValueError('Only one of patch, minor, major can be incremented.')
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
lines = f.readlines()
for i, line in enumerate(lines):
varmatch = re.match("__([a-z]+)__ = '([^']+)'", line)
if varmatch:
if varmatch.group(1) == 'version':
version = Version(varmatch.group(2))
vdict = version._version._asdict()
print('Current version:', version)
increment_release = True
if dev:
if vdict['dev']:
vdict['dev'] = (vdict['dev'][0], vdict['dev'][1] + 1)
increment_release = False
if sum([int(x) for x in (patch, minor, major)]) > 0:
raise ValueError('Cannot increment patch, minor, or major between dev versions.')
else:
vdict['dev'] = ('dev', 0)
else:
if vdict['dev']:
vdict['dev'] = None
increment_release = False
if increment_release:
rel = vdict['release']
if major:
vdict['release'] = (rel[0] + 1, 0, 0)
elif patch:
vdict['release'] = (rel[0], rel[1], rel[2] + 1)
else: # minor is default
vdict['release'] = (rel[0], rel[1] + 1, 0)
version._version = _Version(**vdict)
print('Version bumped to:', version)
lines[i] = "__version__ = '{!s}'\n".format(version)
break
with open(str(INIT_PATH), 'w') as f:
f.writelines(lines)
if not nocommit:
call(['git', 'add', 'bucketcache/__init__.py'])
call(['git', 'commit', '-m', 'Bumped version number to {!s}'.format(version)])
return version
|
python
|
def bump(dev=False, patch=False, minor=False, major=False, nocommit=False):
"""Bump version number and commit change."""
if sum([int(x) for x in (patch, minor, major)]) > 1:
raise ValueError('Only one of patch, minor, major can be incremented.')
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
lines = f.readlines()
for i, line in enumerate(lines):
varmatch = re.match("__([a-z]+)__ = '([^']+)'", line)
if varmatch:
if varmatch.group(1) == 'version':
version = Version(varmatch.group(2))
vdict = version._version._asdict()
print('Current version:', version)
increment_release = True
if dev:
if vdict['dev']:
vdict['dev'] = (vdict['dev'][0], vdict['dev'][1] + 1)
increment_release = False
if sum([int(x) for x in (patch, minor, major)]) > 0:
raise ValueError('Cannot increment patch, minor, or major between dev versions.')
else:
vdict['dev'] = ('dev', 0)
else:
if vdict['dev']:
vdict['dev'] = None
increment_release = False
if increment_release:
rel = vdict['release']
if major:
vdict['release'] = (rel[0] + 1, 0, 0)
elif patch:
vdict['release'] = (rel[0], rel[1], rel[2] + 1)
else: # minor is default
vdict['release'] = (rel[0], rel[1] + 1, 0)
version._version = _Version(**vdict)
print('Version bumped to:', version)
lines[i] = "__version__ = '{!s}'\n".format(version)
break
with open(str(INIT_PATH), 'w') as f:
f.writelines(lines)
if not nocommit:
call(['git', 'add', 'bucketcache/__init__.py'])
call(['git', 'commit', '-m', 'Bumped version number to {!s}'.format(version)])
return version
|
[
"def",
"bump",
"(",
"dev",
"=",
"False",
",",
"patch",
"=",
"False",
",",
"minor",
"=",
"False",
",",
"major",
"=",
"False",
",",
"nocommit",
"=",
"False",
")",
":",
"if",
"sum",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"patch",
",",
"minor",
",",
"major",
")",
"]",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Only one of patch, minor, major can be incremented.'",
")",
"if",
"check_staged",
"(",
")",
":",
"raise",
"EnvironmentError",
"(",
"'There are staged changes, abort.'",
")",
"with",
"open",
"(",
"str",
"(",
"INIT_PATH",
")",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"varmatch",
"=",
"re",
".",
"match",
"(",
"\"__([a-z]+)__ = '([^']+)'\"",
",",
"line",
")",
"if",
"varmatch",
":",
"if",
"varmatch",
".",
"group",
"(",
"1",
")",
"==",
"'version'",
":",
"version",
"=",
"Version",
"(",
"varmatch",
".",
"group",
"(",
"2",
")",
")",
"vdict",
"=",
"version",
".",
"_version",
".",
"_asdict",
"(",
")",
"print",
"(",
"'Current version:'",
",",
"version",
")",
"increment_release",
"=",
"True",
"if",
"dev",
":",
"if",
"vdict",
"[",
"'dev'",
"]",
":",
"vdict",
"[",
"'dev'",
"]",
"=",
"(",
"vdict",
"[",
"'dev'",
"]",
"[",
"0",
"]",
",",
"vdict",
"[",
"'dev'",
"]",
"[",
"1",
"]",
"+",
"1",
")",
"increment_release",
"=",
"False",
"if",
"sum",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"patch",
",",
"minor",
",",
"major",
")",
"]",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Cannot increment patch, minor, or major between dev versions.'",
")",
"else",
":",
"vdict",
"[",
"'dev'",
"]",
"=",
"(",
"'dev'",
",",
"0",
")",
"else",
":",
"if",
"vdict",
"[",
"'dev'",
"]",
":",
"vdict",
"[",
"'dev'",
"]",
"=",
"None",
"increment_release",
"=",
"False",
"if",
"increment_release",
":",
"rel",
"=",
"vdict",
"[",
"'release'",
"]",
"if",
"major",
":",
"vdict",
"[",
"'release'",
"]",
"=",
"(",
"rel",
"[",
"0",
"]",
"+",
"1",
",",
"0",
",",
"0",
")",
"elif",
"patch",
":",
"vdict",
"[",
"'release'",
"]",
"=",
"(",
"rel",
"[",
"0",
"]",
",",
"rel",
"[",
"1",
"]",
",",
"rel",
"[",
"2",
"]",
"+",
"1",
")",
"else",
":",
"# minor is default",
"vdict",
"[",
"'release'",
"]",
"=",
"(",
"rel",
"[",
"0",
"]",
",",
"rel",
"[",
"1",
"]",
"+",
"1",
",",
"0",
")",
"version",
".",
"_version",
"=",
"_Version",
"(",
"*",
"*",
"vdict",
")",
"print",
"(",
"'Version bumped to:'",
",",
"version",
")",
"lines",
"[",
"i",
"]",
"=",
"\"__version__ = '{!s}'\\n\"",
".",
"format",
"(",
"version",
")",
"break",
"with",
"open",
"(",
"str",
"(",
"INIT_PATH",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"writelines",
"(",
"lines",
")",
"if",
"not",
"nocommit",
":",
"call",
"(",
"[",
"'git'",
",",
"'add'",
",",
"'bucketcache/__init__.py'",
"]",
")",
"call",
"(",
"[",
"'git'",
",",
"'commit'",
",",
"'-m'",
",",
"'Bumped version number to {!s}'",
".",
"format",
"(",
"version",
")",
"]",
")",
"return",
"version"
] |
Bump version number and commit change.
|
[
"Bump",
"version",
"number",
"and",
"commit",
"change",
"."
] |
8d9b163b73da8c498793cce2f22f6a7cbe524d94
|
https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L19-L71
|
245,116
|
RazerM/bucketcache
|
shovel/version.py
|
tag
|
def tag():
"""Tag current version."""
if check_unstaged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", f.read()))
version = metadata['version']
check_output(['git', 'tag', version, '-m', 'Release v{}'.format(version)])
|
python
|
def tag():
"""Tag current version."""
if check_unstaged():
raise EnvironmentError('There are staged changes, abort.')
with open(str(INIT_PATH)) as f:
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", f.read()))
version = metadata['version']
check_output(['git', 'tag', version, '-m', 'Release v{}'.format(version)])
|
[
"def",
"tag",
"(",
")",
":",
"if",
"check_unstaged",
"(",
")",
":",
"raise",
"EnvironmentError",
"(",
"'There are staged changes, abort.'",
")",
"with",
"open",
"(",
"str",
"(",
"INIT_PATH",
")",
")",
"as",
"f",
":",
"metadata",
"=",
"dict",
"(",
"re",
".",
"findall",
"(",
"\"__([a-z]+)__ = '([^']+)'\"",
",",
"f",
".",
"read",
"(",
")",
")",
")",
"version",
"=",
"metadata",
"[",
"'version'",
"]",
"check_output",
"(",
"[",
"'git'",
",",
"'tag'",
",",
"version",
",",
"'-m'",
",",
"'Release v{}'",
".",
"format",
"(",
"version",
")",
"]",
")"
] |
Tag current version.
|
[
"Tag",
"current",
"version",
"."
] |
8d9b163b73da8c498793cce2f22f6a7cbe524d94
|
https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L75-L82
|
245,117
|
RazerM/bucketcache
|
shovel/version.py
|
upload
|
def upload():
"""Upload source to PyPI using twine."""
try:
o = check_output(['twine', 'upload'] + glob('dist/*'))
except CalledProcessError:
call(['twine', 'upload'] + glob('dist/*'))
raise
print(o.decode('utf-8'))
|
python
|
def upload():
"""Upload source to PyPI using twine."""
try:
o = check_output(['twine', 'upload'] + glob('dist/*'))
except CalledProcessError:
call(['twine', 'upload'] + glob('dist/*'))
raise
print(o.decode('utf-8'))
|
[
"def",
"upload",
"(",
")",
":",
"try",
":",
"o",
"=",
"check_output",
"(",
"[",
"'twine'",
",",
"'upload'",
"]",
"+",
"glob",
"(",
"'dist/*'",
")",
")",
"except",
"CalledProcessError",
":",
"call",
"(",
"[",
"'twine'",
",",
"'upload'",
"]",
"+",
"glob",
"(",
"'dist/*'",
")",
")",
"raise",
"print",
"(",
"o",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] |
Upload source to PyPI using twine.
|
[
"Upload",
"source",
"to",
"PyPI",
"using",
"twine",
"."
] |
8d9b163b73da8c498793cce2f22f6a7cbe524d94
|
https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L94-L101
|
245,118
|
RazerM/bucketcache
|
shovel/version.py
|
release
|
def release():
"""Bump version, tag, build, gen docs."""
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
if check_unstaged():
raise EnvironmentError('There are unstaged changes, abort.')
bump()
tag()
build()
doc_gen()
puts(colored.yellow("Remember to upload documentation and package:"))
with indent(2):
puts(colored.cyan("shovel doc.upload"))
puts(colored.cyan("shovel version.upload"))
|
python
|
def release():
"""Bump version, tag, build, gen docs."""
if check_staged():
raise EnvironmentError('There are staged changes, abort.')
if check_unstaged():
raise EnvironmentError('There are unstaged changes, abort.')
bump()
tag()
build()
doc_gen()
puts(colored.yellow("Remember to upload documentation and package:"))
with indent(2):
puts(colored.cyan("shovel doc.upload"))
puts(colored.cyan("shovel version.upload"))
|
[
"def",
"release",
"(",
")",
":",
"if",
"check_staged",
"(",
")",
":",
"raise",
"EnvironmentError",
"(",
"'There are staged changes, abort.'",
")",
"if",
"check_unstaged",
"(",
")",
":",
"raise",
"EnvironmentError",
"(",
"'There are unstaged changes, abort.'",
")",
"bump",
"(",
")",
"tag",
"(",
")",
"build",
"(",
")",
"doc_gen",
"(",
")",
"puts",
"(",
"colored",
".",
"yellow",
"(",
"\"Remember to upload documentation and package:\"",
")",
")",
"with",
"indent",
"(",
"2",
")",
":",
"puts",
"(",
"colored",
".",
"cyan",
"(",
"\"shovel doc.upload\"",
")",
")",
"puts",
"(",
"colored",
".",
"cyan",
"(",
"\"shovel version.upload\"",
")",
")"
] |
Bump version, tag, build, gen docs.
|
[
"Bump",
"version",
"tag",
"build",
"gen",
"docs",
"."
] |
8d9b163b73da8c498793cce2f22f6a7cbe524d94
|
https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L105-L118
|
245,119
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
validate_rid
|
def validate_rid(model, rid):
""" Ensure the resource id is proper """
rid_field = getattr(model, model.rid_field)
if isinstance(rid_field, IntType):
try:
int(rid)
except (TypeError, ValueError):
abort(exceptions.InvalidURL(**{
'detail': 'The resource id {} in your request is not '
'syntactically correct. Only numeric type '
'resource id\'s are allowed'.format(rid)
}))
|
python
|
def validate_rid(model, rid):
""" Ensure the resource id is proper """
rid_field = getattr(model, model.rid_field)
if isinstance(rid_field, IntType):
try:
int(rid)
except (TypeError, ValueError):
abort(exceptions.InvalidURL(**{
'detail': 'The resource id {} in your request is not '
'syntactically correct. Only numeric type '
'resource id\'s are allowed'.format(rid)
}))
|
[
"def",
"validate_rid",
"(",
"model",
",",
"rid",
")",
":",
"rid_field",
"=",
"getattr",
"(",
"model",
",",
"model",
".",
"rid_field",
")",
"if",
"isinstance",
"(",
"rid_field",
",",
"IntType",
")",
":",
"try",
":",
"int",
"(",
"rid",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"abort",
"(",
"exceptions",
".",
"InvalidURL",
"(",
"*",
"*",
"{",
"'detail'",
":",
"'The resource id {} in your request is not '",
"'syntactically correct. Only numeric type '",
"'resource id\\'s are allowed'",
".",
"format",
"(",
"rid",
")",
"}",
")",
")"
] |
Ensure the resource id is proper
|
[
"Ensure",
"the",
"resource",
"id",
"is",
"proper"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L25-L38
|
245,120
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
find
|
def find(model, rid):
""" Find a model from the store by resource id """
validate_rid(model, rid)
rid_field = model.rid_field
model = goldman.sess.store.find(model.RTYPE, rid_field, rid)
if not model:
abort(exceptions.DocumentNotFound)
return model
|
python
|
def find(model, rid):
""" Find a model from the store by resource id """
validate_rid(model, rid)
rid_field = model.rid_field
model = goldman.sess.store.find(model.RTYPE, rid_field, rid)
if not model:
abort(exceptions.DocumentNotFound)
return model
|
[
"def",
"find",
"(",
"model",
",",
"rid",
")",
":",
"validate_rid",
"(",
"model",
",",
"rid",
")",
"rid_field",
"=",
"model",
".",
"rid_field",
"model",
"=",
"goldman",
".",
"sess",
".",
"store",
".",
"find",
"(",
"model",
".",
"RTYPE",
",",
"rid_field",
",",
"rid",
")",
"if",
"not",
"model",
":",
"abort",
"(",
"exceptions",
".",
"DocumentNotFound",
")",
"return",
"model"
] |
Find a model from the store by resource id
|
[
"Find",
"a",
"model",
"from",
"the",
"store",
"by",
"resource",
"id"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L41-L52
|
245,121
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_blank
|
def _from_rest_blank(model, props):
""" Set empty strings to None where allowed
This is done on fields with `allow_blank=True` which takes
an incoming empty string & sets it to None so validations
are skipped. This is useful on fields that aren't required
with format validations like URLType, EmailType, etc.
"""
blank = model.get_fields_by_prop('allow_blank', True)
for field in blank:
try:
if props[field] == '':
props[field] = None
except KeyError:
continue
|
python
|
def _from_rest_blank(model, props):
""" Set empty strings to None where allowed
This is done on fields with `allow_blank=True` which takes
an incoming empty string & sets it to None so validations
are skipped. This is useful on fields that aren't required
with format validations like URLType, EmailType, etc.
"""
blank = model.get_fields_by_prop('allow_blank', True)
for field in blank:
try:
if props[field] == '':
props[field] = None
except KeyError:
continue
|
[
"def",
"_from_rest_blank",
"(",
"model",
",",
"props",
")",
":",
"blank",
"=",
"model",
".",
"get_fields_by_prop",
"(",
"'allow_blank'",
",",
"True",
")",
"for",
"field",
"in",
"blank",
":",
"try",
":",
"if",
"props",
"[",
"field",
"]",
"==",
"''",
":",
"props",
"[",
"field",
"]",
"=",
"None",
"except",
"KeyError",
":",
"continue"
] |
Set empty strings to None where allowed
This is done on fields with `allow_blank=True` which takes
an incoming empty string & sets it to None so validations
are skipped. This is useful on fields that aren't required
with format validations like URLType, EmailType, etc.
|
[
"Set",
"empty",
"strings",
"to",
"None",
"where",
"allowed"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L55-L71
|
245,122
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_hide
|
def _from_rest_hide(model, props):
""" Purge fields not allowed during a REST deserialization
This is done on fields with `from_rest=False`.
"""
hide = model.get_fields_by_prop('from_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
continue
|
python
|
def _from_rest_hide(model, props):
""" Purge fields not allowed during a REST deserialization
This is done on fields with `from_rest=False`.
"""
hide = model.get_fields_by_prop('from_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
continue
|
[
"def",
"_from_rest_hide",
"(",
"model",
",",
"props",
")",
":",
"hide",
"=",
"model",
".",
"get_fields_by_prop",
"(",
"'from_rest'",
",",
"False",
")",
"for",
"field",
"in",
"hide",
":",
"try",
":",
"del",
"props",
"[",
"field",
"]",
"except",
"KeyError",
":",
"continue"
] |
Purge fields not allowed during a REST deserialization
This is done on fields with `from_rest=False`.
|
[
"Purge",
"fields",
"not",
"allowed",
"during",
"a",
"REST",
"deserialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L74-L86
|
245,123
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_ignore
|
def _from_rest_ignore(model, props):
""" Purge fields that are completely unknown """
fields = model.all_fields
for prop in props.keys():
if prop not in fields:
del props[prop]
|
python
|
def _from_rest_ignore(model, props):
""" Purge fields that are completely unknown """
fields = model.all_fields
for prop in props.keys():
if prop not in fields:
del props[prop]
|
[
"def",
"_from_rest_ignore",
"(",
"model",
",",
"props",
")",
":",
"fields",
"=",
"model",
".",
"all_fields",
"for",
"prop",
"in",
"props",
".",
"keys",
"(",
")",
":",
"if",
"prop",
"not",
"in",
"fields",
":",
"del",
"props",
"[",
"prop",
"]"
] |
Purge fields that are completely unknown
|
[
"Purge",
"fields",
"that",
"are",
"completely",
"unknown"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L89-L96
|
245,124
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_lower
|
def _from_rest_lower(model, props):
""" Lowercase fields requesting it during a REST deserialization """
for field in model.to_lower:
try:
props[field] = props[field].lower()
except (AttributeError, KeyError):
continue
|
python
|
def _from_rest_lower(model, props):
""" Lowercase fields requesting it during a REST deserialization """
for field in model.to_lower:
try:
props[field] = props[field].lower()
except (AttributeError, KeyError):
continue
|
[
"def",
"_from_rest_lower",
"(",
"model",
",",
"props",
")",
":",
"for",
"field",
"in",
"model",
".",
"to_lower",
":",
"try",
":",
"props",
"[",
"field",
"]",
"=",
"props",
"[",
"field",
"]",
".",
"lower",
"(",
")",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"continue"
] |
Lowercase fields requesting it during a REST deserialization
|
[
"Lowercase",
"fields",
"requesting",
"it",
"during",
"a",
"REST",
"deserialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L99-L106
|
245,125
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_on_create
|
def _from_rest_on_create(model, props):
""" Assign the default values when creating a model
This is done on fields with `on_create=<value>`.
"""
fields = model.get_fields_with_prop('on_create')
for field in fields:
props[field[0]] = field[1]
|
python
|
def _from_rest_on_create(model, props):
""" Assign the default values when creating a model
This is done on fields with `on_create=<value>`.
"""
fields = model.get_fields_with_prop('on_create')
for field in fields:
props[field[0]] = field[1]
|
[
"def",
"_from_rest_on_create",
"(",
"model",
",",
"props",
")",
":",
"fields",
"=",
"model",
".",
"get_fields_with_prop",
"(",
"'on_create'",
")",
"for",
"field",
"in",
"fields",
":",
"props",
"[",
"field",
"[",
"0",
"]",
"]",
"=",
"field",
"[",
"1",
"]"
] |
Assign the default values when creating a model
This is done on fields with `on_create=<value>`.
|
[
"Assign",
"the",
"default",
"values",
"when",
"creating",
"a",
"model"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L109-L118
|
245,126
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_on_update
|
def _from_rest_on_update(model, props):
""" Assign the default values when updating a model
This is done on fields with `on_update=<value>`.
"""
fields = model.get_fields_with_prop('on_update')
for field in fields:
props[field[0]] = field[1]
|
python
|
def _from_rest_on_update(model, props):
""" Assign the default values when updating a model
This is done on fields with `on_update=<value>`.
"""
fields = model.get_fields_with_prop('on_update')
for field in fields:
props[field[0]] = field[1]
|
[
"def",
"_from_rest_on_update",
"(",
"model",
",",
"props",
")",
":",
"fields",
"=",
"model",
".",
"get_fields_with_prop",
"(",
"'on_update'",
")",
"for",
"field",
"in",
"fields",
":",
"props",
"[",
"field",
"[",
"0",
"]",
"]",
"=",
"field",
"[",
"1",
"]"
] |
Assign the default values when updating a model
This is done on fields with `on_update=<value>`.
|
[
"Assign",
"the",
"default",
"values",
"when",
"updating",
"a",
"model"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L121-L130
|
245,127
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_from_rest_reject_update
|
def _from_rest_reject_update(model):
""" Reject any field updates not allowed on POST
This is done on fields with `reject_update=True`.
"""
dirty = model.dirty_fields
fields = model.get_fields_by_prop('reject_update', True)
reject = []
for field in fields:
if field in dirty:
reject.append(field)
if reject:
mod_fail('These fields cannot be updated: %s' % ', '.join(reject))
|
python
|
def _from_rest_reject_update(model):
""" Reject any field updates not allowed on POST
This is done on fields with `reject_update=True`.
"""
dirty = model.dirty_fields
fields = model.get_fields_by_prop('reject_update', True)
reject = []
for field in fields:
if field in dirty:
reject.append(field)
if reject:
mod_fail('These fields cannot be updated: %s' % ', '.join(reject))
|
[
"def",
"_from_rest_reject_update",
"(",
"model",
")",
":",
"dirty",
"=",
"model",
".",
"dirty_fields",
"fields",
"=",
"model",
".",
"get_fields_by_prop",
"(",
"'reject_update'",
",",
"True",
")",
"reject",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
"in",
"dirty",
":",
"reject",
".",
"append",
"(",
"field",
")",
"if",
"reject",
":",
"mod_fail",
"(",
"'These fields cannot be updated: %s'",
"%",
"', '",
".",
"join",
"(",
"reject",
")",
")"
] |
Reject any field updates not allowed on POST
This is done on fields with `reject_update=True`.
|
[
"Reject",
"any",
"field",
"updates",
"not",
"allowed",
"on",
"POST"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L133-L148
|
245,128
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
from_rest
|
def from_rest(model, props):
""" Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
* lowercase certain fields that need it
* merge new data with existing & validate
* mutate the existing model
* abort on validation errors
* coerce all the values
"""
req = goldman.sess.req
_from_rest_blank(model, props)
_from_rest_hide(model, props)
_from_rest_ignore(model, props)
_from_rest_lower(model, props)
if req.is_posting:
_from_rest_on_create(model, props)
elif req.is_patching:
_from_rest_on_update(model, props)
model.merge(props, validate=True)
if req.is_patching:
_from_rest_reject_update(model)
|
python
|
def from_rest(model, props):
""" Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
* lowercase certain fields that need it
* merge new data with existing & validate
* mutate the existing model
* abort on validation errors
* coerce all the values
"""
req = goldman.sess.req
_from_rest_blank(model, props)
_from_rest_hide(model, props)
_from_rest_ignore(model, props)
_from_rest_lower(model, props)
if req.is_posting:
_from_rest_on_create(model, props)
elif req.is_patching:
_from_rest_on_update(model, props)
model.merge(props, validate=True)
if req.is_patching:
_from_rest_reject_update(model)
|
[
"def",
"from_rest",
"(",
"model",
",",
"props",
")",
":",
"req",
"=",
"goldman",
".",
"sess",
".",
"req",
"_from_rest_blank",
"(",
"model",
",",
"props",
")",
"_from_rest_hide",
"(",
"model",
",",
"props",
")",
"_from_rest_ignore",
"(",
"model",
",",
"props",
")",
"_from_rest_lower",
"(",
"model",
",",
"props",
")",
"if",
"req",
".",
"is_posting",
":",
"_from_rest_on_create",
"(",
"model",
",",
"props",
")",
"elif",
"req",
".",
"is_patching",
":",
"_from_rest_on_update",
"(",
"model",
",",
"props",
")",
"model",
".",
"merge",
"(",
"props",
",",
"validate",
"=",
"True",
")",
"if",
"req",
".",
"is_patching",
":",
"_from_rest_reject_update",
"(",
"model",
")"
] |
Map the REST data onto the model
Additionally, perform the following tasks:
* set all blank strings to None where needed
* purge all fields not allowed as incoming data
* purge all unknown fields from the incoming data
* lowercase certain fields that need it
* merge new data with existing & validate
* mutate the existing model
* abort on validation errors
* coerce all the values
|
[
"Map",
"the",
"REST",
"data",
"onto",
"the",
"model"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L151-L181
|
245,129
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_to_rest_hide
|
def _to_rest_hide(model, props):
""" Purge fields not allowed during a REST serialization
This is done on fields with `to_rest=False`.
"""
hide = model.get_fields_by_prop('to_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
continue
|
python
|
def _to_rest_hide(model, props):
""" Purge fields not allowed during a REST serialization
This is done on fields with `to_rest=False`.
"""
hide = model.get_fields_by_prop('to_rest', False)
for field in hide:
try:
del props[field]
except KeyError:
continue
|
[
"def",
"_to_rest_hide",
"(",
"model",
",",
"props",
")",
":",
"hide",
"=",
"model",
".",
"get_fields_by_prop",
"(",
"'to_rest'",
",",
"False",
")",
"for",
"field",
"in",
"hide",
":",
"try",
":",
"del",
"props",
"[",
"field",
"]",
"except",
"KeyError",
":",
"continue"
] |
Purge fields not allowed during a REST serialization
This is done on fields with `to_rest=False`.
|
[
"Purge",
"fields",
"not",
"allowed",
"during",
"a",
"REST",
"serialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L184-L196
|
245,130
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_to_rest_includes
|
def _to_rest_includes(models, includes):
""" Fetch the models to be included
The includes should follow a few basic rules:
* the include MUST not already be an array member
of the included array (no dupes)
* the include MUST not be the same as the primary
data if the primary data is a single resource
object (no dupes)
* the include MUST not be an array member of the
primary data if the primary data an array of
resource objects (no dupes)
Basically, each included array member should be the only
instance of that resource object in the entire restified
data.
"""
included = []
includes = includes or []
if not isinstance(models, list):
models = [models]
for include in includes:
for model in models:
rel = getattr(model, include)
if hasattr(rel, 'model') and rel.model:
rel_models = [rel.model]
elif hasattr(rel, 'models') and rel.models:
rel_models = rel.models
for rel_model in rel_models:
if rel_model in models or rel_model in included:
continue
else:
included.append(rel_model)
for idx, val in enumerate(included):
included[idx] = _to_rest(val)
return included
|
python
|
def _to_rest_includes(models, includes):
""" Fetch the models to be included
The includes should follow a few basic rules:
* the include MUST not already be an array member
of the included array (no dupes)
* the include MUST not be the same as the primary
data if the primary data is a single resource
object (no dupes)
* the include MUST not be an array member of the
primary data if the primary data an array of
resource objects (no dupes)
Basically, each included array member should be the only
instance of that resource object in the entire restified
data.
"""
included = []
includes = includes or []
if not isinstance(models, list):
models = [models]
for include in includes:
for model in models:
rel = getattr(model, include)
if hasattr(rel, 'model') and rel.model:
rel_models = [rel.model]
elif hasattr(rel, 'models') and rel.models:
rel_models = rel.models
for rel_model in rel_models:
if rel_model in models or rel_model in included:
continue
else:
included.append(rel_model)
for idx, val in enumerate(included):
included[idx] = _to_rest(val)
return included
|
[
"def",
"_to_rest_includes",
"(",
"models",
",",
"includes",
")",
":",
"included",
"=",
"[",
"]",
"includes",
"=",
"includes",
"or",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"models",
",",
"list",
")",
":",
"models",
"=",
"[",
"models",
"]",
"for",
"include",
"in",
"includes",
":",
"for",
"model",
"in",
"models",
":",
"rel",
"=",
"getattr",
"(",
"model",
",",
"include",
")",
"if",
"hasattr",
"(",
"rel",
",",
"'model'",
")",
"and",
"rel",
".",
"model",
":",
"rel_models",
"=",
"[",
"rel",
".",
"model",
"]",
"elif",
"hasattr",
"(",
"rel",
",",
"'models'",
")",
"and",
"rel",
".",
"models",
":",
"rel_models",
"=",
"rel",
".",
"models",
"for",
"rel_model",
"in",
"rel_models",
":",
"if",
"rel_model",
"in",
"models",
"or",
"rel_model",
"in",
"included",
":",
"continue",
"else",
":",
"included",
".",
"append",
"(",
"rel_model",
")",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"included",
")",
":",
"included",
"[",
"idx",
"]",
"=",
"_to_rest",
"(",
"val",
")",
"return",
"included"
] |
Fetch the models to be included
The includes should follow a few basic rules:
* the include MUST not already be an array member
of the included array (no dupes)
* the include MUST not be the same as the primary
data if the primary data is a single resource
object (no dupes)
* the include MUST not be an array member of the
primary data if the primary data an array of
resource objects (no dupes)
Basically, each included array member should be the only
instance of that resource object in the entire restified
data.
|
[
"Fetch",
"the",
"models",
"to",
"be",
"included"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L199-L244
|
245,131
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_to_rest_rels
|
def _to_rest_rels(model, props):
""" Move the relationships to appropriate location in the props
All to_ones should be in a to_one key while all to_manys
should be in a to_many key.
"""
props['to_many'] = {}
props['to_one'] = {}
for key in model.to_one:
try:
props['to_one'][key] = props.pop(key)
except KeyError:
continue
for key in model.to_many:
try:
props['to_many'][key] = props.pop(key)
except KeyError:
continue
|
python
|
def _to_rest_rels(model, props):
""" Move the relationships to appropriate location in the props
All to_ones should be in a to_one key while all to_manys
should be in a to_many key.
"""
props['to_many'] = {}
props['to_one'] = {}
for key in model.to_one:
try:
props['to_one'][key] = props.pop(key)
except KeyError:
continue
for key in model.to_many:
try:
props['to_many'][key] = props.pop(key)
except KeyError:
continue
|
[
"def",
"_to_rest_rels",
"(",
"model",
",",
"props",
")",
":",
"props",
"[",
"'to_many'",
"]",
"=",
"{",
"}",
"props",
"[",
"'to_one'",
"]",
"=",
"{",
"}",
"for",
"key",
"in",
"model",
".",
"to_one",
":",
"try",
":",
"props",
"[",
"'to_one'",
"]",
"[",
"key",
"]",
"=",
"props",
".",
"pop",
"(",
"key",
")",
"except",
"KeyError",
":",
"continue",
"for",
"key",
"in",
"model",
".",
"to_many",
":",
"try",
":",
"props",
"[",
"'to_many'",
"]",
"[",
"key",
"]",
"=",
"props",
".",
"pop",
"(",
"key",
")",
"except",
"KeyError",
":",
"continue"
] |
Move the relationships to appropriate location in the props
All to_ones should be in a to_one key while all to_manys
should be in a to_many key.
|
[
"Move",
"the",
"relationships",
"to",
"appropriate",
"location",
"in",
"the",
"props"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L247-L267
|
245,132
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
_to_rest
|
def _to_rest(model, includes=None):
""" Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are implicitly added as well & automatically loaded.
Then normalize the includes, hide private fields, & munge
the relationships into a format the serializers are
expecting.
"""
includes = includes or []
sparse = goldman.sess.req.fields.get(model.rtype, [])
if sparse:
sparse += [model.rid_field, model.rtype_field]
sparse += includes
props = model.to_primitive(
load_rels=includes,
sparse_fields=sparse,
)
props['rid'] = props.pop(model.rid_field)
props['rtype'] = props.pop(model.rtype_field)
_to_rest_hide(model, props)
_to_rest_rels(model, props)
return props
|
python
|
def _to_rest(model, includes=None):
""" Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are implicitly added as well & automatically loaded.
Then normalize the includes, hide private fields, & munge
the relationships into a format the serializers are
expecting.
"""
includes = includes or []
sparse = goldman.sess.req.fields.get(model.rtype, [])
if sparse:
sparse += [model.rid_field, model.rtype_field]
sparse += includes
props = model.to_primitive(
load_rels=includes,
sparse_fields=sparse,
)
props['rid'] = props.pop(model.rid_field)
props['rtype'] = props.pop(model.rtype_field)
_to_rest_hide(model, props)
_to_rest_rels(model, props)
return props
|
[
"def",
"_to_rest",
"(",
"model",
",",
"includes",
"=",
"None",
")",
":",
"includes",
"=",
"includes",
"or",
"[",
"]",
"sparse",
"=",
"goldman",
".",
"sess",
".",
"req",
".",
"fields",
".",
"get",
"(",
"model",
".",
"rtype",
",",
"[",
"]",
")",
"if",
"sparse",
":",
"sparse",
"+=",
"[",
"model",
".",
"rid_field",
",",
"model",
".",
"rtype_field",
"]",
"sparse",
"+=",
"includes",
"props",
"=",
"model",
".",
"to_primitive",
"(",
"load_rels",
"=",
"includes",
",",
"sparse_fields",
"=",
"sparse",
",",
")",
"props",
"[",
"'rid'",
"]",
"=",
"props",
".",
"pop",
"(",
"model",
".",
"rid_field",
")",
"props",
"[",
"'rtype'",
"]",
"=",
"props",
".",
"pop",
"(",
"model",
".",
"rtype_field",
")",
"_to_rest_hide",
"(",
"model",
",",
"props",
")",
"_to_rest_rels",
"(",
"model",
",",
"props",
")",
"return",
"props"
] |
Convert the model into a dict for serialization
Notify schematics of the sparse fields requested while
also forcing the resource id & resource type fields to always
be present no matter the request. Additionally, any includes
are implicitly added as well & automatically loaded.
Then normalize the includes, hide private fields, & munge
the relationships into a format the serializers are
expecting.
|
[
"Convert",
"the",
"model",
"into",
"a",
"dict",
"for",
"serialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L270-L301
|
245,133
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
to_rest_model
|
def to_rest_model(model, includes=None):
""" Convert the single model into a dict for serialization
:return: dict
"""
props = {}
props['data'] = _to_rest(model, includes=includes)
props['included'] = _to_rest_includes(model, includes=includes)
return props
|
python
|
def to_rest_model(model, includes=None):
""" Convert the single model into a dict for serialization
:return: dict
"""
props = {}
props['data'] = _to_rest(model, includes=includes)
props['included'] = _to_rest_includes(model, includes=includes)
return props
|
[
"def",
"to_rest_model",
"(",
"model",
",",
"includes",
"=",
"None",
")",
":",
"props",
"=",
"{",
"}",
"props",
"[",
"'data'",
"]",
"=",
"_to_rest",
"(",
"model",
",",
"includes",
"=",
"includes",
")",
"props",
"[",
"'included'",
"]",
"=",
"_to_rest_includes",
"(",
"model",
",",
"includes",
"=",
"includes",
")",
"return",
"props"
] |
Convert the single model into a dict for serialization
:return: dict
|
[
"Convert",
"the",
"single",
"model",
"into",
"a",
"dict",
"for",
"serialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L304-L314
|
245,134
|
sassoo/goldman
|
goldman/utils/responder_helpers.py
|
to_rest_models
|
def to_rest_models(models, includes=None):
""" Convert the models into a dict for serialization
models should be an array of single model objects that
will each be serialized.
:return: dict
"""
props = {}
props['data'] = []
for model in models:
props['data'].append(_to_rest(model, includes=includes))
props['included'] = _to_rest_includes(models, includes=includes)
return props
|
python
|
def to_rest_models(models, includes=None):
""" Convert the models into a dict for serialization
models should be an array of single model objects that
will each be serialized.
:return: dict
"""
props = {}
props['data'] = []
for model in models:
props['data'].append(_to_rest(model, includes=includes))
props['included'] = _to_rest_includes(models, includes=includes)
return props
|
[
"def",
"to_rest_models",
"(",
"models",
",",
"includes",
"=",
"None",
")",
":",
"props",
"=",
"{",
"}",
"props",
"[",
"'data'",
"]",
"=",
"[",
"]",
"for",
"model",
"in",
"models",
":",
"props",
"[",
"'data'",
"]",
".",
"append",
"(",
"_to_rest",
"(",
"model",
",",
"includes",
"=",
"includes",
")",
")",
"props",
"[",
"'included'",
"]",
"=",
"_to_rest_includes",
"(",
"models",
",",
"includes",
"=",
"includes",
")",
"return",
"props"
] |
Convert the models into a dict for serialization
models should be an array of single model objects that
will each be serialized.
:return: dict
|
[
"Convert",
"the",
"models",
"into",
"a",
"dict",
"for",
"serialization"
] |
b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2
|
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L317-L334
|
245,135
|
mbodenhamer/syn
|
syn/tree/b/node.py
|
Node.collect_by_type
|
def collect_by_type(self, typ):
'''A more efficient way to collect nodes of a specified type than
collect_nodes.
'''
nodes = []
if isinstance(self, typ):
nodes.append(self)
for c in self:
nodes.extend(c.collect_by_type(typ))
return nodes
|
python
|
def collect_by_type(self, typ):
'''A more efficient way to collect nodes of a specified type than
collect_nodes.
'''
nodes = []
if isinstance(self, typ):
nodes.append(self)
for c in self:
nodes.extend(c.collect_by_type(typ))
return nodes
|
[
"def",
"collect_by_type",
"(",
"self",
",",
"typ",
")",
":",
"nodes",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
",",
"typ",
")",
":",
"nodes",
".",
"append",
"(",
"self",
")",
"for",
"c",
"in",
"self",
":",
"nodes",
".",
"extend",
"(",
"c",
".",
"collect_by_type",
"(",
"typ",
")",
")",
"return",
"nodes"
] |
A more efficient way to collect nodes of a specified type than
collect_nodes.
|
[
"A",
"more",
"efficient",
"way",
"to",
"collect",
"nodes",
"of",
"a",
"specified",
"type",
"than",
"collect_nodes",
"."
] |
aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258
|
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/tree/b/node.py#L170-L179
|
245,136
|
xtream1101/web-wrapper
|
web_wrapper/driver_selenium_chrome.py
|
DriverSeleniumChrome.set_proxy
|
def set_proxy(self, proxy, update=True):
"""
Set proxy for chrome session
"""
update_web_driver = False
if self.current_proxy != proxy:
# Did we change proxies?
update_web_driver = True
self.current_proxy = proxy
if proxy is None:
# TODO: Need to be able to remove a proxy if one is set
pass
else:
proxy_parts = cutil.get_proxy_parts(proxy)
if proxy_parts.get('user') is not None:
# Proxy has auth, create extension to add to driver
self.opts.add_extension(self._proxy_extension(proxy_parts))
else:
# Use the full proxy address passed in
self.opts.add_argument('--proxy-server={}'.format(proxy))
# Recreate webdriver with new proxy settings
if update_web_driver is True:
self._update()
|
python
|
def set_proxy(self, proxy, update=True):
"""
Set proxy for chrome session
"""
update_web_driver = False
if self.current_proxy != proxy:
# Did we change proxies?
update_web_driver = True
self.current_proxy = proxy
if proxy is None:
# TODO: Need to be able to remove a proxy if one is set
pass
else:
proxy_parts = cutil.get_proxy_parts(proxy)
if proxy_parts.get('user') is not None:
# Proxy has auth, create extension to add to driver
self.opts.add_extension(self._proxy_extension(proxy_parts))
else:
# Use the full proxy address passed in
self.opts.add_argument('--proxy-server={}'.format(proxy))
# Recreate webdriver with new proxy settings
if update_web_driver is True:
self._update()
|
[
"def",
"set_proxy",
"(",
"self",
",",
"proxy",
",",
"update",
"=",
"True",
")",
":",
"update_web_driver",
"=",
"False",
"if",
"self",
".",
"current_proxy",
"!=",
"proxy",
":",
"# Did we change proxies?",
"update_web_driver",
"=",
"True",
"self",
".",
"current_proxy",
"=",
"proxy",
"if",
"proxy",
"is",
"None",
":",
"# TODO: Need to be able to remove a proxy if one is set",
"pass",
"else",
":",
"proxy_parts",
"=",
"cutil",
".",
"get_proxy_parts",
"(",
"proxy",
")",
"if",
"proxy_parts",
".",
"get",
"(",
"'user'",
")",
"is",
"not",
"None",
":",
"# Proxy has auth, create extension to add to driver",
"self",
".",
"opts",
".",
"add_extension",
"(",
"self",
".",
"_proxy_extension",
"(",
"proxy_parts",
")",
")",
"else",
":",
"# Use the full proxy address passed in",
"self",
".",
"opts",
".",
"add_argument",
"(",
"'--proxy-server={}'",
".",
"format",
"(",
"proxy",
")",
")",
"# Recreate webdriver with new proxy settings",
"if",
"update_web_driver",
"is",
"True",
":",
"self",
".",
"_update",
"(",
")"
] |
Set proxy for chrome session
|
[
"Set",
"proxy",
"for",
"chrome",
"session"
] |
2bfc63caa7d316564088951f01a490db493ea240
|
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L46-L71
|
245,137
|
xtream1101/web-wrapper
|
web_wrapper/driver_selenium_chrome.py
|
DriverSeleniumChrome._header_extension
|
def _header_extension(self, remove_headers=[], add_or_modify_headers={}):
"""Create modheaders extension
Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/
kwargs:
remove_headers (list): headers name to remove
add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"}
return str -> plugin path
"""
import string
import zipfile
plugin_file = 'custom_headers_plugin.zip'
if remove_headers is None:
remove_headers = []
if add_or_modify_headers is None:
add_or_modify_headers = {}
if isinstance(remove_headers, list) is False:
logger.error("remove_headers must be a list")
return None
if isinstance(add_or_modify_headers, dict) is False:
logger.error("add_or_modify_headers must be dict")
return None
# only keeping the unique headers key in remove_headers list
remove_headers = list(set(remove_headers))
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome HeaderModV",
"permissions": [
"webRequest",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template("""
function callbackFn(details) {
var remove_headers = ${remove_headers};
var add_or_modify_headers = ${add_or_modify_headers};
function inarray(arr, obj) {
return (arr.indexOf(obj) != -1);
}
// remove headers
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (inarray(remove_headers, details.requestHeaders[i].name)) {
details.requestHeaders.splice(i, 1);
var index = remove_headers.indexOf(5);
remove_headers.splice(index, 1);
}
if (!remove_headers.length) break;
}
// modify headers
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (add_or_modify_headers.hasOwnProperty(details.requestHeaders[i].name)) {
details.requestHeaders[i].value = add_or_modify_headers[details.requestHeaders[i].name];
delete add_or_modify_headers[details.requestHeaders[i].name];
}
}
// add modify
for (var prop in add_or_modify_headers) {
details.requestHeaders.push(
{name: prop, value: add_or_modify_headers[prop]}
);
}
return {requestHeaders: details.requestHeaders};
}
chrome.webRequest.onBeforeSendHeaders.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking', 'requestHeaders']
);
"""
).substitute(remove_headers=remove_headers,
add_or_modify_headers=add_or_modify_headers,
)
with zipfile.ZipFile(plugin_file, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_file
|
python
|
def _header_extension(self, remove_headers=[], add_or_modify_headers={}):
"""Create modheaders extension
Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/
kwargs:
remove_headers (list): headers name to remove
add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"}
return str -> plugin path
"""
import string
import zipfile
plugin_file = 'custom_headers_plugin.zip'
if remove_headers is None:
remove_headers = []
if add_or_modify_headers is None:
add_or_modify_headers = {}
if isinstance(remove_headers, list) is False:
logger.error("remove_headers must be a list")
return None
if isinstance(add_or_modify_headers, dict) is False:
logger.error("add_or_modify_headers must be dict")
return None
# only keeping the unique headers key in remove_headers list
remove_headers = list(set(remove_headers))
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome HeaderModV",
"permissions": [
"webRequest",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template("""
function callbackFn(details) {
var remove_headers = ${remove_headers};
var add_or_modify_headers = ${add_or_modify_headers};
function inarray(arr, obj) {
return (arr.indexOf(obj) != -1);
}
// remove headers
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (inarray(remove_headers, details.requestHeaders[i].name)) {
details.requestHeaders.splice(i, 1);
var index = remove_headers.indexOf(5);
remove_headers.splice(index, 1);
}
if (!remove_headers.length) break;
}
// modify headers
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (add_or_modify_headers.hasOwnProperty(details.requestHeaders[i].name)) {
details.requestHeaders[i].value = add_or_modify_headers[details.requestHeaders[i].name];
delete add_or_modify_headers[details.requestHeaders[i].name];
}
}
// add modify
for (var prop in add_or_modify_headers) {
details.requestHeaders.push(
{name: prop, value: add_or_modify_headers[prop]}
);
}
return {requestHeaders: details.requestHeaders};
}
chrome.webRequest.onBeforeSendHeaders.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking', 'requestHeaders']
);
"""
).substitute(remove_headers=remove_headers,
add_or_modify_headers=add_or_modify_headers,
)
with zipfile.ZipFile(plugin_file, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_file
|
[
"def",
"_header_extension",
"(",
"self",
",",
"remove_headers",
"=",
"[",
"]",
",",
"add_or_modify_headers",
"=",
"{",
"}",
")",
":",
"import",
"string",
"import",
"zipfile",
"plugin_file",
"=",
"'custom_headers_plugin.zip'",
"if",
"remove_headers",
"is",
"None",
":",
"remove_headers",
"=",
"[",
"]",
"if",
"add_or_modify_headers",
"is",
"None",
":",
"add_or_modify_headers",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"remove_headers",
",",
"list",
")",
"is",
"False",
":",
"logger",
".",
"error",
"(",
"\"remove_headers must be a list\"",
")",
"return",
"None",
"if",
"isinstance",
"(",
"add_or_modify_headers",
",",
"dict",
")",
"is",
"False",
":",
"logger",
".",
"error",
"(",
"\"add_or_modify_headers must be dict\"",
")",
"return",
"None",
"# only keeping the unique headers key in remove_headers list",
"remove_headers",
"=",
"list",
"(",
"set",
"(",
"remove_headers",
")",
")",
"manifest_json",
"=",
"\"\"\"\n {\n \"version\": \"1.0.0\",\n \"manifest_version\": 2,\n \"name\": \"Chrome HeaderModV\",\n \"permissions\": [\n \"webRequest\",\n \"tabs\",\n \"unlimitedStorage\",\n \"storage\",\n \"<all_urls>\",\n \"webRequestBlocking\"\n ],\n \"background\": {\n \"scripts\": [\"background.js\"]\n },\n \"minimum_chrome_version\":\"22.0.0\"\n }\n \"\"\"",
"background_js",
"=",
"string",
".",
"Template",
"(",
"\"\"\"\n function callbackFn(details) {\n var remove_headers = ${remove_headers};\n var add_or_modify_headers = ${add_or_modify_headers};\n\n function inarray(arr, obj) {\n return (arr.indexOf(obj) != -1);\n }\n\n // remove headers\n for (var i = 0; i < details.requestHeaders.length; ++i) {\n if (inarray(remove_headers, details.requestHeaders[i].name)) {\n details.requestHeaders.splice(i, 1);\n var index = remove_headers.indexOf(5);\n remove_headers.splice(index, 1);\n }\n if (!remove_headers.length) break;\n }\n\n // modify headers\n for (var i = 0; i < details.requestHeaders.length; ++i) {\n if (add_or_modify_headers.hasOwnProperty(details.requestHeaders[i].name)) {\n details.requestHeaders[i].value = add_or_modify_headers[details.requestHeaders[i].name];\n delete add_or_modify_headers[details.requestHeaders[i].name];\n }\n }\n\n // add modify\n for (var prop in add_or_modify_headers) {\n details.requestHeaders.push(\n {name: prop, value: add_or_modify_headers[prop]}\n );\n }\n\n return {requestHeaders: details.requestHeaders};\n }\n\n chrome.webRequest.onBeforeSendHeaders.addListener(\n callbackFn,\n {urls: [\"<all_urls>\"]},\n ['blocking', 'requestHeaders']\n );\n \"\"\"",
")",
".",
"substitute",
"(",
"remove_headers",
"=",
"remove_headers",
",",
"add_or_modify_headers",
"=",
"add_or_modify_headers",
",",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"plugin_file",
",",
"'w'",
")",
"as",
"zp",
":",
"zp",
".",
"writestr",
"(",
"\"manifest.json\"",
",",
"manifest_json",
")",
"zp",
".",
"writestr",
"(",
"\"background.js\"",
",",
"background_js",
")",
"return",
"plugin_file"
] |
Create modheaders extension
Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/
kwargs:
remove_headers (list): headers name to remove
add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"}
return str -> plugin path
|
[
"Create",
"modheaders",
"extension"
] |
2bfc63caa7d316564088951f01a490db493ea240
|
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L175-L279
|
245,138
|
kwarunek/file2py
|
file2py/conv.py
|
Converter.set_template
|
def set_template(self, template):
""" Sets template to be used when generating output
:param template TEmplate instance
:type instance of BasicTemplate
"""
if isinstance(template, templates.BasicTemplate):
self.template = template
else:
raise TypeError('converter#set_template:'
'Template must inherit from BasicTemplate')
|
python
|
def set_template(self, template):
""" Sets template to be used when generating output
:param template TEmplate instance
:type instance of BasicTemplate
"""
if isinstance(template, templates.BasicTemplate):
self.template = template
else:
raise TypeError('converter#set_template:'
'Template must inherit from BasicTemplate')
|
[
"def",
"set_template",
"(",
"self",
",",
"template",
")",
":",
"if",
"isinstance",
"(",
"template",
",",
"templates",
".",
"BasicTemplate",
")",
":",
"self",
".",
"template",
"=",
"template",
"else",
":",
"raise",
"TypeError",
"(",
"'converter#set_template:'",
"'Template must inherit from BasicTemplate'",
")"
] |
Sets template to be used when generating output
:param template TEmplate instance
:type instance of BasicTemplate
|
[
"Sets",
"template",
"to",
"be",
"used",
"when",
"generating",
"output"
] |
f94730b6d4f40ea22b5f048126f60fa14c0e2bf0
|
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L36-L46
|
245,139
|
kwarunek/file2py
|
file2py/conv.py
|
Converter.save
|
def save(self, filename=None):
""" Generates output and saves to given file
:param filename File name
:type str or unicode
"""
if filename is None:
raise IOError('Converter#save: Undefined filename')
cnt = self.output()
with (open(filename, 'wb+')) as f:
f.write(cnt.encode('utf-8'))
|
python
|
def save(self, filename=None):
""" Generates output and saves to given file
:param filename File name
:type str or unicode
"""
if filename is None:
raise IOError('Converter#save: Undefined filename')
cnt = self.output()
with (open(filename, 'wb+')) as f:
f.write(cnt.encode('utf-8'))
|
[
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"raise",
"IOError",
"(",
"'Converter#save: Undefined filename'",
")",
"cnt",
"=",
"self",
".",
"output",
"(",
")",
"with",
"(",
"open",
"(",
"filename",
",",
"'wb+'",
")",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"cnt",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] |
Generates output and saves to given file
:param filename File name
:type str or unicode
|
[
"Generates",
"output",
"and",
"saves",
"to",
"given",
"file"
] |
f94730b6d4f40ea22b5f048126f60fa14c0e2bf0
|
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L48-L58
|
245,140
|
kwarunek/file2py
|
file2py/conv.py
|
Converter.add_file
|
def add_file(self, filename):
""" Read and adds given file's content to data array
that will be used to generate output
:param filename File name to add
:type str or unicode
"""
with (open(filename, 'rb')) as f:
data = f.read()
# below won't handle the same name files
# in different paths
fname = os.path.basename(filename)
self.files[fname] = base64.b64encode(data)
|
python
|
def add_file(self, filename):
""" Read and adds given file's content to data array
that will be used to generate output
:param filename File name to add
:type str or unicode
"""
with (open(filename, 'rb')) as f:
data = f.read()
# below won't handle the same name files
# in different paths
fname = os.path.basename(filename)
self.files[fname] = base64.b64encode(data)
|
[
"def",
"add_file",
"(",
"self",
",",
"filename",
")",
":",
"with",
"(",
"open",
"(",
"filename",
",",
"'rb'",
")",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"# below won't handle the same name files",
"# in different paths",
"fname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"self",
".",
"files",
"[",
"fname",
"]",
"=",
"base64",
".",
"b64encode",
"(",
"data",
")"
] |
Read and adds given file's content to data array
that will be used to generate output
:param filename File name to add
:type str or unicode
|
[
"Read",
"and",
"adds",
"given",
"file",
"s",
"content",
"to",
"data",
"array",
"that",
"will",
"be",
"used",
"to",
"generate",
"output"
] |
f94730b6d4f40ea22b5f048126f60fa14c0e2bf0
|
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L60-L72
|
245,141
|
kwarunek/file2py
|
file2py/conv.py
|
Converter.output
|
def output(self):
""" Generates output from data array
:returns Pythoned file
:rtype str or unicode
"""
if len(self.files) < 1:
raise Exception('Converter#output: No files to convert')
return self.template.render(self.files)
|
python
|
def output(self):
""" Generates output from data array
:returns Pythoned file
:rtype str or unicode
"""
if len(self.files) < 1:
raise Exception('Converter#output: No files to convert')
return self.template.render(self.files)
|
[
"def",
"output",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"files",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'Converter#output: No files to convert'",
")",
"return",
"self",
".",
"template",
".",
"render",
"(",
"self",
".",
"files",
")"
] |
Generates output from data array
:returns Pythoned file
:rtype str or unicode
|
[
"Generates",
"output",
"from",
"data",
"array"
] |
f94730b6d4f40ea22b5f048126f60fa14c0e2bf0
|
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L82-L90
|
245,142
|
PyMLGame/pymlgame
|
game_example.py
|
Game.update
|
def update(self):
"""
Update the screens contents in every loop.
"""
# this is not really neccesary because the surface is black after initializing
self.corners.fill(BLACK)
self.corners.draw_dot((0, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, self.screen.height - 1),
self.colors[0])
self.corners.draw_dot((0, self.screen.height - 1), self.colors[0])
self.lines.fill(BLACK)
self.lines.draw_line((1, 0), (self.lines.width - 1, 0), self.colors[1])
self.lines.draw_line((0, 1), (0, self.lines.height - 1), self.colors[3])
self.lines.draw_line((0, 0), (self.lines.width - 1,
self.lines.height - 1), self.colors[2])
self.rects.fill(BLACK)
self.rects.draw_rect((0, 0), (int(self.rects.width / 2) - 1,
self.rects.height),
self.colors[2], self.colors[3])
self.rects.draw_rect((int(self.rects.width / 2) + 1, 0),
(int(self.rects.width / 2) - 1,
self.rects.height),
self.colors[3], self.colors[2])
self.circle.fill(BLACK)
radius = int(min(self.circle.width, self.circle.height) / 2) - 1
self.circle.draw_circle((int(self.circle.width / 2) - 1,
int(self.circle.height / 2) - 1), radius,
self.colors[4], self.colors[5])
self.filled.fill(self.colors[6])
|
python
|
def update(self):
"""
Update the screens contents in every loop.
"""
# this is not really neccesary because the surface is black after initializing
self.corners.fill(BLACK)
self.corners.draw_dot((0, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, 0), self.colors[0])
self.corners.draw_dot((self.screen.width - 1, self.screen.height - 1),
self.colors[0])
self.corners.draw_dot((0, self.screen.height - 1), self.colors[0])
self.lines.fill(BLACK)
self.lines.draw_line((1, 0), (self.lines.width - 1, 0), self.colors[1])
self.lines.draw_line((0, 1), (0, self.lines.height - 1), self.colors[3])
self.lines.draw_line((0, 0), (self.lines.width - 1,
self.lines.height - 1), self.colors[2])
self.rects.fill(BLACK)
self.rects.draw_rect((0, 0), (int(self.rects.width / 2) - 1,
self.rects.height),
self.colors[2], self.colors[3])
self.rects.draw_rect((int(self.rects.width / 2) + 1, 0),
(int(self.rects.width / 2) - 1,
self.rects.height),
self.colors[3], self.colors[2])
self.circle.fill(BLACK)
radius = int(min(self.circle.width, self.circle.height) / 2) - 1
self.circle.draw_circle((int(self.circle.width / 2) - 1,
int(self.circle.height / 2) - 1), radius,
self.colors[4], self.colors[5])
self.filled.fill(self.colors[6])
|
[
"def",
"update",
"(",
"self",
")",
":",
"# this is not really neccesary because the surface is black after initializing",
"self",
".",
"corners",
".",
"fill",
"(",
"BLACK",
")",
"self",
".",
"corners",
".",
"draw_dot",
"(",
"(",
"0",
",",
"0",
")",
",",
"self",
".",
"colors",
"[",
"0",
"]",
")",
"self",
".",
"corners",
".",
"draw_dot",
"(",
"(",
"self",
".",
"screen",
".",
"width",
"-",
"1",
",",
"0",
")",
",",
"self",
".",
"colors",
"[",
"0",
"]",
")",
"self",
".",
"corners",
".",
"draw_dot",
"(",
"(",
"self",
".",
"screen",
".",
"width",
"-",
"1",
",",
"self",
".",
"screen",
".",
"height",
"-",
"1",
")",
",",
"self",
".",
"colors",
"[",
"0",
"]",
")",
"self",
".",
"corners",
".",
"draw_dot",
"(",
"(",
"0",
",",
"self",
".",
"screen",
".",
"height",
"-",
"1",
")",
",",
"self",
".",
"colors",
"[",
"0",
"]",
")",
"self",
".",
"lines",
".",
"fill",
"(",
"BLACK",
")",
"self",
".",
"lines",
".",
"draw_line",
"(",
"(",
"1",
",",
"0",
")",
",",
"(",
"self",
".",
"lines",
".",
"width",
"-",
"1",
",",
"0",
")",
",",
"self",
".",
"colors",
"[",
"1",
"]",
")",
"self",
".",
"lines",
".",
"draw_line",
"(",
"(",
"0",
",",
"1",
")",
",",
"(",
"0",
",",
"self",
".",
"lines",
".",
"height",
"-",
"1",
")",
",",
"self",
".",
"colors",
"[",
"3",
"]",
")",
"self",
".",
"lines",
".",
"draw_line",
"(",
"(",
"0",
",",
"0",
")",
",",
"(",
"self",
".",
"lines",
".",
"width",
"-",
"1",
",",
"self",
".",
"lines",
".",
"height",
"-",
"1",
")",
",",
"self",
".",
"colors",
"[",
"2",
"]",
")",
"self",
".",
"rects",
".",
"fill",
"(",
"BLACK",
")",
"self",
".",
"rects",
".",
"draw_rect",
"(",
"(",
"0",
",",
"0",
")",
",",
"(",
"int",
"(",
"self",
".",
"rects",
".",
"width",
"/",
"2",
")",
"-",
"1",
",",
"self",
".",
"rects",
".",
"height",
")",
",",
"self",
".",
"colors",
"[",
"2",
"]",
",",
"self",
".",
"colors",
"[",
"3",
"]",
")",
"self",
".",
"rects",
".",
"draw_rect",
"(",
"(",
"int",
"(",
"self",
".",
"rects",
".",
"width",
"/",
"2",
")",
"+",
"1",
",",
"0",
")",
",",
"(",
"int",
"(",
"self",
".",
"rects",
".",
"width",
"/",
"2",
")",
"-",
"1",
",",
"self",
".",
"rects",
".",
"height",
")",
",",
"self",
".",
"colors",
"[",
"3",
"]",
",",
"self",
".",
"colors",
"[",
"2",
"]",
")",
"self",
".",
"circle",
".",
"fill",
"(",
"BLACK",
")",
"radius",
"=",
"int",
"(",
"min",
"(",
"self",
".",
"circle",
".",
"width",
",",
"self",
".",
"circle",
".",
"height",
")",
"/",
"2",
")",
"-",
"1",
"self",
".",
"circle",
".",
"draw_circle",
"(",
"(",
"int",
"(",
"self",
".",
"circle",
".",
"width",
"/",
"2",
")",
"-",
"1",
",",
"int",
"(",
"self",
".",
"circle",
".",
"height",
"/",
"2",
")",
"-",
"1",
")",
",",
"radius",
",",
"self",
".",
"colors",
"[",
"4",
"]",
",",
"self",
".",
"colors",
"[",
"5",
"]",
")",
"self",
".",
"filled",
".",
"fill",
"(",
"self",
".",
"colors",
"[",
"6",
"]",
")"
] |
Update the screens contents in every loop.
|
[
"Update",
"the",
"screens",
"contents",
"in",
"every",
"loop",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L63-L96
|
245,143
|
PyMLGame/pymlgame
|
game_example.py
|
Game.render
|
def render(self):
"""
Send the current screen content to Mate Light.
"""
self.screen.reset()
self.screen.blit(self.corners)
self.screen.blit(self.lines, (1, 1))
self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1))
self.screen.blit(self.circle, (0, int(self.screen.height / 2) + 1))
self.screen.blit(self.filled, (int(self.screen.width / 2) + 1,
int(self.screen.height / 2) + 1))
self.screen.update()
self.clock.tick()
|
python
|
def render(self):
"""
Send the current screen content to Mate Light.
"""
self.screen.reset()
self.screen.blit(self.corners)
self.screen.blit(self.lines, (1, 1))
self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1))
self.screen.blit(self.circle, (0, int(self.screen.height / 2) + 1))
self.screen.blit(self.filled, (int(self.screen.width / 2) + 1,
int(self.screen.height / 2) + 1))
self.screen.update()
self.clock.tick()
|
[
"def",
"render",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"reset",
"(",
")",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"corners",
")",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"lines",
",",
"(",
"1",
",",
"1",
")",
")",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"rects",
",",
"(",
"int",
"(",
"self",
".",
"screen",
".",
"width",
"/",
"2",
")",
"+",
"1",
",",
"1",
")",
")",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"circle",
",",
"(",
"0",
",",
"int",
"(",
"self",
".",
"screen",
".",
"height",
"/",
"2",
")",
"+",
"1",
")",
")",
"self",
".",
"screen",
".",
"blit",
"(",
"self",
".",
"filled",
",",
"(",
"int",
"(",
"self",
".",
"screen",
".",
"width",
"/",
"2",
")",
"+",
"1",
",",
"int",
"(",
"self",
".",
"screen",
".",
"height",
"/",
"2",
")",
"+",
"1",
")",
")",
"self",
".",
"screen",
".",
"update",
"(",
")",
"self",
".",
"clock",
".",
"tick",
"(",
")"
] |
Send the current screen content to Mate Light.
|
[
"Send",
"the",
"current",
"screen",
"content",
"to",
"Mate",
"Light",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L98-L111
|
245,144
|
PyMLGame/pymlgame
|
game_example.py
|
Game.handle_events
|
def handle_events(self):
"""
Loop through all events.
"""
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
#print(datetime.now(), '### new player connected with uid', event.uid)
self.players[event.uid] = {'name': 'alien_{}'.format(event.uid), 'score': 0}
elif event.type == E_DISCONNECT:
#print(datetime.now(), '### player with uid {} disconnected'.format(event.uid))
self.players.pop(event.uid)
elif event.type == E_KEYDOWN:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'pressed', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_KEYUP:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'released', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_PING:
#print(datetime.now(), '### ping from', self.players[event.uid]['name'])
pass
|
python
|
def handle_events(self):
"""
Loop through all events.
"""
for event in pymlgame.get_events():
if event.type == E_NEWCTLR:
#print(datetime.now(), '### new player connected with uid', event.uid)
self.players[event.uid] = {'name': 'alien_{}'.format(event.uid), 'score': 0}
elif event.type == E_DISCONNECT:
#print(datetime.now(), '### player with uid {} disconnected'.format(event.uid))
self.players.pop(event.uid)
elif event.type == E_KEYDOWN:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'pressed', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_KEYUP:
#print(datetime.now(), '###', self.players[event.uid]['name'], 'released', event.button)
self.colors.append(self.colors.pop(0))
elif event.type == E_PING:
#print(datetime.now(), '### ping from', self.players[event.uid]['name'])
pass
|
[
"def",
"handle_events",
"(",
"self",
")",
":",
"for",
"event",
"in",
"pymlgame",
".",
"get_events",
"(",
")",
":",
"if",
"event",
".",
"type",
"==",
"E_NEWCTLR",
":",
"#print(datetime.now(), '### new player connected with uid', event.uid)",
"self",
".",
"players",
"[",
"event",
".",
"uid",
"]",
"=",
"{",
"'name'",
":",
"'alien_{}'",
".",
"format",
"(",
"event",
".",
"uid",
")",
",",
"'score'",
":",
"0",
"}",
"elif",
"event",
".",
"type",
"==",
"E_DISCONNECT",
":",
"#print(datetime.now(), '### player with uid {} disconnected'.format(event.uid))",
"self",
".",
"players",
".",
"pop",
"(",
"event",
".",
"uid",
")",
"elif",
"event",
".",
"type",
"==",
"E_KEYDOWN",
":",
"#print(datetime.now(), '###', self.players[event.uid]['name'], 'pressed', event.button)",
"self",
".",
"colors",
".",
"append",
"(",
"self",
".",
"colors",
".",
"pop",
"(",
"0",
")",
")",
"elif",
"event",
".",
"type",
"==",
"E_KEYUP",
":",
"#print(datetime.now(), '###', self.players[event.uid]['name'], 'released', event.button)",
"self",
".",
"colors",
".",
"append",
"(",
"self",
".",
"colors",
".",
"pop",
"(",
"0",
")",
")",
"elif",
"event",
".",
"type",
"==",
"E_PING",
":",
"#print(datetime.now(), '### ping from', self.players[event.uid]['name'])",
"pass"
] |
Loop through all events.
|
[
"Loop",
"through",
"all",
"events",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L113-L132
|
245,145
|
PyMLGame/pymlgame
|
game_example.py
|
Game.gameloop
|
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass
|
python
|
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass
|
[
"def",
"gameloop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"self",
".",
"handle_events",
"(",
")",
"self",
".",
"update",
"(",
")",
"self",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] |
A game loop that circles through the methods.
|
[
"A",
"game",
"loop",
"that",
"circles",
"through",
"the",
"methods",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L134-L144
|
245,146
|
TC01/calcpkg
|
calcrepo/output.py
|
CalcpkgOutput.write
|
def write(self, string):
"""The write method for a CalcpkgOutput object- print the string"""
if ("" == string or '\n' == string or '\r' == string):
return
# Filter out any \r newlines.
string = string.replace("\r", "")
# if '\r\n' in string:
# string = util.replaceNewlines(string, '\r\n')
if self.printData:
print >> sys.__stdout__, string
if self.logData:
self.logWrite(string)
|
python
|
def write(self, string):
"""The write method for a CalcpkgOutput object- print the string"""
if ("" == string or '\n' == string or '\r' == string):
return
# Filter out any \r newlines.
string = string.replace("\r", "")
# if '\r\n' in string:
# string = util.replaceNewlines(string, '\r\n')
if self.printData:
print >> sys.__stdout__, string
if self.logData:
self.logWrite(string)
|
[
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"if",
"(",
"\"\"",
"==",
"string",
"or",
"'\\n'",
"==",
"string",
"or",
"'\\r'",
"==",
"string",
")",
":",
"return",
"# Filter out any \\r newlines.",
"string",
"=",
"string",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\"",
")",
"#\t\tif '\\r\\n' in string:",
"#\t\t\tstring = util.replaceNewlines(string, '\\r\\n')",
"if",
"self",
".",
"printData",
":",
"print",
">>",
"sys",
".",
"__stdout__",
",",
"string",
"if",
"self",
".",
"logData",
":",
"self",
".",
"logWrite",
"(",
"string",
")"
] |
The write method for a CalcpkgOutput object- print the string
|
[
"The",
"write",
"method",
"for",
"a",
"CalcpkgOutput",
"object",
"-",
"print",
"the",
"string"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L34-L47
|
245,147
|
TC01/calcpkg
|
calcrepo/output.py
|
CalcpkgOutput.logWrite
|
def logWrite(self, string):
"""Only write text to the log file, do not print"""
logFile = open(self.logFile, 'at')
logFile.write(string + '\n')
logFile.close()
|
python
|
def logWrite(self, string):
"""Only write text to the log file, do not print"""
logFile = open(self.logFile, 'at')
logFile.write(string + '\n')
logFile.close()
|
[
"def",
"logWrite",
"(",
"self",
",",
"string",
")",
":",
"logFile",
"=",
"open",
"(",
"self",
".",
"logFile",
",",
"'at'",
")",
"logFile",
".",
"write",
"(",
"string",
"+",
"'\\n'",
")",
"logFile",
".",
"close",
"(",
")"
] |
Only write text to the log file, do not print
|
[
"Only",
"write",
"text",
"to",
"the",
"log",
"file",
"do",
"not",
"print"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L49-L53
|
245,148
|
TC01/calcpkg
|
calcrepo/output.py
|
CalcpkgOutput.setupLogFile
|
def setupLogFile(self):
"""Set up the logging file for a new session- include date and some whitespace"""
self.logWrite("\n###############################################")
self.logWrite("calcpkg.py log from " + str(datetime.datetime.now()))
self.changeLogging(True)
|
python
|
def setupLogFile(self):
"""Set up the logging file for a new session- include date and some whitespace"""
self.logWrite("\n###############################################")
self.logWrite("calcpkg.py log from " + str(datetime.datetime.now()))
self.changeLogging(True)
|
[
"def",
"setupLogFile",
"(",
"self",
")",
":",
"self",
".",
"logWrite",
"(",
"\"\\n###############################################\"",
")",
"self",
".",
"logWrite",
"(",
"\"calcpkg.py log from \"",
"+",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"self",
".",
"changeLogging",
"(",
"True",
")"
] |
Set up the logging file for a new session- include date and some whitespace
|
[
"Set",
"up",
"the",
"logging",
"file",
"for",
"a",
"new",
"session",
"-",
"include",
"date",
"and",
"some",
"whitespace"
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L55-L59
|
245,149
|
TC01/calcpkg
|
calcrepo/output.py
|
CalcpkgOutput.getLoggingLocation
|
def getLoggingLocation(self):
"""Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go."""
if sys.platform == "win32":
modulePath = os.path.realpath(__file__)
modulePath = modulePath[:modulePath.rfind("/")]
return modulePath
else:
return "/tmp"
return ""
|
python
|
def getLoggingLocation(self):
"""Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go."""
if sys.platform == "win32":
modulePath = os.path.realpath(__file__)
modulePath = modulePath[:modulePath.rfind("/")]
return modulePath
else:
return "/tmp"
return ""
|
[
"def",
"getLoggingLocation",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"modulePath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
"modulePath",
"=",
"modulePath",
"[",
":",
"modulePath",
".",
"rfind",
"(",
"\"/\"",
")",
"]",
"return",
"modulePath",
"else",
":",
"return",
"\"/tmp\"",
"return",
"\"\""
] |
Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.
|
[
"Return",
"the",
"path",
"for",
"the",
"calcpkg",
".",
"log",
"file",
"-",
"at",
"the",
"moment",
"only",
"use",
"a",
"Linux",
"path",
"since",
"I",
"don",
"t",
"know",
"where",
"Windows",
"thinks",
"logs",
"should",
"go",
"."
] |
5168f606264620a090b42a64354331d208b00d5f
|
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L61-L69
|
245,150
|
narfman0/helga-markovify
|
helga_markovify/twitter.py
|
twitter_timeline
|
def twitter_timeline(screen_name, since_id=None):
""" Return relevant twitter timeline """
consumer_key = twitter_credential('consumer_key')
consumer_secret = twitter_credential('consumer_secret')
access_token = twitter_credential('access_token')
access_token_secret = twitter_credential('access_secret')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
return get_all_tweets(screen_name, api, since_id)
|
python
|
def twitter_timeline(screen_name, since_id=None):
""" Return relevant twitter timeline """
consumer_key = twitter_credential('consumer_key')
consumer_secret = twitter_credential('consumer_secret')
access_token = twitter_credential('access_token')
access_token_secret = twitter_credential('access_secret')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
return get_all_tweets(screen_name, api, since_id)
|
[
"def",
"twitter_timeline",
"(",
"screen_name",
",",
"since_id",
"=",
"None",
")",
":",
"consumer_key",
"=",
"twitter_credential",
"(",
"'consumer_key'",
")",
"consumer_secret",
"=",
"twitter_credential",
"(",
"'consumer_secret'",
")",
"access_token",
"=",
"twitter_credential",
"(",
"'access_token'",
")",
"access_token_secret",
"=",
"twitter_credential",
"(",
"'access_secret'",
")",
"auth",
"=",
"tweepy",
".",
"OAuthHandler",
"(",
"consumer_key",
",",
"consumer_secret",
")",
"auth",
".",
"set_access_token",
"(",
"access_token",
",",
"access_token_secret",
")",
"api",
"=",
"tweepy",
".",
"API",
"(",
"auth",
")",
"return",
"get_all_tweets",
"(",
"screen_name",
",",
"api",
",",
"since_id",
")"
] |
Return relevant twitter timeline
|
[
"Return",
"relevant",
"twitter",
"timeline"
] |
b5a82de070102e6da1fd3f5f81cad12d0a9185d8
|
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/twitter.py#L5-L14
|
245,151
|
narfman0/helga-markovify
|
helga_markovify/twitter.py
|
twitter_credential
|
def twitter_credential(name):
""" Grab twitter credential from settings """
credential_name = 'TWITTER_' + name.upper()
if hasattr(settings, credential_name):
return getattr(settings, credential_name)
else:
raise AttributeError('Missing twitter credential in settings: ' + credential_name)
|
python
|
def twitter_credential(name):
""" Grab twitter credential from settings """
credential_name = 'TWITTER_' + name.upper()
if hasattr(settings, credential_name):
return getattr(settings, credential_name)
else:
raise AttributeError('Missing twitter credential in settings: ' + credential_name)
|
[
"def",
"twitter_credential",
"(",
"name",
")",
":",
"credential_name",
"=",
"'TWITTER_'",
"+",
"name",
".",
"upper",
"(",
")",
"if",
"hasattr",
"(",
"settings",
",",
"credential_name",
")",
":",
"return",
"getattr",
"(",
"settings",
",",
"credential_name",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"'Missing twitter credential in settings: '",
"+",
"credential_name",
")"
] |
Grab twitter credential from settings
|
[
"Grab",
"twitter",
"credential",
"from",
"settings"
] |
b5a82de070102e6da1fd3f5f81cad12d0a9185d8
|
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/twitter.py#L36-L42
|
245,152
|
praekelt/panya
|
panya/utils/__init__.py
|
modify_class
|
def modify_class(original_class, modifier_class, override=True):
"""
Adds class methods from modifier_class to original_class.
If override is True existing methods in original_class are overriden by those provided by modifier_class.
"""
# get members to add
modifier_methods = inspect.getmembers(modifier_class, inspect.ismethod)
# set methods
for method_tuple in modifier_methods:
name = method_tuple[0]
method = method_tuple[1]
if isinstance(method, types.UnboundMethodType):
if hasattr(original_class, name) and not override:
return None
else:
setattr(original_class, name, method.im_func)
|
python
|
def modify_class(original_class, modifier_class, override=True):
"""
Adds class methods from modifier_class to original_class.
If override is True existing methods in original_class are overriden by those provided by modifier_class.
"""
# get members to add
modifier_methods = inspect.getmembers(modifier_class, inspect.ismethod)
# set methods
for method_tuple in modifier_methods:
name = method_tuple[0]
method = method_tuple[1]
if isinstance(method, types.UnboundMethodType):
if hasattr(original_class, name) and not override:
return None
else:
setattr(original_class, name, method.im_func)
|
[
"def",
"modify_class",
"(",
"original_class",
",",
"modifier_class",
",",
"override",
"=",
"True",
")",
":",
"# get members to add",
"modifier_methods",
"=",
"inspect",
".",
"getmembers",
"(",
"modifier_class",
",",
"inspect",
".",
"ismethod",
")",
"# set methods",
"for",
"method_tuple",
"in",
"modifier_methods",
":",
"name",
"=",
"method_tuple",
"[",
"0",
"]",
"method",
"=",
"method_tuple",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"method",
",",
"types",
".",
"UnboundMethodType",
")",
":",
"if",
"hasattr",
"(",
"original_class",
",",
"name",
")",
"and",
"not",
"override",
":",
"return",
"None",
"else",
":",
"setattr",
"(",
"original_class",
",",
"name",
",",
"method",
".",
"im_func",
")"
] |
Adds class methods from modifier_class to original_class.
If override is True existing methods in original_class are overriden by those provided by modifier_class.
|
[
"Adds",
"class",
"methods",
"from",
"modifier_class",
"to",
"original_class",
".",
"If",
"override",
"is",
"True",
"existing",
"methods",
"in",
"original_class",
"are",
"overriden",
"by",
"those",
"provided",
"by",
"modifier_class",
"."
] |
0fd621e15a7c11a2716a9554a2f820d6259818e5
|
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/utils/__init__.py#L29-L45
|
245,153
|
Aperture-py/aperture-lib
|
aperturelib/resize.py
|
resize_image
|
def resize_image(image, tuple_wh, preserve_aspect=True):
"""Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
image: An instance of a PIL Image.
tuple_wh: A tuple containing the (width, height) for resizing.
preserve_aspect: A boolean that determines whether or not the
resizing should preserve the image's aspect ratio.
Returns: A resized copy of the provided PIL image.
"""
if preserve_aspect:
img_cpy = image.copy()
img_cpy.thumbnail(tuple_wh)
return img_cpy
else:
return image.resize(tuple_wh)
|
python
|
def resize_image(image, tuple_wh, preserve_aspect=True):
"""Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
image: An instance of a PIL Image.
tuple_wh: A tuple containing the (width, height) for resizing.
preserve_aspect: A boolean that determines whether or not the
resizing should preserve the image's aspect ratio.
Returns: A resized copy of the provided PIL image.
"""
if preserve_aspect:
img_cpy = image.copy()
img_cpy.thumbnail(tuple_wh)
return img_cpy
else:
return image.resize(tuple_wh)
|
[
"def",
"resize_image",
"(",
"image",
",",
"tuple_wh",
",",
"preserve_aspect",
"=",
"True",
")",
":",
"if",
"preserve_aspect",
":",
"img_cpy",
"=",
"image",
".",
"copy",
"(",
")",
"img_cpy",
".",
"thumbnail",
"(",
"tuple_wh",
")",
"return",
"img_cpy",
"else",
":",
"return",
"image",
".",
"resize",
"(",
"tuple_wh",
")"
] |
Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
image: An instance of a PIL Image.
tuple_wh: A tuple containing the (width, height) for resizing.
preserve_aspect: A boolean that determines whether or not the
resizing should preserve the image's aspect ratio.
Returns: A resized copy of the provided PIL image.
|
[
"Resizes",
"an",
"instance",
"of",
"a",
"PIL",
"Image",
"."
] |
5c54af216319f297ddf96181a16f088cf1ba23f3
|
https://github.com/Aperture-py/aperture-lib/blob/5c54af216319f297ddf96181a16f088cf1ba23f3/aperturelib/resize.py#L1-L23
|
245,154
|
deformio/python-deform
|
pydeform/utils.py
|
format_datetime
|
def format_datetime(date):
"""
Convert datetime to UTC ISO 8601
"""
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcoffset()
utc_date = date - utc_offset_sec
utc_date_without_offset = utc_date.replace(tzinfo=None)
return utc_date_without_offset.isoformat() + 'Z'
|
python
|
def format_datetime(date):
"""
Convert datetime to UTC ISO 8601
"""
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcoffset()
utc_date = date - utc_offset_sec
utc_date_without_offset = utc_date.replace(tzinfo=None)
return utc_date_without_offset.isoformat() + 'Z'
|
[
"def",
"format_datetime",
"(",
"date",
")",
":",
"# todo: test me",
"if",
"date",
".",
"utcoffset",
"(",
")",
"is",
"None",
":",
"return",
"date",
".",
"isoformat",
"(",
")",
"+",
"'Z'",
"utc_offset_sec",
"=",
"date",
".",
"utcoffset",
"(",
")",
"utc_date",
"=",
"date",
"-",
"utc_offset_sec",
"utc_date_without_offset",
"=",
"utc_date",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"return",
"utc_date_without_offset",
".",
"isoformat",
"(",
")",
"+",
"'Z'"
] |
Convert datetime to UTC ISO 8601
|
[
"Convert",
"datetime",
"to",
"UTC",
"ISO",
"8601"
] |
c1edc7572881b83a4981b2dd39898527e518bd1f
|
https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/utils.py#L102-L113
|
245,155
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.log
|
def log(self, msg, error=False):
"""Log message helper."""
output = self.stdout
if error:
output = self.stderr
output.write(msg)
output.write('\n')
|
python
|
def log(self, msg, error=False):
"""Log message helper."""
output = self.stdout
if error:
output = self.stderr
output.write(msg)
output.write('\n')
|
[
"def",
"log",
"(",
"self",
",",
"msg",
",",
"error",
"=",
"False",
")",
":",
"output",
"=",
"self",
".",
"stdout",
"if",
"error",
":",
"output",
"=",
"self",
".",
"stderr",
"output",
".",
"write",
"(",
"msg",
")",
"output",
".",
"write",
"(",
"'\\n'",
")"
] |
Log message helper.
|
[
"Log",
"message",
"helper",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L66-L73
|
245,156
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.parse_emails
|
def parse_emails(self, email_filename, index=0):
"""Generator function that parse and extract emails from the file
`email_filename` starting from the position `index`.
Yield: An instance of `mailbox.mboxMessage` for each email in the
file.
"""
self.log("Parsing email dump: %s." % email_filename)
mbox = mailbox.mbox(email_filename, factory=CustomMessage)
# Get each email from mbox file
#
# The following implementation was used because the object
# mbox does not support slicing. Converting the object to a
# tuple (as represented in the code down here) was a valid
# option but its performance was too poor.
#
# for message in tuple(mbox)[index:]:
# yield message
#
key = index
while key in mbox:
key += 1
yield key-1, mbox[key-1]
|
python
|
def parse_emails(self, email_filename, index=0):
"""Generator function that parse and extract emails from the file
`email_filename` starting from the position `index`.
Yield: An instance of `mailbox.mboxMessage` for each email in the
file.
"""
self.log("Parsing email dump: %s." % email_filename)
mbox = mailbox.mbox(email_filename, factory=CustomMessage)
# Get each email from mbox file
#
# The following implementation was used because the object
# mbox does not support slicing. Converting the object to a
# tuple (as represented in the code down here) was a valid
# option but its performance was too poor.
#
# for message in tuple(mbox)[index:]:
# yield message
#
key = index
while key in mbox:
key += 1
yield key-1, mbox[key-1]
|
[
"def",
"parse_emails",
"(",
"self",
",",
"email_filename",
",",
"index",
"=",
"0",
")",
":",
"self",
".",
"log",
"(",
"\"Parsing email dump: %s.\"",
"%",
"email_filename",
")",
"mbox",
"=",
"mailbox",
".",
"mbox",
"(",
"email_filename",
",",
"factory",
"=",
"CustomMessage",
")",
"# Get each email from mbox file",
"#",
"# The following implementation was used because the object",
"# mbox does not support slicing. Converting the object to a",
"# tuple (as represented in the code down here) was a valid",
"# option but its performance was too poor.",
"#",
"# for message in tuple(mbox)[index:]:",
"# yield message",
"#",
"key",
"=",
"index",
"while",
"key",
"in",
"mbox",
":",
"key",
"+=",
"1",
"yield",
"key",
"-",
"1",
",",
"mbox",
"[",
"key",
"-",
"1",
"]"
] |
Generator function that parse and extract emails from the file
`email_filename` starting from the position `index`.
Yield: An instance of `mailbox.mboxMessage` for each email in the
file.
|
[
"Generator",
"function",
"that",
"parse",
"and",
"extract",
"emails",
"from",
"the",
"file",
"email_filename",
"starting",
"from",
"the",
"position",
"index",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L75-L99
|
245,157
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.get_emails
|
def get_emails(self, mailinglist_dir, all, exclude_lists):
"""Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previously imported. The lists set in `exclude_lists`
won't be imported.
Yield: A tuple in the form: (mailing list name, email message).
"""
self.log("Getting emails dumps from: %s" % mailinglist_dir)
# Get the list of directories ending with .mbox
mailing_lists_mboxes = (mbox for mbox in os.listdir(mailinglist_dir)
if mbox.endswith('.mbox'))
# Get messages from each mbox
for mbox in mailing_lists_mboxes:
mbox_path = os.path.join(mailinglist_dir, mbox, mbox)
mailinglist_name = mbox.split('.')[0]
# Check if the mailinglist is set not to be imported
if exclude_lists and mailinglist_name in exclude_lists:
continue
# Find the index of the last imported message
if all:
n_msgs = 0
else:
try:
mailinglist = MailingList.objects.get(
name=mailinglist_name
)
n_msgs = mailinglist.last_imported_index
except MailingList.DoesNotExist:
n_msgs = 0
for index, msg in self.parse_emails(mbox_path, n_msgs):
yield mailinglist_name, msg, index
|
python
|
def get_emails(self, mailinglist_dir, all, exclude_lists):
"""Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previously imported. The lists set in `exclude_lists`
won't be imported.
Yield: A tuple in the form: (mailing list name, email message).
"""
self.log("Getting emails dumps from: %s" % mailinglist_dir)
# Get the list of directories ending with .mbox
mailing_lists_mboxes = (mbox for mbox in os.listdir(mailinglist_dir)
if mbox.endswith('.mbox'))
# Get messages from each mbox
for mbox in mailing_lists_mboxes:
mbox_path = os.path.join(mailinglist_dir, mbox, mbox)
mailinglist_name = mbox.split('.')[0]
# Check if the mailinglist is set not to be imported
if exclude_lists and mailinglist_name in exclude_lists:
continue
# Find the index of the last imported message
if all:
n_msgs = 0
else:
try:
mailinglist = MailingList.objects.get(
name=mailinglist_name
)
n_msgs = mailinglist.last_imported_index
except MailingList.DoesNotExist:
n_msgs = 0
for index, msg in self.parse_emails(mbox_path, n_msgs):
yield mailinglist_name, msg, index
|
[
"def",
"get_emails",
"(",
"self",
",",
"mailinglist_dir",
",",
"all",
",",
"exclude_lists",
")",
":",
"self",
".",
"log",
"(",
"\"Getting emails dumps from: %s\"",
"%",
"mailinglist_dir",
")",
"# Get the list of directories ending with .mbox",
"mailing_lists_mboxes",
"=",
"(",
"mbox",
"for",
"mbox",
"in",
"os",
".",
"listdir",
"(",
"mailinglist_dir",
")",
"if",
"mbox",
".",
"endswith",
"(",
"'.mbox'",
")",
")",
"# Get messages from each mbox",
"for",
"mbox",
"in",
"mailing_lists_mboxes",
":",
"mbox_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mailinglist_dir",
",",
"mbox",
",",
"mbox",
")",
"mailinglist_name",
"=",
"mbox",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# Check if the mailinglist is set not to be imported",
"if",
"exclude_lists",
"and",
"mailinglist_name",
"in",
"exclude_lists",
":",
"continue",
"# Find the index of the last imported message",
"if",
"all",
":",
"n_msgs",
"=",
"0",
"else",
":",
"try",
":",
"mailinglist",
"=",
"MailingList",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"mailinglist_name",
")",
"n_msgs",
"=",
"mailinglist",
".",
"last_imported_index",
"except",
"MailingList",
".",
"DoesNotExist",
":",
"n_msgs",
"=",
"0",
"for",
"index",
",",
"msg",
"in",
"self",
".",
"parse_emails",
"(",
"mbox_path",
",",
"n_msgs",
")",
":",
"yield",
"mailinglist_name",
",",
"msg",
",",
"index"
] |
Generator function that get the emails from each mailing
list dump dirctory. If `all` is set to True all the emails in the
mbox will be imported if not it will just resume from the last
message previously imported. The lists set in `exclude_lists`
won't be imported.
Yield: A tuple in the form: (mailing list name, email message).
|
[
"Generator",
"function",
"that",
"get",
"the",
"emails",
"from",
"each",
"mailing",
"list",
"dump",
"dirctory",
".",
"If",
"all",
"is",
"set",
"to",
"True",
"all",
"the",
"emails",
"in",
"the",
"mbox",
"will",
"be",
"imported",
"if",
"not",
"it",
"will",
"just",
"resume",
"from",
"the",
"last",
"message",
"previously",
"imported",
".",
"The",
"lists",
"set",
"in",
"exclude_lists",
"won",
"t",
"be",
"imported",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L101-L139
|
245,158
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.get_thread
|
def get_thread(self, email, mailinglist):
"""Group messages by thread looking for similar subjects"""
subject_slug = slugify(email.subject_clean)
thread = self.THREAD_CACHE.get(subject_slug, {}).get(mailinglist.id)
if thread is None:
thread = Thread.all_objects.get_or_create(
mailinglist=mailinglist,
subject_token=subject_slug
)[0]
if self.THREAD_CACHE.get(subject_slug) is None:
self.THREAD_CACHE[subject_slug] = dict()
self.THREAD_CACHE[subject_slug][mailinglist.id] = thread
thread.latest_message = email
thread.update_keywords()
thread.save()
return thread
|
python
|
def get_thread(self, email, mailinglist):
"""Group messages by thread looking for similar subjects"""
subject_slug = slugify(email.subject_clean)
thread = self.THREAD_CACHE.get(subject_slug, {}).get(mailinglist.id)
if thread is None:
thread = Thread.all_objects.get_or_create(
mailinglist=mailinglist,
subject_token=subject_slug
)[0]
if self.THREAD_CACHE.get(subject_slug) is None:
self.THREAD_CACHE[subject_slug] = dict()
self.THREAD_CACHE[subject_slug][mailinglist.id] = thread
thread.latest_message = email
thread.update_keywords()
thread.save()
return thread
|
[
"def",
"get_thread",
"(",
"self",
",",
"email",
",",
"mailinglist",
")",
":",
"subject_slug",
"=",
"slugify",
"(",
"email",
".",
"subject_clean",
")",
"thread",
"=",
"self",
".",
"THREAD_CACHE",
".",
"get",
"(",
"subject_slug",
",",
"{",
"}",
")",
".",
"get",
"(",
"mailinglist",
".",
"id",
")",
"if",
"thread",
"is",
"None",
":",
"thread",
"=",
"Thread",
".",
"all_objects",
".",
"get_or_create",
"(",
"mailinglist",
"=",
"mailinglist",
",",
"subject_token",
"=",
"subject_slug",
")",
"[",
"0",
"]",
"if",
"self",
".",
"THREAD_CACHE",
".",
"get",
"(",
"subject_slug",
")",
"is",
"None",
":",
"self",
".",
"THREAD_CACHE",
"[",
"subject_slug",
"]",
"=",
"dict",
"(",
")",
"self",
".",
"THREAD_CACHE",
"[",
"subject_slug",
"]",
"[",
"mailinglist",
".",
"id",
"]",
"=",
"thread",
"thread",
".",
"latest_message",
"=",
"email",
"thread",
".",
"update_keywords",
"(",
")",
"thread",
".",
"save",
"(",
")",
"return",
"thread"
] |
Group messages by thread looking for similar subjects
|
[
"Group",
"messages",
"by",
"thread",
"looking",
"for",
"similar",
"subjects"
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L141-L159
|
245,159
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.save_email
|
def save_email(self, list_name, email_msg, index):
"""Save email message into the database."""
msg_id = email_msg.get('Message-ID')
if not msg_id:
return
# Update last imported message into the DB
mailinglist, created = MailingList.objects.get_or_create(
name=list_name
)
mailinglist.last_imported_index = index
if created:
# if the mailinglist is newly created it's sure that the message
# is not in the DB yet.
self.create_email(mailinglist, email_msg)
else:
# If the message is already at the database don't do anything
try:
Message.all_objects.get(
message_id=msg_id,
thread__mailinglist=mailinglist
)
except Message.DoesNotExist:
self.create_email(mailinglist, email_msg)
mailinglist.save()
|
python
|
def save_email(self, list_name, email_msg, index):
"""Save email message into the database."""
msg_id = email_msg.get('Message-ID')
if not msg_id:
return
# Update last imported message into the DB
mailinglist, created = MailingList.objects.get_or_create(
name=list_name
)
mailinglist.last_imported_index = index
if created:
# if the mailinglist is newly created it's sure that the message
# is not in the DB yet.
self.create_email(mailinglist, email_msg)
else:
# If the message is already at the database don't do anything
try:
Message.all_objects.get(
message_id=msg_id,
thread__mailinglist=mailinglist
)
except Message.DoesNotExist:
self.create_email(mailinglist, email_msg)
mailinglist.save()
|
[
"def",
"save_email",
"(",
"self",
",",
"list_name",
",",
"email_msg",
",",
"index",
")",
":",
"msg_id",
"=",
"email_msg",
".",
"get",
"(",
"'Message-ID'",
")",
"if",
"not",
"msg_id",
":",
"return",
"# Update last imported message into the DB",
"mailinglist",
",",
"created",
"=",
"MailingList",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"list_name",
")",
"mailinglist",
".",
"last_imported_index",
"=",
"index",
"if",
"created",
":",
"# if the mailinglist is newly created it's sure that the message",
"# is not in the DB yet.",
"self",
".",
"create_email",
"(",
"mailinglist",
",",
"email_msg",
")",
"else",
":",
"# If the message is already at the database don't do anything",
"try",
":",
"Message",
".",
"all_objects",
".",
"get",
"(",
"message_id",
"=",
"msg_id",
",",
"thread__mailinglist",
"=",
"mailinglist",
")",
"except",
"Message",
".",
"DoesNotExist",
":",
"self",
".",
"create_email",
"(",
"mailinglist",
",",
"email_msg",
")",
"mailinglist",
".",
"save",
"(",
")"
] |
Save email message into the database.
|
[
"Save",
"email",
"message",
"into",
"the",
"database",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L161-L190
|
245,160
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.import_emails
|
def import_emails(self, archives_path, all, exclude_lists=None):
"""Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previously
imported. The lists set in `exclude_lists` won't be imported.
"""
count = 0
email_generator = self.get_emails(archives_path, all, exclude_lists)
for mailinglist_name, msg, index in email_generator:
try:
self.save_email(mailinglist_name, msg, index)
except:
# This anti-pattern is needed to avoid the transations to
# get stuck in case of errors.
transaction.rollback()
raise
count += 1
if count % 1000 == 0:
transaction.commit()
transaction.commit()
|
python
|
def import_emails(self, archives_path, all, exclude_lists=None):
"""Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previously
imported. The lists set in `exclude_lists` won't be imported.
"""
count = 0
email_generator = self.get_emails(archives_path, all, exclude_lists)
for mailinglist_name, msg, index in email_generator:
try:
self.save_email(mailinglist_name, msg, index)
except:
# This anti-pattern is needed to avoid the transations to
# get stuck in case of errors.
transaction.rollback()
raise
count += 1
if count % 1000 == 0:
transaction.commit()
transaction.commit()
|
[
"def",
"import_emails",
"(",
"self",
",",
"archives_path",
",",
"all",
",",
"exclude_lists",
"=",
"None",
")",
":",
"count",
"=",
"0",
"email_generator",
"=",
"self",
".",
"get_emails",
"(",
"archives_path",
",",
"all",
",",
"exclude_lists",
")",
"for",
"mailinglist_name",
",",
"msg",
",",
"index",
"in",
"email_generator",
":",
"try",
":",
"self",
".",
"save_email",
"(",
"mailinglist_name",
",",
"msg",
",",
"index",
")",
"except",
":",
"# This anti-pattern is needed to avoid the transations to",
"# get stuck in case of errors.",
"transaction",
".",
"rollback",
"(",
")",
"raise",
"count",
"+=",
"1",
"if",
"count",
"%",
"1000",
"==",
"0",
":",
"transaction",
".",
"commit",
"(",
")",
"transaction",
".",
"commit",
"(",
")"
] |
Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previously
imported. The lists set in `exclude_lists` won't be imported.
|
[
"Get",
"emails",
"from",
"the",
"filesystem",
"from",
"the",
"archives_path",
"and",
"store",
"them",
"into",
"the",
"database",
".",
"If",
"all",
"is",
"set",
"to",
"True",
"all",
"the",
"filesystem",
"storage",
"will",
"be",
"imported",
"otherwise",
"the",
"importation",
"will",
"resume",
"from",
"the",
"last",
"message",
"previously",
"imported",
".",
"The",
"lists",
"set",
"in",
"exclude_lists",
"won",
"t",
"be",
"imported",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L239-L263
|
245,161
|
colab/colab-superarchives-plugin
|
src/colab_superarchives/management/commands/import_emails.py
|
Command.handle
|
def handle(self, *args, **options):
"""Main command method."""
# Already running, so quit
if os.path.exists(self.lock_file):
self.log(("This script is already running. "
"(If your are sure it's not please "
"delete the lock file in {}')").format(self.lock_file))
sys.exit(0)
if not os.path.exists(os.path.dirname(self.lock_file)):
os.mkdir(os.path.dirname(self.lock_file), 0755)
archives_path = options.get('archives_path')
self.log('Using archives_path `%s`' % settings.SUPER_ARCHIVES_PATH)
if not os.path.exists(archives_path):
msg = 'archives_path ({}) does not exist'.format(archives_path)
raise CommandError(msg)
run_lock = file(self.lock_file, 'w')
run_lock.close()
try:
self.import_emails(
archives_path,
options.get('all'),
options.get('exclude_lists'),
)
except Exception as e:
logging.exception(e)
raise
finally:
os.remove(self.lock_file)
for mlist in MailingList.objects.all():
mlist.update_privacy()
mlist.save()
|
python
|
def handle(self, *args, **options):
"""Main command method."""
# Already running, so quit
if os.path.exists(self.lock_file):
self.log(("This script is already running. "
"(If your are sure it's not please "
"delete the lock file in {}')").format(self.lock_file))
sys.exit(0)
if not os.path.exists(os.path.dirname(self.lock_file)):
os.mkdir(os.path.dirname(self.lock_file), 0755)
archives_path = options.get('archives_path')
self.log('Using archives_path `%s`' % settings.SUPER_ARCHIVES_PATH)
if not os.path.exists(archives_path):
msg = 'archives_path ({}) does not exist'.format(archives_path)
raise CommandError(msg)
run_lock = file(self.lock_file, 'w')
run_lock.close()
try:
self.import_emails(
archives_path,
options.get('all'),
options.get('exclude_lists'),
)
except Exception as e:
logging.exception(e)
raise
finally:
os.remove(self.lock_file)
for mlist in MailingList.objects.all():
mlist.update_privacy()
mlist.save()
|
[
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# Already running, so quit",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"lock_file",
")",
":",
"self",
".",
"log",
"(",
"(",
"\"This script is already running. \"",
"\"(If your are sure it's not please \"",
"\"delete the lock file in {}')\"",
")",
".",
"format",
"(",
"self",
".",
"lock_file",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"lock_file",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"lock_file",
")",
",",
"0755",
")",
"archives_path",
"=",
"options",
".",
"get",
"(",
"'archives_path'",
")",
"self",
".",
"log",
"(",
"'Using archives_path `%s`'",
"%",
"settings",
".",
"SUPER_ARCHIVES_PATH",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archives_path",
")",
":",
"msg",
"=",
"'archives_path ({}) does not exist'",
".",
"format",
"(",
"archives_path",
")",
"raise",
"CommandError",
"(",
"msg",
")",
"run_lock",
"=",
"file",
"(",
"self",
".",
"lock_file",
",",
"'w'",
")",
"run_lock",
".",
"close",
"(",
")",
"try",
":",
"self",
".",
"import_emails",
"(",
"archives_path",
",",
"options",
".",
"get",
"(",
"'all'",
")",
",",
"options",
".",
"get",
"(",
"'exclude_lists'",
")",
",",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"e",
")",
"raise",
"finally",
":",
"os",
".",
"remove",
"(",
"self",
".",
"lock_file",
")",
"for",
"mlist",
"in",
"MailingList",
".",
"objects",
".",
"all",
"(",
")",
":",
"mlist",
".",
"update_privacy",
"(",
")",
"mlist",
".",
"save",
"(",
")"
] |
Main command method.
|
[
"Main",
"command",
"method",
"."
] |
fe588a1d4fac874ccad2063ee19a857028a22721
|
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L265-L301
|
245,162
|
praekelt/panya
|
panya/models.py
|
set_managers
|
def set_managers(sender, **kwargs):
"""
Make sure all classes have the appropriate managers
"""
cls = sender
if issubclass(cls, ModelBase):
cls.add_to_class('permitted', PermittedManager())
|
python
|
def set_managers(sender, **kwargs):
"""
Make sure all classes have the appropriate managers
"""
cls = sender
if issubclass(cls, ModelBase):
cls.add_to_class('permitted', PermittedManager())
|
[
"def",
"set_managers",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"sender",
"if",
"issubclass",
"(",
"cls",
",",
"ModelBase",
")",
":",
"cls",
".",
"add_to_class",
"(",
"'permitted'",
",",
"PermittedManager",
"(",
")",
")"
] |
Make sure all classes have the appropriate managers
|
[
"Make",
"sure",
"all",
"classes",
"have",
"the",
"appropriate",
"managers"
] |
0fd621e15a7c11a2716a9554a2f820d6259818e5
|
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L290-L297
|
245,163
|
praekelt/panya
|
panya/models.py
|
ModelBase.vote_total
|
def vote_total(self):
"""
Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses.
"""
modelbase_obj = self.modelbase_obj
return modelbase_obj.votes.filter(vote=+1).count() - modelbase_obj.votes.filter(vote=-1).count()
|
python
|
def vote_total(self):
"""
Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses.
"""
modelbase_obj = self.modelbase_obj
return modelbase_obj.votes.filter(vote=+1).count() - modelbase_obj.votes.filter(vote=-1).count()
|
[
"def",
"vote_total",
"(",
"self",
")",
":",
"modelbase_obj",
"=",
"self",
".",
"modelbase_obj",
"return",
"modelbase_obj",
".",
"votes",
".",
"filter",
"(",
"vote",
"=",
"+",
"1",
")",
".",
"count",
"(",
")",
"-",
"modelbase_obj",
".",
"votes",
".",
"filter",
"(",
"vote",
"=",
"-",
"1",
")",
".",
"count",
"(",
")"
] |
Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses.
|
[
"Calculates",
"vote",
"total",
"as",
"total_upvotes",
"-",
"total_downvotes",
".",
"We",
"are",
"adding",
"a",
"method",
"here",
"instead",
"of",
"relying",
"on",
"django",
"-",
"secretballot",
"s",
"addition",
"since",
"that",
"doesn",
"t",
"work",
"for",
"subclasses",
"."
] |
0fd621e15a7c11a2716a9554a2f820d6259818e5
|
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L252-L257
|
245,164
|
praekelt/panya
|
panya/models.py
|
ModelBase.comment_count
|
def comment_count(self):
"""
Counts total number of comments on ModelBase object.
Comments should always be recorded on ModelBase objects.
"""
# Get the comment model.
comment_model = comments.get_model()
modelbase_content_type = ContentType.objects.get(app_label="panya", model="modelbase")
# Create a qs filtered for the ModelBase or content_type objects.
qs = comment_model.objects.filter(
content_type__in = [self.content_type, modelbase_content_type],
object_pk = smart_unicode(self.pk),
site__pk = settings.SITE_ID,
)
# The is_public and is_removed fields are implementation details of the
# built-in comment model's spam filtering system, so they might not
# be present on a custom comment model subclass. If they exist, we
# should filter on them.
field_names = [f.name for f in comment_model._meta.fields]
if 'is_public' in field_names:
qs = qs.filter(is_public=True)
if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names:
qs = qs.filter(is_removed=False)
# Return ammount of items in qs.
return qs.count()
|
python
|
def comment_count(self):
"""
Counts total number of comments on ModelBase object.
Comments should always be recorded on ModelBase objects.
"""
# Get the comment model.
comment_model = comments.get_model()
modelbase_content_type = ContentType.objects.get(app_label="panya", model="modelbase")
# Create a qs filtered for the ModelBase or content_type objects.
qs = comment_model.objects.filter(
content_type__in = [self.content_type, modelbase_content_type],
object_pk = smart_unicode(self.pk),
site__pk = settings.SITE_ID,
)
# The is_public and is_removed fields are implementation details of the
# built-in comment model's spam filtering system, so they might not
# be present on a custom comment model subclass. If they exist, we
# should filter on them.
field_names = [f.name for f in comment_model._meta.fields]
if 'is_public' in field_names:
qs = qs.filter(is_public=True)
if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names:
qs = qs.filter(is_removed=False)
# Return ammount of items in qs.
return qs.count()
|
[
"def",
"comment_count",
"(",
"self",
")",
":",
"# Get the comment model.",
"comment_model",
"=",
"comments",
".",
"get_model",
"(",
")",
"modelbase_content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"\"panya\"",
",",
"model",
"=",
"\"modelbase\"",
")",
"# Create a qs filtered for the ModelBase or content_type objects.",
"qs",
"=",
"comment_model",
".",
"objects",
".",
"filter",
"(",
"content_type__in",
"=",
"[",
"self",
".",
"content_type",
",",
"modelbase_content_type",
"]",
",",
"object_pk",
"=",
"smart_unicode",
"(",
"self",
".",
"pk",
")",
",",
"site__pk",
"=",
"settings",
".",
"SITE_ID",
",",
")",
"# The is_public and is_removed fields are implementation details of the",
"# built-in comment model's spam filtering system, so they might not",
"# be present on a custom comment model subclass. If they exist, we",
"# should filter on them.",
"field_names",
"=",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"comment_model",
".",
"_meta",
".",
"fields",
"]",
"if",
"'is_public'",
"in",
"field_names",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"is_public",
"=",
"True",
")",
"if",
"getattr",
"(",
"settings",
",",
"'COMMENTS_HIDE_REMOVED'",
",",
"True",
")",
"and",
"'is_removed'",
"in",
"field_names",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"is_removed",
"=",
"False",
")",
"# Return ammount of items in qs.",
"return",
"qs",
".",
"count",
"(",
")"
] |
Counts total number of comments on ModelBase object.
Comments should always be recorded on ModelBase objects.
|
[
"Counts",
"total",
"number",
"of",
"comments",
"on",
"ModelBase",
"object",
".",
"Comments",
"should",
"always",
"be",
"recorded",
"on",
"ModelBase",
"objects",
"."
] |
0fd621e15a7c11a2716a9554a2f820d6259818e5
|
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L260-L288
|
245,165
|
delfick/aws_syncr
|
aws_syncr/actions.py
|
sync
|
def sync(collector):
"""Sync an environment"""
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
# Convert everything before we try and sync anything
log.info("Converting configuration")
converted = {}
for thing in collector.configuration["__registered__"]:
if thing in collector.configuration:
converted[thing] = collector.configuration[thing]
# Do the sync
for typ in collector.configuration["__registered__"]:
if typ in converted:
thing = converted[typ]
if not aws_syncr.artifact or aws_syncr.artifact == typ:
log.info("Syncing {0}".format(typ))
for name, item in thing.items.items():
thing.sync_one(aws_syncr, amazon, item)
if not amazon.changes:
log.info("No changes were made!!")
|
python
|
def sync(collector):
"""Sync an environment"""
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
# Convert everything before we try and sync anything
log.info("Converting configuration")
converted = {}
for thing in collector.configuration["__registered__"]:
if thing in collector.configuration:
converted[thing] = collector.configuration[thing]
# Do the sync
for typ in collector.configuration["__registered__"]:
if typ in converted:
thing = converted[typ]
if not aws_syncr.artifact or aws_syncr.artifact == typ:
log.info("Syncing {0}".format(typ))
for name, item in thing.items.items():
thing.sync_one(aws_syncr, amazon, item)
if not amazon.changes:
log.info("No changes were made!!")
|
[
"def",
"sync",
"(",
"collector",
")",
":",
"amazon",
"=",
"collector",
".",
"configuration",
"[",
"'amazon'",
"]",
"aws_syncr",
"=",
"collector",
".",
"configuration",
"[",
"'aws_syncr'",
"]",
"# Convert everything before we try and sync anything",
"log",
".",
"info",
"(",
"\"Converting configuration\"",
")",
"converted",
"=",
"{",
"}",
"for",
"thing",
"in",
"collector",
".",
"configuration",
"[",
"\"__registered__\"",
"]",
":",
"if",
"thing",
"in",
"collector",
".",
"configuration",
":",
"converted",
"[",
"thing",
"]",
"=",
"collector",
".",
"configuration",
"[",
"thing",
"]",
"# Do the sync",
"for",
"typ",
"in",
"collector",
".",
"configuration",
"[",
"\"__registered__\"",
"]",
":",
"if",
"typ",
"in",
"converted",
":",
"thing",
"=",
"converted",
"[",
"typ",
"]",
"if",
"not",
"aws_syncr",
".",
"artifact",
"or",
"aws_syncr",
".",
"artifact",
"==",
"typ",
":",
"log",
".",
"info",
"(",
"\"Syncing {0}\"",
".",
"format",
"(",
"typ",
")",
")",
"for",
"name",
",",
"item",
"in",
"thing",
".",
"items",
".",
"items",
"(",
")",
":",
"thing",
".",
"sync_one",
"(",
"aws_syncr",
",",
"amazon",
",",
"item",
")",
"if",
"not",
"amazon",
".",
"changes",
":",
"log",
".",
"info",
"(",
"\"No changes were made!!\"",
")"
] |
Sync an environment
|
[
"Sync",
"an",
"environment"
] |
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
|
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L141-L163
|
245,166
|
delfick/aws_syncr
|
aws_syncr/actions.py
|
deploy_lambda
|
def deploy_lambda(collector):
"""Deploy a lambda function"""
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon)
|
python
|
def deploy_lambda(collector):
"""Deploy a lambda function"""
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon)
|
[
"def",
"deploy_lambda",
"(",
"collector",
")",
":",
"amazon",
"=",
"collector",
".",
"configuration",
"[",
"'amazon'",
"]",
"aws_syncr",
"=",
"collector",
".",
"configuration",
"[",
"'aws_syncr'",
"]",
"find_lambda_function",
"(",
"aws_syncr",
",",
"collector",
".",
"configuration",
")",
".",
"deploy",
"(",
"aws_syncr",
",",
"amazon",
")"
] |
Deploy a lambda function
|
[
"Deploy",
"a",
"lambda",
"function"
] |
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
|
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L166-L170
|
245,167
|
delfick/aws_syncr
|
aws_syncr/actions.py
|
deploy_gateway
|
def deploy_gateway(collector):
"""Deploy the apigateway to a particular stage"""
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration)
gateway.deploy(aws_syncr, amazon, stage)
if not configuration['amazon'].changes:
log.info("No changes were made!!")
|
python
|
def deploy_gateway(collector):
"""Deploy the apigateway to a particular stage"""
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration)
gateway.deploy(aws_syncr, amazon, stage)
if not configuration['amazon'].changes:
log.info("No changes were made!!")
|
[
"def",
"deploy_gateway",
"(",
"collector",
")",
":",
"configuration",
"=",
"collector",
".",
"configuration",
"aws_syncr",
"=",
"configuration",
"[",
"'aws_syncr'",
"]",
"aws_syncr",
",",
"amazon",
",",
"stage",
",",
"gateway",
"=",
"find_gateway",
"(",
"aws_syncr",
",",
"configuration",
")",
"gateway",
".",
"deploy",
"(",
"aws_syncr",
",",
"amazon",
",",
"stage",
")",
"if",
"not",
"configuration",
"[",
"'amazon'",
"]",
".",
"changes",
":",
"log",
".",
"info",
"(",
"\"No changes were made!!\"",
")"
] |
Deploy the apigateway to a particular stage
|
[
"Deploy",
"the",
"apigateway",
"to",
"a",
"particular",
"stage"
] |
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
|
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L188-L196
|
245,168
|
delfick/aws_syncr
|
aws_syncr/actions.py
|
sync_and_deploy_gateway
|
def sync_and_deploy_gateway(collector):
"""Do a sync followed by deploying the gateway"""
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
find_gateway(aws_syncr, configuration)
artifact = aws_syncr.artifact
aws_syncr.artifact = ""
sync(collector)
aws_syncr.artifact = artifact
deploy_gateway(collector)
|
python
|
def sync_and_deploy_gateway(collector):
"""Do a sync followed by deploying the gateway"""
configuration = collector.configuration
aws_syncr = configuration['aws_syncr']
find_gateway(aws_syncr, configuration)
artifact = aws_syncr.artifact
aws_syncr.artifact = ""
sync(collector)
aws_syncr.artifact = artifact
deploy_gateway(collector)
|
[
"def",
"sync_and_deploy_gateway",
"(",
"collector",
")",
":",
"configuration",
"=",
"collector",
".",
"configuration",
"aws_syncr",
"=",
"configuration",
"[",
"'aws_syncr'",
"]",
"find_gateway",
"(",
"aws_syncr",
",",
"configuration",
")",
"artifact",
"=",
"aws_syncr",
".",
"artifact",
"aws_syncr",
".",
"artifact",
"=",
"\"\"",
"sync",
"(",
"collector",
")",
"aws_syncr",
".",
"artifact",
"=",
"artifact",
"deploy_gateway",
"(",
"collector",
")"
] |
Do a sync followed by deploying the gateway
|
[
"Do",
"a",
"sync",
"followed",
"by",
"deploying",
"the",
"gateway"
] |
8cd214b27c1eee98dfba4632cbb8bc0ae36356bd
|
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L199-L210
|
245,169
|
edwards-lab/MVtest
|
meanvar/mvresult.py
|
MVResult.print_result
|
def print_result(self, f=sys.stdout, verbose=False):
"""Print result to f
:param f: stream to print output
:param verbose: print all data or only the most important parts?
"""
var_count = len(self.betas)/2
if verbose:
results = [str(x) for x in [
self.chr,
self.pos,
self.rsid,
self.ph_label,
self.non_miss,
self.maj_allele,
self.min_allele,
"%.4e" % self.eff_alcount,
"%.4e" % self.p_mvtest,
"%.4e" % self.lmpv
]]
for i in range(var_count):
results.append("%.3e" % self.betas[i])
results.append(self.stringify(self.beta_stderr[i]))
results.append(self.stringify(self.beta_pvalues[i]))
results.append(self.stringify(self.betas[i+var_count]))
results.append(self.stringify(self.beta_stderr[i+var_count]))
results.append(self.stringify(self.beta_pvalues[i+var_count]))
print >> f, "\t".join([str(x) for x in results])
else:
print >> f, "\t".join(str(x) for x in [
self.chr,
self.pos,
self.rsid,
self.ph_label,
self.non_miss,
self.maj_allele,
self.min_allele,
"%.3e" % self.eff_alcount,
"%.3e" % self.p_mvtest,
"%.3e" % self.betas[1],
self.stringify(self.beta_stderr[1]),
"%.3e" % self.beta_pvalues[1],
"%.3e" % self.betas[1+var_count],
self.stringify(self.beta_stderr[1+var_count]),
"%.3e" % self.beta_pvalues[1+var_count],
])
|
python
|
def print_result(self, f=sys.stdout, verbose=False):
"""Print result to f
:param f: stream to print output
:param verbose: print all data or only the most important parts?
"""
var_count = len(self.betas)/2
if verbose:
results = [str(x) for x in [
self.chr,
self.pos,
self.rsid,
self.ph_label,
self.non_miss,
self.maj_allele,
self.min_allele,
"%.4e" % self.eff_alcount,
"%.4e" % self.p_mvtest,
"%.4e" % self.lmpv
]]
for i in range(var_count):
results.append("%.3e" % self.betas[i])
results.append(self.stringify(self.beta_stderr[i]))
results.append(self.stringify(self.beta_pvalues[i]))
results.append(self.stringify(self.betas[i+var_count]))
results.append(self.stringify(self.beta_stderr[i+var_count]))
results.append(self.stringify(self.beta_pvalues[i+var_count]))
print >> f, "\t".join([str(x) for x in results])
else:
print >> f, "\t".join(str(x) for x in [
self.chr,
self.pos,
self.rsid,
self.ph_label,
self.non_miss,
self.maj_allele,
self.min_allele,
"%.3e" % self.eff_alcount,
"%.3e" % self.p_mvtest,
"%.3e" % self.betas[1],
self.stringify(self.beta_stderr[1]),
"%.3e" % self.beta_pvalues[1],
"%.3e" % self.betas[1+var_count],
self.stringify(self.beta_stderr[1+var_count]),
"%.3e" % self.beta_pvalues[1+var_count],
])
|
[
"def",
"print_result",
"(",
"self",
",",
"f",
"=",
"sys",
".",
"stdout",
",",
"verbose",
"=",
"False",
")",
":",
"var_count",
"=",
"len",
"(",
"self",
".",
"betas",
")",
"/",
"2",
"if",
"verbose",
":",
"results",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"[",
"self",
".",
"chr",
",",
"self",
".",
"pos",
",",
"self",
".",
"rsid",
",",
"self",
".",
"ph_label",
",",
"self",
".",
"non_miss",
",",
"self",
".",
"maj_allele",
",",
"self",
".",
"min_allele",
",",
"\"%.4e\"",
"%",
"self",
".",
"eff_alcount",
",",
"\"%.4e\"",
"%",
"self",
".",
"p_mvtest",
",",
"\"%.4e\"",
"%",
"self",
".",
"lmpv",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"var_count",
")",
":",
"results",
".",
"append",
"(",
"\"%.3e\"",
"%",
"self",
".",
"betas",
"[",
"i",
"]",
")",
"results",
".",
"append",
"(",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_stderr",
"[",
"i",
"]",
")",
")",
"results",
".",
"append",
"(",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_pvalues",
"[",
"i",
"]",
")",
")",
"results",
".",
"append",
"(",
"self",
".",
"stringify",
"(",
"self",
".",
"betas",
"[",
"i",
"+",
"var_count",
"]",
")",
")",
"results",
".",
"append",
"(",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_stderr",
"[",
"i",
"+",
"var_count",
"]",
")",
")",
"results",
".",
"append",
"(",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_pvalues",
"[",
"i",
"+",
"var_count",
"]",
")",
")",
"print",
">>",
"f",
",",
"\"\\t\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"results",
"]",
")",
"else",
":",
"print",
">>",
"f",
",",
"\"\\t\"",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"[",
"self",
".",
"chr",
",",
"self",
".",
"pos",
",",
"self",
".",
"rsid",
",",
"self",
".",
"ph_label",
",",
"self",
".",
"non_miss",
",",
"self",
".",
"maj_allele",
",",
"self",
".",
"min_allele",
",",
"\"%.3e\"",
"%",
"self",
".",
"eff_alcount",
",",
"\"%.3e\"",
"%",
"self",
".",
"p_mvtest",
",",
"\"%.3e\"",
"%",
"self",
".",
"betas",
"[",
"1",
"]",
",",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_stderr",
"[",
"1",
"]",
")",
",",
"\"%.3e\"",
"%",
"self",
".",
"beta_pvalues",
"[",
"1",
"]",
",",
"\"%.3e\"",
"%",
"self",
".",
"betas",
"[",
"1",
"+",
"var_count",
"]",
",",
"self",
".",
"stringify",
"(",
"self",
".",
"beta_stderr",
"[",
"1",
"+",
"var_count",
"]",
")",
",",
"\"%.3e\"",
"%",
"self",
".",
"beta_pvalues",
"[",
"1",
"+",
"var_count",
"]",
",",
"]",
")"
] |
Print result to f
:param f: stream to print output
:param verbose: print all data or only the most important parts?
|
[
"Print",
"result",
"to",
"f"
] |
fe8cf627464ef59d68b7eda628a19840d033882f
|
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/mvresult.py#L119-L166
|
245,170
|
LesPatamechanix/patalib
|
src/patalib/synonym.py
|
Synonym.generate_synonym
|
def generate_synonym(self, input_word):
""" Generate Synonym using a WordNet
synset.
"""
results = []
results.append(input_word)
synset = wordnet.synsets(input_word)
for i in synset:
index = 0
syn = i.name.split('.')
if syn[index]!= input_word:
name = syn[0]
results.append(PataLib().strip_underscore(name))
else:
index = index + 1
results = {'input' : input_word, 'results' : results, 'category' : 'synonym'}
return results
|
python
|
def generate_synonym(self, input_word):
""" Generate Synonym using a WordNet
synset.
"""
results = []
results.append(input_word)
synset = wordnet.synsets(input_word)
for i in synset:
index = 0
syn = i.name.split('.')
if syn[index]!= input_word:
name = syn[0]
results.append(PataLib().strip_underscore(name))
else:
index = index + 1
results = {'input' : input_word, 'results' : results, 'category' : 'synonym'}
return results
|
[
"def",
"generate_synonym",
"(",
"self",
",",
"input_word",
")",
":",
"results",
"=",
"[",
"]",
"results",
".",
"append",
"(",
"input_word",
")",
"synset",
"=",
"wordnet",
".",
"synsets",
"(",
"input_word",
")",
"for",
"i",
"in",
"synset",
":",
"index",
"=",
"0",
"syn",
"=",
"i",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"if",
"syn",
"[",
"index",
"]",
"!=",
"input_word",
":",
"name",
"=",
"syn",
"[",
"0",
"]",
"results",
".",
"append",
"(",
"PataLib",
"(",
")",
".",
"strip_underscore",
"(",
"name",
")",
")",
"else",
":",
"index",
"=",
"index",
"+",
"1",
"results",
"=",
"{",
"'input'",
":",
"input_word",
",",
"'results'",
":",
"results",
",",
"'category'",
":",
"'synonym'",
"}",
"return",
"results"
] |
Generate Synonym using a WordNet
synset.
|
[
"Generate",
"Synonym",
"using",
"a",
"WordNet",
"synset",
"."
] |
d88cca409b1750fdeb88cece048b308f2a710955
|
https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/synonym.py#L10-L26
|
245,171
|
matthewdeanmartin/jiggle_version
|
extra/vendorized/pep440.py
|
is_canonical
|
def is_canonical(version, loosedev=False): # type: (str, bool) -> bool
"""
Return whether or not the version string is canonical according to Pep 440
"""
if loosedev:
return loose440re.match(version) is not None
return pep440re.match(version) is not None
|
python
|
def is_canonical(version, loosedev=False): # type: (str, bool) -> bool
"""
Return whether or not the version string is canonical according to Pep 440
"""
if loosedev:
return loose440re.match(version) is not None
return pep440re.match(version) is not None
|
[
"def",
"is_canonical",
"(",
"version",
",",
"loosedev",
"=",
"False",
")",
":",
"# type: (str, bool) -> bool",
"if",
"loosedev",
":",
"return",
"loose440re",
".",
"match",
"(",
"version",
")",
"is",
"not",
"None",
"return",
"pep440re",
".",
"match",
"(",
"version",
")",
"is",
"not",
"None"
] |
Return whether or not the version string is canonical according to Pep 440
|
[
"Return",
"whether",
"or",
"not",
"the",
"version",
"string",
"is",
"canonical",
"according",
"to",
"Pep",
"440"
] |
963656a0a47b7162780a5f6c8f4b8bbbebc148f5
|
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/extra/vendorized/pep440.py#L50-L56
|
245,172
|
edeposit/edeposit.amqp.ftp
|
src/edeposit/amqp/ftp/decoders/parser_json.py
|
decode
|
def decode(data):
"""
Handles decoding of the JSON `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
"""
decoded = None
try:
decoded = json.loads(data)
except Exception, e:
raise MetaParsingException("Can't parse your JSON data: %s" % e.message)
decoded = validator.check_structure(decoded)
return decoded
|
python
|
def decode(data):
"""
Handles decoding of the JSON `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
"""
decoded = None
try:
decoded = json.loads(data)
except Exception, e:
raise MetaParsingException("Can't parse your JSON data: %s" % e.message)
decoded = validator.check_structure(decoded)
return decoded
|
[
"def",
"decode",
"(",
"data",
")",
":",
"decoded",
"=",
"None",
"try",
":",
"decoded",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"Exception",
",",
"e",
":",
"raise",
"MetaParsingException",
"(",
"\"Can't parse your JSON data: %s\"",
"%",
"e",
".",
"message",
")",
"decoded",
"=",
"validator",
".",
"check_structure",
"(",
"decoded",
")",
"return",
"decoded"
] |
Handles decoding of the JSON `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
|
[
"Handles",
"decoding",
"of",
"the",
"JSON",
"data",
"."
] |
fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71
|
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/decoders/parser_json.py#L49-L67
|
245,173
|
PyMLGame/pymlgame
|
pymlgame/__init__.py
|
init
|
def init(host='0.0.0.0', port=1338):
"""
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events.
:param host: Bind to this address
:param port: Bind to this port
:type host: str
:type port: int
"""
CONTROLLER.host = host
CONTROLLER.port = port
CONTROLLER.setDaemon(True) # because it's a deamon it will exit together with the main thread
CONTROLLER.start()
|
python
|
def init(host='0.0.0.0', port=1338):
"""
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events.
:param host: Bind to this address
:param port: Bind to this port
:type host: str
:type port: int
"""
CONTROLLER.host = host
CONTROLLER.port = port
CONTROLLER.setDaemon(True) # because it's a deamon it will exit together with the main thread
CONTROLLER.start()
|
[
"def",
"init",
"(",
"host",
"=",
"'0.0.0.0'",
",",
"port",
"=",
"1338",
")",
":",
"CONTROLLER",
".",
"host",
"=",
"host",
"CONTROLLER",
".",
"port",
"=",
"port",
"CONTROLLER",
".",
"setDaemon",
"(",
"True",
")",
"# because it's a deamon it will exit together with the main thread",
"CONTROLLER",
".",
"start",
"(",
")"
] |
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events.
:param host: Bind to this address
:param port: Bind to this port
:type host: str
:type port: int
|
[
"Initialize",
"PyMLGame",
".",
"This",
"creates",
"a",
"controller",
"thread",
"that",
"listens",
"for",
"game",
"controllers",
"and",
"events",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/__init__.py#L25-L37
|
245,174
|
PyMLGame/pymlgame
|
pymlgame/__init__.py
|
get_events
|
def get_events(maximum=10):
"""
Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
:param maximum: Maximum number of events
:type maximum: int
:return: List of events
:rtype: list
"""
events = []
for ev in range(0, maximum):
try:
if CONTROLLER.queue.empty():
break
else:
events.append(CONTROLLER.queue.get_nowait())
except NameError:
print('PyMLGame is not initialized correctly. Use pymlgame.init() first.')
events = False
break
return events
|
python
|
def get_events(maximum=10):
"""
Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
:param maximum: Maximum number of events
:type maximum: int
:return: List of events
:rtype: list
"""
events = []
for ev in range(0, maximum):
try:
if CONTROLLER.queue.empty():
break
else:
events.append(CONTROLLER.queue.get_nowait())
except NameError:
print('PyMLGame is not initialized correctly. Use pymlgame.init() first.')
events = False
break
return events
|
[
"def",
"get_events",
"(",
"maximum",
"=",
"10",
")",
":",
"events",
"=",
"[",
"]",
"for",
"ev",
"in",
"range",
"(",
"0",
",",
"maximum",
")",
":",
"try",
":",
"if",
"CONTROLLER",
".",
"queue",
".",
"empty",
"(",
")",
":",
"break",
"else",
":",
"events",
".",
"append",
"(",
"CONTROLLER",
".",
"queue",
".",
"get_nowait",
"(",
")",
")",
"except",
"NameError",
":",
"print",
"(",
"'PyMLGame is not initialized correctly. Use pymlgame.init() first.'",
")",
"events",
"=",
"False",
"break",
"return",
"events"
] |
Get all events since the last time you asked for them. You can define a maximum which is 10 by default.
:param maximum: Maximum number of events
:type maximum: int
:return: List of events
:rtype: list
|
[
"Get",
"all",
"events",
"since",
"the",
"last",
"time",
"you",
"asked",
"for",
"them",
".",
"You",
"can",
"define",
"a",
"maximum",
"which",
"is",
"10",
"by",
"default",
"."
] |
450fe77d35f9a26c107586d6954f69c3895bf504
|
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/__init__.py#L40-L60
|
245,175
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
clean_entry
|
def clean_entry(entry):
"""Consolidate some entry attributes and rename a few others.
Consolidate address attributes into a single field and replace some field
names with others as described in FIELD_TRANSFORM_INDEX.
@param entry: The entry attributes to update.
@type entry: dict
@return: Entry copy after running clean operations
@rtype: dict
"""
newEntry = {}
if 'Address1' in entry:
address = str(entry['Address1'])
if entry['Address2'] != '':
address = address + ' ' + str(entry['Address2'])
newEntry['address'] = address
del entry['Address1']
del entry['Address2']
for key in entry.keys():
if key != None:
if key in FIELD_TRANSFORM_INDEX:
newKey = FIELD_TRANSFORM_INDEX[key]
else:
newKey = key
newKey = newKey[:1].lower() + newKey[1:]
newEntry[newKey] = entry[key]
return newEntry
|
python
|
def clean_entry(entry):
"""Consolidate some entry attributes and rename a few others.
Consolidate address attributes into a single field and replace some field
names with others as described in FIELD_TRANSFORM_INDEX.
@param entry: The entry attributes to update.
@type entry: dict
@return: Entry copy after running clean operations
@rtype: dict
"""
newEntry = {}
if 'Address1' in entry:
address = str(entry['Address1'])
if entry['Address2'] != '':
address = address + ' ' + str(entry['Address2'])
newEntry['address'] = address
del entry['Address1']
del entry['Address2']
for key in entry.keys():
if key != None:
if key in FIELD_TRANSFORM_INDEX:
newKey = FIELD_TRANSFORM_INDEX[key]
else:
newKey = key
newKey = newKey[:1].lower() + newKey[1:]
newEntry[newKey] = entry[key]
return newEntry
|
[
"def",
"clean_entry",
"(",
"entry",
")",
":",
"newEntry",
"=",
"{",
"}",
"if",
"'Address1'",
"in",
"entry",
":",
"address",
"=",
"str",
"(",
"entry",
"[",
"'Address1'",
"]",
")",
"if",
"entry",
"[",
"'Address2'",
"]",
"!=",
"''",
":",
"address",
"=",
"address",
"+",
"' '",
"+",
"str",
"(",
"entry",
"[",
"'Address2'",
"]",
")",
"newEntry",
"[",
"'address'",
"]",
"=",
"address",
"del",
"entry",
"[",
"'Address1'",
"]",
"del",
"entry",
"[",
"'Address2'",
"]",
"for",
"key",
"in",
"entry",
".",
"keys",
"(",
")",
":",
"if",
"key",
"!=",
"None",
":",
"if",
"key",
"in",
"FIELD_TRANSFORM_INDEX",
":",
"newKey",
"=",
"FIELD_TRANSFORM_INDEX",
"[",
"key",
"]",
"else",
":",
"newKey",
"=",
"key",
"newKey",
"=",
"newKey",
"[",
":",
"1",
"]",
".",
"lower",
"(",
")",
"+",
"newKey",
"[",
"1",
":",
"]",
"newEntry",
"[",
"newKey",
"]",
"=",
"entry",
"[",
"key",
"]",
"return",
"newEntry"
] |
Consolidate some entry attributes and rename a few others.
Consolidate address attributes into a single field and replace some field
names with others as described in FIELD_TRANSFORM_INDEX.
@param entry: The entry attributes to update.
@type entry: dict
@return: Entry copy after running clean operations
@rtype: dict
|
[
"Consolidate",
"some",
"entry",
"attributes",
"and",
"rename",
"a",
"few",
"others",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L78-L111
|
245,176
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
update_expenditure_entry
|
def update_expenditure_entry(database, entry):
"""Update a record of a expenditure report in the provided database.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
"""
entry = clean_entry(entry)
database.expenditures.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=True
)
|
python
|
def update_expenditure_entry(database, entry):
"""Update a record of a expenditure report in the provided database.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
"""
entry = clean_entry(entry)
database.expenditures.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=True
)
|
[
"def",
"update_expenditure_entry",
"(",
"database",
",",
"entry",
")",
":",
"entry",
"=",
"clean_entry",
"(",
"entry",
")",
"database",
".",
"expenditures",
".",
"update",
"(",
"{",
"'recordID'",
":",
"entry",
"[",
"'recordID'",
"]",
"}",
",",
"{",
"'$set'",
":",
"entry",
"}",
",",
"upsert",
"=",
"True",
")"
] |
Update a record of a expenditure report in the provided database.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
|
[
"Update",
"a",
"record",
"of",
"a",
"expenditure",
"report",
"in",
"the",
"provided",
"database",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L132-L147
|
245,177
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
update_loan_entry
|
def update_loan_entry(database, entry):
"""Update a record of a loan report in the provided database.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
"""
entry = clean_entry(entry)
database.loans.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=True
)
|
python
|
def update_loan_entry(database, entry):
"""Update a record of a loan report in the provided database.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
"""
entry = clean_entry(entry)
database.loans.update(
{'recordID': entry['recordID']},
{'$set': entry},
upsert=True
)
|
[
"def",
"update_loan_entry",
"(",
"database",
",",
"entry",
")",
":",
"entry",
"=",
"clean_entry",
"(",
"entry",
")",
"database",
".",
"loans",
".",
"update",
"(",
"{",
"'recordID'",
":",
"entry",
"[",
"'recordID'",
"]",
"}",
",",
"{",
"'$set'",
":",
"entry",
"}",
",",
"upsert",
"=",
"True",
")"
] |
Update a record of a loan report in the provided database.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entry: The entry to insert into the database, updating the entry with
the same recordID if one exists.
@type entry: dict
|
[
"Update",
"a",
"record",
"of",
"a",
"loan",
"report",
"in",
"the",
"provided",
"database",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L150-L165
|
245,178
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
insert_contribution_entries
|
def insert_contribution_entries(database, entries):
"""Insert a set of records of a contribution report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param database: The MongoDB database to operate on. The contributions
collection will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.contributions.insert(entries, continue_on_error=True)
|
python
|
def insert_contribution_entries(database, entries):
"""Insert a set of records of a contribution report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param database: The MongoDB database to operate on. The contributions
collection will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.contributions.insert(entries, continue_on_error=True)
|
[
"def",
"insert_contribution_entries",
"(",
"database",
",",
"entries",
")",
":",
"entries",
"=",
"map",
"(",
"clean_entry",
",",
"entries",
")",
"database",
".",
"contributions",
".",
"insert",
"(",
"entries",
",",
"continue_on_error",
"=",
"True",
")"
] |
Insert a set of records of a contribution report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param database: The MongoDB database to operate on. The contributions
collection will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
|
[
"Insert",
"a",
"set",
"of",
"records",
"of",
"a",
"contribution",
"report",
"in",
"the",
"provided",
"database",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L168-L181
|
245,179
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
insert_expenditure_entries
|
def insert_expenditure_entries(database, entries):
"""Insert a set of records of a expenditure report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.expenditures.insert(entries, continue_on_error=True)
|
python
|
def insert_expenditure_entries(database, entries):
"""Insert a set of records of a expenditure report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.expenditures.insert(entries, continue_on_error=True)
|
[
"def",
"insert_expenditure_entries",
"(",
"database",
",",
"entries",
")",
":",
"entries",
"=",
"map",
"(",
"clean_entry",
",",
"entries",
")",
"database",
".",
"expenditures",
".",
"insert",
"(",
"entries",
",",
"continue_on_error",
"=",
"True",
")"
] |
Insert a set of records of a expenditure report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The expenditures collection
will be used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
|
[
"Insert",
"a",
"set",
"of",
"records",
"of",
"a",
"expenditure",
"report",
"in",
"the",
"provided",
"database",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L184-L197
|
245,180
|
sampottinger/pycotracer
|
pycotracer/mongo_aggregator.py
|
insert_loan_entries
|
def insert_loan_entries(database, entries):
"""Insert a set of records of a loan report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.loans.insert(entries, continue_on_error=True)
|
python
|
def insert_loan_entries(database, entries):
"""Insert a set of records of a loan report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
"""
entries = map(clean_entry, entries)
database.loans.insert(entries, continue_on_error=True)
|
[
"def",
"insert_loan_entries",
"(",
"database",
",",
"entries",
")",
":",
"entries",
"=",
"map",
"(",
"clean_entry",
",",
"entries",
")",
"database",
".",
"loans",
".",
"insert",
"(",
"entries",
",",
"continue_on_error",
"=",
"True",
")"
] |
Insert a set of records of a loan report in the provided database.
Insert a set of new records into the provided database without checking
for conflicting entries.
@param db: The MongoDB database to operate on. The loans collection will be
used from this database.
@type db: pymongo.database.Database
@param entries: The entries to insert into the database.
@type entries: dict
|
[
"Insert",
"a",
"set",
"of",
"records",
"of",
"a",
"loan",
"report",
"in",
"the",
"provided",
"database",
"."
] |
c66c3230949b7bee8c9fec5fc00ab392865a0c8b
|
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L200-L213
|
245,181
|
emory-libraries/eulcommon
|
eulcommon/searchutil/templatetags/search_utils.py
|
pagination_links
|
def pagination_links(paginator_page, show_pages, url_params=None,
first_page_label=None, last_page_label=None,
page_url=''):
'''Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class:`~django.core.paginator.Page` of a
:class:`~django.core.paginator.Paginator` object
* a dictionary of the pages to be displayed, in the format
generated by :meth:`eulcommon.searchutil.pages_to_show`
* optional url params to include in pagination link (e.g., search
terms when paginating search results)
* optional first page label (only used when first page is not in
list of pages to be shown)
* optional last page label (only used when last page is not in
list of pages to be shown)
* optional url to use for page links (only needed when the url is
different from the current one)
Example use::
{% load search_utils %}
{% pagination_links paged_items show_pages %}
'''
return {
'items': paginator_page,
'show_pages': show_pages,
'url_params': url_params,
'first_page_label': first_page_label,
'last_page_label': last_page_label,
'page_url': page_url,
}
|
python
|
def pagination_links(paginator_page, show_pages, url_params=None,
first_page_label=None, last_page_label=None,
page_url=''):
'''Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class:`~django.core.paginator.Page` of a
:class:`~django.core.paginator.Paginator` object
* a dictionary of the pages to be displayed, in the format
generated by :meth:`eulcommon.searchutil.pages_to_show`
* optional url params to include in pagination link (e.g., search
terms when paginating search results)
* optional first page label (only used when first page is not in
list of pages to be shown)
* optional last page label (only used when last page is not in
list of pages to be shown)
* optional url to use for page links (only needed when the url is
different from the current one)
Example use::
{% load search_utils %}
{% pagination_links paged_items show_pages %}
'''
return {
'items': paginator_page,
'show_pages': show_pages,
'url_params': url_params,
'first_page_label': first_page_label,
'last_page_label': last_page_label,
'page_url': page_url,
}
|
[
"def",
"pagination_links",
"(",
"paginator_page",
",",
"show_pages",
",",
"url_params",
"=",
"None",
",",
"first_page_label",
"=",
"None",
",",
"last_page_label",
"=",
"None",
",",
"page_url",
"=",
"''",
")",
":",
"return",
"{",
"'items'",
":",
"paginator_page",
",",
"'show_pages'",
":",
"show_pages",
",",
"'url_params'",
":",
"url_params",
",",
"'first_page_label'",
":",
"first_page_label",
",",
"'last_page_label'",
":",
"last_page_label",
",",
"'page_url'",
":",
"page_url",
",",
"}"
] |
Django template tag to display pagination links for a paginated
list of items.
Expects the following variables:
* the current :class:`~django.core.paginator.Page` of a
:class:`~django.core.paginator.Paginator` object
* a dictionary of the pages to be displayed, in the format
generated by :meth:`eulcommon.searchutil.pages_to_show`
* optional url params to include in pagination link (e.g., search
terms when paginating search results)
* optional first page label (only used when first page is not in
list of pages to be shown)
* optional last page label (only used when last page is not in
list of pages to be shown)
* optional url to use for page links (only needed when the url is
different from the current one)
Example use::
{% load search_utils %}
{% pagination_links paged_items show_pages %}
|
[
"Django",
"template",
"tag",
"to",
"display",
"pagination",
"links",
"for",
"a",
"paginated",
"list",
"of",
"items",
"."
] |
dc63a9b3b5e38205178235e0d716d1b28158d3a9
|
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/searchutil/templatetags/search_utils.py#L6-L40
|
245,182
|
praekelt/panya
|
panya/__init__.py
|
modify_classes
|
def modify_classes():
"""
Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when
not present. This forces an import on them to modify any classes they
may want.
"""
import copy
from django.conf import settings
from django.contrib.admin.sites import site
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's class_modifier module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.class_modifiers' % app)
except:
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an class_modifier module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'class_modifiers'):
raise
|
python
|
def modify_classes():
"""
Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when
not present. This forces an import on them to modify any classes they
may want.
"""
import copy
from django.conf import settings
from django.contrib.admin.sites import site
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's class_modifier module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.class_modifiers' % app)
except:
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an class_modifier module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'class_modifiers'):
raise
|
[
"def",
"modify_classes",
"(",
")",
":",
"import",
"copy",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"sites",
"import",
"site",
"from",
"django",
".",
"utils",
".",
"importlib",
"import",
"import_module",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"module_has_submodule",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"mod",
"=",
"import_module",
"(",
"app",
")",
"# Attempt to import the app's class_modifier module.",
"try",
":",
"before_import_registry",
"=",
"copy",
".",
"copy",
"(",
"site",
".",
"_registry",
")",
"import_module",
"(",
"'%s.class_modifiers'",
"%",
"app",
")",
"except",
":",
"site",
".",
"_registry",
"=",
"before_import_registry",
"# Decide whether to bubble up this error. If the app just",
"# doesn't have an class_modifier module, we can ignore the error",
"# attempting to import it, otherwise we want it to bubble up.",
"if",
"module_has_submodule",
"(",
"mod",
",",
"'class_modifiers'",
")",
":",
"raise"
] |
Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when
not present. This forces an import on them to modify any classes they
may want.
|
[
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"class_modifiers",
".",
"py",
"modules",
"and",
"fail",
"silently",
"when",
"not",
"present",
".",
"This",
"forces",
"an",
"import",
"on",
"them",
"to",
"modify",
"any",
"classes",
"they",
"may",
"want",
"."
] |
0fd621e15a7c11a2716a9554a2f820d6259818e5
|
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/__init__.py#L1-L25
|
245,183
|
ch3pjw/junction
|
jcn/textwrap.py
|
TextWrapper.wrap
|
def wrap(self, text):
'''Wraps the text object to width, breaking at whitespaces. Runs of
whitespace characters are preserved, provided they do not fall at a
line boundary. The implementation is based on that of textwrap from the
standard library, but we can cope with StringWithFormatting objects.
:returns: a list of string-like objects.
'''
result = []
chunks = self._chunk(text)
while chunks:
self._lstrip(chunks)
current_line = []
current_line_length = 0
current_chunk_length = 0
while chunks:
current_chunk_length = len(chunks[0])
if current_line_length + current_chunk_length <= self.width:
current_line.append(chunks.pop(0))
current_line_length += current_chunk_length
else:
# Line is full
break
# Handle case where chunk is bigger than an entire line
if current_chunk_length > self.width:
space_left = self.width - current_line_length
current_line.append(chunks[0][:space_left])
chunks[0] = chunks[0][space_left:]
self._rstrip(current_line)
if current_line:
result.append(reduce(
lambda x, y: x + y, current_line[1:], current_line[0]))
else:
# FIXME: should this line go? Removing it makes at least simple
# cases like wrap(' ', 10) actually behave like
# textwrap.wrap...
result.append('')
return result
|
python
|
def wrap(self, text):
'''Wraps the text object to width, breaking at whitespaces. Runs of
whitespace characters are preserved, provided they do not fall at a
line boundary. The implementation is based on that of textwrap from the
standard library, but we can cope with StringWithFormatting objects.
:returns: a list of string-like objects.
'''
result = []
chunks = self._chunk(text)
while chunks:
self._lstrip(chunks)
current_line = []
current_line_length = 0
current_chunk_length = 0
while chunks:
current_chunk_length = len(chunks[0])
if current_line_length + current_chunk_length <= self.width:
current_line.append(chunks.pop(0))
current_line_length += current_chunk_length
else:
# Line is full
break
# Handle case where chunk is bigger than an entire line
if current_chunk_length > self.width:
space_left = self.width - current_line_length
current_line.append(chunks[0][:space_left])
chunks[0] = chunks[0][space_left:]
self._rstrip(current_line)
if current_line:
result.append(reduce(
lambda x, y: x + y, current_line[1:], current_line[0]))
else:
# FIXME: should this line go? Removing it makes at least simple
# cases like wrap(' ', 10) actually behave like
# textwrap.wrap...
result.append('')
return result
|
[
"def",
"wrap",
"(",
"self",
",",
"text",
")",
":",
"result",
"=",
"[",
"]",
"chunks",
"=",
"self",
".",
"_chunk",
"(",
"text",
")",
"while",
"chunks",
":",
"self",
".",
"_lstrip",
"(",
"chunks",
")",
"current_line",
"=",
"[",
"]",
"current_line_length",
"=",
"0",
"current_chunk_length",
"=",
"0",
"while",
"chunks",
":",
"current_chunk_length",
"=",
"len",
"(",
"chunks",
"[",
"0",
"]",
")",
"if",
"current_line_length",
"+",
"current_chunk_length",
"<=",
"self",
".",
"width",
":",
"current_line",
".",
"append",
"(",
"chunks",
".",
"pop",
"(",
"0",
")",
")",
"current_line_length",
"+=",
"current_chunk_length",
"else",
":",
"# Line is full",
"break",
"# Handle case where chunk is bigger than an entire line",
"if",
"current_chunk_length",
">",
"self",
".",
"width",
":",
"space_left",
"=",
"self",
".",
"width",
"-",
"current_line_length",
"current_line",
".",
"append",
"(",
"chunks",
"[",
"0",
"]",
"[",
":",
"space_left",
"]",
")",
"chunks",
"[",
"0",
"]",
"=",
"chunks",
"[",
"0",
"]",
"[",
"space_left",
":",
"]",
"self",
".",
"_rstrip",
"(",
"current_line",
")",
"if",
"current_line",
":",
"result",
".",
"append",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"+",
"y",
",",
"current_line",
"[",
"1",
":",
"]",
",",
"current_line",
"[",
"0",
"]",
")",
")",
"else",
":",
"# FIXME: should this line go? Removing it makes at least simple",
"# cases like wrap(' ', 10) actually behave like",
"# textwrap.wrap...",
"result",
".",
"append",
"(",
"''",
")",
"return",
"result"
] |
Wraps the text object to width, breaking at whitespaces. Runs of
whitespace characters are preserved, provided they do not fall at a
line boundary. The implementation is based on that of textwrap from the
standard library, but we can cope with StringWithFormatting objects.
:returns: a list of string-like objects.
|
[
"Wraps",
"the",
"text",
"object",
"to",
"width",
"breaking",
"at",
"whitespaces",
".",
"Runs",
"of",
"whitespace",
"characters",
"are",
"preserved",
"provided",
"they",
"do",
"not",
"fall",
"at",
"a",
"line",
"boundary",
".",
"The",
"implementation",
"is",
"based",
"on",
"that",
"of",
"textwrap",
"from",
"the",
"standard",
"library",
"but",
"we",
"can",
"cope",
"with",
"StringWithFormatting",
"objects",
"."
] |
7d0c4d279589bee8ae7b3ac4dee2ab425c0b1b0e
|
https://github.com/ch3pjw/junction/blob/7d0c4d279589bee8ae7b3ac4dee2ab425c0b1b0e/jcn/textwrap.py#L58-L95
|
245,184
|
Othernet-Project/chainable-validators
|
validators/chain.py
|
chainable
|
def chainable(fn):
""" Make function a chainable validator
The returned function is a chainable validator factory which takes the next
function in the chain and returns a chained version of the original
validator: ``fn(next(value))``.
The chainable validators are used with the ``make_chain()`` function.
"""
@functools.wraps(fn)
def wrapper(nxt=lambda x: x):
if hasattr(nxt, '__call__'):
return lambda x: nxt(fn(x))
# Value has been passsed directly, so we don't chain
return fn(nxt)
return wrapper
|
python
|
def chainable(fn):
""" Make function a chainable validator
The returned function is a chainable validator factory which takes the next
function in the chain and returns a chained version of the original
validator: ``fn(next(value))``.
The chainable validators are used with the ``make_chain()`` function.
"""
@functools.wraps(fn)
def wrapper(nxt=lambda x: x):
if hasattr(nxt, '__call__'):
return lambda x: nxt(fn(x))
# Value has been passsed directly, so we don't chain
return fn(nxt)
return wrapper
|
[
"def",
"chainable",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"nxt",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"if",
"hasattr",
"(",
"nxt",
",",
"'__call__'",
")",
":",
"return",
"lambda",
"x",
":",
"nxt",
"(",
"fn",
"(",
"x",
")",
")",
"# Value has been passsed directly, so we don't chain",
"return",
"fn",
"(",
"nxt",
")",
"return",
"wrapper"
] |
Make function a chainable validator
The returned function is a chainable validator factory which takes the next
function in the chain and returns a chained version of the original
validator: ``fn(next(value))``.
The chainable validators are used with the ``make_chain()`` function.
|
[
"Make",
"function",
"a",
"chainable",
"validator"
] |
8c0afebfaaa131440ffb2a960b9b38978f00d88f
|
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/chain.py#L19-L34
|
245,185
|
Othernet-Project/chainable-validators
|
validators/chain.py
|
make_chain
|
def make_chain(fns):
""" Take a list of chainable validators and return a chained validator
The functions should be decorated with ``chainable`` decorator.
Any exceptions raised by any of the validators are propagated except for
``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception
is trapped, the original value passed to the chained validator is returned
as is.
"""
chain = lambda x: x
for fn in reversed(fns):
chain = fn(chain)
def validator(v):
try:
return chain(v)
except ReturnEarly:
return v
return validator
|
python
|
def make_chain(fns):
""" Take a list of chainable validators and return a chained validator
The functions should be decorated with ``chainable`` decorator.
Any exceptions raised by any of the validators are propagated except for
``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception
is trapped, the original value passed to the chained validator is returned
as is.
"""
chain = lambda x: x
for fn in reversed(fns):
chain = fn(chain)
def validator(v):
try:
return chain(v)
except ReturnEarly:
return v
return validator
|
[
"def",
"make_chain",
"(",
"fns",
")",
":",
"chain",
"=",
"lambda",
"x",
":",
"x",
"for",
"fn",
"in",
"reversed",
"(",
"fns",
")",
":",
"chain",
"=",
"fn",
"(",
"chain",
")",
"def",
"validator",
"(",
"v",
")",
":",
"try",
":",
"return",
"chain",
"(",
"v",
")",
"except",
"ReturnEarly",
":",
"return",
"v",
"return",
"validator"
] |
Take a list of chainable validators and return a chained validator
The functions should be decorated with ``chainable`` decorator.
Any exceptions raised by any of the validators are propagated except for
``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception
is trapped, the original value passed to the chained validator is returned
as is.
|
[
"Take",
"a",
"list",
"of",
"chainable",
"validators",
"and",
"return",
"a",
"chained",
"validator"
] |
8c0afebfaaa131440ffb2a960b9b38978f00d88f
|
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/chain.py#L37-L57
|
245,186
|
pip-services3-python/pip-services3-components-python
|
pip_services3_components/build/Factory.py
|
Factory.register
|
def register(self, locator, factory):
"""
Registers a component using a factory method.
:param locator: a locator to identify component to be created.
:param factory: a factory function that receives a locator and returns a created component.
"""
if locator == None:
raise Exception("Locator cannot be null")
if factory == None:
raise Exception("Factory cannot be null")
self._registrations.append(Registration(locator, factory))
|
python
|
def register(self, locator, factory):
"""
Registers a component using a factory method.
:param locator: a locator to identify component to be created.
:param factory: a factory function that receives a locator and returns a created component.
"""
if locator == None:
raise Exception("Locator cannot be null")
if factory == None:
raise Exception("Factory cannot be null")
self._registrations.append(Registration(locator, factory))
|
[
"def",
"register",
"(",
"self",
",",
"locator",
",",
"factory",
")",
":",
"if",
"locator",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Locator cannot be null\"",
")",
"if",
"factory",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Factory cannot be null\"",
")",
"self",
".",
"_registrations",
".",
"append",
"(",
"Registration",
"(",
"locator",
",",
"factory",
")",
")"
] |
Registers a component using a factory method.
:param locator: a locator to identify component to be created.
:param factory: a factory function that receives a locator and returns a created component.
|
[
"Registers",
"a",
"component",
"using",
"a",
"factory",
"method",
"."
] |
1de9c1bb544cf1891111e9a5f5d67653f62c9b52
|
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/build/Factory.py#L37-L50
|
245,187
|
pip-services3-python/pip-services3-components-python
|
pip_services3_components/build/Factory.py
|
Factory.create
|
def create(self, locator):
"""
Creates a component identified by given locator.
:param locator: a locator to identify component to be created.
:return: the created component.
"""
for registration in self._registrations:
this_locator = registration.locator
if this_locator == locator:
try:
return registration.factory(locator)
except Exception as ex:
if isinstance(ex, CreateException):
raise ex
raise CreateException(
None,
"Failed to create object for " + str(locator)
).with_cause(ex)
|
python
|
def create(self, locator):
"""
Creates a component identified by given locator.
:param locator: a locator to identify component to be created.
:return: the created component.
"""
for registration in self._registrations:
this_locator = registration.locator
if this_locator == locator:
try:
return registration.factory(locator)
except Exception as ex:
if isinstance(ex, CreateException):
raise ex
raise CreateException(
None,
"Failed to create object for " + str(locator)
).with_cause(ex)
|
[
"def",
"create",
"(",
"self",
",",
"locator",
")",
":",
"for",
"registration",
"in",
"self",
".",
"_registrations",
":",
"this_locator",
"=",
"registration",
".",
"locator",
"if",
"this_locator",
"==",
"locator",
":",
"try",
":",
"return",
"registration",
".",
"factory",
"(",
"locator",
")",
"except",
"Exception",
"as",
"ex",
":",
"if",
"isinstance",
"(",
"ex",
",",
"CreateException",
")",
":",
"raise",
"ex",
"raise",
"CreateException",
"(",
"None",
",",
"\"Failed to create object for \"",
"+",
"str",
"(",
"locator",
")",
")",
".",
"with_cause",
"(",
"ex",
")"
] |
Creates a component identified by given locator.
:param locator: a locator to identify component to be created.
:return: the created component.
|
[
"Creates",
"a",
"component",
"identified",
"by",
"given",
"locator",
"."
] |
1de9c1bb544cf1891111e9a5f5d67653f62c9b52
|
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/build/Factory.py#L88-L109
|
245,188
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.update
|
def update(self, catalog=None, dependencies=None, allow_overwrite=False):
'''
Convenience method to update this Di instance with the specified contents.
:param catalog: ICatalog supporting class or mapping
:type catalog: ICatalog or collections.Mapping
:param dependencies: Mapping of dependencies
:type dependencies: collections.Mapping
:param allow_overwrite: If True, allow overwriting existing keys. Only applies to providers.
:type allow_overwrite: bool
'''
if catalog:
self._providers.update(catalog, allow_overwrite=allow_overwrite)
if dependencies:
self._dependencies.update(dependencies)
|
python
|
def update(self, catalog=None, dependencies=None, allow_overwrite=False):
'''
Convenience method to update this Di instance with the specified contents.
:param catalog: ICatalog supporting class or mapping
:type catalog: ICatalog or collections.Mapping
:param dependencies: Mapping of dependencies
:type dependencies: collections.Mapping
:param allow_overwrite: If True, allow overwriting existing keys. Only applies to providers.
:type allow_overwrite: bool
'''
if catalog:
self._providers.update(catalog, allow_overwrite=allow_overwrite)
if dependencies:
self._dependencies.update(dependencies)
|
[
"def",
"update",
"(",
"self",
",",
"catalog",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"catalog",
":",
"self",
".",
"_providers",
".",
"update",
"(",
"catalog",
",",
"allow_overwrite",
"=",
"allow_overwrite",
")",
"if",
"dependencies",
":",
"self",
".",
"_dependencies",
".",
"update",
"(",
"dependencies",
")"
] |
Convenience method to update this Di instance with the specified contents.
:param catalog: ICatalog supporting class or mapping
:type catalog: ICatalog or collections.Mapping
:param dependencies: Mapping of dependencies
:type dependencies: collections.Mapping
:param allow_overwrite: If True, allow overwriting existing keys. Only applies to providers.
:type allow_overwrite: bool
|
[
"Convenience",
"method",
"to",
"update",
"this",
"Di",
"instance",
"with",
"the",
"specified",
"contents",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L47-L61
|
245,189
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.get_missing_deps
|
def get_missing_deps(self, obj):
'''
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
'''
deps = self.get_deps(obj)
ret = []
for key in deps:
provider = self._providers.get(key)
if provider and provider.providable:
continue
ret.append(key)
return ret
|
python
|
def get_missing_deps(self, obj):
'''
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
'''
deps = self.get_deps(obj)
ret = []
for key in deps:
provider = self._providers.get(key)
if provider and provider.providable:
continue
ret.append(key)
return ret
|
[
"def",
"get_missing_deps",
"(",
"self",
",",
"obj",
")",
":",
"deps",
"=",
"self",
".",
"get_deps",
"(",
"obj",
")",
"ret",
"=",
"[",
"]",
"for",
"key",
"in",
"deps",
":",
"provider",
"=",
"self",
".",
"_providers",
".",
"get",
"(",
"key",
")",
"if",
"provider",
"and",
"provider",
".",
"providable",
":",
"continue",
"ret",
".",
"append",
"(",
"key",
")",
"return",
"ret"
] |
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
|
[
"Returns",
"missing",
"dependencies",
"for",
"provider",
"key",
".",
"Missing",
"meaning",
"no",
"instance",
"can",
"be",
"provided",
"at",
"this",
"time",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L74-L91
|
245,190
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.iresolve
|
def iresolve(self, *keys):
'''
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
'''
for key in keys:
missing = self.get_missing_deps(key)
if missing:
raise UnresolvableError("Missing dependencies for %s: %s" % (key, missing))
provider = self._providers.get(key)
if not provider:
raise UnresolvableError("Provider does not exist for %s" % key)
yield provider()
|
python
|
def iresolve(self, *keys):
'''
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
'''
for key in keys:
missing = self.get_missing_deps(key)
if missing:
raise UnresolvableError("Missing dependencies for %s: %s" % (key, missing))
provider = self._providers.get(key)
if not provider:
raise UnresolvableError("Provider does not exist for %s" % key)
yield provider()
|
[
"def",
"iresolve",
"(",
"self",
",",
"*",
"keys",
")",
":",
"for",
"key",
"in",
"keys",
":",
"missing",
"=",
"self",
".",
"get_missing_deps",
"(",
"key",
")",
"if",
"missing",
":",
"raise",
"UnresolvableError",
"(",
"\"Missing dependencies for %s: %s\"",
"%",
"(",
"key",
",",
"missing",
")",
")",
"provider",
"=",
"self",
".",
"_providers",
".",
"get",
"(",
"key",
")",
"if",
"not",
"provider",
":",
"raise",
"UnresolvableError",
"(",
"\"Provider does not exist for %s\"",
"%",
"key",
")",
"yield",
"provider",
"(",
")"
] |
Iterates over resolved instances for given provider keys.
:param keys: Provider keys
:type keys: tuple
:return: Iterator of resolved instances
:rtype: generator
|
[
"Iterates",
"over",
"resolved",
"instances",
"for",
"given",
"provider",
"keys",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L93-L111
|
245,191
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.resolve
|
def resolve(self, *keys):
'''
Returns resolved instances for given provider keys.
If only one positional argument is given, only one is returned.
:param keys: Provider keys
:type keys: tuple
:return: Resolved instance(s); if only one key given, otherwise list of them.
:rtype: object or list
'''
instances = list(self.iresolve(*keys))
if len(keys) == 1:
return instances[0]
return instances
|
python
|
def resolve(self, *keys):
'''
Returns resolved instances for given provider keys.
If only one positional argument is given, only one is returned.
:param keys: Provider keys
:type keys: tuple
:return: Resolved instance(s); if only one key given, otherwise list of them.
:rtype: object or list
'''
instances = list(self.iresolve(*keys))
if len(keys) == 1:
return instances[0]
return instances
|
[
"def",
"resolve",
"(",
"self",
",",
"*",
"keys",
")",
":",
"instances",
"=",
"list",
"(",
"self",
".",
"iresolve",
"(",
"*",
"keys",
")",
")",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"return",
"instances",
"[",
"0",
"]",
"return",
"instances"
] |
Returns resolved instances for given provider keys.
If only one positional argument is given, only one is returned.
:param keys: Provider keys
:type keys: tuple
:return: Resolved instance(s); if only one key given, otherwise list of them.
:rtype: object or list
|
[
"Returns",
"resolved",
"instances",
"for",
"given",
"provider",
"keys",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L113-L127
|
245,192
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.resolve_deps
|
def resolve_deps(self, obj):
'''
Returns list of resolved dependencies for given obj.
:param obj: Object to lookup dependencies for
:type obj: object
:return: Resolved dependencies
:rtype: list
'''
deps = self.get_deps(obj)
return list(self.iresolve(*deps))
|
python
|
def resolve_deps(self, obj):
'''
Returns list of resolved dependencies for given obj.
:param obj: Object to lookup dependencies for
:type obj: object
:return: Resolved dependencies
:rtype: list
'''
deps = self.get_deps(obj)
return list(self.iresolve(*deps))
|
[
"def",
"resolve_deps",
"(",
"self",
",",
"obj",
")",
":",
"deps",
"=",
"self",
".",
"get_deps",
"(",
"obj",
")",
"return",
"list",
"(",
"self",
".",
"iresolve",
"(",
"*",
"deps",
")",
")"
] |
Returns list of resolved dependencies for given obj.
:param obj: Object to lookup dependencies for
:type obj: object
:return: Resolved dependencies
:rtype: list
|
[
"Returns",
"list",
"of",
"resolved",
"dependencies",
"for",
"given",
"obj",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L129-L139
|
245,193
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.register_factory
|
def register_factory(self, key, factory=_sentinel, scope=NoneScope, allow_overwrite=False):
'''
Creates and registers a provider using the given key, factory, and scope.
Can also be used as a decorator.
:param key: Provider key
:type key: object
:param factory: Factory callable
:type factory: callable
:param scope: Scope key, factory, or instance
:type scope: object or callable
:return: Factory (or None if we're creating a provider without a factory)
:rtype: callable or None
'''
if factory is _sentinel:
return functools.partial(self.register_factory, key, scope=scope, allow_overwrite=allow_overwrite)
if not allow_overwrite and key in self._providers:
raise KeyError("Key %s already exists" % key)
provider = self.provider(factory, scope)
self._providers[key] = provider
return factory
|
python
|
def register_factory(self, key, factory=_sentinel, scope=NoneScope, allow_overwrite=False):
'''
Creates and registers a provider using the given key, factory, and scope.
Can also be used as a decorator.
:param key: Provider key
:type key: object
:param factory: Factory callable
:type factory: callable
:param scope: Scope key, factory, or instance
:type scope: object or callable
:return: Factory (or None if we're creating a provider without a factory)
:rtype: callable or None
'''
if factory is _sentinel:
return functools.partial(self.register_factory, key, scope=scope, allow_overwrite=allow_overwrite)
if not allow_overwrite and key in self._providers:
raise KeyError("Key %s already exists" % key)
provider = self.provider(factory, scope)
self._providers[key] = provider
return factory
|
[
"def",
"register_factory",
"(",
"self",
",",
"key",
",",
"factory",
"=",
"_sentinel",
",",
"scope",
"=",
"NoneScope",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"factory",
"is",
"_sentinel",
":",
"return",
"functools",
".",
"partial",
"(",
"self",
".",
"register_factory",
",",
"key",
",",
"scope",
"=",
"scope",
",",
"allow_overwrite",
"=",
"allow_overwrite",
")",
"if",
"not",
"allow_overwrite",
"and",
"key",
"in",
"self",
".",
"_providers",
":",
"raise",
"KeyError",
"(",
"\"Key %s already exists\"",
"%",
"key",
")",
"provider",
"=",
"self",
".",
"provider",
"(",
"factory",
",",
"scope",
")",
"self",
".",
"_providers",
"[",
"key",
"]",
"=",
"provider",
"return",
"factory"
] |
Creates and registers a provider using the given key, factory, and scope.
Can also be used as a decorator.
:param key: Provider key
:type key: object
:param factory: Factory callable
:type factory: callable
:param scope: Scope key, factory, or instance
:type scope: object or callable
:return: Factory (or None if we're creating a provider without a factory)
:rtype: callable or None
|
[
"Creates",
"and",
"registers",
"a",
"provider",
"using",
"the",
"given",
"key",
"factory",
"and",
"scope",
".",
"Can",
"also",
"be",
"used",
"as",
"a",
"decorator",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L141-L161
|
245,194
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.set_instance
|
def set_instance(self, key, instance, default_scope=GlobalScope):
'''
Sets instance under specified provider key. If a provider for specified key does not exist, one is created
without a factory using the given scope.
:param key: Provider key
:type key: object
:param instance: Instance
:type instance: object
:param default_scope: Scope key, factory, or instance
:type default_scope: object or callable
'''
if key not in self._providers:
# We don't know how to create this kind of instance at this time, so add it without a factory.
factory = None
self.register_factory(key, factory, default_scope)
self._providers[key].set_instance(instance)
|
python
|
def set_instance(self, key, instance, default_scope=GlobalScope):
'''
Sets instance under specified provider key. If a provider for specified key does not exist, one is created
without a factory using the given scope.
:param key: Provider key
:type key: object
:param instance: Instance
:type instance: object
:param default_scope: Scope key, factory, or instance
:type default_scope: object or callable
'''
if key not in self._providers:
# We don't know how to create this kind of instance at this time, so add it without a factory.
factory = None
self.register_factory(key, factory, default_scope)
self._providers[key].set_instance(instance)
|
[
"def",
"set_instance",
"(",
"self",
",",
"key",
",",
"instance",
",",
"default_scope",
"=",
"GlobalScope",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_providers",
":",
"# We don't know how to create this kind of instance at this time, so add it without a factory.",
"factory",
"=",
"None",
"self",
".",
"register_factory",
"(",
"key",
",",
"factory",
",",
"default_scope",
")",
"self",
".",
"_providers",
"[",
"key",
"]",
".",
"set_instance",
"(",
"instance",
")"
] |
Sets instance under specified provider key. If a provider for specified key does not exist, one is created
without a factory using the given scope.
:param key: Provider key
:type key: object
:param instance: Instance
:type instance: object
:param default_scope: Scope key, factory, or instance
:type default_scope: object or callable
|
[
"Sets",
"instance",
"under",
"specified",
"provider",
"key",
".",
"If",
"a",
"provider",
"for",
"specified",
"key",
"does",
"not",
"exist",
"one",
"is",
"created",
"without",
"a",
"factory",
"using",
"the",
"given",
"scope",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L165-L181
|
245,195
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.depends_on
|
def depends_on(self, *keys):
'''
Decorator that marks the wrapped as depending on specified provider keys.
:param keys: Provider keys to mark as dependencies for wrapped
:type keys: tuple
:return: decorator
:rtype: decorator
'''
def decorator(wrapped):
if keys:
if wrapped not in self._dependencies:
self._dependencies[wrapped] = set()
self._dependencies[wrapped].update(keys)
return wrapped
return decorator
|
python
|
def depends_on(self, *keys):
'''
Decorator that marks the wrapped as depending on specified provider keys.
:param keys: Provider keys to mark as dependencies for wrapped
:type keys: tuple
:return: decorator
:rtype: decorator
'''
def decorator(wrapped):
if keys:
if wrapped not in self._dependencies:
self._dependencies[wrapped] = set()
self._dependencies[wrapped].update(keys)
return wrapped
return decorator
|
[
"def",
"depends_on",
"(",
"self",
",",
"*",
"keys",
")",
":",
"def",
"decorator",
"(",
"wrapped",
")",
":",
"if",
"keys",
":",
"if",
"wrapped",
"not",
"in",
"self",
".",
"_dependencies",
":",
"self",
".",
"_dependencies",
"[",
"wrapped",
"]",
"=",
"set",
"(",
")",
"self",
".",
"_dependencies",
"[",
"wrapped",
"]",
".",
"update",
"(",
"keys",
")",
"return",
"wrapped",
"return",
"decorator"
] |
Decorator that marks the wrapped as depending on specified provider keys.
:param keys: Provider keys to mark as dependencies for wrapped
:type keys: tuple
:return: decorator
:rtype: decorator
|
[
"Decorator",
"that",
"marks",
"the",
"wrapped",
"as",
"depending",
"on",
"specified",
"provider",
"keys",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L183-L200
|
245,196
|
akatrevorjay/mainline
|
mainline/di.py
|
Di.inject_classproperty
|
def inject_classproperty(self, key, name=None, replace_on_access=False):
'''
Decorator that injects the specified key as a classproperty.
If replace_on_access is True, then it replaces itself with the instance on first lookup.
:param key: Provider key
:type key: object
:param name: Name of classproperty, defaults to key
:type name: str
:param replace_on_access: If True, replace the classproperty with the actual value on first lookup
:type replace_on_access: bool
'''
return ClassPropertyInjector(self, key, name=name, replace_on_access=replace_on_access)
|
python
|
def inject_classproperty(self, key, name=None, replace_on_access=False):
'''
Decorator that injects the specified key as a classproperty.
If replace_on_access is True, then it replaces itself with the instance on first lookup.
:param key: Provider key
:type key: object
:param name: Name of classproperty, defaults to key
:type name: str
:param replace_on_access: If True, replace the classproperty with the actual value on first lookup
:type replace_on_access: bool
'''
return ClassPropertyInjector(self, key, name=name, replace_on_access=replace_on_access)
|
[
"def",
"inject_classproperty",
"(",
"self",
",",
"key",
",",
"name",
"=",
"None",
",",
"replace_on_access",
"=",
"False",
")",
":",
"return",
"ClassPropertyInjector",
"(",
"self",
",",
"key",
",",
"name",
"=",
"name",
",",
"replace_on_access",
"=",
"replace_on_access",
")"
] |
Decorator that injects the specified key as a classproperty.
If replace_on_access is True, then it replaces itself with the instance on first lookup.
:param key: Provider key
:type key: object
:param name: Name of classproperty, defaults to key
:type name: str
:param replace_on_access: If True, replace the classproperty with the actual value on first lookup
:type replace_on_access: bool
|
[
"Decorator",
"that",
"injects",
"the",
"specified",
"key",
"as",
"a",
"classproperty",
"."
] |
8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986
|
https://github.com/akatrevorjay/mainline/blob/8aa7f6ef6cad4051fcd5f8d43d2ba8cdad681986/mainline/di.py#L202-L215
|
245,197
|
deifyed/vault
|
libconman/target.py
|
Target.getTarget
|
def getTarget(iid):
'''
A static method which returns a Target object identified by
iid. Returns None if a Target object was not found
'''
db = getDataCommunicator()
verbose('Loading target with id {}'.format(iid))
data = db.getTarget(iid)
if data:
verbose('Found target')
return Target(data['name'], data['path'], _id=iid)
verbose('Could not find target belonging to id {}'.format(iid))
return data
|
python
|
def getTarget(iid):
'''
A static method which returns a Target object identified by
iid. Returns None if a Target object was not found
'''
db = getDataCommunicator()
verbose('Loading target with id {}'.format(iid))
data = db.getTarget(iid)
if data:
verbose('Found target')
return Target(data['name'], data['path'], _id=iid)
verbose('Could not find target belonging to id {}'.format(iid))
return data
|
[
"def",
"getTarget",
"(",
"iid",
")",
":",
"db",
"=",
"getDataCommunicator",
"(",
")",
"verbose",
"(",
"'Loading target with id {}'",
".",
"format",
"(",
"iid",
")",
")",
"data",
"=",
"db",
".",
"getTarget",
"(",
"iid",
")",
"if",
"data",
":",
"verbose",
"(",
"'Found target'",
")",
"return",
"Target",
"(",
"data",
"[",
"'name'",
"]",
",",
"data",
"[",
"'path'",
"]",
",",
"_id",
"=",
"iid",
")",
"verbose",
"(",
"'Could not find target belonging to id {}'",
".",
"format",
"(",
"iid",
")",
")",
"return",
"data"
] |
A static method which returns a Target object identified by
iid. Returns None if a Target object was not found
|
[
"A",
"static",
"method",
"which",
"returns",
"a",
"Target",
"object",
"identified",
"by",
"iid",
".",
"Returns",
"None",
"if",
"a",
"Target",
"object",
"was",
"not",
"found"
] |
e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97
|
https://github.com/deifyed/vault/blob/e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97/libconman/target.py#L13-L28
|
245,198
|
deifyed/vault
|
libconman/target.py
|
Target.delete
|
def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not have an id')
return False
# Removes link from vault directory
verbose('Removing link from vault directory')
os.remove(self.vault_path)
verbose('Removing information from database')
# Removing information from database
self.db.removeTarget(self._id)
self._id = -1
return True
|
python
|
def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not have an id')
return False
# Removes link from vault directory
verbose('Removing link from vault directory')
os.remove(self.vault_path)
verbose('Removing information from database')
# Removing information from database
self.db.removeTarget(self._id)
self._id = -1
return True
|
[
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_id",
":",
"verbose",
"(",
"'This target does not have an id'",
")",
"return",
"False",
"# Removes link from vault directory",
"verbose",
"(",
"'Removing link from vault directory'",
")",
"os",
".",
"remove",
"(",
"self",
".",
"vault_path",
")",
"verbose",
"(",
"'Removing information from database'",
")",
"# Removing information from database",
"self",
".",
"db",
".",
"removeTarget",
"(",
"self",
".",
"_id",
")",
"self",
".",
"_id",
"=",
"-",
"1",
"return",
"True"
] |
Deletes link from vault and removes database information
|
[
"Deletes",
"link",
"from",
"vault",
"and",
"removes",
"database",
"information"
] |
e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97
|
https://github.com/deifyed/vault/blob/e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97/libconman/target.py#L51-L68
|
245,199
|
deifyed/vault
|
libconman/target.py
|
Target.secure
|
def secure(self):
'''
Creates a hard link to the target file in the vault directory
and saves information about the target file in the database
'''
verbose('Saving information about target into conman database')
self._id = self.db.insertTarget(self.name, self.path)
verbose('Creating a hard link from {} to {} directory'.format(
str(self), config.CONMAN_PATH
))
link(self.real_path, self.vault_path)
|
python
|
def secure(self):
'''
Creates a hard link to the target file in the vault directory
and saves information about the target file in the database
'''
verbose('Saving information about target into conman database')
self._id = self.db.insertTarget(self.name, self.path)
verbose('Creating a hard link from {} to {} directory'.format(
str(self), config.CONMAN_PATH
))
link(self.real_path, self.vault_path)
|
[
"def",
"secure",
"(",
"self",
")",
":",
"verbose",
"(",
"'Saving information about target into conman database'",
")",
"self",
".",
"_id",
"=",
"self",
".",
"db",
".",
"insertTarget",
"(",
"self",
".",
"name",
",",
"self",
".",
"path",
")",
"verbose",
"(",
"'Creating a hard link from {} to {} directory'",
".",
"format",
"(",
"str",
"(",
"self",
")",
",",
"config",
".",
"CONMAN_PATH",
")",
")",
"link",
"(",
"self",
".",
"real_path",
",",
"self",
".",
"vault_path",
")"
] |
Creates a hard link to the target file in the vault directory
and saves information about the target file in the database
|
[
"Creates",
"a",
"hard",
"link",
"to",
"the",
"target",
"file",
"in",
"the",
"vault",
"directory",
"and",
"saves",
"information",
"about",
"the",
"target",
"file",
"in",
"the",
"database"
] |
e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97
|
https://github.com/deifyed/vault/blob/e3c37ade6c3e6b61a76ec6cd2ba98881c7401d97/libconman/target.py#L70-L81
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.