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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
248,300 | 20c/twentyc.tools | twentyc/tools/cli.py | CLIEnv.check_config | def check_config(self, section, name, has_default=False, value=None, allowEmpty=False):
"""
Check if a config value is set
Returns
True - config value is set and valid
False - config value is not set or invalid
"""
cfg = self.config
if not cfg.has_key(section) or not cfg.get(section).has_key(name):
if not has_default:
self.config_errors.append("%s: %s -> missing" % (section, name))
return False
else:
return True
v = cfg.get(section).get(name)
if v == "" and not allowEmpty:
self.config_errors.append("%s: %s -> empty" % (section, name))
return False
return True | python | def check_config(self, section, name, has_default=False, value=None, allowEmpty=False):
"""
Check if a config value is set
Returns
True - config value is set and valid
False - config value is not set or invalid
"""
cfg = self.config
if not cfg.has_key(section) or not cfg.get(section).has_key(name):
if not has_default:
self.config_errors.append("%s: %s -> missing" % (section, name))
return False
else:
return True
v = cfg.get(section).get(name)
if v == "" and not allowEmpty:
self.config_errors.append("%s: %s -> empty" % (section, name))
return False
return True | [
"def",
"check_config",
"(",
"self",
",",
"section",
",",
"name",
",",
"has_default",
"=",
"False",
",",
"value",
"=",
"None",
",",
"allowEmpty",
"=",
"False",
")",
":",
"cfg",
"=",
"self",
".",
"config",
"if",
"not",
"cfg",
".",
"has_key",
"(",
"section",
")",
"or",
"not",
"cfg",
".",
"get",
"(",
"section",
")",
".",
"has_key",
"(",
"name",
")",
":",
"if",
"not",
"has_default",
":",
"self",
".",
"config_errors",
".",
"append",
"(",
"\"%s: %s -> missing\"",
"%",
"(",
"section",
",",
"name",
")",
")",
"return",
"False",
"else",
":",
"return",
"True",
"v",
"=",
"cfg",
".",
"get",
"(",
"section",
")",
".",
"get",
"(",
"name",
")",
"if",
"v",
"==",
"\"\"",
"and",
"not",
"allowEmpty",
":",
"self",
".",
"config_errors",
".",
"append",
"(",
"\"%s: %s -> empty\"",
"%",
"(",
"section",
",",
"name",
")",
")",
"return",
"False",
"return",
"True"
] | Check if a config value is set
Returns
True - config value is set and valid
False - config value is not set or invalid | [
"Check",
"if",
"a",
"config",
"value",
"is",
"set"
] | f8f681e64f58d449bfc32646ba8bcc57db90a233 | https://github.com/20c/twentyc.tools/blob/f8f681e64f58d449bfc32646ba8bcc57db90a233/twentyc/tools/cli.py#L56-L80 |
248,301 | neuroticnerd/armory | armory/utils/encoding.py | UnicodeTransformChar.transform | def transform(self, text):
"""Replaces characters in string ``text`` based in regex sub"""
return re.sub(self.regex, self.repl, text) | python | def transform(self, text):
"""Replaces characters in string ``text`` based in regex sub"""
return re.sub(self.regex, self.repl, text) | [
"def",
"transform",
"(",
"self",
",",
"text",
")",
":",
"return",
"re",
".",
"sub",
"(",
"self",
".",
"regex",
",",
"self",
".",
"repl",
",",
"text",
")"
] | Replaces characters in string ``text`` based in regex sub | [
"Replaces",
"characters",
"in",
"string",
"text",
"based",
"in",
"regex",
"sub"
] | d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1 | https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/utils/encoding.py#L17-L19 |
248,302 | msfrank/cifparser | cifparser/valuetree.py | dump | def dump(values):
"""
Dump a ValueTree instance, returning its dict representation.
:param values:
:type values: ValueTree
:return:
:rtype: dict
"""
root = {}
def _dump(_values, container):
for name,value in _values._values.items():
if isinstance(value, ValueTree):
container[name] = _dump(value, {})
elif isinstance(value, list):
items = []
for item in value:
if not isinstance(item, str):
raise ValueError()
items.append(item)
container[name] = items
elif isinstance(value, str):
container[name] = value
else:
raise ValueError()
return container
return _dump(values, root) | python | def dump(values):
"""
Dump a ValueTree instance, returning its dict representation.
:param values:
:type values: ValueTree
:return:
:rtype: dict
"""
root = {}
def _dump(_values, container):
for name,value in _values._values.items():
if isinstance(value, ValueTree):
container[name] = _dump(value, {})
elif isinstance(value, list):
items = []
for item in value:
if not isinstance(item, str):
raise ValueError()
items.append(item)
container[name] = items
elif isinstance(value, str):
container[name] = value
else:
raise ValueError()
return container
return _dump(values, root) | [
"def",
"dump",
"(",
"values",
")",
":",
"root",
"=",
"{",
"}",
"def",
"_dump",
"(",
"_values",
",",
"container",
")",
":",
"for",
"name",
",",
"value",
"in",
"_values",
".",
"_values",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ValueTree",
")",
":",
"container",
"[",
"name",
"]",
"=",
"_dump",
"(",
"value",
",",
"{",
"}",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"items",
"=",
"[",
"]",
"for",
"item",
"in",
"value",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
")",
"items",
".",
"append",
"(",
"item",
")",
"container",
"[",
"name",
"]",
"=",
"items",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"container",
"[",
"name",
"]",
"=",
"value",
"else",
":",
"raise",
"ValueError",
"(",
")",
"return",
"container",
"return",
"_dump",
"(",
"values",
",",
"root",
")"
] | Dump a ValueTree instance, returning its dict representation.
:param values:
:type values: ValueTree
:return:
:rtype: dict | [
"Dump",
"a",
"ValueTree",
"instance",
"returning",
"its",
"dict",
"representation",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L330-L356 |
248,303 | msfrank/cifparser | cifparser/valuetree.py | load | def load(obj):
"""
Load a ValueTree instance from its dict representation.
:param obj:
:type obj: dict
:return:
:rtype: ValueTree
"""
values = ValueTree()
def _load(_obj, container):
for name,value in _obj.items():
if isinstance(value, dict):
path = make_path(name)
container.put_container(path)
_load(value, container.get_container(path))
elif isinstance(value, list):
for item in value:
container.append_field(ROOT_PATH, name, item)
elif isinstance(value, str):
container.put_field(ROOT_PATH, name, value)
else:
raise ValueError()
_load(obj, values)
return values | python | def load(obj):
"""
Load a ValueTree instance from its dict representation.
:param obj:
:type obj: dict
:return:
:rtype: ValueTree
"""
values = ValueTree()
def _load(_obj, container):
for name,value in _obj.items():
if isinstance(value, dict):
path = make_path(name)
container.put_container(path)
_load(value, container.get_container(path))
elif isinstance(value, list):
for item in value:
container.append_field(ROOT_PATH, name, item)
elif isinstance(value, str):
container.put_field(ROOT_PATH, name, value)
else:
raise ValueError()
_load(obj, values)
return values | [
"def",
"load",
"(",
"obj",
")",
":",
"values",
"=",
"ValueTree",
"(",
")",
"def",
"_load",
"(",
"_obj",
",",
"container",
")",
":",
"for",
"name",
",",
"value",
"in",
"_obj",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"path",
"=",
"make_path",
"(",
"name",
")",
"container",
".",
"put_container",
"(",
"path",
")",
"_load",
"(",
"value",
",",
"container",
".",
"get_container",
"(",
"path",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"for",
"item",
"in",
"value",
":",
"container",
".",
"append_field",
"(",
"ROOT_PATH",
",",
"name",
",",
"item",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"container",
".",
"put_field",
"(",
"ROOT_PATH",
",",
"name",
",",
"value",
")",
"else",
":",
"raise",
"ValueError",
"(",
")",
"_load",
"(",
"obj",
",",
"values",
")",
"return",
"values"
] | Load a ValueTree instance from its dict representation.
:param obj:
:type obj: dict
:return:
:rtype: ValueTree | [
"Load",
"a",
"ValueTree",
"instance",
"from",
"its",
"dict",
"representation",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L358-L382 |
248,304 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.put_container | def put_container(self, path):
"""
Creates a container at the specified path, creating any necessary
intermediate containers.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
"""
path = make_path(path)
container = self
for segment in path:
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
valuetree = ValueTree()
container._values[segment] = valuetree
container = valuetree | python | def put_container(self, path):
"""
Creates a container at the specified path, creating any necessary
intermediate containers.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
"""
path = make_path(path)
container = self
for segment in path:
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
valuetree = ValueTree()
container._values[segment] = valuetree
container = valuetree | [
"def",
"put_container",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"make_path",
"(",
"path",
")",
"container",
"=",
"self",
"for",
"segment",
"in",
"path",
":",
"try",
":",
"container",
"=",
"container",
".",
"_values",
"[",
"segment",
"]",
"if",
"not",
"isinstance",
"(",
"container",
",",
"ValueTree",
")",
":",
"raise",
"ValueError",
"(",
")",
"except",
"KeyError",
":",
"valuetree",
"=",
"ValueTree",
"(",
")",
"container",
".",
"_values",
"[",
"segment",
"]",
"=",
"valuetree",
"container",
"=",
"valuetree"
] | Creates a container at the specified path, creating any necessary
intermediate containers.
:param path: str or Path instance
:raises ValueError: A component of path is a field name. | [
"Creates",
"a",
"container",
"at",
"the",
"specified",
"path",
"creating",
"any",
"necessary",
"intermediate",
"containers",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L14-L32 |
248,305 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.remove_container | def remove_container(self, path):
"""
Removes the container at the specified path.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
"""
path = make_path(path)
container = self
parent = None
for segment in path:
parent = container
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
raise KeyError()
del parent._values[path.segments[-1]] | python | def remove_container(self, path):
"""
Removes the container at the specified path.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
"""
path = make_path(path)
container = self
parent = None
for segment in path:
parent = container
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
raise KeyError()
del parent._values[path.segments[-1]] | [
"def",
"remove_container",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"make_path",
"(",
"path",
")",
"container",
"=",
"self",
"parent",
"=",
"None",
"for",
"segment",
"in",
"path",
":",
"parent",
"=",
"container",
"try",
":",
"container",
"=",
"container",
".",
"_values",
"[",
"segment",
"]",
"if",
"not",
"isinstance",
"(",
"container",
",",
"ValueTree",
")",
":",
"raise",
"ValueError",
"(",
")",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
")",
"del",
"parent",
".",
"_values",
"[",
"path",
".",
"segments",
"[",
"-",
"1",
"]",
"]"
] | Removes the container at the specified path.
:param path: str or Path instance
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist. | [
"Removes",
"the",
"container",
"at",
"the",
"specified",
"path",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L34-L53 |
248,306 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.get_container | def get_container(self, path):
"""
Retrieves the container at the specified path.
:param path: str or Path instance
:return:
:rtype: ValueTree
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
"""
path = make_path(path)
container = self
for segment in path:
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
raise KeyError()
return container | python | def get_container(self, path):
"""
Retrieves the container at the specified path.
:param path: str or Path instance
:return:
:rtype: ValueTree
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
"""
path = make_path(path)
container = self
for segment in path:
try:
container = container._values[segment]
if not isinstance(container, ValueTree):
raise ValueError()
except KeyError:
raise KeyError()
return container | [
"def",
"get_container",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"make_path",
"(",
"path",
")",
"container",
"=",
"self",
"for",
"segment",
"in",
"path",
":",
"try",
":",
"container",
"=",
"container",
".",
"_values",
"[",
"segment",
"]",
"if",
"not",
"isinstance",
"(",
"container",
",",
"ValueTree",
")",
":",
"raise",
"ValueError",
"(",
")",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
")",
"return",
"container"
] | Retrieves the container at the specified path.
:param path: str or Path instance
:return:
:rtype: ValueTree
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist. | [
"Retrieves",
"the",
"container",
"at",
"the",
"specified",
"path",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L55-L74 |
248,307 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.contains_container | def contains_container(self, path):
"""
Returns True if a container exists at the specified path,
otherwise False.
:param path: str or Path instance
:return:
:rtype: bool
:raises ValueError: A component of path is a field name.
"""
path = make_path(path)
try:
self.get_container(path)
return True
except KeyError:
return False | python | def contains_container(self, path):
"""
Returns True if a container exists at the specified path,
otherwise False.
:param path: str or Path instance
:return:
:rtype: bool
:raises ValueError: A component of path is a field name.
"""
path = make_path(path)
try:
self.get_container(path)
return True
except KeyError:
return False | [
"def",
"contains_container",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"make_path",
"(",
"path",
")",
"try",
":",
"self",
".",
"get_container",
"(",
"path",
")",
"return",
"True",
"except",
"KeyError",
":",
"return",
"False"
] | Returns True if a container exists at the specified path,
otherwise False.
:param path: str or Path instance
:return:
:rtype: bool
:raises ValueError: A component of path is a field name. | [
"Returns",
"True",
"if",
"a",
"container",
"exists",
"at",
"the",
"specified",
"path",
"otherwise",
"False",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L107-L122 |
248,308 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.put_field | def put_field(self, path, name, value):
"""
Creates a field with the specified name an value at path. If the
field already exists, it will be overwritten with the new value.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str
"""
if not isinstance(value, str):
raise ValueError()
path = make_path(path)
container = self.get_container(path)
current = self._values.get(name)
if current is not None and isinstance(current, ValueTree):
raise TypeError()
container._values[name] = value | python | def put_field(self, path, name, value):
"""
Creates a field with the specified name an value at path. If the
field already exists, it will be overwritten with the new value.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str
"""
if not isinstance(value, str):
raise ValueError()
path = make_path(path)
container = self.get_container(path)
current = self._values.get(name)
if current is not None and isinstance(current, ValueTree):
raise TypeError()
container._values[name] = value | [
"def",
"put_field",
"(",
"self",
",",
"path",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"ValueError",
"(",
")",
"path",
"=",
"make_path",
"(",
"path",
")",
"container",
"=",
"self",
".",
"get_container",
"(",
"path",
")",
"current",
"=",
"self",
".",
"_values",
".",
"get",
"(",
"name",
")",
"if",
"current",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"current",
",",
"ValueTree",
")",
":",
"raise",
"TypeError",
"(",
")",
"container",
".",
"_values",
"[",
"name",
"]",
"=",
"value"
] | Creates a field with the specified name an value at path. If the
field already exists, it will be overwritten with the new value.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str | [
"Creates",
"a",
"field",
"with",
"the",
"specified",
"name",
"an",
"value",
"at",
"path",
".",
"If",
"the",
"field",
"already",
"exists",
"it",
"will",
"be",
"overwritten",
"with",
"the",
"new",
"value",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L139-L157 |
248,309 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.append_field | def append_field(self, path, name, value):
"""
Appends the field to the container at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str
"""
path = make_path(path)
container = self.get_container(path)
current = container._values.get(name, None)
if current is None:
container._values[name] = value
elif isinstance(current, ValueTree):
raise TypeError()
elif isinstance(current, list):
container._values[name] = current + [value]
else:
container._values[name] = [current, value] | python | def append_field(self, path, name, value):
"""
Appends the field to the container at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str
"""
path = make_path(path)
container = self.get_container(path)
current = container._values.get(name, None)
if current is None:
container._values[name] = value
elif isinstance(current, ValueTree):
raise TypeError()
elif isinstance(current, list):
container._values[name] = current + [value]
else:
container._values[name] = [current, value] | [
"def",
"append_field",
"(",
"self",
",",
"path",
",",
"name",
",",
"value",
")",
":",
"path",
"=",
"make_path",
"(",
"path",
")",
"container",
"=",
"self",
".",
"get_container",
"(",
"path",
")",
"current",
"=",
"container",
".",
"_values",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"current",
"is",
"None",
":",
"container",
".",
"_values",
"[",
"name",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"current",
",",
"ValueTree",
")",
":",
"raise",
"TypeError",
"(",
")",
"elif",
"isinstance",
"(",
"current",
",",
"list",
")",
":",
"container",
".",
"_values",
"[",
"name",
"]",
"=",
"current",
"+",
"[",
"value",
"]",
"else",
":",
"container",
".",
"_values",
"[",
"name",
"]",
"=",
"[",
"current",
",",
"value",
"]"
] | Appends the field to the container at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:param value:
:type value: str | [
"Appends",
"the",
"field",
"to",
"the",
"container",
"at",
"the",
"specified",
"path",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L177-L197 |
248,310 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.get_field | def get_field(self, path, name):
"""
Retrieves the value of the field at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
:raises TypeError: The field name is a component of a path.
"""
try:
value = self.get(path, name)
if not isinstance(value, str):
raise TypeError()
return value
except KeyError:
raise KeyError() | python | def get_field(self, path, name):
"""
Retrieves the value of the field at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
:raises TypeError: The field name is a component of a path.
"""
try:
value = self.get(path, name)
if not isinstance(value, str):
raise TypeError()
return value
except KeyError:
raise KeyError() | [
"def",
"get_field",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"get",
"(",
"path",
",",
"name",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
")",
"return",
"value",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
")"
] | Retrieves the value of the field at the specified path.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises KeyError: A component of path doesn't exist.
:raises TypeError: The field name is a component of a path. | [
"Retrieves",
"the",
"value",
"of",
"the",
"field",
"at",
"the",
"specified",
"path",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L228-L246 |
248,311 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.contains_field | def contains_field(self, path, name):
"""
Returns True if a field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path.
"""
try:
self.get_field(path, name)
return True
except KeyError:
return False | python | def contains_field(self, path, name):
"""
Returns True if a field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path.
"""
try:
self.get_field(path, name)
return True
except KeyError:
return False | [
"def",
"contains_field",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"get_field",
"(",
"path",
",",
"name",
")",
"return",
"True",
"except",
"KeyError",
":",
"return",
"False"
] | Returns True if a field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path. | [
"Returns",
"True",
"if",
"a",
"field",
"exists",
"at",
"the",
"specified",
"path",
"otherwise",
"False",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L267-L282 |
248,312 | msfrank/cifparser | cifparser/valuetree.py | ValueTree.contains_field_list | def contains_field_list(self, path, name):
"""
Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path.
"""
try:
self.get_field_list(path, name)
return True
except KeyError:
return False | python | def contains_field_list(self, path, name):
"""
Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path.
"""
try:
self.get_field_list(path, name)
return True
except KeyError:
return False | [
"def",
"contains_field_list",
"(",
"self",
",",
"path",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"get_field_list",
"(",
"path",
",",
"name",
")",
"return",
"True",
"except",
"KeyError",
":",
"return",
"False"
] | Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
:raises TypeError: The field name is a component of a path. | [
"Returns",
"True",
"if",
"a",
"multi",
"-",
"valued",
"field",
"exists",
"at",
"the",
"specified",
"path",
"otherwise",
"False",
"."
] | ecd899ba2e7b990e2cec62b115742d830e7e4384 | https://github.com/msfrank/cifparser/blob/ecd899ba2e7b990e2cec62b115742d830e7e4384/cifparser/valuetree.py#L284-L299 |
248,313 | opinkerfi/nago | nago/extensions/facts.py | get | def get():
""" Get local facts about this machine.
Returns:
json-compatible dict with all facts of this host
"""
result = runCommand('facter --json', raise_error_on_fail=True)
json_facts = result[1]
facts = json.loads(json_facts)
return facts | python | def get():
""" Get local facts about this machine.
Returns:
json-compatible dict with all facts of this host
"""
result = runCommand('facter --json', raise_error_on_fail=True)
json_facts = result[1]
facts = json.loads(json_facts)
return facts | [
"def",
"get",
"(",
")",
":",
"result",
"=",
"runCommand",
"(",
"'facter --json'",
",",
"raise_error_on_fail",
"=",
"True",
")",
"json_facts",
"=",
"result",
"[",
"1",
"]",
"facts",
"=",
"json",
".",
"loads",
"(",
"json_facts",
")",
"return",
"facts"
] | Get local facts about this machine.
Returns:
json-compatible dict with all facts of this host | [
"Get",
"local",
"facts",
"about",
"this",
"machine",
"."
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/facts.py#L20-L29 |
248,314 | opinkerfi/nago | nago/extensions/facts.py | get_all | def get_all():
""" Get all facts about all nodes """
result = {}
for k,v in nago.extensions.info.node_data.items():
result[k] = v.get('facts', {})
return result | python | def get_all():
""" Get all facts about all nodes """
result = {}
for k,v in nago.extensions.info.node_data.items():
result[k] = v.get('facts', {})
return result | [
"def",
"get_all",
"(",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"nago",
".",
"extensions",
".",
"info",
".",
"node_data",
".",
"items",
"(",
")",
":",
"result",
"[",
"k",
"]",
"=",
"v",
".",
"get",
"(",
"'facts'",
",",
"{",
"}",
")",
"return",
"result"
] | Get all facts about all nodes | [
"Get",
"all",
"facts",
"about",
"all",
"nodes"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/facts.py#L43-L48 |
248,315 | opinkerfi/nago | nago/extensions/facts.py | send | def send(remote_host=None):
""" Send my facts to a remote host
if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master.
"""
my_facts = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(remote_host)
if not remote_node:
raise Exception("Remote host with token='%s' not found" % remote_host)
response = remote_node.send_command('facts', 'post', host_token=remote_node.token, **my_facts)
result = {}
result['server_response'] = response
result['message'] = "sent %s facts to remote node '%s'" % (len(my_facts), remote_node.get('host_name'))
return result | python | def send(remote_host=None):
""" Send my facts to a remote host
if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master.
"""
my_facts = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(remote_host)
if not remote_node:
raise Exception("Remote host with token='%s' not found" % remote_host)
response = remote_node.send_command('facts', 'post', host_token=remote_node.token, **my_facts)
result = {}
result['server_response'] = response
result['message'] = "sent %s facts to remote node '%s'" % (len(my_facts), remote_node.get('host_name'))
return result | [
"def",
"send",
"(",
"remote_host",
"=",
"None",
")",
":",
"my_facts",
"=",
"get",
"(",
")",
"if",
"not",
"remote_host",
":",
"remote_host",
"=",
"nago",
".",
"extensions",
".",
"settings",
".",
"get",
"(",
"'server'",
")",
"remote_node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"remote_host",
")",
"if",
"not",
"remote_node",
":",
"raise",
"Exception",
"(",
"\"Remote host with token='%s' not found\"",
"%",
"remote_host",
")",
"response",
"=",
"remote_node",
".",
"send_command",
"(",
"'facts'",
",",
"'post'",
",",
"host_token",
"=",
"remote_node",
".",
"token",
",",
"*",
"*",
"my_facts",
")",
"result",
"=",
"{",
"}",
"result",
"[",
"'server_response'",
"]",
"=",
"response",
"result",
"[",
"'message'",
"]",
"=",
"\"sent %s facts to remote node '%s'\"",
"%",
"(",
"len",
"(",
"my_facts",
")",
",",
"remote_node",
".",
"get",
"(",
"'host_name'",
")",
")",
"return",
"result"
] | Send my facts to a remote host
if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master. | [
"Send",
"my",
"facts",
"to",
"a",
"remote",
"host"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/facts.py#L51-L66 |
248,316 | eddiejessup/fealty | fealty/lattice.py | extend_array | def extend_array(a, n):
"""Increase the resolution of an array by duplicating its values to fill
a larger array.
Parameters
----------
a: array, shape (a1, a2, a3, ...)
n: integer
Factor by which to expand the array.
Returns
-------
ae: array, shape (n * a1, n * a2, n * a3, ...)
"""
a_new = a.copy()
for d in range(a.ndim):
a_new = np.repeat(a_new, n, axis=d)
return a_new | python | def extend_array(a, n):
"""Increase the resolution of an array by duplicating its values to fill
a larger array.
Parameters
----------
a: array, shape (a1, a2, a3, ...)
n: integer
Factor by which to expand the array.
Returns
-------
ae: array, shape (n * a1, n * a2, n * a3, ...)
"""
a_new = a.copy()
for d in range(a.ndim):
a_new = np.repeat(a_new, n, axis=d)
return a_new | [
"def",
"extend_array",
"(",
"a",
",",
"n",
")",
":",
"a_new",
"=",
"a",
".",
"copy",
"(",
")",
"for",
"d",
"in",
"range",
"(",
"a",
".",
"ndim",
")",
":",
"a_new",
"=",
"np",
".",
"repeat",
"(",
"a_new",
",",
"n",
",",
"axis",
"=",
"d",
")",
"return",
"a_new"
] | Increase the resolution of an array by duplicating its values to fill
a larger array.
Parameters
----------
a: array, shape (a1, a2, a3, ...)
n: integer
Factor by which to expand the array.
Returns
-------
ae: array, shape (n * a1, n * a2, n * a3, ...) | [
"Increase",
"the",
"resolution",
"of",
"an",
"array",
"by",
"duplicating",
"its",
"values",
"to",
"fill",
"a",
"larger",
"array",
"."
] | 03745eb98d85bc2a5d08920773ab9c4515462d30 | https://github.com/eddiejessup/fealty/blob/03745eb98d85bc2a5d08920773ab9c4515462d30/fealty/lattice.py#L9-L26 |
248,317 | eddiejessup/fealty | fealty/lattice.py | field_subset | def field_subset(f, inds, rank=0):
"""Return the value of a field at a subset of points.
Parameters
----------
f: array, shape (a1, a2, ..., ad, r1, r2, ..., rrank)
Rank-r field in d dimensions
inds: integer array, shape (n, d)
Index vectors
rank: integer
The rank of the field (0: scalar field, 1: vector field and so on).
Returns
-------
f_sub: array, shape (n, rank)
The subset of field values.
"""
f_dim_space = f.ndim - rank
if inds.ndim > 2:
raise Exception('Too many dimensions in indices array')
if inds.ndim == 1:
if f_dim_space == 1:
return f[inds]
else:
raise Exception('Indices array is 1d but field is not')
if inds.shape[1] != f_dim_space:
raise Exception('Indices and field dimensions do not match')
# It's magic, don't touch it!
return f[tuple([inds[:, i] for i in range(inds.shape[1])])] | python | def field_subset(f, inds, rank=0):
"""Return the value of a field at a subset of points.
Parameters
----------
f: array, shape (a1, a2, ..., ad, r1, r2, ..., rrank)
Rank-r field in d dimensions
inds: integer array, shape (n, d)
Index vectors
rank: integer
The rank of the field (0: scalar field, 1: vector field and so on).
Returns
-------
f_sub: array, shape (n, rank)
The subset of field values.
"""
f_dim_space = f.ndim - rank
if inds.ndim > 2:
raise Exception('Too many dimensions in indices array')
if inds.ndim == 1:
if f_dim_space == 1:
return f[inds]
else:
raise Exception('Indices array is 1d but field is not')
if inds.shape[1] != f_dim_space:
raise Exception('Indices and field dimensions do not match')
# It's magic, don't touch it!
return f[tuple([inds[:, i] for i in range(inds.shape[1])])] | [
"def",
"field_subset",
"(",
"f",
",",
"inds",
",",
"rank",
"=",
"0",
")",
":",
"f_dim_space",
"=",
"f",
".",
"ndim",
"-",
"rank",
"if",
"inds",
".",
"ndim",
">",
"2",
":",
"raise",
"Exception",
"(",
"'Too many dimensions in indices array'",
")",
"if",
"inds",
".",
"ndim",
"==",
"1",
":",
"if",
"f_dim_space",
"==",
"1",
":",
"return",
"f",
"[",
"inds",
"]",
"else",
":",
"raise",
"Exception",
"(",
"'Indices array is 1d but field is not'",
")",
"if",
"inds",
".",
"shape",
"[",
"1",
"]",
"!=",
"f_dim_space",
":",
"raise",
"Exception",
"(",
"'Indices and field dimensions do not match'",
")",
"# It's magic, don't touch it!",
"return",
"f",
"[",
"tuple",
"(",
"[",
"inds",
"[",
":",
",",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"inds",
".",
"shape",
"[",
"1",
"]",
")",
"]",
")",
"]"
] | Return the value of a field at a subset of points.
Parameters
----------
f: array, shape (a1, a2, ..., ad, r1, r2, ..., rrank)
Rank-r field in d dimensions
inds: integer array, shape (n, d)
Index vectors
rank: integer
The rank of the field (0: scalar field, 1: vector field and so on).
Returns
-------
f_sub: array, shape (n, rank)
The subset of field values. | [
"Return",
"the",
"value",
"of",
"a",
"field",
"at",
"a",
"subset",
"of",
"points",
"."
] | 03745eb98d85bc2a5d08920773ab9c4515462d30 | https://github.com/eddiejessup/fealty/blob/03745eb98d85bc2a5d08920773ab9c4515462d30/fealty/lattice.py#L29-L57 |
248,318 | eddiejessup/fealty | fealty/lattice.py | pad_to_3d | def pad_to_3d(a):
"""Return 1- or 2-dimensional cartesian vectors, converted into a
3-dimensional representation, with additional dimensional coordinates
assumed to be zero.
Parameters
----------
a: array, shape (n, d), d < 3
Returns
-------
ap: array, shape (n, 3)
"""
a_pad = np.zeros([len(a), 3], dtype=a.dtype)
a_pad[:, :a.shape[-1]] = a
return a_pad | python | def pad_to_3d(a):
"""Return 1- or 2-dimensional cartesian vectors, converted into a
3-dimensional representation, with additional dimensional coordinates
assumed to be zero.
Parameters
----------
a: array, shape (n, d), d < 3
Returns
-------
ap: array, shape (n, 3)
"""
a_pad = np.zeros([len(a), 3], dtype=a.dtype)
a_pad[:, :a.shape[-1]] = a
return a_pad | [
"def",
"pad_to_3d",
"(",
"a",
")",
":",
"a_pad",
"=",
"np",
".",
"zeros",
"(",
"[",
"len",
"(",
"a",
")",
",",
"3",
"]",
",",
"dtype",
"=",
"a",
".",
"dtype",
")",
"a_pad",
"[",
":",
",",
":",
"a",
".",
"shape",
"[",
"-",
"1",
"]",
"]",
"=",
"a",
"return",
"a_pad"
] | Return 1- or 2-dimensional cartesian vectors, converted into a
3-dimensional representation, with additional dimensional coordinates
assumed to be zero.
Parameters
----------
a: array, shape (n, d), d < 3
Returns
-------
ap: array, shape (n, 3) | [
"Return",
"1",
"-",
"or",
"2",
"-",
"dimensional",
"cartesian",
"vectors",
"converted",
"into",
"a",
"3",
"-",
"dimensional",
"representation",
"with",
"additional",
"dimensional",
"coordinates",
"assumed",
"to",
"be",
"zero",
"."
] | 03745eb98d85bc2a5d08920773ab9c4515462d30 | https://github.com/eddiejessup/fealty/blob/03745eb98d85bc2a5d08920773ab9c4515462d30/fealty/lattice.py#L60-L75 |
248,319 | Cologler/fsoopify-python | fsoopify/nodes.py | NodeInfo.get_parent | def get_parent(self, level=1):
'''
get parent dir as a `DirectoryInfo`.
return `None` if self is top.
'''
try:
parent_path = self.path.get_parent(level)
except ValueError: # abspath cannot get parent
return None
assert parent_path
return DirectoryInfo(parent_path) | python | def get_parent(self, level=1):
'''
get parent dir as a `DirectoryInfo`.
return `None` if self is top.
'''
try:
parent_path = self.path.get_parent(level)
except ValueError: # abspath cannot get parent
return None
assert parent_path
return DirectoryInfo(parent_path) | [
"def",
"get_parent",
"(",
"self",
",",
"level",
"=",
"1",
")",
":",
"try",
":",
"parent_path",
"=",
"self",
".",
"path",
".",
"get_parent",
"(",
"level",
")",
"except",
"ValueError",
":",
"# abspath cannot get parent",
"return",
"None",
"assert",
"parent_path",
"return",
"DirectoryInfo",
"(",
"parent_path",
")"
] | get parent dir as a `DirectoryInfo`.
return `None` if self is top. | [
"get",
"parent",
"dir",
"as",
"a",
"DirectoryInfo",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L52-L63 |
248,320 | Cologler/fsoopify-python | fsoopify/nodes.py | NodeInfo.from_path | def from_path(path):
'''
create from path.
return `None` if path is not exists.
'''
if os.path.isdir(path):
return DirectoryInfo(path)
if os.path.isfile(path):
return FileInfo(path)
return None | python | def from_path(path):
'''
create from path.
return `None` if path is not exists.
'''
if os.path.isdir(path):
return DirectoryInfo(path)
if os.path.isfile(path):
return FileInfo(path)
return None | [
"def",
"from_path",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"DirectoryInfo",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"return",
"FileInfo",
"(",
"path",
")",
"return",
"None"
] | create from path.
return `None` if path is not exists. | [
"create",
"from",
"path",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L66-L78 |
248,321 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.open | def open(self, mode='r', *, buffering=-1, encoding=None, newline=None, closefd=True):
''' open the file. '''
return open(self._path,
mode=mode,
buffering=buffering,
encoding=encoding,
newline=newline,
closefd=closefd) | python | def open(self, mode='r', *, buffering=-1, encoding=None, newline=None, closefd=True):
''' open the file. '''
return open(self._path,
mode=mode,
buffering=buffering,
encoding=encoding,
newline=newline,
closefd=closefd) | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"*",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"closefd",
"=",
"True",
")",
":",
"return",
"open",
"(",
"self",
".",
"_path",
",",
"mode",
"=",
"mode",
",",
"buffering",
"=",
"buffering",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"newline",
",",
"closefd",
"=",
"closefd",
")"
] | open the file. | [
"open",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L134-L141 |
248,322 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.write | def write(self, data, *, mode=None, buffering=-1, encoding=None, newline=None):
''' write data into the file. '''
if mode is None:
mode = 'w' if isinstance(data, str) else 'wb'
with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
return fp.write(data) | python | def write(self, data, *, mode=None, buffering=-1, encoding=None, newline=None):
''' write data into the file. '''
if mode is None:
mode = 'w' if isinstance(data, str) else 'wb'
with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
return fp.write(data) | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"*",
",",
"mode",
"=",
"None",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"if",
"mode",
"is",
"None",
":",
"mode",
"=",
"'w'",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
"else",
"'wb'",
"with",
"self",
".",
"open",
"(",
"mode",
"=",
"mode",
",",
"buffering",
"=",
"buffering",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"newline",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"write",
"(",
"data",
")"
] | write data into the file. | [
"write",
"data",
"into",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L148-L153 |
248,323 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.read | def read(self, mode='r', *, buffering=-1, encoding=None, newline=None):
''' read data from the file. '''
with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
return fp.read() | python | def read(self, mode='r', *, buffering=-1, encoding=None, newline=None):
''' read data from the file. '''
with self.open(mode=mode, buffering=buffering, encoding=encoding, newline=newline) as fp:
return fp.read() | [
"def",
"read",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"*",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"with",
"self",
".",
"open",
"(",
"mode",
"=",
"mode",
",",
"buffering",
"=",
"buffering",
",",
"encoding",
"=",
"encoding",
",",
"newline",
"=",
"newline",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"read",
"(",
")"
] | read data from the file. | [
"read",
"data",
"from",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L155-L158 |
248,324 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.write_text | def write_text(self, text: str, *, encoding='utf-8', append=True):
''' write text into the file. '''
mode = 'a' if append else 'w'
return self.write(text, mode=mode, encoding=encoding) | python | def write_text(self, text: str, *, encoding='utf-8', append=True):
''' write text into the file. '''
mode = 'a' if append else 'w'
return self.write(text, mode=mode, encoding=encoding) | [
"def",
"write_text",
"(",
"self",
",",
"text",
":",
"str",
",",
"*",
",",
"encoding",
"=",
"'utf-8'",
",",
"append",
"=",
"True",
")",
":",
"mode",
"=",
"'a'",
"if",
"append",
"else",
"'w'",
"return",
"self",
".",
"write",
"(",
"text",
",",
"mode",
"=",
"mode",
",",
"encoding",
"=",
"encoding",
")"
] | write text into the file. | [
"write",
"text",
"into",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L160-L163 |
248,325 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.write_bytes | def write_bytes(self, data: bytes, *, append=True):
''' write bytes into the file. '''
mode = 'ab' if append else 'wb'
return self.write(data, mode=mode) | python | def write_bytes(self, data: bytes, *, append=True):
''' write bytes into the file. '''
mode = 'ab' if append else 'wb'
return self.write(data, mode=mode) | [
"def",
"write_bytes",
"(",
"self",
",",
"data",
":",
"bytes",
",",
"*",
",",
"append",
"=",
"True",
")",
":",
"mode",
"=",
"'ab'",
"if",
"append",
"else",
"'wb'",
"return",
"self",
".",
"write",
"(",
"data",
",",
"mode",
"=",
"mode",
")"
] | write bytes into the file. | [
"write",
"bytes",
"into",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L165-L168 |
248,326 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.copy_to | def copy_to(self, dest, buffering: int = -1):
'''
copy the file to dest path.
`dest` canbe `str`, `FileInfo` or `DirectoryInfo`.
if `dest` is `DirectoryInfo`, that mean copy into the dir with same name.
'''
if isinstance(dest, str):
dest_path = dest
elif isinstance(dest, FileInfo):
dest_path = dest.path
elif isinstance(dest, DirectoryInfo):
dest_path = dest.path / self.path.name
else:
raise TypeError('dest is not one of `str`, `FileInfo`, `DirectoryInfo`')
with open(self._path, 'rb', buffering=buffering) as source:
# use x mode to ensure dest does not exists.
with open(dest_path, 'xb') as dest_file:
for buffer in source:
dest_file.write(buffer) | python | def copy_to(self, dest, buffering: int = -1):
'''
copy the file to dest path.
`dest` canbe `str`, `FileInfo` or `DirectoryInfo`.
if `dest` is `DirectoryInfo`, that mean copy into the dir with same name.
'''
if isinstance(dest, str):
dest_path = dest
elif isinstance(dest, FileInfo):
dest_path = dest.path
elif isinstance(dest, DirectoryInfo):
dest_path = dest.path / self.path.name
else:
raise TypeError('dest is not one of `str`, `FileInfo`, `DirectoryInfo`')
with open(self._path, 'rb', buffering=buffering) as source:
# use x mode to ensure dest does not exists.
with open(dest_path, 'xb') as dest_file:
for buffer in source:
dest_file.write(buffer) | [
"def",
"copy_to",
"(",
"self",
",",
"dest",
",",
"buffering",
":",
"int",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"dest",
",",
"str",
")",
":",
"dest_path",
"=",
"dest",
"elif",
"isinstance",
"(",
"dest",
",",
"FileInfo",
")",
":",
"dest_path",
"=",
"dest",
".",
"path",
"elif",
"isinstance",
"(",
"dest",
",",
"DirectoryInfo",
")",
":",
"dest_path",
"=",
"dest",
".",
"path",
"/",
"self",
".",
"path",
".",
"name",
"else",
":",
"raise",
"TypeError",
"(",
"'dest is not one of `str`, `FileInfo`, `DirectoryInfo`'",
")",
"with",
"open",
"(",
"self",
".",
"_path",
",",
"'rb'",
",",
"buffering",
"=",
"buffering",
")",
"as",
"source",
":",
"# use x mode to ensure dest does not exists.",
"with",
"open",
"(",
"dest_path",
",",
"'xb'",
")",
"as",
"dest_file",
":",
"for",
"buffer",
"in",
"source",
":",
"dest_file",
".",
"write",
"(",
"buffer",
")"
] | copy the file to dest path.
`dest` canbe `str`, `FileInfo` or `DirectoryInfo`.
if `dest` is `DirectoryInfo`, that mean copy into the dir with same name. | [
"copy",
"the",
"file",
"to",
"dest",
"path",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L170-L191 |
248,327 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.read_text | def read_text(self, encoding='utf-8') -> str:
''' read all text into memory. '''
with self.open('r', encoding=encoding) as fp:
return fp.read() | python | def read_text(self, encoding='utf-8') -> str:
''' read all text into memory. '''
with self.open('r', encoding=encoding) as fp:
return fp.read() | [
"def",
"read_text",
"(",
"self",
",",
"encoding",
"=",
"'utf-8'",
")",
"->",
"str",
":",
"with",
"self",
".",
"open",
"(",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"fp",
":",
"return",
"fp",
".",
"read",
"(",
")"
] | read all text into memory. | [
"read",
"all",
"text",
"into",
"memory",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L193-L196 |
248,328 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.load | def load(self, format=None, *, kwargs={}):
'''
deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions.
'''
return load(self, format=format, kwargs=kwargs) | python | def load(self, format=None, *, kwargs={}):
'''
deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions.
'''
return load(self, format=format, kwargs=kwargs) | [
"def",
"load",
"(",
"self",
",",
"format",
"=",
"None",
",",
"*",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"return",
"load",
"(",
"self",
",",
"format",
"=",
"format",
",",
"kwargs",
"=",
"kwargs",
")"
] | deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions. | [
"deserialize",
"object",
"from",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L228-L238 |
248,329 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.dump | def dump(self, obj, format=None, *, kwargs={}):
'''
serialize the `obj` into file.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions.
'''
return dump(self, obj, format=format, kwargs=kwargs) | python | def dump(self, obj, format=None, *, kwargs={}):
'''
serialize the `obj` into file.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions.
'''
return dump(self, obj, format=format, kwargs=kwargs) | [
"def",
"dump",
"(",
"self",
",",
"obj",
",",
"format",
"=",
"None",
",",
"*",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"return",
"dump",
"(",
"self",
",",
"obj",
",",
"format",
"=",
"format",
",",
"kwargs",
"=",
"kwargs",
")"
] | serialize the `obj` into file.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any serialize exceptions. | [
"serialize",
"the",
"obj",
"into",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L240-L247 |
248,330 | Cologler/fsoopify-python | fsoopify/nodes.py | FileInfo.get_file_hash | def get_file_hash(self, *algorithms: str):
'''
get lower case hash of file.
return value is a tuple, you may need to unpack it.
for example: `get_file_hash('md5', 'sha1')` return `('XXXX1', 'XXXX2')`
'''
from .hashs import hashfile_hexdigest
return hashfile_hexdigest(self._path, algorithms) | python | def get_file_hash(self, *algorithms: str):
'''
get lower case hash of file.
return value is a tuple, you may need to unpack it.
for example: `get_file_hash('md5', 'sha1')` return `('XXXX1', 'XXXX2')`
'''
from .hashs import hashfile_hexdigest
return hashfile_hexdigest(self._path, algorithms) | [
"def",
"get_file_hash",
"(",
"self",
",",
"*",
"algorithms",
":",
"str",
")",
":",
"from",
".",
"hashs",
"import",
"hashfile_hexdigest",
"return",
"hashfile_hexdigest",
"(",
"self",
".",
"_path",
",",
"algorithms",
")"
] | get lower case hash of file.
return value is a tuple, you may need to unpack it.
for example: `get_file_hash('md5', 'sha1')` return `('XXXX1', 'XXXX2')` | [
"get",
"lower",
"case",
"hash",
"of",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L251-L260 |
248,331 | Cologler/fsoopify-python | fsoopify/nodes.py | DirectoryInfo.iter_items | def iter_items(self, depth: int = 1):
'''
get items from directory.
'''
if depth is not None and not isinstance(depth, int):
raise TypeError
def itor(root, d):
if d is not None:
d -= 1
if d < 0:
return
for name in os.listdir(root):
path = os.path.join(root, name)
node = NodeInfo.from_path(path)
yield node
if isinstance(node, DirectoryInfo):
yield from itor(path, d)
yield from itor(self._path, depth) | python | def iter_items(self, depth: int = 1):
'''
get items from directory.
'''
if depth is not None and not isinstance(depth, int):
raise TypeError
def itor(root, d):
if d is not None:
d -= 1
if d < 0:
return
for name in os.listdir(root):
path = os.path.join(root, name)
node = NodeInfo.from_path(path)
yield node
if isinstance(node, DirectoryInfo):
yield from itor(path, d)
yield from itor(self._path, depth) | [
"def",
"iter_items",
"(",
"self",
",",
"depth",
":",
"int",
"=",
"1",
")",
":",
"if",
"depth",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"depth",
",",
"int",
")",
":",
"raise",
"TypeError",
"def",
"itor",
"(",
"root",
",",
"d",
")",
":",
"if",
"d",
"is",
"not",
"None",
":",
"d",
"-=",
"1",
"if",
"d",
"<",
"0",
":",
"return",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"root",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
"node",
"=",
"NodeInfo",
".",
"from_path",
"(",
"path",
")",
"yield",
"node",
"if",
"isinstance",
"(",
"node",
",",
"DirectoryInfo",
")",
":",
"yield",
"from",
"itor",
"(",
"path",
",",
"d",
")",
"yield",
"from",
"itor",
"(",
"self",
".",
"_path",
",",
"depth",
")"
] | get items from directory. | [
"get",
"items",
"from",
"directory",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L274-L291 |
248,332 | Cologler/fsoopify-python | fsoopify/nodes.py | DirectoryInfo.has_file | def has_file(self, name: str):
'''
check whether this directory contains the file.
'''
return os.path.isfile(self._path / name) | python | def has_file(self, name: str):
'''
check whether this directory contains the file.
'''
return os.path.isfile(self._path / name) | [
"def",
"has_file",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_path",
"/",
"name",
")"
] | check whether this directory contains the file. | [
"check",
"whether",
"this",
"directory",
"contains",
"the",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L299-L303 |
248,333 | Cologler/fsoopify-python | fsoopify/nodes.py | DirectoryInfo.has_directory | def has_directory(self, name: str):
'''
check whether this directory contains the directory.
'''
return os.path.isdir(self._path / name) | python | def has_directory(self, name: str):
'''
check whether this directory contains the directory.
'''
return os.path.isdir(self._path / name) | [
"def",
"has_directory",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"_path",
"/",
"name",
")"
] | check whether this directory contains the directory. | [
"check",
"whether",
"this",
"directory",
"contains",
"the",
"directory",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L305-L309 |
248,334 | Cologler/fsoopify-python | fsoopify/nodes.py | DirectoryInfo.create_file | def create_file(self, name: str, generate_unique_name: bool = False):
'''
create a `FileInfo` for a new file.
if the file was exists, and `generate_unique_name` if `False`, raise `FileExistsError`.
the op does mean the file is created on disk.
'''
def enumerate_name():
yield name
index = 0
while True:
index += 1
yield f'{name} ({index})'
for n in enumerate_name():
path = os.path.join(self._path, n)
if os.path.exists(path):
if not generate_unique_name:
raise FileExistsError
return FileInfo(path) | python | def create_file(self, name: str, generate_unique_name: bool = False):
'''
create a `FileInfo` for a new file.
if the file was exists, and `generate_unique_name` if `False`, raise `FileExistsError`.
the op does mean the file is created on disk.
'''
def enumerate_name():
yield name
index = 0
while True:
index += 1
yield f'{name} ({index})'
for n in enumerate_name():
path = os.path.join(self._path, n)
if os.path.exists(path):
if not generate_unique_name:
raise FileExistsError
return FileInfo(path) | [
"def",
"create_file",
"(",
"self",
",",
"name",
":",
"str",
",",
"generate_unique_name",
":",
"bool",
"=",
"False",
")",
":",
"def",
"enumerate_name",
"(",
")",
":",
"yield",
"name",
"index",
"=",
"0",
"while",
"True",
":",
"index",
"+=",
"1",
"yield",
"f'{name} ({index})'",
"for",
"n",
"in",
"enumerate_name",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"n",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"not",
"generate_unique_name",
":",
"raise",
"FileExistsError",
"return",
"FileInfo",
"(",
"path",
")"
] | create a `FileInfo` for a new file.
if the file was exists, and `generate_unique_name` if `False`, raise `FileExistsError`.
the op does mean the file is created on disk. | [
"create",
"a",
"FileInfo",
"for",
"a",
"new",
"file",
"."
] | 83d45f16ae9abdea4fcc829373c32df501487dda | https://github.com/Cologler/fsoopify-python/blob/83d45f16ae9abdea4fcc829373c32df501487dda/fsoopify/nodes.py#L323-L342 |
248,335 | ulf1/oxyba | oxyba/rand_bivar.py | rand_bivar | def rand_bivar(X, rho):
"""Transform two unrelated random variables into correlated bivariate data
X : ndarray
two univariate random variables
with N observations as <N x 2> matrix
rho : float
The Pearson correlations coefficient
as number between [-1, +1]
"""
import numpy as np
Y = np.empty(X.shape)
Y[:, 0] = X[:, 0]
Y[:, 1] = rho * X[:, 0] + np.sqrt(1.0 - rho**2) * X[:, 1]
return Y | python | def rand_bivar(X, rho):
"""Transform two unrelated random variables into correlated bivariate data
X : ndarray
two univariate random variables
with N observations as <N x 2> matrix
rho : float
The Pearson correlations coefficient
as number between [-1, +1]
"""
import numpy as np
Y = np.empty(X.shape)
Y[:, 0] = X[:, 0]
Y[:, 1] = rho * X[:, 0] + np.sqrt(1.0 - rho**2) * X[:, 1]
return Y | [
"def",
"rand_bivar",
"(",
"X",
",",
"rho",
")",
":",
"import",
"numpy",
"as",
"np",
"Y",
"=",
"np",
".",
"empty",
"(",
"X",
".",
"shape",
")",
"Y",
"[",
":",
",",
"0",
"]",
"=",
"X",
"[",
":",
",",
"0",
"]",
"Y",
"[",
":",
",",
"1",
"]",
"=",
"rho",
"*",
"X",
"[",
":",
",",
"0",
"]",
"+",
"np",
".",
"sqrt",
"(",
"1.0",
"-",
"rho",
"**",
"2",
")",
"*",
"X",
"[",
":",
",",
"1",
"]",
"return",
"Y"
] | Transform two unrelated random variables into correlated bivariate data
X : ndarray
two univariate random variables
with N observations as <N x 2> matrix
rho : float
The Pearson correlations coefficient
as number between [-1, +1] | [
"Transform",
"two",
"unrelated",
"random",
"variables",
"into",
"correlated",
"bivariate",
"data"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/rand_bivar.py#L2-L17 |
248,336 | kervi/kervi-core | kervi/values/kervi_value.py | KerviValue.link_to | def link_to(self, source, transformation=None):
"""
Kervi values may be linked together.
A KerviValue is configured to be either an input or output.
When an output value is linked to an input value the input will become
an observer of the output. Every time the output value change it will notify the input
about the change.
:param source:
It is possible to make direct and indirect link.
If the type of the source parameter is of type KerviValue a direct link is created.
this is a fast link where the output can notify directly to input.
This type of link is possible if both output and input resides in the same process.
If the type of the source parameter is a string it is expected to hold the id of a another KerviValue.
In this mode the input value will listen on the kervi spine for events from the output value.
This mode is useful if the output and input does not exists in the same process.
This type of link must be made by the input.
:type source: ``str`` or ``KerviValue``
:param transformation:
A function or lambda expression that transform the value before the output is update.
This is usefull if the input expects other ranges that the output produce
or need to change the sign of the value.
"""
if isinstance(source, KerviValue):
if source.is_input and not self.is_input:
self.add_observer(source, transformation)
elif not source.is_input and self.is_input:
source.add_observer(self, transformation)
else:
raise Exception("input/output mismatch in kervi value link:{0} - {1}".format(source.name, self.name))
elif isinstance(source, str):
if len(self._spine_observers) == 0:
self.spine.register_event_handler("valueChanged", self._link_changed_event)
self._spine_observers[source] = transformation | python | def link_to(self, source, transformation=None):
"""
Kervi values may be linked together.
A KerviValue is configured to be either an input or output.
When an output value is linked to an input value the input will become
an observer of the output. Every time the output value change it will notify the input
about the change.
:param source:
It is possible to make direct and indirect link.
If the type of the source parameter is of type KerviValue a direct link is created.
this is a fast link where the output can notify directly to input.
This type of link is possible if both output and input resides in the same process.
If the type of the source parameter is a string it is expected to hold the id of a another KerviValue.
In this mode the input value will listen on the kervi spine for events from the output value.
This mode is useful if the output and input does not exists in the same process.
This type of link must be made by the input.
:type source: ``str`` or ``KerviValue``
:param transformation:
A function or lambda expression that transform the value before the output is update.
This is usefull if the input expects other ranges that the output produce
or need to change the sign of the value.
"""
if isinstance(source, KerviValue):
if source.is_input and not self.is_input:
self.add_observer(source, transformation)
elif not source.is_input and self.is_input:
source.add_observer(self, transformation)
else:
raise Exception("input/output mismatch in kervi value link:{0} - {1}".format(source.name, self.name))
elif isinstance(source, str):
if len(self._spine_observers) == 0:
self.spine.register_event_handler("valueChanged", self._link_changed_event)
self._spine_observers[source] = transformation | [
"def",
"link_to",
"(",
"self",
",",
"source",
",",
"transformation",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"KerviValue",
")",
":",
"if",
"source",
".",
"is_input",
"and",
"not",
"self",
".",
"is_input",
":",
"self",
".",
"add_observer",
"(",
"source",
",",
"transformation",
")",
"elif",
"not",
"source",
".",
"is_input",
"and",
"self",
".",
"is_input",
":",
"source",
".",
"add_observer",
"(",
"self",
",",
"transformation",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"input/output mismatch in kervi value link:{0} - {1}\"",
".",
"format",
"(",
"source",
".",
"name",
",",
"self",
".",
"name",
")",
")",
"elif",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"if",
"len",
"(",
"self",
".",
"_spine_observers",
")",
"==",
"0",
":",
"self",
".",
"spine",
".",
"register_event_handler",
"(",
"\"valueChanged\"",
",",
"self",
".",
"_link_changed_event",
")",
"self",
".",
"_spine_observers",
"[",
"source",
"]",
"=",
"transformation"
] | Kervi values may be linked together.
A KerviValue is configured to be either an input or output.
When an output value is linked to an input value the input will become
an observer of the output. Every time the output value change it will notify the input
about the change.
:param source:
It is possible to make direct and indirect link.
If the type of the source parameter is of type KerviValue a direct link is created.
this is a fast link where the output can notify directly to input.
This type of link is possible if both output and input resides in the same process.
If the type of the source parameter is a string it is expected to hold the id of a another KerviValue.
In this mode the input value will listen on the kervi spine for events from the output value.
This mode is useful if the output and input does not exists in the same process.
This type of link must be made by the input.
:type source: ``str`` or ``KerviValue``
:param transformation:
A function or lambda expression that transform the value before the output is update.
This is usefull if the input expects other ranges that the output produce
or need to change the sign of the value. | [
"Kervi",
"values",
"may",
"be",
"linked",
"together",
".",
"A",
"KerviValue",
"is",
"configured",
"to",
"be",
"either",
"an",
"input",
"or",
"output",
".",
"When",
"an",
"output",
"value",
"is",
"linked",
"to",
"an",
"input",
"value",
"the",
"input",
"will",
"become",
"an",
"observer",
"of",
"the",
"output",
".",
"Every",
"time",
"the",
"output",
"value",
"change",
"it",
"will",
"notify",
"the",
"input",
"about",
"the",
"change",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/kervi_value.py#L157-L196 |
248,337 | kervi/kervi-core | kervi/values/kervi_value.py | KerviValue.link_to_dashboard | def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs):
r"""
Links this value to a dashboard panel.
:param dashboard_id:
Id of the dashboard to link to.
:type dashboard_id: str
:param panel_id:
Id of the panel on the dashboard to link to.
:type panel_id: str
:param \**kwargs:
Use the kwargs below to override default values for ui parameters
:Keyword Arguments:
* *link_to_header* (``str``) -- Link this value to header of the panel.
* *label_icon* (``str``) -- Icon that should be displayed together with label.
* *label* (``str``) -- Label text, default value is the name of the value.
* *flat* (``bool``) -- Flat look and feel.
* *inline* (``bool``) -- Display value and label in its actual size
If you set inline to true the size parameter is ignored.
The value will only occupy as much space as the label and input takes.
* *input_size* (``int``) -- width of the slider as a percentage of the total container it sits in.
* *value_size* (``int``) -- width of the value area as a percentage of the total container it sits in.
"""
KerviComponent.link_to_dashboard(
self,
dashboard_id,
panel_id,
**kwargs
) | python | def link_to_dashboard(self, dashboard_id=None, panel_id=None, **kwargs):
r"""
Links this value to a dashboard panel.
:param dashboard_id:
Id of the dashboard to link to.
:type dashboard_id: str
:param panel_id:
Id of the panel on the dashboard to link to.
:type panel_id: str
:param \**kwargs:
Use the kwargs below to override default values for ui parameters
:Keyword Arguments:
* *link_to_header* (``str``) -- Link this value to header of the panel.
* *label_icon* (``str``) -- Icon that should be displayed together with label.
* *label* (``str``) -- Label text, default value is the name of the value.
* *flat* (``bool``) -- Flat look and feel.
* *inline* (``bool``) -- Display value and label in its actual size
If you set inline to true the size parameter is ignored.
The value will only occupy as much space as the label and input takes.
* *input_size* (``int``) -- width of the slider as a percentage of the total container it sits in.
* *value_size* (``int``) -- width of the value area as a percentage of the total container it sits in.
"""
KerviComponent.link_to_dashboard(
self,
dashboard_id,
panel_id,
**kwargs
) | [
"def",
"link_to_dashboard",
"(",
"self",
",",
"dashboard_id",
"=",
"None",
",",
"panel_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"KerviComponent",
".",
"link_to_dashboard",
"(",
"self",
",",
"dashboard_id",
",",
"panel_id",
",",
"*",
"*",
"kwargs",
")"
] | r"""
Links this value to a dashboard panel.
:param dashboard_id:
Id of the dashboard to link to.
:type dashboard_id: str
:param panel_id:
Id of the panel on the dashboard to link to.
:type panel_id: str
:param \**kwargs:
Use the kwargs below to override default values for ui parameters
:Keyword Arguments:
* *link_to_header* (``str``) -- Link this value to header of the panel.
* *label_icon* (``str``) -- Icon that should be displayed together with label.
* *label* (``str``) -- Label text, default value is the name of the value.
* *flat* (``bool``) -- Flat look and feel.
* *inline* (``bool``) -- Display value and label in its actual size
If you set inline to true the size parameter is ignored.
The value will only occupy as much space as the label and input takes.
* *input_size* (``int``) -- width of the slider as a percentage of the total container it sits in.
* *value_size* (``int``) -- width of the value area as a percentage of the total container it sits in. | [
"r",
"Links",
"this",
"value",
"to",
"a",
"dashboard",
"panel",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/kervi_value.py#L198-L236 |
248,338 | mmk2410/uulm-mensa | uulm_mensa/cli.py | get | def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data | python | def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data | [
"def",
"get",
"(",
"url",
")",
":",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"url",
")",
"data",
"=",
"response",
".",
"read",
"(",
")",
"data",
"=",
"data",
".",
"decode",
"(",
"\"utf-8\"",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"return",
"data"
] | Recieving the JSON file from uulm | [
"Recieving",
"the",
"JSON",
"file",
"from",
"uulm"
] | 17c915655525f5bc3a6de06a8a86fa8df4401363 | https://github.com/mmk2410/uulm-mensa/blob/17c915655525f5bc3a6de06a8a86fa8df4401363/uulm_mensa/cli.py#L37-L43 |
248,339 | mmk2410/uulm-mensa | uulm_mensa/cli.py | get_day | def get_day():
"""Function for retrieving the wanted day"""
day = datetime.datetime.today().weekday()
if len(sys.argv) == 3:
if sys.argv[2] == "mon":
day = 0
elif sys.argv[2] == "tue":
day = 1
elif sys.argv[2] == "wed":
day = 2
elif sys.argv[2] == "thur":
day = 3
elif sys.argv[2] == "fri":
day = 4
else:
day = 5
if day > 4:
print("There is no information about the menu today.")
exit(5)
return day | python | def get_day():
"""Function for retrieving the wanted day"""
day = datetime.datetime.today().weekday()
if len(sys.argv) == 3:
if sys.argv[2] == "mon":
day = 0
elif sys.argv[2] == "tue":
day = 1
elif sys.argv[2] == "wed":
day = 2
elif sys.argv[2] == "thur":
day = 3
elif sys.argv[2] == "fri":
day = 4
else:
day = 5
if day > 4:
print("There is no information about the menu today.")
exit(5)
return day | [
"def",
"get_day",
"(",
")",
":",
"day",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
".",
"weekday",
"(",
")",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"3",
":",
"if",
"sys",
".",
"argv",
"[",
"2",
"]",
"==",
"\"mon\"",
":",
"day",
"=",
"0",
"elif",
"sys",
".",
"argv",
"[",
"2",
"]",
"==",
"\"tue\"",
":",
"day",
"=",
"1",
"elif",
"sys",
".",
"argv",
"[",
"2",
"]",
"==",
"\"wed\"",
":",
"day",
"=",
"2",
"elif",
"sys",
".",
"argv",
"[",
"2",
"]",
"==",
"\"thur\"",
":",
"day",
"=",
"3",
"elif",
"sys",
".",
"argv",
"[",
"2",
"]",
"==",
"\"fri\"",
":",
"day",
"=",
"4",
"else",
":",
"day",
"=",
"5",
"if",
"day",
">",
"4",
":",
"print",
"(",
"\"There is no information about the menu today.\"",
")",
"exit",
"(",
"5",
")",
"return",
"day"
] | Function for retrieving the wanted day | [
"Function",
"for",
"retrieving",
"the",
"wanted",
"day"
] | 17c915655525f5bc3a6de06a8a86fa8df4401363 | https://github.com/mmk2410/uulm-mensa/blob/17c915655525f5bc3a6de06a8a86fa8df4401363/uulm_mensa/cli.py#L45-L64 |
248,340 | mmk2410/uulm-mensa | uulm_mensa/cli.py | print_menu | def print_menu(place, static=False):
"""Function for printing the menu
Keyword arguments:
place -- name of the cafeteria / mensa
static -- set true if a static menu exists (default: False)
"""
day = get_day()
if static:
plan = get(FILES[1])
for meal in plan["weeks"][0]["days"][day][place]["meals"]:
if place == "Diner":
print(meal["category"] + " " + meal["meal"])
else:
print(meal["category"] + ": " + meal["meal"])
else:
plan = get(FILES[0])
for meal in plan["weeks"][0]["days"][day][place]["meals"]:
print(meal["category"] + ": " + meal["meal"]) | python | def print_menu(place, static=False):
"""Function for printing the menu
Keyword arguments:
place -- name of the cafeteria / mensa
static -- set true if a static menu exists (default: False)
"""
day = get_day()
if static:
plan = get(FILES[1])
for meal in plan["weeks"][0]["days"][day][place]["meals"]:
if place == "Diner":
print(meal["category"] + " " + meal["meal"])
else:
print(meal["category"] + ": " + meal["meal"])
else:
plan = get(FILES[0])
for meal in plan["weeks"][0]["days"][day][place]["meals"]:
print(meal["category"] + ": " + meal["meal"]) | [
"def",
"print_menu",
"(",
"place",
",",
"static",
"=",
"False",
")",
":",
"day",
"=",
"get_day",
"(",
")",
"if",
"static",
":",
"plan",
"=",
"get",
"(",
"FILES",
"[",
"1",
"]",
")",
"for",
"meal",
"in",
"plan",
"[",
"\"weeks\"",
"]",
"[",
"0",
"]",
"[",
"\"days\"",
"]",
"[",
"day",
"]",
"[",
"place",
"]",
"[",
"\"meals\"",
"]",
":",
"if",
"place",
"==",
"\"Diner\"",
":",
"print",
"(",
"meal",
"[",
"\"category\"",
"]",
"+",
"\" \"",
"+",
"meal",
"[",
"\"meal\"",
"]",
")",
"else",
":",
"print",
"(",
"meal",
"[",
"\"category\"",
"]",
"+",
"\": \"",
"+",
"meal",
"[",
"\"meal\"",
"]",
")",
"else",
":",
"plan",
"=",
"get",
"(",
"FILES",
"[",
"0",
"]",
")",
"for",
"meal",
"in",
"plan",
"[",
"\"weeks\"",
"]",
"[",
"0",
"]",
"[",
"\"days\"",
"]",
"[",
"day",
"]",
"[",
"place",
"]",
"[",
"\"meals\"",
"]",
":",
"print",
"(",
"meal",
"[",
"\"category\"",
"]",
"+",
"\": \"",
"+",
"meal",
"[",
"\"meal\"",
"]",
")"
] | Function for printing the menu
Keyword arguments:
place -- name of the cafeteria / mensa
static -- set true if a static menu exists (default: False) | [
"Function",
"for",
"printing",
"the",
"menu"
] | 17c915655525f5bc3a6de06a8a86fa8df4401363 | https://github.com/mmk2410/uulm-mensa/blob/17c915655525f5bc3a6de06a8a86fa8df4401363/uulm_mensa/cli.py#L66-L84 |
248,341 | miquelo/resort | packages/resort/__init__.py | command_init | def command_init(prog_name, prof_mgr, prof_name, prog_args):
"""
Initialize a profile.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"type",
metavar="type",
type=str,
nargs=1,
help="profile type"
)
args = parser.parse_args(prog_args)
# Profile store
prof_type = args.type[0]
prof_mgr.store(prof_name, prof_type) | python | def command_init(prog_name, prof_mgr, prof_name, prog_args):
"""
Initialize a profile.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"type",
metavar="type",
type=str,
nargs=1,
help="profile type"
)
args = parser.parse_args(prog_args)
# Profile store
prof_type = args.type[0]
prof_mgr.store(prof_name, prof_type) | [
"def",
"command_init",
"(",
"prog_name",
",",
"prof_mgr",
",",
"prof_name",
",",
"prog_args",
")",
":",
"# Retrieve arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog_name",
")",
"parser",
".",
"add_argument",
"(",
"\"type\"",
",",
"metavar",
"=",
"\"type\"",
",",
"type",
"=",
"str",
",",
"nargs",
"=",
"1",
",",
"help",
"=",
"\"profile type\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"prog_args",
")",
"# Profile store",
"prof_type",
"=",
"args",
".",
"type",
"[",
"0",
"]",
"prof_mgr",
".",
"store",
"(",
"prof_name",
",",
"prof_type",
")"
] | Initialize a profile. | [
"Initialize",
"a",
"profile",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/__init__.py#L194-L215 |
248,342 | miquelo/resort | packages/resort/__init__.py | command_list | def command_list(prog_name, prof_mgr, prof_name, prog_args):
"""
Print the list of components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Print component list
out = io.StringIO()
for comp_stub in prof_stub.component_list():
if comp_stub.name() is not None:
out.write(comp_stub.name())
out.write("\n")
out.seek(0)
sys.stdout.write(out.read()) | python | def command_list(prog_name, prof_mgr, prof_name, prog_args):
"""
Print the list of components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Print component list
out = io.StringIO()
for comp_stub in prof_stub.component_list():
if comp_stub.name() is not None:
out.write(comp_stub.name())
out.write("\n")
out.seek(0)
sys.stdout.write(out.read()) | [
"def",
"command_list",
"(",
"prog_name",
",",
"prof_mgr",
",",
"prof_name",
",",
"prog_args",
")",
":",
"# Retrieve arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog_name",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"prog_args",
")",
"# Profile load",
"prof_stub",
"=",
"prof_mgr",
".",
"load",
"(",
"prof_name",
")",
"# Print component list",
"out",
"=",
"io",
".",
"StringIO",
"(",
")",
"for",
"comp_stub",
"in",
"prof_stub",
".",
"component_list",
"(",
")",
":",
"if",
"comp_stub",
".",
"name",
"(",
")",
"is",
"not",
"None",
":",
"out",
".",
"write",
"(",
"comp_stub",
".",
"name",
"(",
")",
")",
"out",
".",
"write",
"(",
"\"\\n\"",
")",
"out",
".",
"seek",
"(",
"0",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"out",
".",
"read",
"(",
")",
")"
] | Print the list of components. | [
"Print",
"the",
"list",
"of",
"components",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/__init__.py#L220-L242 |
248,343 | miquelo/resort | packages/resort/__init__.py | command_status | def command_status(prog_name, prof_mgr, prof_name, prog_args):
"""
Show status of component tree.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"-t",
"--type",
required=False,
action="store_true",
default=False,
dest="show_type",
help="show component qualified class name"
)
parser.add_argument(
"-d",
"--depth",
metavar="tree_depth",
required=False,
type=argparse_status_depth,
default=None,
dest="tree_depth",
help="integer value of dependency tree depth"
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
# Print status
show_type = args.show_type
tree_depth = args.tree_depth
context = prof_stub.context()
out = io.StringIO()
for i, comp_stub in enumerate(comp_stubs):
last = i == len(comp_stubs) - 1
print_component_status(out, context, comp_stub, last, 1, [], show_type,
tree_depth)
out.seek(0)
sys.stdout.write(out.read()) | python | def command_status(prog_name, prof_mgr, prof_name, prog_args):
"""
Show status of component tree.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"-t",
"--type",
required=False,
action="store_true",
default=False,
dest="show_type",
help="show component qualified class name"
)
parser.add_argument(
"-d",
"--depth",
metavar="tree_depth",
required=False,
type=argparse_status_depth,
default=None,
dest="tree_depth",
help="integer value of dependency tree depth"
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
# Print status
show_type = args.show_type
tree_depth = args.tree_depth
context = prof_stub.context()
out = io.StringIO()
for i, comp_stub in enumerate(comp_stubs):
last = i == len(comp_stubs) - 1
print_component_status(out, context, comp_stub, last, 1, [], show_type,
tree_depth)
out.seek(0)
sys.stdout.write(out.read()) | [
"def",
"command_status",
"(",
"prog_name",
",",
"prof_mgr",
",",
"prof_name",
",",
"prog_args",
")",
":",
"# Retrieve arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog_name",
")",
"parser",
".",
"add_argument",
"(",
"\"-t\"",
",",
"\"--type\"",
",",
"required",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"dest",
"=",
"\"show_type\"",
",",
"help",
"=",
"\"show component qualified class name\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-d\"",
",",
"\"--depth\"",
",",
"metavar",
"=",
"\"tree_depth\"",
",",
"required",
"=",
"False",
",",
"type",
"=",
"argparse_status_depth",
",",
"default",
"=",
"None",
",",
"dest",
"=",
"\"tree_depth\"",
",",
"help",
"=",
"\"integer value of dependency tree depth\"",
")",
"parser",
".",
"add_argument",
"(",
"\"components\"",
",",
"metavar",
"=",
"\"comps\"",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"system components\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"prog_args",
")",
"# Profile load",
"prof_stub",
"=",
"prof_mgr",
".",
"load",
"(",
"prof_name",
")",
"# Collect component stubs",
"comp_stubs",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
".",
"components",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Empty component list\"",
")",
"for",
"comp_name",
"in",
"args",
".",
"components",
":",
"comp_stub",
"=",
"prof_stub",
".",
"component",
"(",
"comp_name",
")",
"component_exists",
"(",
"prof_stub",
",",
"comp_stub",
")",
"comp_stubs",
".",
"append",
"(",
"comp_stub",
")",
"# Print status",
"show_type",
"=",
"args",
".",
"show_type",
"tree_depth",
"=",
"args",
".",
"tree_depth",
"context",
"=",
"prof_stub",
".",
"context",
"(",
")",
"out",
"=",
"io",
".",
"StringIO",
"(",
")",
"for",
"i",
",",
"comp_stub",
"in",
"enumerate",
"(",
"comp_stubs",
")",
":",
"last",
"=",
"i",
"==",
"len",
"(",
"comp_stubs",
")",
"-",
"1",
"print_component_status",
"(",
"out",
",",
"context",
",",
"comp_stub",
",",
"last",
",",
"1",
",",
"[",
"]",
",",
"show_type",
",",
"tree_depth",
")",
"out",
".",
"seek",
"(",
"0",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"out",
".",
"read",
"(",
")",
")"
] | Show status of component tree. | [
"Show",
"status",
"of",
"component",
"tree",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/__init__.py#L247-L306 |
248,344 | miquelo/resort | packages/resort/__init__.py | command_insert | def command_insert(prog_name, prof_mgr, prof_name, prog_args):
"""
Insert components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
# Create insert plan
context = prof_stub.context()
plan = []
for comp_stub in comp_stubs:
comp_stub.insert(context, plan)
# Execute insert plan
for op in plan:
operation_execute(op, context) | python | def command_insert(prog_name, prof_mgr, prof_name, prog_args):
"""
Insert components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
# Create insert plan
context = prof_stub.context()
plan = []
for comp_stub in comp_stubs:
comp_stub.insert(context, plan)
# Execute insert plan
for op in plan:
operation_execute(op, context) | [
"def",
"command_insert",
"(",
"prog_name",
",",
"prof_mgr",
",",
"prof_name",
",",
"prog_args",
")",
":",
"# Retrieve arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog_name",
")",
"parser",
".",
"add_argument",
"(",
"\"components\"",
",",
"metavar",
"=",
"\"comps\"",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"system components\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"prog_args",
")",
"# Profile load",
"prof_stub",
"=",
"prof_mgr",
".",
"load",
"(",
"prof_name",
")",
"# Collect component stubs",
"comp_stubs",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
".",
"components",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Empty component list\"",
")",
"for",
"comp_name",
"in",
"args",
".",
"components",
":",
"comp_stub",
"=",
"prof_stub",
".",
"component",
"(",
"comp_name",
")",
"component_exists",
"(",
"prof_stub",
",",
"comp_stub",
")",
"comp_stubs",
".",
"append",
"(",
"comp_stub",
")",
"# Create insert plan",
"context",
"=",
"prof_stub",
".",
"context",
"(",
")",
"plan",
"=",
"[",
"]",
"for",
"comp_stub",
"in",
"comp_stubs",
":",
"comp_stub",
".",
"insert",
"(",
"context",
",",
"plan",
")",
"# Execute insert plan",
"for",
"op",
"in",
"plan",
":",
"operation_execute",
"(",
"op",
",",
"context",
")"
] | Insert components. | [
"Insert",
"components",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/__init__.py#L311-L349 |
248,345 | miquelo/resort | packages/resort/__init__.py | command_update | def command_update(prog_name, prof_mgr, prof_name, prog_args):
"""
Update components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
context = prof_stub.context()
# Create delete plan
plan = []
for comp_stub in comp_stubs:
comp_stub.delete(context, plan)
# Execute delete plan
for op in plan:
operation_execute(op, context)
# Update component stub list
for op in plan:
comp_stub = prof_stub.component(op.name())
if comp_stub not in comp_stubs:
comp_stubs.append(comp_stub)
# Create insert plan
plan = []
for comp_stub in comp_stubs:
comp_stub.insert(context, plan)
# Execute insert plan
for op in plan:
operation_execute(op, context) | python | def command_update(prog_name, prof_mgr, prof_name, prog_args):
"""
Update components.
"""
# Retrieve arguments
parser = argparse.ArgumentParser(
prog=prog_name
)
parser.add_argument(
"components",
metavar="comps",
nargs=argparse.REMAINDER,
help="system components"
)
args = parser.parse_args(prog_args)
# Profile load
prof_stub = prof_mgr.load(prof_name)
# Collect component stubs
comp_stubs = []
if len(args.components) == 0:
raise Exception("Empty component list")
for comp_name in args.components:
comp_stub = prof_stub.component(comp_name)
component_exists(prof_stub, comp_stub)
comp_stubs.append(comp_stub)
context = prof_stub.context()
# Create delete plan
plan = []
for comp_stub in comp_stubs:
comp_stub.delete(context, plan)
# Execute delete plan
for op in plan:
operation_execute(op, context)
# Update component stub list
for op in plan:
comp_stub = prof_stub.component(op.name())
if comp_stub not in comp_stubs:
comp_stubs.append(comp_stub)
# Create insert plan
plan = []
for comp_stub in comp_stubs:
comp_stub.insert(context, plan)
# Execute insert plan
for op in plan:
operation_execute(op, context) | [
"def",
"command_update",
"(",
"prog_name",
",",
"prof_mgr",
",",
"prof_name",
",",
"prog_args",
")",
":",
"# Retrieve arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"prog_name",
")",
"parser",
".",
"add_argument",
"(",
"\"components\"",
",",
"metavar",
"=",
"\"comps\"",
",",
"nargs",
"=",
"argparse",
".",
"REMAINDER",
",",
"help",
"=",
"\"system components\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"prog_args",
")",
"# Profile load",
"prof_stub",
"=",
"prof_mgr",
".",
"load",
"(",
"prof_name",
")",
"# Collect component stubs",
"comp_stubs",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
".",
"components",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Empty component list\"",
")",
"for",
"comp_name",
"in",
"args",
".",
"components",
":",
"comp_stub",
"=",
"prof_stub",
".",
"component",
"(",
"comp_name",
")",
"component_exists",
"(",
"prof_stub",
",",
"comp_stub",
")",
"comp_stubs",
".",
"append",
"(",
"comp_stub",
")",
"context",
"=",
"prof_stub",
".",
"context",
"(",
")",
"# Create delete plan",
"plan",
"=",
"[",
"]",
"for",
"comp_stub",
"in",
"comp_stubs",
":",
"comp_stub",
".",
"delete",
"(",
"context",
",",
"plan",
")",
"# Execute delete plan",
"for",
"op",
"in",
"plan",
":",
"operation_execute",
"(",
"op",
",",
"context",
")",
"# Update component stub list",
"for",
"op",
"in",
"plan",
":",
"comp_stub",
"=",
"prof_stub",
".",
"component",
"(",
"op",
".",
"name",
"(",
")",
")",
"if",
"comp_stub",
"not",
"in",
"comp_stubs",
":",
"comp_stubs",
".",
"append",
"(",
"comp_stub",
")",
"# Create insert plan",
"plan",
"=",
"[",
"]",
"for",
"comp_stub",
"in",
"comp_stubs",
":",
"comp_stub",
".",
"insert",
"(",
"context",
",",
"plan",
")",
"# Execute insert plan",
"for",
"op",
"in",
"plan",
":",
"operation_execute",
"(",
"op",
",",
"context",
")"
] | Update components. | [
"Update",
"components",
"."
] | 097a25d3257c91a75c194fd44c2797ab356f85dd | https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/__init__.py#L397-L451 |
248,346 | tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_sims.py | gp_sims_panel | def gp_sims_panel(version):
"""panel plot of cocktail simulations at all energies, includ. total
:param version: plot version / input subdir name
:type version: str
"""
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
mesons = ['pion', 'eta', 'etap', 'rho', 'omega', 'phi', 'jpsi']
fstems = ['cocktail_contribs/'+m for m in mesons] + ['cocktail', 'cocktail_contribs/ccbar']
data = OrderedDict((energy, [
np.loadtxt(open(os.path.join(inDir, fstem+str(energy)+'.dat'), 'rb'))
for fstem in fstems
]) for energy in energies)
for v in data.values():
# keep syserrs for total cocktail
v[-2][:,(2,3)] = 0
# all errors zero for cocktail contribs
v[-1][:,2:] = 0
for d in v[:-2]: d[:,2:] = 0
make_panel(
dpt_dict = OrderedDict((
' '.join([getEnergy4Key(str(energy)), 'GeV']),
[ data[energy], [
'with %s lc %s lw 5 lt %d' % (
'lines' if i!=len(fstems)-2 else 'filledcurves pt 0',
default_colors[(-2*i-2) if i!=len(fstems)-2 else 0] \
if i!=len(fstems)-1 else default_colors[1], int(i==3)+1
) for i in xrange(len(fstems))
], [particleLabel4Key(m) for m in mesons] + [
'Cocktail (w/o {/Symbol \162})', particleLabel4Key('ccbar')
]]
) for energy in energies),
name = os.path.join(outDir, 'sims_panel'),
ylog = True, xr = [0.,3.2], yr = [1e-6,9],
xlabel = xlabel, ylabel = ylabel,
layout = '2x2', size = '7in,9in',
key = ['width -4', 'spacing 1.5', 'nobox', 'at graph 0.9,0.95']
) | python | def gp_sims_panel(version):
"""panel plot of cocktail simulations at all energies, includ. total
:param version: plot version / input subdir name
:type version: str
"""
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
mesons = ['pion', 'eta', 'etap', 'rho', 'omega', 'phi', 'jpsi']
fstems = ['cocktail_contribs/'+m for m in mesons] + ['cocktail', 'cocktail_contribs/ccbar']
data = OrderedDict((energy, [
np.loadtxt(open(os.path.join(inDir, fstem+str(energy)+'.dat'), 'rb'))
for fstem in fstems
]) for energy in energies)
for v in data.values():
# keep syserrs for total cocktail
v[-2][:,(2,3)] = 0
# all errors zero for cocktail contribs
v[-1][:,2:] = 0
for d in v[:-2]: d[:,2:] = 0
make_panel(
dpt_dict = OrderedDict((
' '.join([getEnergy4Key(str(energy)), 'GeV']),
[ data[energy], [
'with %s lc %s lw 5 lt %d' % (
'lines' if i!=len(fstems)-2 else 'filledcurves pt 0',
default_colors[(-2*i-2) if i!=len(fstems)-2 else 0] \
if i!=len(fstems)-1 else default_colors[1], int(i==3)+1
) for i in xrange(len(fstems))
], [particleLabel4Key(m) for m in mesons] + [
'Cocktail (w/o {/Symbol \162})', particleLabel4Key('ccbar')
]]
) for energy in energies),
name = os.path.join(outDir, 'sims_panel'),
ylog = True, xr = [0.,3.2], yr = [1e-6,9],
xlabel = xlabel, ylabel = ylabel,
layout = '2x2', size = '7in,9in',
key = ['width -4', 'spacing 1.5', 'nobox', 'at graph 0.9,0.95']
) | [
"def",
"gp_sims_panel",
"(",
"version",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"inDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"version",
")",
"mesons",
"=",
"[",
"'pion'",
",",
"'eta'",
",",
"'etap'",
",",
"'rho'",
",",
"'omega'",
",",
"'phi'",
",",
"'jpsi'",
"]",
"fstems",
"=",
"[",
"'cocktail_contribs/'",
"+",
"m",
"for",
"m",
"in",
"mesons",
"]",
"+",
"[",
"'cocktail'",
",",
"'cocktail_contribs/ccbar'",
"]",
"data",
"=",
"OrderedDict",
"(",
"(",
"energy",
",",
"[",
"np",
".",
"loadtxt",
"(",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"fstem",
"+",
"str",
"(",
"energy",
")",
"+",
"'.dat'",
")",
",",
"'rb'",
")",
")",
"for",
"fstem",
"in",
"fstems",
"]",
")",
"for",
"energy",
"in",
"energies",
")",
"for",
"v",
"in",
"data",
".",
"values",
"(",
")",
":",
"# keep syserrs for total cocktail",
"v",
"[",
"-",
"2",
"]",
"[",
":",
",",
"(",
"2",
",",
"3",
")",
"]",
"=",
"0",
"# all errors zero for cocktail contribs",
"v",
"[",
"-",
"1",
"]",
"[",
":",
",",
"2",
":",
"]",
"=",
"0",
"for",
"d",
"in",
"v",
"[",
":",
"-",
"2",
"]",
":",
"d",
"[",
":",
",",
"2",
":",
"]",
"=",
"0",
"make_panel",
"(",
"dpt_dict",
"=",
"OrderedDict",
"(",
"(",
"' '",
".",
"join",
"(",
"[",
"getEnergy4Key",
"(",
"str",
"(",
"energy",
")",
")",
",",
"'GeV'",
"]",
")",
",",
"[",
"data",
"[",
"energy",
"]",
",",
"[",
"'with %s lc %s lw 5 lt %d'",
"%",
"(",
"'lines'",
"if",
"i",
"!=",
"len",
"(",
"fstems",
")",
"-",
"2",
"else",
"'filledcurves pt 0'",
",",
"default_colors",
"[",
"(",
"-",
"2",
"*",
"i",
"-",
"2",
")",
"if",
"i",
"!=",
"len",
"(",
"fstems",
")",
"-",
"2",
"else",
"0",
"]",
"if",
"i",
"!=",
"len",
"(",
"fstems",
")",
"-",
"1",
"else",
"default_colors",
"[",
"1",
"]",
",",
"int",
"(",
"i",
"==",
"3",
")",
"+",
"1",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"fstems",
")",
")",
"]",
",",
"[",
"particleLabel4Key",
"(",
"m",
")",
"for",
"m",
"in",
"mesons",
"]",
"+",
"[",
"'Cocktail (w/o {/Symbol \\162})'",
",",
"particleLabel4Key",
"(",
"'ccbar'",
")",
"]",
"]",
")",
"for",
"energy",
"in",
"energies",
")",
",",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outDir",
",",
"'sims_panel'",
")",
",",
"ylog",
"=",
"True",
",",
"xr",
"=",
"[",
"0.",
",",
"3.2",
"]",
",",
"yr",
"=",
"[",
"1e-6",
",",
"9",
"]",
",",
"xlabel",
"=",
"xlabel",
",",
"ylabel",
"=",
"ylabel",
",",
"layout",
"=",
"'2x2'",
",",
"size",
"=",
"'7in,9in'",
",",
"key",
"=",
"[",
"'width -4'",
",",
"'spacing 1.5'",
",",
"'nobox'",
",",
"'at graph 0.9,0.95'",
"]",
")"
] | panel plot of cocktail simulations at all energies, includ. total
:param version: plot version / input subdir name
:type version: str | [
"panel",
"plot",
"of",
"cocktail",
"simulations",
"at",
"all",
"energies",
"includ",
".",
"total"
] | e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2 | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_sims.py#L62-L100 |
248,347 | tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_sims.py | gp_sims_total_overlay | def gp_sims_total_overlay(version):
"""single plot comparing total cocktails at all energies
:param version: plot version / input subdir name
:type version: str
"""
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
data = OrderedDict()
for energy in energies:
fname = os.path.join(inDir, 'cocktail'+str(energy)+'.dat')
data[energy] = np.loadtxt(open(fname, 'rb'))
data[energy][:,2:] = 0
make_plot(
data = data.values(),
properties = [
'with lines lc %s lw 4 lt 1' % (default_colors[i])
for i in xrange(len(energies))
],
titles = [
' '.join([getEnergy4Key(str(energy)), 'GeV'])
for energy in energies
],
xlabel = xlabel, ylabel = ylabel,
name = os.path.join(outDir, 'sims_total_overlay'),
ylog = True, xr = [0.,3.2], yr = [1e-6,9],
tmargin = 0.98, rmargin = 0.99, bmargin = 0.14,
size = '8.5in,8in',
) | python | def gp_sims_total_overlay(version):
"""single plot comparing total cocktails at all energies
:param version: plot version / input subdir name
:type version: str
"""
inDir, outDir = getWorkDirs()
inDir = os.path.join(inDir, version)
data = OrderedDict()
for energy in energies:
fname = os.path.join(inDir, 'cocktail'+str(energy)+'.dat')
data[energy] = np.loadtxt(open(fname, 'rb'))
data[energy][:,2:] = 0
make_plot(
data = data.values(),
properties = [
'with lines lc %s lw 4 lt 1' % (default_colors[i])
for i in xrange(len(energies))
],
titles = [
' '.join([getEnergy4Key(str(energy)), 'GeV'])
for energy in energies
],
xlabel = xlabel, ylabel = ylabel,
name = os.path.join(outDir, 'sims_total_overlay'),
ylog = True, xr = [0.,3.2], yr = [1e-6,9],
tmargin = 0.98, rmargin = 0.99, bmargin = 0.14,
size = '8.5in,8in',
) | [
"def",
"gp_sims_total_overlay",
"(",
"version",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"inDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"version",
")",
"data",
"=",
"OrderedDict",
"(",
")",
"for",
"energy",
"in",
"energies",
":",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"'cocktail'",
"+",
"str",
"(",
"energy",
")",
"+",
"'.dat'",
")",
"data",
"[",
"energy",
"]",
"=",
"np",
".",
"loadtxt",
"(",
"open",
"(",
"fname",
",",
"'rb'",
")",
")",
"data",
"[",
"energy",
"]",
"[",
":",
",",
"2",
":",
"]",
"=",
"0",
"make_plot",
"(",
"data",
"=",
"data",
".",
"values",
"(",
")",
",",
"properties",
"=",
"[",
"'with lines lc %s lw 4 lt 1'",
"%",
"(",
"default_colors",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"energies",
")",
")",
"]",
",",
"titles",
"=",
"[",
"' '",
".",
"join",
"(",
"[",
"getEnergy4Key",
"(",
"str",
"(",
"energy",
")",
")",
",",
"'GeV'",
"]",
")",
"for",
"energy",
"in",
"energies",
"]",
",",
"xlabel",
"=",
"xlabel",
",",
"ylabel",
"=",
"ylabel",
",",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outDir",
",",
"'sims_total_overlay'",
")",
",",
"ylog",
"=",
"True",
",",
"xr",
"=",
"[",
"0.",
",",
"3.2",
"]",
",",
"yr",
"=",
"[",
"1e-6",
",",
"9",
"]",
",",
"tmargin",
"=",
"0.98",
",",
"rmargin",
"=",
"0.99",
",",
"bmargin",
"=",
"0.14",
",",
"size",
"=",
"'8.5in,8in'",
",",
")"
] | single plot comparing total cocktails at all energies
:param version: plot version / input subdir name
:type version: str | [
"single",
"plot",
"comparing",
"total",
"cocktails",
"at",
"all",
"energies"
] | e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2 | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_sims.py#L102-L130 |
248,348 | yougov/vr.runners | vr/runners/image.py | prepare_image | def prepare_image(tarpath, outfolder, **kwargs):
"""Unpack the OS image stored at tarpath to outfolder.
Prepare the unpacked image for use as a VR base image.
"""
outfolder = path.Path(outfolder)
untar(tarpath, outfolder, **kwargs)
# Some OSes have started making /etc/resolv.conf into a symlink to
# /run/resolv.conf. That prevents us from bind-mounting to that
# location. So delete that symlink, if it exists.
resolv_path = outfolder / 'etc' / 'resolv.conf'
if resolv_path.islink():
resolv_path.remove().write_text('', encoding='ascii') | python | def prepare_image(tarpath, outfolder, **kwargs):
"""Unpack the OS image stored at tarpath to outfolder.
Prepare the unpacked image for use as a VR base image.
"""
outfolder = path.Path(outfolder)
untar(tarpath, outfolder, **kwargs)
# Some OSes have started making /etc/resolv.conf into a symlink to
# /run/resolv.conf. That prevents us from bind-mounting to that
# location. So delete that symlink, if it exists.
resolv_path = outfolder / 'etc' / 'resolv.conf'
if resolv_path.islink():
resolv_path.remove().write_text('', encoding='ascii') | [
"def",
"prepare_image",
"(",
"tarpath",
",",
"outfolder",
",",
"*",
"*",
"kwargs",
")",
":",
"outfolder",
"=",
"path",
".",
"Path",
"(",
"outfolder",
")",
"untar",
"(",
"tarpath",
",",
"outfolder",
",",
"*",
"*",
"kwargs",
")",
"# Some OSes have started making /etc/resolv.conf into a symlink to",
"# /run/resolv.conf. That prevents us from bind-mounting to that",
"# location. So delete that symlink, if it exists.",
"resolv_path",
"=",
"outfolder",
"/",
"'etc'",
"/",
"'resolv.conf'",
"if",
"resolv_path",
".",
"islink",
"(",
")",
":",
"resolv_path",
".",
"remove",
"(",
")",
".",
"write_text",
"(",
"''",
",",
"encoding",
"=",
"'ascii'",
")"
] | Unpack the OS image stored at tarpath to outfolder.
Prepare the unpacked image for use as a VR base image. | [
"Unpack",
"the",
"OS",
"image",
"stored",
"at",
"tarpath",
"to",
"outfolder",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/image.py#L29-L43 |
248,349 | yougov/vr.runners | vr/runners/image.py | ImageRunner.ensure_image | def ensure_image(self):
"""
Ensure that config.image_url has been downloaded and unpacked.
"""
image_folder = self.get_image_folder()
if os.path.exists(image_folder):
print(
'OS image directory {} exists...not overwriting' .format(
image_folder))
return
ensure_image(
self.config.image_name,
self.config.image_url,
IMAGES_ROOT,
getattr(self.config, 'image_md5', None),
self.get_image_folder()
) | python | def ensure_image(self):
"""
Ensure that config.image_url has been downloaded and unpacked.
"""
image_folder = self.get_image_folder()
if os.path.exists(image_folder):
print(
'OS image directory {} exists...not overwriting' .format(
image_folder))
return
ensure_image(
self.config.image_name,
self.config.image_url,
IMAGES_ROOT,
getattr(self.config, 'image_md5', None),
self.get_image_folder()
) | [
"def",
"ensure_image",
"(",
"self",
")",
":",
"image_folder",
"=",
"self",
".",
"get_image_folder",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"image_folder",
")",
":",
"print",
"(",
"'OS image directory {} exists...not overwriting'",
".",
"format",
"(",
"image_folder",
")",
")",
"return",
"ensure_image",
"(",
"self",
".",
"config",
".",
"image_name",
",",
"self",
".",
"config",
".",
"image_url",
",",
"IMAGES_ROOT",
",",
"getattr",
"(",
"self",
".",
"config",
",",
"'image_md5'",
",",
"None",
")",
",",
"self",
".",
"get_image_folder",
"(",
")",
")"
] | Ensure that config.image_url has been downloaded and unpacked. | [
"Ensure",
"that",
"config",
".",
"image_url",
"has",
"been",
"downloaded",
"and",
"unpacked",
"."
] | f43ba50a64b17ee4f07596fe225bcb38ca6652ad | https://github.com/yougov/vr.runners/blob/f43ba50a64b17ee4f07596fe225bcb38ca6652ad/vr/runners/image.py#L79-L96 |
248,350 | lthibault/expmpp | expmpp/client.py | Client.notify | def notify(self, msg):
"""Send a notification to all registered listeners.
msg : str
Message to send to each listener
"""
for listener in self.listeners:
self._send(listener, msg) | python | def notify(self, msg):
"""Send a notification to all registered listeners.
msg : str
Message to send to each listener
"""
for listener in self.listeners:
self._send(listener, msg) | [
"def",
"notify",
"(",
"self",
",",
"msg",
")",
":",
"for",
"listener",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"_send",
"(",
"listener",
",",
"msg",
")"
] | Send a notification to all registered listeners.
msg : str
Message to send to each listener | [
"Send",
"a",
"notification",
"to",
"all",
"registered",
"listeners",
"."
] | 635fb3187fe4021410e0f06ca6896098b5e1d3b4 | https://github.com/lthibault/expmpp/blob/635fb3187fe4021410e0f06ca6896098b5e1d3b4/expmpp/client.py#L87-L94 |
248,351 | emencia/dr-dump | drdump/builder.py | ScriptBuilder.get_deps_manager | def get_deps_manager(self, *args, **kwargs):
"""
Return instance of the dependancies manager using given args and kwargs
Add 'silent_key_error' option in kwargs if not given.
"""
if 'silent_key_error' not in kwargs:
kwargs['silent_key_error'] = self.silent_key_error
return self.deps_manager(*args, **kwargs) | python | def get_deps_manager(self, *args, **kwargs):
"""
Return instance of the dependancies manager using given args and kwargs
Add 'silent_key_error' option in kwargs if not given.
"""
if 'silent_key_error' not in kwargs:
kwargs['silent_key_error'] = self.silent_key_error
return self.deps_manager(*args, **kwargs) | [
"def",
"get_deps_manager",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'silent_key_error'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'silent_key_error'",
"]",
"=",
"self",
".",
"silent_key_error",
"return",
"self",
".",
"deps_manager",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return instance of the dependancies manager using given args and kwargs
Add 'silent_key_error' option in kwargs if not given. | [
"Return",
"instance",
"of",
"the",
"dependancies",
"manager",
"using",
"given",
"args",
"and",
"kwargs"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L67-L75 |
248,352 | emencia/dr-dump | drdump/builder.py | ScriptBuilder.build_template | def build_template(self, mapfile, names, renderer):
"""
Build source from global and item templates
"""
AVAILABLE_DUMPS = json.load(open(mapfile, "r"))
manager = self.get_deps_manager(AVAILABLE_DUMPS)
fp = StringIO.StringIO()
for i, item in enumerate(manager.get_dump_order(names), start=1):
fp = renderer(fp, i, item, manager[item])
if self.dump_other_apps:
exclude_models = ['-e {0}'.format(app) for app in
self.exclude_apps]
for i, item in enumerate(manager.get_dump_order(names), start=1):
for model in manager[item]['models']:
if '-e ' not in model:
model = "-e {0}".format(model)
if model not in exclude_models:
exclude_models.append(model)
fp = renderer(fp, i+1, 'other_apps', {'models': exclude_models,
'use_natural_key': True})
content = fp.getvalue()
fp.close()
context = self.get_global_context().copy()
context.update({'items': content})
return self.base_template.format(**context) | python | def build_template(self, mapfile, names, renderer):
"""
Build source from global and item templates
"""
AVAILABLE_DUMPS = json.load(open(mapfile, "r"))
manager = self.get_deps_manager(AVAILABLE_DUMPS)
fp = StringIO.StringIO()
for i, item in enumerate(manager.get_dump_order(names), start=1):
fp = renderer(fp, i, item, manager[item])
if self.dump_other_apps:
exclude_models = ['-e {0}'.format(app) for app in
self.exclude_apps]
for i, item in enumerate(manager.get_dump_order(names), start=1):
for model in manager[item]['models']:
if '-e ' not in model:
model = "-e {0}".format(model)
if model not in exclude_models:
exclude_models.append(model)
fp = renderer(fp, i+1, 'other_apps', {'models': exclude_models,
'use_natural_key': True})
content = fp.getvalue()
fp.close()
context = self.get_global_context().copy()
context.update({'items': content})
return self.base_template.format(**context) | [
"def",
"build_template",
"(",
"self",
",",
"mapfile",
",",
"names",
",",
"renderer",
")",
":",
"AVAILABLE_DUMPS",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"mapfile",
",",
"\"r\"",
")",
")",
"manager",
"=",
"self",
".",
"get_deps_manager",
"(",
"AVAILABLE_DUMPS",
")",
"fp",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"manager",
".",
"get_dump_order",
"(",
"names",
")",
",",
"start",
"=",
"1",
")",
":",
"fp",
"=",
"renderer",
"(",
"fp",
",",
"i",
",",
"item",
",",
"manager",
"[",
"item",
"]",
")",
"if",
"self",
".",
"dump_other_apps",
":",
"exclude_models",
"=",
"[",
"'-e {0}'",
".",
"format",
"(",
"app",
")",
"for",
"app",
"in",
"self",
".",
"exclude_apps",
"]",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"manager",
".",
"get_dump_order",
"(",
"names",
")",
",",
"start",
"=",
"1",
")",
":",
"for",
"model",
"in",
"manager",
"[",
"item",
"]",
"[",
"'models'",
"]",
":",
"if",
"'-e '",
"not",
"in",
"model",
":",
"model",
"=",
"\"-e {0}\"",
".",
"format",
"(",
"model",
")",
"if",
"model",
"not",
"in",
"exclude_models",
":",
"exclude_models",
".",
"append",
"(",
"model",
")",
"fp",
"=",
"renderer",
"(",
"fp",
",",
"i",
"+",
"1",
",",
"'other_apps'",
",",
"{",
"'models'",
":",
"exclude_models",
",",
"'use_natural_key'",
":",
"True",
"}",
")",
"content",
"=",
"fp",
".",
"getvalue",
"(",
")",
"fp",
".",
"close",
"(",
")",
"context",
"=",
"self",
".",
"get_global_context",
"(",
")",
".",
"copy",
"(",
")",
"context",
".",
"update",
"(",
"{",
"'items'",
":",
"content",
"}",
")",
"return",
"self",
".",
"base_template",
".",
"format",
"(",
"*",
"*",
"context",
")"
] | Build source from global and item templates | [
"Build",
"source",
"from",
"global",
"and",
"item",
"templates"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L84-L115 |
248,353 | emencia/dr-dump | drdump/builder.py | ScriptBuilder._get_dump_item_context | def _get_dump_item_context(self, index, name, opts):
"""
Return a formated dict context
"""
c = {
'item_no': index,
'label': name,
'name': name,
'models': ' '.join(opts['models']),
'natural_key': '',
}
if opts.get('use_natural_key', False):
c['natural_key'] = ' -n'
c.update(self.get_global_context())
return c | python | def _get_dump_item_context(self, index, name, opts):
"""
Return a formated dict context
"""
c = {
'item_no': index,
'label': name,
'name': name,
'models': ' '.join(opts['models']),
'natural_key': '',
}
if opts.get('use_natural_key', False):
c['natural_key'] = ' -n'
c.update(self.get_global_context())
return c | [
"def",
"_get_dump_item_context",
"(",
"self",
",",
"index",
",",
"name",
",",
"opts",
")",
":",
"c",
"=",
"{",
"'item_no'",
":",
"index",
",",
"'label'",
":",
"name",
",",
"'name'",
":",
"name",
",",
"'models'",
":",
"' '",
".",
"join",
"(",
"opts",
"[",
"'models'",
"]",
")",
",",
"'natural_key'",
":",
"''",
",",
"}",
"if",
"opts",
".",
"get",
"(",
"'use_natural_key'",
",",
"False",
")",
":",
"c",
"[",
"'natural_key'",
"]",
"=",
"' -n'",
"c",
".",
"update",
"(",
"self",
".",
"get_global_context",
"(",
")",
")",
"return",
"c"
] | Return a formated dict context | [
"Return",
"a",
"formated",
"dict",
"context"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L117-L131 |
248,354 | emencia/dr-dump | drdump/builder.py | ScriptBuilder._dumpdata_template | def _dumpdata_template(self, stringbuffer, index, name, opts):
"""
StringIO "templates" to build a command line for 'dumpdata'
"""
context = self._get_dump_item_context(index, name, opts)
stringbuffer.write(self.dumper_item_template.format(**context))
return stringbuffer | python | def _dumpdata_template(self, stringbuffer, index, name, opts):
"""
StringIO "templates" to build a command line for 'dumpdata'
"""
context = self._get_dump_item_context(index, name, opts)
stringbuffer.write(self.dumper_item_template.format(**context))
return stringbuffer | [
"def",
"_dumpdata_template",
"(",
"self",
",",
"stringbuffer",
",",
"index",
",",
"name",
",",
"opts",
")",
":",
"context",
"=",
"self",
".",
"_get_dump_item_context",
"(",
"index",
",",
"name",
",",
"opts",
")",
"stringbuffer",
".",
"write",
"(",
"self",
".",
"dumper_item_template",
".",
"format",
"(",
"*",
"*",
"context",
")",
")",
"return",
"stringbuffer"
] | StringIO "templates" to build a command line for 'dumpdata' | [
"StringIO",
"templates",
"to",
"build",
"a",
"command",
"line",
"for",
"dumpdata"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L133-L141 |
248,355 | emencia/dr-dump | drdump/builder.py | ScriptBuilder._loaddata_template | def _loaddata_template(self, stringbuffer, index, name, opts):
"""
StringIO "templates" to build a command line for 'loaddata'
"""
context = self._get_dump_item_context(index, name, opts)
stringbuffer.write(self.loadder_item_template.format(**context))
return stringbuffer | python | def _loaddata_template(self, stringbuffer, index, name, opts):
"""
StringIO "templates" to build a command line for 'loaddata'
"""
context = self._get_dump_item_context(index, name, opts)
stringbuffer.write(self.loadder_item_template.format(**context))
return stringbuffer | [
"def",
"_loaddata_template",
"(",
"self",
",",
"stringbuffer",
",",
"index",
",",
"name",
",",
"opts",
")",
":",
"context",
"=",
"self",
".",
"_get_dump_item_context",
"(",
"index",
",",
"name",
",",
"opts",
")",
"stringbuffer",
".",
"write",
"(",
"self",
".",
"loadder_item_template",
".",
"format",
"(",
"*",
"*",
"context",
")",
")",
"return",
"stringbuffer"
] | StringIO "templates" to build a command line for 'loaddata' | [
"StringIO",
"templates",
"to",
"build",
"a",
"command",
"line",
"for",
"loaddata"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L143-L151 |
248,356 | emencia/dr-dump | drdump/builder.py | ScriptBuilder.generate_dumper | def generate_dumper(self, mapfile, names):
"""
Build dumpdata commands
"""
return self.build_template(mapfile, names, self._dumpdata_template) | python | def generate_dumper(self, mapfile, names):
"""
Build dumpdata commands
"""
return self.build_template(mapfile, names, self._dumpdata_template) | [
"def",
"generate_dumper",
"(",
"self",
",",
"mapfile",
",",
"names",
")",
":",
"return",
"self",
".",
"build_template",
"(",
"mapfile",
",",
"names",
",",
"self",
".",
"_dumpdata_template",
")"
] | Build dumpdata commands | [
"Build",
"dumpdata",
"commands"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L153-L157 |
248,357 | emencia/dr-dump | drdump/builder.py | ScriptBuilder.generate_loader | def generate_loader(self, mapfile, names):
"""
Build loaddata commands
"""
return self.build_template(mapfile, names, self._loaddata_template) | python | def generate_loader(self, mapfile, names):
"""
Build loaddata commands
"""
return self.build_template(mapfile, names, self._loaddata_template) | [
"def",
"generate_loader",
"(",
"self",
",",
"mapfile",
",",
"names",
")",
":",
"return",
"self",
".",
"build_template",
"(",
"mapfile",
",",
"names",
",",
"self",
".",
"_loaddata_template",
")"
] | Build loaddata commands | [
"Build",
"loaddata",
"commands"
] | f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b | https://github.com/emencia/dr-dump/blob/f03a2ed01fb82e6fe1df66f7fa82e646a3822d4b/drdump/builder.py#L159-L163 |
248,358 | abe-winter/pg13-py | pg13/misc.py | tbframes | def tbframes(tb):
'unwind traceback tb_next structure to array'
frames=[tb.tb_frame]
while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame)
return frames | python | def tbframes(tb):
'unwind traceback tb_next structure to array'
frames=[tb.tb_frame]
while tb.tb_next: tb=tb.tb_next; frames.append(tb.tb_frame)
return frames | [
"def",
"tbframes",
"(",
"tb",
")",
":",
"frames",
"=",
"[",
"tb",
".",
"tb_frame",
"]",
"while",
"tb",
".",
"tb_next",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"frames",
".",
"append",
"(",
"tb",
".",
"tb_frame",
")",
"return",
"frames"
] | unwind traceback tb_next structure to array | [
"unwind",
"traceback",
"tb_next",
"structure",
"to",
"array"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/misc.py#L7-L11 |
248,359 | abe-winter/pg13-py | pg13/misc.py | tbfuncs | def tbfuncs(frames):
'this takes the frames array returned by tbframes'
return ['%s:%s:%s'%(os.path.split(f.f_code.co_filename)[-1],f.f_code.co_name,f.f_lineno) for f in frames] | python | def tbfuncs(frames):
'this takes the frames array returned by tbframes'
return ['%s:%s:%s'%(os.path.split(f.f_code.co_filename)[-1],f.f_code.co_name,f.f_lineno) for f in frames] | [
"def",
"tbfuncs",
"(",
"frames",
")",
":",
"return",
"[",
"'%s:%s:%s'",
"%",
"(",
"os",
".",
"path",
".",
"split",
"(",
"f",
".",
"f_code",
".",
"co_filename",
")",
"[",
"-",
"1",
"]",
",",
"f",
".",
"f_code",
".",
"co_name",
",",
"f",
".",
"f_lineno",
")",
"for",
"f",
"in",
"frames",
"]"
] | this takes the frames array returned by tbframes | [
"this",
"takes",
"the",
"frames",
"array",
"returned",
"by",
"tbframes"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/misc.py#L12-L14 |
248,360 | BenjaminSchubert/NitPycker | nitpycker/result.py | InterProcessResult.add_result | def add_result(self, _type, test, exc_info=None):
"""
Adds the given result to the list
:param _type: type of the state of the test (TestState.failure, TestState.error, ...)
:param test: the test
:param exc_info: additional execution information
"""
if exc_info is not None:
exc_info = FrozenExcInfo(exc_info)
test.time_taken = time.time() - self.start_time
test._outcome = None
self.result_queue.put((_type, test, exc_info)) | python | def add_result(self, _type, test, exc_info=None):
"""
Adds the given result to the list
:param _type: type of the state of the test (TestState.failure, TestState.error, ...)
:param test: the test
:param exc_info: additional execution information
"""
if exc_info is not None:
exc_info = FrozenExcInfo(exc_info)
test.time_taken = time.time() - self.start_time
test._outcome = None
self.result_queue.put((_type, test, exc_info)) | [
"def",
"add_result",
"(",
"self",
",",
"_type",
",",
"test",
",",
"exc_info",
"=",
"None",
")",
":",
"if",
"exc_info",
"is",
"not",
"None",
":",
"exc_info",
"=",
"FrozenExcInfo",
"(",
"exc_info",
")",
"test",
".",
"time_taken",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
"test",
".",
"_outcome",
"=",
"None",
"self",
".",
"result_queue",
".",
"put",
"(",
"(",
"_type",
",",
"test",
",",
"exc_info",
")",
")"
] | Adds the given result to the list
:param _type: type of the state of the test (TestState.failure, TestState.error, ...)
:param test: the test
:param exc_info: additional execution information | [
"Adds",
"the",
"given",
"result",
"to",
"the",
"list"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L58-L70 |
248,361 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addError | def addError(self, test, err):
"""
registers a test as error
:param test: test to register
:param err: error the test gave
"""
super().addError(test, err)
self.test_info(test)
self._call_test_results('addError', test, err) | python | def addError(self, test, err):
"""
registers a test as error
:param test: test to register
:param err: error the test gave
"""
super().addError(test, err)
self.test_info(test)
self._call_test_results('addError', test, err) | [
"def",
"addError",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"super",
"(",
")",
".",
"addError",
"(",
"test",
",",
"err",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addError'",
",",
"test",
",",
"err",
")"
] | registers a test as error
:param test: test to register
:param err: error the test gave | [
"registers",
"a",
"test",
"as",
"error"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L211-L220 |
248,362 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addExpectedFailure | def addExpectedFailure(self, test, err):
"""
registers as test as expected failure
:param test: test to register
:param err: error the test gave
"""
super().addExpectedFailure(test, err)
self.test_info(test)
self._call_test_results('addExpectedFailure', test, err) | python | def addExpectedFailure(self, test, err):
"""
registers as test as expected failure
:param test: test to register
:param err: error the test gave
"""
super().addExpectedFailure(test, err)
self.test_info(test)
self._call_test_results('addExpectedFailure', test, err) | [
"def",
"addExpectedFailure",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"super",
"(",
")",
".",
"addExpectedFailure",
"(",
"test",
",",
"err",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addExpectedFailure'",
",",
"test",
",",
"err",
")"
] | registers as test as expected failure
:param test: test to register
:param err: error the test gave | [
"registers",
"as",
"test",
"as",
"expected",
"failure"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L222-L231 |
248,363 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addFailure | def addFailure(self, test, err):
"""
registers a test as failure
:param test: test to register
:param err: error the test gave
"""
super().addFailure(test, err)
self.test_info(test)
self._call_test_results('addFailure', test, err) | python | def addFailure(self, test, err):
"""
registers a test as failure
:param test: test to register
:param err: error the test gave
"""
super().addFailure(test, err)
self.test_info(test)
self._call_test_results('addFailure', test, err) | [
"def",
"addFailure",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"super",
"(",
")",
".",
"addFailure",
"(",
"test",
",",
"err",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addFailure'",
",",
"test",
",",
"err",
")"
] | registers a test as failure
:param test: test to register
:param err: error the test gave | [
"registers",
"a",
"test",
"as",
"failure"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L233-L242 |
248,364 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addSkip | def addSkip(self, test, reason):
"""
registers a test as skipped
:param test: test to register
:param reason: reason why the test was skipped
"""
super().addSkip(test, reason)
self.test_info(test)
self._call_test_results('addSkip', test, reason) | python | def addSkip(self, test, reason):
"""
registers a test as skipped
:param test: test to register
:param reason: reason why the test was skipped
"""
super().addSkip(test, reason)
self.test_info(test)
self._call_test_results('addSkip', test, reason) | [
"def",
"addSkip",
"(",
"self",
",",
"test",
",",
"reason",
")",
":",
"super",
"(",
")",
".",
"addSkip",
"(",
"test",
",",
"reason",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addSkip'",
",",
"test",
",",
"reason",
")"
] | registers a test as skipped
:param test: test to register
:param reason: reason why the test was skipped | [
"registers",
"a",
"test",
"as",
"skipped"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L244-L253 |
248,365 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addSuccess | def addSuccess(self, test):
"""
registers a test as successful
:param test: test to register
"""
super().addSuccess(test)
self.test_info(test)
self._call_test_results('addSuccess', test) | python | def addSuccess(self, test):
"""
registers a test as successful
:param test: test to register
"""
super().addSuccess(test)
self.test_info(test)
self._call_test_results('addSuccess', test) | [
"def",
"addSuccess",
"(",
"self",
",",
"test",
")",
":",
"super",
"(",
")",
".",
"addSuccess",
"(",
"test",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addSuccess'",
",",
"test",
")"
] | registers a test as successful
:param test: test to register | [
"registers",
"a",
"test",
"as",
"successful"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L255-L263 |
248,366 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.addUnexpectedSuccess | def addUnexpectedSuccess(self, test):
"""
registers a test as an unexpected success
:param test: test to register
"""
super().addUnexpectedSuccess(test)
self.test_info(test)
self._call_test_results('addUnexpectedSuccess', test) | python | def addUnexpectedSuccess(self, test):
"""
registers a test as an unexpected success
:param test: test to register
"""
super().addUnexpectedSuccess(test)
self.test_info(test)
self._call_test_results('addUnexpectedSuccess', test) | [
"def",
"addUnexpectedSuccess",
"(",
"self",
",",
"test",
")",
":",
"super",
"(",
")",
".",
"addUnexpectedSuccess",
"(",
"test",
")",
"self",
".",
"test_info",
"(",
"test",
")",
"self",
".",
"_call_test_results",
"(",
"'addUnexpectedSuccess'",
",",
"test",
")"
] | registers a test as an unexpected success
:param test: test to register | [
"registers",
"a",
"test",
"as",
"an",
"unexpected",
"success"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L265-L273 |
248,367 | BenjaminSchubert/NitPycker | nitpycker/result.py | ResultCollector.run | def run(self) -> None:
"""
processes entries in the queue until told to stop
"""
while not self.cleanup:
try:
result, test, additional_info = self.result_queue.get(timeout=1)
except queue.Empty:
continue
self.result_queue.task_done()
if result == TestState.serialization_failure:
test = self.tests[test]
warnings.warn("Serialization error: {} on test {}".format(
additional_info, test), SerializationWarning)
test(self)
else:
self.testsRun += 1
if result == TestState.success:
self.addSuccess(test)
elif result == TestState.failure:
self.addFailure(test, additional_info)
elif result == TestState.error:
self.addError(test, additional_info)
elif result == TestState.skipped:
self.addSkip(test, additional_info)
elif result == TestState.expected_failure:
self.addExpectedFailure(test, additional_info)
elif result == TestState.unexpected_success:
self.addUnexpectedSuccess(test)
else:
raise Exception("This is not a valid test type :", result) | python | def run(self) -> None:
"""
processes entries in the queue until told to stop
"""
while not self.cleanup:
try:
result, test, additional_info = self.result_queue.get(timeout=1)
except queue.Empty:
continue
self.result_queue.task_done()
if result == TestState.serialization_failure:
test = self.tests[test]
warnings.warn("Serialization error: {} on test {}".format(
additional_info, test), SerializationWarning)
test(self)
else:
self.testsRun += 1
if result == TestState.success:
self.addSuccess(test)
elif result == TestState.failure:
self.addFailure(test, additional_info)
elif result == TestState.error:
self.addError(test, additional_info)
elif result == TestState.skipped:
self.addSkip(test, additional_info)
elif result == TestState.expected_failure:
self.addExpectedFailure(test, additional_info)
elif result == TestState.unexpected_success:
self.addUnexpectedSuccess(test)
else:
raise Exception("This is not a valid test type :", result) | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"while",
"not",
"self",
".",
"cleanup",
":",
"try",
":",
"result",
",",
"test",
",",
"additional_info",
"=",
"self",
".",
"result_queue",
".",
"get",
"(",
"timeout",
"=",
"1",
")",
"except",
"queue",
".",
"Empty",
":",
"continue",
"self",
".",
"result_queue",
".",
"task_done",
"(",
")",
"if",
"result",
"==",
"TestState",
".",
"serialization_failure",
":",
"test",
"=",
"self",
".",
"tests",
"[",
"test",
"]",
"warnings",
".",
"warn",
"(",
"\"Serialization error: {} on test {}\"",
".",
"format",
"(",
"additional_info",
",",
"test",
")",
",",
"SerializationWarning",
")",
"test",
"(",
"self",
")",
"else",
":",
"self",
".",
"testsRun",
"+=",
"1",
"if",
"result",
"==",
"TestState",
".",
"success",
":",
"self",
".",
"addSuccess",
"(",
"test",
")",
"elif",
"result",
"==",
"TestState",
".",
"failure",
":",
"self",
".",
"addFailure",
"(",
"test",
",",
"additional_info",
")",
"elif",
"result",
"==",
"TestState",
".",
"error",
":",
"self",
".",
"addError",
"(",
"test",
",",
"additional_info",
")",
"elif",
"result",
"==",
"TestState",
".",
"skipped",
":",
"self",
".",
"addSkip",
"(",
"test",
",",
"additional_info",
")",
"elif",
"result",
"==",
"TestState",
".",
"expected_failure",
":",
"self",
".",
"addExpectedFailure",
"(",
"test",
",",
"additional_info",
")",
"elif",
"result",
"==",
"TestState",
".",
"unexpected_success",
":",
"self",
".",
"addUnexpectedSuccess",
"(",
"test",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"This is not a valid test type :\"",
",",
"result",
")"
] | processes entries in the queue until told to stop | [
"processes",
"entries",
"in",
"the",
"queue",
"until",
"told",
"to",
"stop"
] | 3ac2b3bf06f1d704b4853167a967311b0465a76f | https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L281-L315 |
248,368 | redhog/pieshell | pieshell/environ.py | Environment._expand_argument | def _expand_argument(self, arg):
"""Performs argument glob expansion on an argument string.
Returns a list of strings.
"""
if isinstance(arg, R): return [arg.str]
scope = self._scope or self._exports
arg = arg % scope
arg = os.path.expanduser(arg)
res = glob.glob(self._expand_path(arg))
if not res: return [arg]
if self._cwd != "/":
for idx in xrange(0, len(res)):
if res[idx].startswith(self._cwd + "/"):
res[idx] = "./" + res[idx][len(self._cwd + "/"):]
return res | python | def _expand_argument(self, arg):
"""Performs argument glob expansion on an argument string.
Returns a list of strings.
"""
if isinstance(arg, R): return [arg.str]
scope = self._scope or self._exports
arg = arg % scope
arg = os.path.expanduser(arg)
res = glob.glob(self._expand_path(arg))
if not res: return [arg]
if self._cwd != "/":
for idx in xrange(0, len(res)):
if res[idx].startswith(self._cwd + "/"):
res[idx] = "./" + res[idx][len(self._cwd + "/"):]
return res | [
"def",
"_expand_argument",
"(",
"self",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"R",
")",
":",
"return",
"[",
"arg",
".",
"str",
"]",
"scope",
"=",
"self",
".",
"_scope",
"or",
"self",
".",
"_exports",
"arg",
"=",
"arg",
"%",
"scope",
"arg",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"arg",
")",
"res",
"=",
"glob",
".",
"glob",
"(",
"self",
".",
"_expand_path",
"(",
"arg",
")",
")",
"if",
"not",
"res",
":",
"return",
"[",
"arg",
"]",
"if",
"self",
".",
"_cwd",
"!=",
"\"/\"",
":",
"for",
"idx",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"res",
")",
")",
":",
"if",
"res",
"[",
"idx",
"]",
".",
"startswith",
"(",
"self",
".",
"_cwd",
"+",
"\"/\"",
")",
":",
"res",
"[",
"idx",
"]",
"=",
"\"./\"",
"+",
"res",
"[",
"idx",
"]",
"[",
"len",
"(",
"self",
".",
"_cwd",
"+",
"\"/\"",
")",
":",
"]",
"return",
"res"
] | Performs argument glob expansion on an argument string.
Returns a list of strings. | [
"Performs",
"argument",
"glob",
"expansion",
"on",
"an",
"argument",
"string",
".",
"Returns",
"a",
"list",
"of",
"strings",
"."
] | 11cff3b93785ee4446f99b9134be20380edeb767 | https://github.com/redhog/pieshell/blob/11cff3b93785ee4446f99b9134be20380edeb767/pieshell/environ.py#L67-L81 |
248,369 | thomasballinger/trellocardupdate | trellocardupdate/trelloupdate.py | retry_on_bad_auth | def retry_on_bad_auth(func):
"""If bad token or board, try again after clearing relevant cache entries"""
@wraps(func)
def retry_version(self, *args, **kwargs):
while True:
try:
return func(self, *args, **kwargs)
except trolly.ResourceUnavailable:
sys.stderr.write('bad request (refresh board id)\n')
self._board_id = None
self.save_key('board_id', None)
except trolly.Unauthorised:
sys.stderr.write('bad permissions (refresh token)\n')
self._client = None
self._token = None
self.save_key('token', None)
return retry_version | python | def retry_on_bad_auth(func):
"""If bad token or board, try again after clearing relevant cache entries"""
@wraps(func)
def retry_version(self, *args, **kwargs):
while True:
try:
return func(self, *args, **kwargs)
except trolly.ResourceUnavailable:
sys.stderr.write('bad request (refresh board id)\n')
self._board_id = None
self.save_key('board_id', None)
except trolly.Unauthorised:
sys.stderr.write('bad permissions (refresh token)\n')
self._client = None
self._token = None
self.save_key('token', None)
return retry_version | [
"def",
"retry_on_bad_auth",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"retry_version",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"trolly",
".",
"ResourceUnavailable",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'bad request (refresh board id)\\n'",
")",
"self",
".",
"_board_id",
"=",
"None",
"self",
".",
"save_key",
"(",
"'board_id'",
",",
"None",
")",
"except",
"trolly",
".",
"Unauthorised",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'bad permissions (refresh token)\\n'",
")",
"self",
".",
"_client",
"=",
"None",
"self",
".",
"_token",
"=",
"None",
"self",
".",
"save_key",
"(",
"'token'",
",",
"None",
")",
"return",
"retry_version"
] | If bad token or board, try again after clearing relevant cache entries | [
"If",
"bad",
"token",
"or",
"board",
"try",
"again",
"after",
"clearing",
"relevant",
"cache",
"entries"
] | 16a648fa15efef144c07cd56fcdb1d8920fac889 | https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/trelloupdate.py#L14-L30 |
248,370 | thomasballinger/trellocardupdate | trellocardupdate/trelloupdate.py | cached_accessor | def cached_accessor(func_or_att):
"""Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments
att = func_or_att.__name__
return cached_accessor(func_or_att.__name__)(func_or_att)
att = func_or_att
def make_cached_function(func):
@wraps(func)
def cached_check_version(self):
private_att = '_'+att
if getattr(self, private_att):
return getattr(self, private_att)
setattr(self, private_att, self.load_key(att))
if getattr(self, private_att):
return getattr(self, private_att)
value = func(self)
setattr(self, private_att, value)
self.save_key(att, value)
return value
return cached_check_version
return make_cached_function | python | def cached_accessor(func_or_att):
"""Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments
att = func_or_att.__name__
return cached_accessor(func_or_att.__name__)(func_or_att)
att = func_or_att
def make_cached_function(func):
@wraps(func)
def cached_check_version(self):
private_att = '_'+att
if getattr(self, private_att):
return getattr(self, private_att)
setattr(self, private_att, self.load_key(att))
if getattr(self, private_att):
return getattr(self, private_att)
value = func(self)
setattr(self, private_att, value)
self.save_key(att, value)
return value
return cached_check_version
return make_cached_function | [
"def",
"cached_accessor",
"(",
"func_or_att",
")",
":",
"if",
"callable",
"(",
"func_or_att",
")",
":",
"#allows decorator to be called without arguments",
"att",
"=",
"func_or_att",
".",
"__name__",
"return",
"cached_accessor",
"(",
"func_or_att",
".",
"__name__",
")",
"(",
"func_or_att",
")",
"att",
"=",
"func_or_att",
"def",
"make_cached_function",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"cached_check_version",
"(",
"self",
")",
":",
"private_att",
"=",
"'_'",
"+",
"att",
"if",
"getattr",
"(",
"self",
",",
"private_att",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"private_att",
")",
"setattr",
"(",
"self",
",",
"private_att",
",",
"self",
".",
"load_key",
"(",
"att",
")",
")",
"if",
"getattr",
"(",
"self",
",",
"private_att",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"private_att",
")",
"value",
"=",
"func",
"(",
"self",
")",
"setattr",
"(",
"self",
",",
"private_att",
",",
"value",
")",
"self",
".",
"save_key",
"(",
"att",
",",
"value",
")",
"return",
"value",
"return",
"cached_check_version",
"return",
"make_cached_function"
] | Decorated function checks in-memory cache and disc cache for att first | [
"Decorated",
"function",
"checks",
"in",
"-",
"memory",
"cache",
"and",
"disc",
"cache",
"for",
"att",
"first"
] | 16a648fa15efef144c07cd56fcdb1d8920fac889 | https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/trelloupdate.py#L32-L52 |
248,371 | thomasballinger/trellocardupdate | trellocardupdate/trelloupdate.py | TrelloUpdater.ask_for_board_id | def ask_for_board_id(self):
"""Factored out in case interface isn't keyboard"""
board_id = raw_input("paste in board id or url: ").strip()
m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id)
if m:
board_id = m.group(1)
return board_id | python | def ask_for_board_id(self):
"""Factored out in case interface isn't keyboard"""
board_id = raw_input("paste in board id or url: ").strip()
m = re.search(r"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)", board_id)
if m:
board_id = m.group(1)
return board_id | [
"def",
"ask_for_board_id",
"(",
"self",
")",
":",
"board_id",
"=",
"raw_input",
"(",
"\"paste in board id or url: \"",
")",
".",
"strip",
"(",
")",
"m",
"=",
"re",
".",
"search",
"(",
"r\"(?:https?://)?(?:trello.com)?/?b?/?([a-zA-Z]{8})/(?:.*)\"",
",",
"board_id",
")",
"if",
"m",
":",
"board_id",
"=",
"m",
".",
"group",
"(",
"1",
")",
"return",
"board_id"
] | Factored out in case interface isn't keyboard | [
"Factored",
"out",
"in",
"case",
"interface",
"isn",
"t",
"keyboard"
] | 16a648fa15efef144c07cd56fcdb1d8920fac889 | https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/trelloupdate.py#L110-L116 |
248,372 | mrallen1/pygett | pygett/base.py | Gett.get_share | def get_share(self, sharename):
"""
Get a specific share. Does not require authentication.
Input:
* A sharename
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
share = client.get_share("4ddfds")
"""
response = GettRequest().get("/shares/%s" % sharename)
if response.http_status == 200:
return GettShare(self.user, **response.response) | python | def get_share(self, sharename):
"""
Get a specific share. Does not require authentication.
Input:
* A sharename
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
share = client.get_share("4ddfds")
"""
response = GettRequest().get("/shares/%s" % sharename)
if response.http_status == 200:
return GettShare(self.user, **response.response) | [
"def",
"get_share",
"(",
"self",
",",
"sharename",
")",
":",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/shares/%s\"",
"%",
"sharename",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"return",
"GettShare",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")"
] | Get a specific share. Does not require authentication.
Input:
* A sharename
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
share = client.get_share("4ddfds") | [
"Get",
"a",
"specific",
"share",
".",
"Does",
"not",
"require",
"authentication",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L115-L133 |
248,373 | mrallen1/pygett | pygett/base.py | Gett.get_file | def get_file(self, sharename, fileid):
"""
Get a specific file. Does not require authentication.
Input:
* A sharename
* A fileid - must be an integer
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.get_file("4ddfds", 0)
"""
if not isinstance(fileid, int):
raise TypeError("'fileid' must be an integer")
response = GettRequest().get("/files/%s/%d" % (sharename, fileid))
if response.http_status == 200:
return GettFile(self.user, **response.response) | python | def get_file(self, sharename, fileid):
"""
Get a specific file. Does not require authentication.
Input:
* A sharename
* A fileid - must be an integer
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.get_file("4ddfds", 0)
"""
if not isinstance(fileid, int):
raise TypeError("'fileid' must be an integer")
response = GettRequest().get("/files/%s/%d" % (sharename, fileid))
if response.http_status == 200:
return GettFile(self.user, **response.response) | [
"def",
"get_file",
"(",
"self",
",",
"sharename",
",",
"fileid",
")",
":",
"if",
"not",
"isinstance",
"(",
"fileid",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"'fileid' must be an integer\"",
")",
"response",
"=",
"GettRequest",
"(",
")",
".",
"get",
"(",
"\"/files/%s/%d\"",
"%",
"(",
"sharename",
",",
"fileid",
")",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"return",
"GettFile",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")"
] | Get a specific file. Does not require authentication.
Input:
* A sharename
* A fileid - must be an integer
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.get_file("4ddfds", 0) | [
"Get",
"a",
"specific",
"file",
".",
"Does",
"not",
"require",
"authentication",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L135-L157 |
248,374 | mrallen1/pygett | pygett/base.py | Gett.create_share | def create_share(self, **kwargs):
"""
Create a new share. Takes a keyword argument.
Input:
* ``title`` optional share title (optional)
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
new_share = client.create_share( title="Example Title" )
"""
params = None
if 'title' in kwargs:
params = {"title": kwargs['title']}
response = GettRequest().post(("/shares/create?accesstoken=%s" % self.user.access_token()), params)
if response.http_status == 200:
return GettShare(self.user, **response.response) | python | def create_share(self, **kwargs):
"""
Create a new share. Takes a keyword argument.
Input:
* ``title`` optional share title (optional)
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
new_share = client.create_share( title="Example Title" )
"""
params = None
if 'title' in kwargs:
params = {"title": kwargs['title']}
response = GettRequest().post(("/shares/create?accesstoken=%s" % self.user.access_token()), params)
if response.http_status == 200:
return GettShare(self.user, **response.response) | [
"def",
"create_share",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"None",
"if",
"'title'",
"in",
"kwargs",
":",
"params",
"=",
"{",
"\"title\"",
":",
"kwargs",
"[",
"'title'",
"]",
"}",
"response",
"=",
"GettRequest",
"(",
")",
".",
"post",
"(",
"(",
"\"/shares/create?accesstoken=%s\"",
"%",
"self",
".",
"user",
".",
"access_token",
"(",
")",
")",
",",
"params",
")",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"return",
"GettShare",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")"
] | Create a new share. Takes a keyword argument.
Input:
* ``title`` optional share title (optional)
Output:
* A :py:mod:`pygett.shares.GettShare` object
Example::
new_share = client.create_share( title="Example Title" ) | [
"Create",
"a",
"new",
"share",
".",
"Takes",
"a",
"keyword",
"argument",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L159-L181 |
248,375 | mrallen1/pygett | pygett/base.py | Gett.upload_file | def upload_file(self, **kwargs):
"""
Upload a file to the Gett service. Takes keyword arguments.
Input:
* ``filename`` the filename to use in the Gett service (required)
* ``data`` the file contents to store in the Gett service (required) - must be a string
* ``sharename`` the name of the share in which to store the data (optional); if not given, a new share will be created.
* ``title`` the share title to use if a new share is created (optional)
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.upload_file(filaname="foo", data=open("foo.txt").read())
"""
params = None
if 'filename' not in kwargs:
raise AttributeError("Parameter 'filename' must be given")
else:
params = {
"filename": kwargs['filename']
}
if 'data' not in kwargs:
raise AttributeError("Parameter 'data' must be given")
sharename = None
if 'sharename' not in kwargs:
share = None
if 'title' in kwargs:
share = self.create_share(title=kwargs['title'])
else:
share = self.create_share()
sharename = share.sharename
else:
sharename = kwargs['sharename']
response = GettRequest().post("/files/%s/create?accesstoken=%s" % (sharename, self.user.access_token()), params)
f = None
if response.http_status == 200:
if 'sharename' not in response.response:
response.response['sharename'] = sharename
f = GettFile(self.user, **response.response)
if f.send_data(data=kwargs['data']):
return f | python | def upload_file(self, **kwargs):
"""
Upload a file to the Gett service. Takes keyword arguments.
Input:
* ``filename`` the filename to use in the Gett service (required)
* ``data`` the file contents to store in the Gett service (required) - must be a string
* ``sharename`` the name of the share in which to store the data (optional); if not given, a new share will be created.
* ``title`` the share title to use if a new share is created (optional)
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.upload_file(filaname="foo", data=open("foo.txt").read())
"""
params = None
if 'filename' not in kwargs:
raise AttributeError("Parameter 'filename' must be given")
else:
params = {
"filename": kwargs['filename']
}
if 'data' not in kwargs:
raise AttributeError("Parameter 'data' must be given")
sharename = None
if 'sharename' not in kwargs:
share = None
if 'title' in kwargs:
share = self.create_share(title=kwargs['title'])
else:
share = self.create_share()
sharename = share.sharename
else:
sharename = kwargs['sharename']
response = GettRequest().post("/files/%s/create?accesstoken=%s" % (sharename, self.user.access_token()), params)
f = None
if response.http_status == 200:
if 'sharename' not in response.response:
response.response['sharename'] = sharename
f = GettFile(self.user, **response.response)
if f.send_data(data=kwargs['data']):
return f | [
"def",
"upload_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"None",
"if",
"'filename'",
"not",
"in",
"kwargs",
":",
"raise",
"AttributeError",
"(",
"\"Parameter 'filename' must be given\"",
")",
"else",
":",
"params",
"=",
"{",
"\"filename\"",
":",
"kwargs",
"[",
"'filename'",
"]",
"}",
"if",
"'data'",
"not",
"in",
"kwargs",
":",
"raise",
"AttributeError",
"(",
"\"Parameter 'data' must be given\"",
")",
"sharename",
"=",
"None",
"if",
"'sharename'",
"not",
"in",
"kwargs",
":",
"share",
"=",
"None",
"if",
"'title'",
"in",
"kwargs",
":",
"share",
"=",
"self",
".",
"create_share",
"(",
"title",
"=",
"kwargs",
"[",
"'title'",
"]",
")",
"else",
":",
"share",
"=",
"self",
".",
"create_share",
"(",
")",
"sharename",
"=",
"share",
".",
"sharename",
"else",
":",
"sharename",
"=",
"kwargs",
"[",
"'sharename'",
"]",
"response",
"=",
"GettRequest",
"(",
")",
".",
"post",
"(",
"\"/files/%s/create?accesstoken=%s\"",
"%",
"(",
"sharename",
",",
"self",
".",
"user",
".",
"access_token",
"(",
")",
")",
",",
"params",
")",
"f",
"=",
"None",
"if",
"response",
".",
"http_status",
"==",
"200",
":",
"if",
"'sharename'",
"not",
"in",
"response",
".",
"response",
":",
"response",
".",
"response",
"[",
"'sharename'",
"]",
"=",
"sharename",
"f",
"=",
"GettFile",
"(",
"self",
".",
"user",
",",
"*",
"*",
"response",
".",
"response",
")",
"if",
"f",
".",
"send_data",
"(",
"data",
"=",
"kwargs",
"[",
"'data'",
"]",
")",
":",
"return",
"f"
] | Upload a file to the Gett service. Takes keyword arguments.
Input:
* ``filename`` the filename to use in the Gett service (required)
* ``data`` the file contents to store in the Gett service (required) - must be a string
* ``sharename`` the name of the share in which to store the data (optional); if not given, a new share will be created.
* ``title`` the share title to use if a new share is created (optional)
Output:
* A :py:mod:`pygett.files.GettFile` object
Example::
file = client.upload_file(filaname="foo", data=open("foo.txt").read()) | [
"Upload",
"a",
"file",
"to",
"the",
"Gett",
"service",
".",
"Takes",
"keyword",
"arguments",
"."
] | 1e21f8674a3634a901af054226670174b5ce2d87 | https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L183-L230 |
248,376 | exekias/droplet | droplet/samba/db.py | samdb_connect | def samdb_connect():
"""
Open and return a SamDB connection
"""
with root():
lp = samba.param.LoadParm()
lp.load("/etc/samba/smb.conf")
creds = Credentials()
creds.guess(lp)
session = system_session()
samdb = SamDB("/var/lib/samba/private/sam.ldb",
session_info=session,
credentials=creds,
lp=lp)
return samdb | python | def samdb_connect():
"""
Open and return a SamDB connection
"""
with root():
lp = samba.param.LoadParm()
lp.load("/etc/samba/smb.conf")
creds = Credentials()
creds.guess(lp)
session = system_session()
samdb = SamDB("/var/lib/samba/private/sam.ldb",
session_info=session,
credentials=creds,
lp=lp)
return samdb | [
"def",
"samdb_connect",
"(",
")",
":",
"with",
"root",
"(",
")",
":",
"lp",
"=",
"samba",
".",
"param",
".",
"LoadParm",
"(",
")",
"lp",
".",
"load",
"(",
"\"/etc/samba/smb.conf\"",
")",
"creds",
"=",
"Credentials",
"(",
")",
"creds",
".",
"guess",
"(",
"lp",
")",
"session",
"=",
"system_session",
"(",
")",
"samdb",
"=",
"SamDB",
"(",
"\"/var/lib/samba/private/sam.ldb\"",
",",
"session_info",
"=",
"session",
",",
"credentials",
"=",
"creds",
",",
"lp",
"=",
"lp",
")",
"return",
"samdb"
] | Open and return a SamDB connection | [
"Open",
"and",
"return",
"a",
"SamDB",
"connection"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/samba/db.py#L15-L29 |
248,377 | exekias/droplet | droplet/samba/db.py | load_schema | def load_schema(ldif_file):
"""
Load a schema from the given file into the SamDB
"""
samdb = samdb_connect()
dn = samdb.domain_dn()
samdb.transaction_start()
try:
setup_add_ldif(samdb, ldif_file, {
"DOMAINDN": dn,
})
except:
samdb.transaction_cancel()
raise
samdb.transaction_commit() | python | def load_schema(ldif_file):
"""
Load a schema from the given file into the SamDB
"""
samdb = samdb_connect()
dn = samdb.domain_dn()
samdb.transaction_start()
try:
setup_add_ldif(samdb, ldif_file, {
"DOMAINDN": dn,
})
except:
samdb.transaction_cancel()
raise
samdb.transaction_commit() | [
"def",
"load_schema",
"(",
"ldif_file",
")",
":",
"samdb",
"=",
"samdb_connect",
"(",
")",
"dn",
"=",
"samdb",
".",
"domain_dn",
"(",
")",
"samdb",
".",
"transaction_start",
"(",
")",
"try",
":",
"setup_add_ldif",
"(",
"samdb",
",",
"ldif_file",
",",
"{",
"\"DOMAINDN\"",
":",
"dn",
",",
"}",
")",
"except",
":",
"samdb",
".",
"transaction_cancel",
"(",
")",
"raise",
"samdb",
".",
"transaction_commit",
"(",
")"
] | Load a schema from the given file into the SamDB | [
"Load",
"a",
"schema",
"from",
"the",
"given",
"file",
"into",
"the",
"SamDB"
] | aeac573a2c1c4b774e99d5414a1c79b1bb734941 | https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/samba/db.py#L32-L48 |
248,378 | refinery29/chassis | chassis/util/tree.py | DependencyNode.add_child | def add_child(self, child):
""" Add a child node """
if not isinstance(child, DependencyNode):
raise TypeError('"child" must be a DependencyNode')
self._children.append(child) | python | def add_child(self, child):
""" Add a child node """
if not isinstance(child, DependencyNode):
raise TypeError('"child" must be a DependencyNode')
self._children.append(child) | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"if",
"not",
"isinstance",
"(",
"child",
",",
"DependencyNode",
")",
":",
"raise",
"TypeError",
"(",
"'\"child\" must be a DependencyNode'",
")",
"self",
".",
"_children",
".",
"append",
"(",
"child",
")"
] | Add a child node | [
"Add",
"a",
"child",
"node"
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/tree.py#L37-L41 |
248,379 | refinery29/chassis | chassis/util/tree.py | DependencyNode.add_children | def add_children(self, children):
""" Add multiple children """
if not isinstance(children, list):
raise TypeError('"children" must be a list')
for child in children:
self.add_child(child) | python | def add_children(self, children):
""" Add multiple children """
if not isinstance(children, list):
raise TypeError('"children" must be a list')
for child in children:
self.add_child(child) | [
"def",
"add_children",
"(",
"self",
",",
"children",
")",
":",
"if",
"not",
"isinstance",
"(",
"children",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'\"children\" must be a list'",
")",
"for",
"child",
"in",
"children",
":",
"self",
".",
"add_child",
"(",
"child",
")"
] | Add multiple children | [
"Add",
"multiple",
"children"
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/tree.py#L43-L48 |
248,380 | refinery29/chassis | chassis/util/tree.py | DependencyTree.head_values | def head_values(self):
""" Return set of the head values """
values = set()
for head in self._heads:
values.add(head.value)
return values | python | def head_values(self):
""" Return set of the head values """
values = set()
for head in self._heads:
values.add(head.value)
return values | [
"def",
"head_values",
"(",
"self",
")",
":",
"values",
"=",
"set",
"(",
")",
"for",
"head",
"in",
"self",
".",
"_heads",
":",
"values",
".",
"add",
"(",
"head",
".",
"value",
")",
"return",
"values"
] | Return set of the head values | [
"Return",
"set",
"of",
"the",
"head",
"values"
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/tree.py#L77-L82 |
248,381 | refinery29/chassis | chassis/util/tree.py | DependencyTree.add_head | def add_head(self, head):
""" Add head Node """
if not isinstance(head, DependencyNode):
raise TypeError('"head" must be a DependencyNode')
self._heads.append(head) | python | def add_head(self, head):
""" Add head Node """
if not isinstance(head, DependencyNode):
raise TypeError('"head" must be a DependencyNode')
self._heads.append(head) | [
"def",
"add_head",
"(",
"self",
",",
"head",
")",
":",
"if",
"not",
"isinstance",
"(",
"head",
",",
"DependencyNode",
")",
":",
"raise",
"TypeError",
"(",
"'\"head\" must be a DependencyNode'",
")",
"self",
".",
"_heads",
".",
"append",
"(",
"head",
")"
] | Add head Node | [
"Add",
"head",
"Node"
] | 1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192 | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/tree.py#L95-L99 |
248,382 | qzmfranklin/easyshell | easyshell/main.py | update_parser | def update_parser(parser):
"""Update the parser object for the shell.
Arguments:
parser: An instance of argparse.ArgumentParser.
"""
def __stdin(s):
if s is None:
return None
if s == '-':
return sys.stdin
return open(s, 'r', encoding = 'utf8')
parser.add_argument('--root-prompt',
metavar = 'STR',
default = 'PlayBoy',
help = 'the root prompt string')
parser.add_argument('--temp-dir',
metavar = 'DIR',
default = '/tmp/easyshell_demo',
help = 'the directory to save history files')
parser.add_argument('--debug',
action = 'store_true',
help = 'turn debug infomation on')
parser.add_argument('file',
metavar = 'FILE',
nargs = '?',
type = __stdin,
help = "execute script in non-interactive mode. '-' = stdin") | python | def update_parser(parser):
"""Update the parser object for the shell.
Arguments:
parser: An instance of argparse.ArgumentParser.
"""
def __stdin(s):
if s is None:
return None
if s == '-':
return sys.stdin
return open(s, 'r', encoding = 'utf8')
parser.add_argument('--root-prompt',
metavar = 'STR',
default = 'PlayBoy',
help = 'the root prompt string')
parser.add_argument('--temp-dir',
metavar = 'DIR',
default = '/tmp/easyshell_demo',
help = 'the directory to save history files')
parser.add_argument('--debug',
action = 'store_true',
help = 'turn debug infomation on')
parser.add_argument('file',
metavar = 'FILE',
nargs = '?',
type = __stdin,
help = "execute script in non-interactive mode. '-' = stdin") | [
"def",
"update_parser",
"(",
"parser",
")",
":",
"def",
"__stdin",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"s",
"==",
"'-'",
":",
"return",
"sys",
".",
"stdin",
"return",
"open",
"(",
"s",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"parser",
".",
"add_argument",
"(",
"'--root-prompt'",
",",
"metavar",
"=",
"'STR'",
",",
"default",
"=",
"'PlayBoy'",
",",
"help",
"=",
"'the root prompt string'",
")",
"parser",
".",
"add_argument",
"(",
"'--temp-dir'",
",",
"metavar",
"=",
"'DIR'",
",",
"default",
"=",
"'/tmp/easyshell_demo'",
",",
"help",
"=",
"'the directory to save history files'",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'turn debug infomation on'",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"metavar",
"=",
"'FILE'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"__stdin",
",",
"help",
"=",
"\"execute script in non-interactive mode. '-' = stdin\"",
")"
] | Update the parser object for the shell.
Arguments:
parser: An instance of argparse.ArgumentParser. | [
"Update",
"the",
"parser",
"object",
"for",
"the",
"shell",
"."
] | 00c2e90e7767d32e7e127fc8c6875845aa308295 | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/main.py#L3-L30 |
248,383 | jmgilman/Neolib | neolib/pyamf/util/imports.py | _init | def _init():
"""
Internal function to install the module finder.
"""
global finder
if finder is None:
finder = ModuleFinder()
if finder not in sys.meta_path:
sys.meta_path.insert(0, finder) | python | def _init():
"""
Internal function to install the module finder.
"""
global finder
if finder is None:
finder = ModuleFinder()
if finder not in sys.meta_path:
sys.meta_path.insert(0, finder) | [
"def",
"_init",
"(",
")",
":",
"global",
"finder",
"if",
"finder",
"is",
"None",
":",
"finder",
"=",
"ModuleFinder",
"(",
")",
"if",
"finder",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"insert",
"(",
"0",
",",
"finder",
")"
] | Internal function to install the module finder. | [
"Internal",
"function",
"to",
"install",
"the",
"module",
"finder",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/imports.py#L123-L133 |
248,384 | jmgilman/Neolib | neolib/pyamf/util/imports.py | ModuleFinder.find_module | def find_module(self, name, path=None):
"""
Called when an import is made. If there are hooks waiting for this
module to be imported then we stop the normal import process and
manually load the module.
@param name: The name of the module being imported.
@param path The root path of the module (if a package). We ignore this.
@return: If we want to hook this module, we return a C{loader}
interface (which is this instance again). If not we return C{None}
to allow the standard import process to continue.
"""
if name in self.loaded_modules:
return None
hooks = self.post_load_hooks.get(name, None)
if hooks:
return self | python | def find_module(self, name, path=None):
"""
Called when an import is made. If there are hooks waiting for this
module to be imported then we stop the normal import process and
manually load the module.
@param name: The name of the module being imported.
@param path The root path of the module (if a package). We ignore this.
@return: If we want to hook this module, we return a C{loader}
interface (which is this instance again). If not we return C{None}
to allow the standard import process to continue.
"""
if name in self.loaded_modules:
return None
hooks = self.post_load_hooks.get(name, None)
if hooks:
return self | [
"def",
"find_module",
"(",
"self",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"loaded_modules",
":",
"return",
"None",
"hooks",
"=",
"self",
".",
"post_load_hooks",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"hooks",
":",
"return",
"self"
] | Called when an import is made. If there are hooks waiting for this
module to be imported then we stop the normal import process and
manually load the module.
@param name: The name of the module being imported.
@param path The root path of the module (if a package). We ignore this.
@return: If we want to hook this module, we return a C{loader}
interface (which is this instance again). If not we return C{None}
to allow the standard import process to continue. | [
"Called",
"when",
"an",
"import",
"is",
"made",
".",
"If",
"there",
"are",
"hooks",
"waiting",
"for",
"this",
"module",
"to",
"be",
"imported",
"then",
"we",
"stop",
"the",
"normal",
"import",
"process",
"and",
"manually",
"load",
"the",
"module",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/imports.py#L52-L70 |
248,385 | jmgilman/Neolib | neolib/pyamf/util/imports.py | ModuleFinder.load_module | def load_module(self, name):
"""
If we get this far, then there are hooks waiting to be called on
import of this module. We manually load the module and then run the
hooks.
@param name: The name of the module to import.
"""
self.loaded_modules.append(name)
try:
__import__(name, {}, {}, [])
mod = sys.modules[name]
self._run_hooks(name, mod)
except:
self.loaded_modules.pop()
raise
return mod | python | def load_module(self, name):
"""
If we get this far, then there are hooks waiting to be called on
import of this module. We manually load the module and then run the
hooks.
@param name: The name of the module to import.
"""
self.loaded_modules.append(name)
try:
__import__(name, {}, {}, [])
mod = sys.modules[name]
self._run_hooks(name, mod)
except:
self.loaded_modules.pop()
raise
return mod | [
"def",
"load_module",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"loaded_modules",
".",
"append",
"(",
"name",
")",
"try",
":",
"__import__",
"(",
"name",
",",
"{",
"}",
",",
"{",
"}",
",",
"[",
"]",
")",
"mod",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"self",
".",
"_run_hooks",
"(",
"name",
",",
"mod",
")",
"except",
":",
"self",
".",
"loaded_modules",
".",
"pop",
"(",
")",
"raise",
"return",
"mod"
] | If we get this far, then there are hooks waiting to be called on
import of this module. We manually load the module and then run the
hooks.
@param name: The name of the module to import. | [
"If",
"we",
"get",
"this",
"far",
"then",
"there",
"are",
"hooks",
"waiting",
"to",
"be",
"called",
"on",
"import",
"of",
"this",
"module",
".",
"We",
"manually",
"load",
"the",
"module",
"and",
"then",
"run",
"the",
"hooks",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/imports.py#L72-L92 |
248,386 | jmgilman/Neolib | neolib/pyamf/util/imports.py | ModuleFinder._run_hooks | def _run_hooks(self, name, module):
"""
Run all hooks for a module.
"""
hooks = self.post_load_hooks.pop(name, [])
for hook in hooks:
hook(module) | python | def _run_hooks(self, name, module):
"""
Run all hooks for a module.
"""
hooks = self.post_load_hooks.pop(name, [])
for hook in hooks:
hook(module) | [
"def",
"_run_hooks",
"(",
"self",
",",
"name",
",",
"module",
")",
":",
"hooks",
"=",
"self",
".",
"post_load_hooks",
".",
"pop",
"(",
"name",
",",
"[",
"]",
")",
"for",
"hook",
"in",
"hooks",
":",
"hook",
"(",
"module",
")"
] | Run all hooks for a module. | [
"Run",
"all",
"hooks",
"for",
"a",
"module",
"."
] | 228fafeaed0f3195676137732384a14820ae285c | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/imports.py#L107-L114 |
248,387 | pjuren/pyokit | src/pyokit/scripts/index.py | index_repeatmasker_alignment_by_id | def index_repeatmasker_alignment_by_id(fh, out_fh, vebrose=False):
"""Build an index for a repeat-masker alignment file by repeat-masker ID."""
def extract_UID(rm_alignment):
return rm_alignment.meta[multipleAlignment.RM_ID_KEY]
index = IndexedFile(fh, repeat_masker_alignment_iterator, extract_UID)
index.write_index(out_fh) | python | def index_repeatmasker_alignment_by_id(fh, out_fh, vebrose=False):
"""Build an index for a repeat-masker alignment file by repeat-masker ID."""
def extract_UID(rm_alignment):
return rm_alignment.meta[multipleAlignment.RM_ID_KEY]
index = IndexedFile(fh, repeat_masker_alignment_iterator, extract_UID)
index.write_index(out_fh) | [
"def",
"index_repeatmasker_alignment_by_id",
"(",
"fh",
",",
"out_fh",
",",
"vebrose",
"=",
"False",
")",
":",
"def",
"extract_UID",
"(",
"rm_alignment",
")",
":",
"return",
"rm_alignment",
".",
"meta",
"[",
"multipleAlignment",
".",
"RM_ID_KEY",
"]",
"index",
"=",
"IndexedFile",
"(",
"fh",
",",
"repeat_masker_alignment_iterator",
",",
"extract_UID",
")",
"index",
".",
"write_index",
"(",
"out_fh",
")"
] | Build an index for a repeat-masker alignment file by repeat-masker ID. | [
"Build",
"an",
"index",
"for",
"a",
"repeat",
"-",
"masker",
"alignment",
"file",
"by",
"repeat",
"-",
"masker",
"ID",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L76-L82 |
248,388 | pjuren/pyokit | src/pyokit/scripts/index.py | index_genome_alignment_by_locus | def index_genome_alignment_by_locus(fh, out_fh, verbose=False):
"""Build an index for a genome alig. using coords in ref genome as keys."""
bound_iter = functools.partial(genome_alignment_iterator,
reference_species="hg19", index_friendly=True)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(fh, bound_iter, hash_func)
idx.write_index(out_fh, verbose=verbose) | python | def index_genome_alignment_by_locus(fh, out_fh, verbose=False):
"""Build an index for a genome alig. using coords in ref genome as keys."""
bound_iter = functools.partial(genome_alignment_iterator,
reference_species="hg19", index_friendly=True)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(fh, bound_iter, hash_func)
idx.write_index(out_fh, verbose=verbose) | [
"def",
"index_genome_alignment_by_locus",
"(",
"fh",
",",
"out_fh",
",",
"verbose",
"=",
"False",
")",
":",
"bound_iter",
"=",
"functools",
".",
"partial",
"(",
"genome_alignment_iterator",
",",
"reference_species",
"=",
"\"hg19\"",
",",
"index_friendly",
"=",
"True",
")",
"hash_func",
"=",
"JustInTimeGenomeAlignmentBlock",
".",
"build_hash",
"idx",
"=",
"IndexedFile",
"(",
"fh",
",",
"bound_iter",
",",
"hash_func",
")",
"idx",
".",
"write_index",
"(",
"out_fh",
",",
"verbose",
"=",
"verbose",
")"
] | Build an index for a genome alig. using coords in ref genome as keys. | [
"Build",
"an",
"index",
"for",
"a",
"genome",
"alig",
".",
"using",
"coords",
"in",
"ref",
"genome",
"as",
"keys",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L85-L91 |
248,389 | pjuren/pyokit | src/pyokit/scripts/index.py | lookup_genome_alignment_index | def lookup_genome_alignment_index(index_fh, indexed_fh, out_fh=sys.stdout,
key=None, verbose=False):
"""Load a GA index and its indexed file and extract one or more blocks.
:param index_fh: the index file to load. Can be a filename or a
stream-like object.
:param indexed_fh: the file that the index was built for,
:param key: A single key, iterable of keys, or None. This key will be
used for lookup. If None, user is prompted to enter keys
interactively.
"""
# load the genome alignment as a JIT object
bound_iter = functools.partial(genome_alignment_iterator,
reference_species="hg19", index_friendly=True)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(record_iterator=bound_iter, record_hash_function=hash_func)
idx.read_index(index_fh, indexed_fh)
if key is None:
while key is None or key.strip() != "":
sys.stderr.write("[WAITING FOR KEY ENTRY ON STDIN; " +
"END WITH EMPTY LINE]\n")
key = raw_input()
# we know keys for genome alignments have tabs as delims, so..
key = '\t'.join(key.split()).strip()
if key != "":
out_fh.write(str(idx[key]) + "\n")
sys.stderr.write("\n")
else:
# we know keys for genome alignments have tabs as delims, so..
key = '\t'.join(key.split())
out_fh.write(str(idx[key]) + "\n") | python | def lookup_genome_alignment_index(index_fh, indexed_fh, out_fh=sys.stdout,
key=None, verbose=False):
"""Load a GA index and its indexed file and extract one or more blocks.
:param index_fh: the index file to load. Can be a filename or a
stream-like object.
:param indexed_fh: the file that the index was built for,
:param key: A single key, iterable of keys, or None. This key will be
used for lookup. If None, user is prompted to enter keys
interactively.
"""
# load the genome alignment as a JIT object
bound_iter = functools.partial(genome_alignment_iterator,
reference_species="hg19", index_friendly=True)
hash_func = JustInTimeGenomeAlignmentBlock.build_hash
idx = IndexedFile(record_iterator=bound_iter, record_hash_function=hash_func)
idx.read_index(index_fh, indexed_fh)
if key is None:
while key is None or key.strip() != "":
sys.stderr.write("[WAITING FOR KEY ENTRY ON STDIN; " +
"END WITH EMPTY LINE]\n")
key = raw_input()
# we know keys for genome alignments have tabs as delims, so..
key = '\t'.join(key.split()).strip()
if key != "":
out_fh.write(str(idx[key]) + "\n")
sys.stderr.write("\n")
else:
# we know keys for genome alignments have tabs as delims, so..
key = '\t'.join(key.split())
out_fh.write(str(idx[key]) + "\n") | [
"def",
"lookup_genome_alignment_index",
"(",
"index_fh",
",",
"indexed_fh",
",",
"out_fh",
"=",
"sys",
".",
"stdout",
",",
"key",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"# load the genome alignment as a JIT object",
"bound_iter",
"=",
"functools",
".",
"partial",
"(",
"genome_alignment_iterator",
",",
"reference_species",
"=",
"\"hg19\"",
",",
"index_friendly",
"=",
"True",
")",
"hash_func",
"=",
"JustInTimeGenomeAlignmentBlock",
".",
"build_hash",
"idx",
"=",
"IndexedFile",
"(",
"record_iterator",
"=",
"bound_iter",
",",
"record_hash_function",
"=",
"hash_func",
")",
"idx",
".",
"read_index",
"(",
"index_fh",
",",
"indexed_fh",
")",
"if",
"key",
"is",
"None",
":",
"while",
"key",
"is",
"None",
"or",
"key",
".",
"strip",
"(",
")",
"!=",
"\"\"",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"[WAITING FOR KEY ENTRY ON STDIN; \"",
"+",
"\"END WITH EMPTY LINE]\\n\"",
")",
"key",
"=",
"raw_input",
"(",
")",
"# we know keys for genome alignments have tabs as delims, so..",
"key",
"=",
"'\\t'",
".",
"join",
"(",
"key",
".",
"split",
"(",
")",
")",
".",
"strip",
"(",
")",
"if",
"key",
"!=",
"\"\"",
":",
"out_fh",
".",
"write",
"(",
"str",
"(",
"idx",
"[",
"key",
"]",
")",
"+",
"\"\\n\"",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n\"",
")",
"else",
":",
"# we know keys for genome alignments have tabs as delims, so..",
"key",
"=",
"'\\t'",
".",
"join",
"(",
"key",
".",
"split",
"(",
")",
")",
"out_fh",
".",
"write",
"(",
"str",
"(",
"idx",
"[",
"key",
"]",
")",
"+",
"\"\\n\"",
")"
] | Load a GA index and its indexed file and extract one or more blocks.
:param index_fh: the index file to load. Can be a filename or a
stream-like object.
:param indexed_fh: the file that the index was built for,
:param key: A single key, iterable of keys, or None. This key will be
used for lookup. If None, user is prompted to enter keys
interactively. | [
"Load",
"a",
"GA",
"index",
"and",
"its",
"indexed",
"file",
"and",
"extract",
"one",
"or",
"more",
"blocks",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L115-L146 |
248,390 | pjuren/pyokit | src/pyokit/scripts/index.py | getUI_build_index | def getUI_build_index(prog_name, args):
"""
build and return a UI object for the 'build' option.
:param args: raw arguments to parse
"""
programName = prog_name
long_description = "Build an index for one or more files."
short_description = long_description
ui = CLI(programName, short_description, long_description)
ui.minArgs = 0
ui.maxArgs = -1
ui.addOption(Option(short="o", long="output", argName="filename",
description="output to given file, else stdout",
required=False, type=str))
ui.addOption(Option(short="t", long="type", argName="filename",
description="the type of the file. If missing, " +
"the script will try to guess the file type. " +
"Supported file types are: " +
", ".join([f.name for f in FileType]),
required=False, type=str))
ui.addOption(Option(short="v", long="verbose",
description="output additional messages to stderr " +
"about run (default: " +
str(DEFAULT_VERBOSITY) + ")",
default=DEFAULT_VERBOSITY, required=False))
ui.addOption(Option(short="h", long="help",
description="show this help message ", special=True))
ui.addOption(Option(short="u", long="test",
description="run unit tests ", special=True))
ui.parseCommandLine(args)
return ui | python | def getUI_build_index(prog_name, args):
"""
build and return a UI object for the 'build' option.
:param args: raw arguments to parse
"""
programName = prog_name
long_description = "Build an index for one or more files."
short_description = long_description
ui = CLI(programName, short_description, long_description)
ui.minArgs = 0
ui.maxArgs = -1
ui.addOption(Option(short="o", long="output", argName="filename",
description="output to given file, else stdout",
required=False, type=str))
ui.addOption(Option(short="t", long="type", argName="filename",
description="the type of the file. If missing, " +
"the script will try to guess the file type. " +
"Supported file types are: " +
", ".join([f.name for f in FileType]),
required=False, type=str))
ui.addOption(Option(short="v", long="verbose",
description="output additional messages to stderr " +
"about run (default: " +
str(DEFAULT_VERBOSITY) + ")",
default=DEFAULT_VERBOSITY, required=False))
ui.addOption(Option(short="h", long="help",
description="show this help message ", special=True))
ui.addOption(Option(short="u", long="test",
description="run unit tests ", special=True))
ui.parseCommandLine(args)
return ui | [
"def",
"getUI_build_index",
"(",
"prog_name",
",",
"args",
")",
":",
"programName",
"=",
"prog_name",
"long_description",
"=",
"\"Build an index for one or more files.\"",
"short_description",
"=",
"long_description",
"ui",
"=",
"CLI",
"(",
"programName",
",",
"short_description",
",",
"long_description",
")",
"ui",
".",
"minArgs",
"=",
"0",
"ui",
".",
"maxArgs",
"=",
"-",
"1",
"ui",
".",
"addOption",
"(",
"Option",
"(",
"short",
"=",
"\"o\"",
",",
"long",
"=",
"\"output\"",
",",
"argName",
"=",
"\"filename\"",
",",
"description",
"=",
"\"output to given file, else stdout\"",
",",
"required",
"=",
"False",
",",
"type",
"=",
"str",
")",
")",
"ui",
".",
"addOption",
"(",
"Option",
"(",
"short",
"=",
"\"t\"",
",",
"long",
"=",
"\"type\"",
",",
"argName",
"=",
"\"filename\"",
",",
"description",
"=",
"\"the type of the file. If missing, \"",
"+",
"\"the script will try to guess the file type. \"",
"+",
"\"Supported file types are: \"",
"+",
"\", \"",
".",
"join",
"(",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"FileType",
"]",
")",
",",
"required",
"=",
"False",
",",
"type",
"=",
"str",
")",
")",
"ui",
".",
"addOption",
"(",
"Option",
"(",
"short",
"=",
"\"v\"",
",",
"long",
"=",
"\"verbose\"",
",",
"description",
"=",
"\"output additional messages to stderr \"",
"+",
"\"about run (default: \"",
"+",
"str",
"(",
"DEFAULT_VERBOSITY",
")",
"+",
"\")\"",
",",
"default",
"=",
"DEFAULT_VERBOSITY",
",",
"required",
"=",
"False",
")",
")",
"ui",
".",
"addOption",
"(",
"Option",
"(",
"short",
"=",
"\"h\"",
",",
"long",
"=",
"\"help\"",
",",
"description",
"=",
"\"show this help message \"",
",",
"special",
"=",
"True",
")",
")",
"ui",
".",
"addOption",
"(",
"Option",
"(",
"short",
"=",
"\"u\"",
",",
"long",
"=",
"\"test\"",
",",
"description",
"=",
"\"run unit tests \"",
",",
"special",
"=",
"True",
")",
")",
"ui",
".",
"parseCommandLine",
"(",
"args",
")",
"return",
"ui"
] | build and return a UI object for the 'build' option.
:param args: raw arguments to parse | [
"build",
"and",
"return",
"a",
"UI",
"object",
"for",
"the",
"build",
"option",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L170-L203 |
248,391 | pjuren/pyokit | src/pyokit/scripts/index.py | __get_indexer | def __get_indexer(in_fns, selected_type=None):
"""Determine which indexer to use based on input files and type option."""
indexer = None
if selected_type is not None:
indexer = get_indexer_by_filetype(selected_type)
else:
if len(in_fns) == 0:
raise IndexError("reading from stdin, unable to guess input file " +
"type, use -t option to set manually.\n")
else:
extension = set([os.path.splitext(f)[1] for f in in_fns])
assert(len(extension) >= 1)
if len(extension) > 1:
raise IndexError("more than one file extension present, unable " +
"to get input type, use -t option to set manually.\n")
else:
indexer = get_indexer_by_file_extension(list(extension)[0])
assert(indexer is not None)
return indexer | python | def __get_indexer(in_fns, selected_type=None):
"""Determine which indexer to use based on input files and type option."""
indexer = None
if selected_type is not None:
indexer = get_indexer_by_filetype(selected_type)
else:
if len(in_fns) == 0:
raise IndexError("reading from stdin, unable to guess input file " +
"type, use -t option to set manually.\n")
else:
extension = set([os.path.splitext(f)[1] for f in in_fns])
assert(len(extension) >= 1)
if len(extension) > 1:
raise IndexError("more than one file extension present, unable " +
"to get input type, use -t option to set manually.\n")
else:
indexer = get_indexer_by_file_extension(list(extension)[0])
assert(indexer is not None)
return indexer | [
"def",
"__get_indexer",
"(",
"in_fns",
",",
"selected_type",
"=",
"None",
")",
":",
"indexer",
"=",
"None",
"if",
"selected_type",
"is",
"not",
"None",
":",
"indexer",
"=",
"get_indexer_by_filetype",
"(",
"selected_type",
")",
"else",
":",
"if",
"len",
"(",
"in_fns",
")",
"==",
"0",
":",
"raise",
"IndexError",
"(",
"\"reading from stdin, unable to guess input file \"",
"+",
"\"type, use -t option to set manually.\\n\"",
")",
"else",
":",
"extension",
"=",
"set",
"(",
"[",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
")",
"[",
"1",
"]",
"for",
"f",
"in",
"in_fns",
"]",
")",
"assert",
"(",
"len",
"(",
"extension",
")",
">=",
"1",
")",
"if",
"len",
"(",
"extension",
")",
">",
"1",
":",
"raise",
"IndexError",
"(",
"\"more than one file extension present, unable \"",
"+",
"\"to get input type, use -t option to set manually.\\n\"",
")",
"else",
":",
"indexer",
"=",
"get_indexer_by_file_extension",
"(",
"list",
"(",
"extension",
")",
"[",
"0",
"]",
")",
"assert",
"(",
"indexer",
"is",
"not",
"None",
")",
"return",
"indexer"
] | Determine which indexer to use based on input files and type option. | [
"Determine",
"which",
"indexer",
"to",
"use",
"based",
"on",
"input",
"files",
"and",
"type",
"option",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L250-L268 |
248,392 | pjuren/pyokit | src/pyokit/scripts/index.py | __get_lookup | def __get_lookup(in_fn, selected_type=None):
"""Determine which lookup func to use based on inpt files and type option."""
lookup_func = None
if selected_type is not None:
lookup_func = get_lookup_by_filetype(selected_type)
else:
extension = os.path.splitext(in_fn)[1]
lookup_func = get_lookup_by_file_extension(extension)
assert(lookup_func is not None)
return lookup_func | python | def __get_lookup(in_fn, selected_type=None):
"""Determine which lookup func to use based on inpt files and type option."""
lookup_func = None
if selected_type is not None:
lookup_func = get_lookup_by_filetype(selected_type)
else:
extension = os.path.splitext(in_fn)[1]
lookup_func = get_lookup_by_file_extension(extension)
assert(lookup_func is not None)
return lookup_func | [
"def",
"__get_lookup",
"(",
"in_fn",
",",
"selected_type",
"=",
"None",
")",
":",
"lookup_func",
"=",
"None",
"if",
"selected_type",
"is",
"not",
"None",
":",
"lookup_func",
"=",
"get_lookup_by_filetype",
"(",
"selected_type",
")",
"else",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"in_fn",
")",
"[",
"1",
"]",
"lookup_func",
"=",
"get_lookup_by_file_extension",
"(",
"extension",
")",
"assert",
"(",
"lookup_func",
"is",
"not",
"None",
")",
"return",
"lookup_func"
] | Determine which lookup func to use based on inpt files and type option. | [
"Determine",
"which",
"lookup",
"func",
"to",
"use",
"based",
"on",
"inpt",
"files",
"and",
"type",
"option",
"."
] | fddae123b5d817daa39496183f19c000d9c3791f | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L271-L280 |
248,393 | tducret/precisionmapper-python | python-flask/swagger_server/controllers/user_controller.py | list_surveys | def list_surveys(): # noqa: E501
"""list the surveys available
List the surveys available # noqa: E501
:rtype: List[Survey]
"""
pm = PrecisionMapper(login=_LOGIN, password=_PASSWORD)
pm.sign_in()
surveys = pm.get_surveys()
shared_surveys = pm.get_shared_surveys()
survey_list = []
for survey in surveys+shared_surveys:
survey_obj = Survey(
date=survey.date, image_nb=survey.image_nb,
location=survey.location, name=survey.name,
sensors=survey.sensor, size=survey.size, survey_id=survey.id)
survey_list.append(survey_obj)
return survey_list | python | def list_surveys(): # noqa: E501
"""list the surveys available
List the surveys available # noqa: E501
:rtype: List[Survey]
"""
pm = PrecisionMapper(login=_LOGIN, password=_PASSWORD)
pm.sign_in()
surveys = pm.get_surveys()
shared_surveys = pm.get_shared_surveys()
survey_list = []
for survey in surveys+shared_surveys:
survey_obj = Survey(
date=survey.date, image_nb=survey.image_nb,
location=survey.location, name=survey.name,
sensors=survey.sensor, size=survey.size, survey_id=survey.id)
survey_list.append(survey_obj)
return survey_list | [
"def",
"list_surveys",
"(",
")",
":",
"# noqa: E501",
"pm",
"=",
"PrecisionMapper",
"(",
"login",
"=",
"_LOGIN",
",",
"password",
"=",
"_PASSWORD",
")",
"pm",
".",
"sign_in",
"(",
")",
"surveys",
"=",
"pm",
".",
"get_surveys",
"(",
")",
"shared_surveys",
"=",
"pm",
".",
"get_shared_surveys",
"(",
")",
"survey_list",
"=",
"[",
"]",
"for",
"survey",
"in",
"surveys",
"+",
"shared_surveys",
":",
"survey_obj",
"=",
"Survey",
"(",
"date",
"=",
"survey",
".",
"date",
",",
"image_nb",
"=",
"survey",
".",
"image_nb",
",",
"location",
"=",
"survey",
".",
"location",
",",
"name",
"=",
"survey",
".",
"name",
",",
"sensors",
"=",
"survey",
".",
"sensor",
",",
"size",
"=",
"survey",
".",
"size",
",",
"survey_id",
"=",
"survey",
".",
"id",
")",
"survey_list",
".",
"append",
"(",
"survey_obj",
")",
"return",
"survey_list"
] | list the surveys available
List the surveys available # noqa: E501
:rtype: List[Survey] | [
"list",
"the",
"surveys",
"available"
] | 462dcc5bccf6edec780b8b7bc42e8c1d717db942 | https://github.com/tducret/precisionmapper-python/blob/462dcc5bccf6edec780b8b7bc42e8c1d717db942/python-flask/swagger_server/controllers/user_controller.py#L15-L35 |
248,394 | merryspankersltd/irenee | irenee/cog.py | pg2df | def pg2df(res):
'''
takes a getlog requests result
returns a table as df
'''
# parse res
soup = BeautifulSoup(res.text)
if u'Pas de r\xe9ponse pour cette recherche.' in soup.text:
pass # <-- don't pass !
else:
params = urlparse.parse_qs(urlparse.urlsplit(res.url)[-2])
tb = soup.find_all('table')[0]
data = [
[col.text for col in row.find_all('td')] + [params['dep'][0], params['mod'][0]]
for row in tb.find_all('tr')[1:]] # <-- escape header row
data = [dict(zip(
[u'depcom', u'date', u'obs', u'dep', u'mod'], lst)) for lst in data]
return pd.DataFrame(data) | python | def pg2df(res):
'''
takes a getlog requests result
returns a table as df
'''
# parse res
soup = BeautifulSoup(res.text)
if u'Pas de r\xe9ponse pour cette recherche.' in soup.text:
pass # <-- don't pass !
else:
params = urlparse.parse_qs(urlparse.urlsplit(res.url)[-2])
tb = soup.find_all('table')[0]
data = [
[col.text for col in row.find_all('td')] + [params['dep'][0], params['mod'][0]]
for row in tb.find_all('tr')[1:]] # <-- escape header row
data = [dict(zip(
[u'depcom', u'date', u'obs', u'dep', u'mod'], lst)) for lst in data]
return pd.DataFrame(data) | [
"def",
"pg2df",
"(",
"res",
")",
":",
"# parse res",
"soup",
"=",
"BeautifulSoup",
"(",
"res",
".",
"text",
")",
"if",
"u'Pas de r\\xe9ponse pour cette recherche.'",
"in",
"soup",
".",
"text",
":",
"pass",
"# <-- don't pass !",
"else",
":",
"params",
"=",
"urlparse",
".",
"parse_qs",
"(",
"urlparse",
".",
"urlsplit",
"(",
"res",
".",
"url",
")",
"[",
"-",
"2",
"]",
")",
"tb",
"=",
"soup",
".",
"find_all",
"(",
"'table'",
")",
"[",
"0",
"]",
"data",
"=",
"[",
"[",
"col",
".",
"text",
"for",
"col",
"in",
"row",
".",
"find_all",
"(",
"'td'",
")",
"]",
"+",
"[",
"params",
"[",
"'dep'",
"]",
"[",
"0",
"]",
",",
"params",
"[",
"'mod'",
"]",
"[",
"0",
"]",
"]",
"for",
"row",
"in",
"tb",
".",
"find_all",
"(",
"'tr'",
")",
"[",
"1",
":",
"]",
"]",
"# <-- escape header row",
"data",
"=",
"[",
"dict",
"(",
"zip",
"(",
"[",
"u'depcom'",
",",
"u'date'",
",",
"u'obs'",
",",
"u'dep'",
",",
"u'mod'",
"]",
",",
"lst",
")",
")",
"for",
"lst",
"in",
"data",
"]",
"return",
"pd",
".",
"DataFrame",
"(",
"data",
")"
] | takes a getlog requests result
returns a table as df | [
"takes",
"a",
"getlog",
"requests",
"result",
"returns",
"a",
"table",
"as",
"df"
] | 8bf3c7644dc69001fa4b09be5fbb770dbf06a465 | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/cog.py#L23-L43 |
248,395 | merryspankersltd/irenee | irenee/cog.py | getlog | def getlog(start, end, deplist=['00'], modlist=['M0'], xlsx=None):
'''
batch gets changelogs for cogs
'''
# entry point url
api = 'http://www.insee.fr/fr/methodes/nomenclatures/cog/recherche_historique.asp'
# build payloads
if modlist == ['M0']:
modlist = ['MA', 'MB', 'MC', 'MD', 'ME', 'MF', 'MG']
payloads = [{'debut':start, 'fin':end, 'dep':dep, 'mod':mod} for dep in deplist for mod in modlist]
# send requests
results = [pg2df(requests.get(api, params=payload)) for payload in payloads]
# make a df and fine tune it (force dtypes)
data = pd.concat(results)
data.reset_index()
data['date'] = pd.to_datetime(data['date'], format='%d/%m/%Y')
data[['dep', 'depcom', 'mod', 'obs']] = data[['dep', 'depcom', 'mod', 'obs']].astype(object)
# write xlsx
if xlsx:
pd.core.format.header_style = None
data.to_excel(xlsx, index=False)
return pd.concat(results) | python | def getlog(start, end, deplist=['00'], modlist=['M0'], xlsx=None):
'''
batch gets changelogs for cogs
'''
# entry point url
api = 'http://www.insee.fr/fr/methodes/nomenclatures/cog/recherche_historique.asp'
# build payloads
if modlist == ['M0']:
modlist = ['MA', 'MB', 'MC', 'MD', 'ME', 'MF', 'MG']
payloads = [{'debut':start, 'fin':end, 'dep':dep, 'mod':mod} for dep in deplist for mod in modlist]
# send requests
results = [pg2df(requests.get(api, params=payload)) for payload in payloads]
# make a df and fine tune it (force dtypes)
data = pd.concat(results)
data.reset_index()
data['date'] = pd.to_datetime(data['date'], format='%d/%m/%Y')
data[['dep', 'depcom', 'mod', 'obs']] = data[['dep', 'depcom', 'mod', 'obs']].astype(object)
# write xlsx
if xlsx:
pd.core.format.header_style = None
data.to_excel(xlsx, index=False)
return pd.concat(results) | [
"def",
"getlog",
"(",
"start",
",",
"end",
",",
"deplist",
"=",
"[",
"'00'",
"]",
",",
"modlist",
"=",
"[",
"'M0'",
"]",
",",
"xlsx",
"=",
"None",
")",
":",
"# entry point url",
"api",
"=",
"'http://www.insee.fr/fr/methodes/nomenclatures/cog/recherche_historique.asp'",
"# build payloads",
"if",
"modlist",
"==",
"[",
"'M0'",
"]",
":",
"modlist",
"=",
"[",
"'MA'",
",",
"'MB'",
",",
"'MC'",
",",
"'MD'",
",",
"'ME'",
",",
"'MF'",
",",
"'MG'",
"]",
"payloads",
"=",
"[",
"{",
"'debut'",
":",
"start",
",",
"'fin'",
":",
"end",
",",
"'dep'",
":",
"dep",
",",
"'mod'",
":",
"mod",
"}",
"for",
"dep",
"in",
"deplist",
"for",
"mod",
"in",
"modlist",
"]",
"# send requests",
"results",
"=",
"[",
"pg2df",
"(",
"requests",
".",
"get",
"(",
"api",
",",
"params",
"=",
"payload",
")",
")",
"for",
"payload",
"in",
"payloads",
"]",
"# make a df and fine tune it (force dtypes)",
"data",
"=",
"pd",
".",
"concat",
"(",
"results",
")",
"data",
".",
"reset_index",
"(",
")",
"data",
"[",
"'date'",
"]",
"=",
"pd",
".",
"to_datetime",
"(",
"data",
"[",
"'date'",
"]",
",",
"format",
"=",
"'%d/%m/%Y'",
")",
"data",
"[",
"[",
"'dep'",
",",
"'depcom'",
",",
"'mod'",
",",
"'obs'",
"]",
"]",
"=",
"data",
"[",
"[",
"'dep'",
",",
"'depcom'",
",",
"'mod'",
",",
"'obs'",
"]",
"]",
".",
"astype",
"(",
"object",
")",
"# write xlsx",
"if",
"xlsx",
":",
"pd",
".",
"core",
".",
"format",
".",
"header_style",
"=",
"None",
"data",
".",
"to_excel",
"(",
"xlsx",
",",
"index",
"=",
"False",
")",
"return",
"pd",
".",
"concat",
"(",
"results",
")"
] | batch gets changelogs for cogs | [
"batch",
"gets",
"changelogs",
"for",
"cogs"
] | 8bf3c7644dc69001fa4b09be5fbb770dbf06a465 | https://github.com/merryspankersltd/irenee/blob/8bf3c7644dc69001fa4b09be5fbb770dbf06a465/irenee/cog.py#L45-L67 |
248,396 | scdoshi/django-bits | bits/currency.py | currency_format | def currency_format(cents):
"""Format currency with symbol and decimal points.
>> currency_format(-600)
- $6.00
TODO: Add localization support.
"""
try:
cents = int(cents)
except ValueError:
return cents
negative = (cents < 0)
if negative:
cents = -1 * cents
if cents < 100:
dollars = 0
else:
dollars = cents / 100
cents = cents % 100
centstr = str(cents)
if len(centstr) < 2:
centstr = '0' + centstr
if negative:
return "- $%s.%s" % (intcomma(dollars), centstr)
return "$%s.%s" % (intcomma(dollars), centstr) | python | def currency_format(cents):
"""Format currency with symbol and decimal points.
>> currency_format(-600)
- $6.00
TODO: Add localization support.
"""
try:
cents = int(cents)
except ValueError:
return cents
negative = (cents < 0)
if negative:
cents = -1 * cents
if cents < 100:
dollars = 0
else:
dollars = cents / 100
cents = cents % 100
centstr = str(cents)
if len(centstr) < 2:
centstr = '0' + centstr
if negative:
return "- $%s.%s" % (intcomma(dollars), centstr)
return "$%s.%s" % (intcomma(dollars), centstr) | [
"def",
"currency_format",
"(",
"cents",
")",
":",
"try",
":",
"cents",
"=",
"int",
"(",
"cents",
")",
"except",
"ValueError",
":",
"return",
"cents",
"negative",
"=",
"(",
"cents",
"<",
"0",
")",
"if",
"negative",
":",
"cents",
"=",
"-",
"1",
"*",
"cents",
"if",
"cents",
"<",
"100",
":",
"dollars",
"=",
"0",
"else",
":",
"dollars",
"=",
"cents",
"/",
"100",
"cents",
"=",
"cents",
"%",
"100",
"centstr",
"=",
"str",
"(",
"cents",
")",
"if",
"len",
"(",
"centstr",
")",
"<",
"2",
":",
"centstr",
"=",
"'0'",
"+",
"centstr",
"if",
"negative",
":",
"return",
"\"- $%s.%s\"",
"%",
"(",
"intcomma",
"(",
"dollars",
")",
",",
"centstr",
")",
"return",
"\"$%s.%s\"",
"%",
"(",
"intcomma",
"(",
"dollars",
")",
",",
"centstr",
")"
] | Format currency with symbol and decimal points.
>> currency_format(-600)
- $6.00
TODO: Add localization support. | [
"Format",
"currency",
"with",
"symbol",
"and",
"decimal",
"points",
"."
] | 0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f | https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/currency.py#L39-L68 |
248,397 | dariosky/wfcli | wfcli/tossl.py | WebfactionWebsiteToSsl.is_website_affected | def is_website_affected(self, website):
""" Tell if the website is affected by the domain change """
if self.domain is None:
return True
if not self.include_subdomains:
return self.domain in website['subdomains']
else:
dotted_domain = "." + self.domain
for subdomain in website['subdomains']:
if subdomain == self.domain or subdomain.endswith(dotted_domain):
return True
return False | python | def is_website_affected(self, website):
""" Tell if the website is affected by the domain change """
if self.domain is None:
return True
if not self.include_subdomains:
return self.domain in website['subdomains']
else:
dotted_domain = "." + self.domain
for subdomain in website['subdomains']:
if subdomain == self.domain or subdomain.endswith(dotted_domain):
return True
return False | [
"def",
"is_website_affected",
"(",
"self",
",",
"website",
")",
":",
"if",
"self",
".",
"domain",
"is",
"None",
":",
"return",
"True",
"if",
"not",
"self",
".",
"include_subdomains",
":",
"return",
"self",
".",
"domain",
"in",
"website",
"[",
"'subdomains'",
"]",
"else",
":",
"dotted_domain",
"=",
"\".\"",
"+",
"self",
".",
"domain",
"for",
"subdomain",
"in",
"website",
"[",
"'subdomains'",
"]",
":",
"if",
"subdomain",
"==",
"self",
".",
"domain",
"or",
"subdomain",
".",
"endswith",
"(",
"dotted_domain",
")",
":",
"return",
"True",
"return",
"False"
] | Tell if the website is affected by the domain change | [
"Tell",
"if",
"the",
"website",
"is",
"affected",
"by",
"the",
"domain",
"change"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/tossl.py#L63-L74 |
248,398 | dariosky/wfcli | wfcli/tossl.py | WebfactionWebsiteToSsl.get_affected_domains | def get_affected_domains(self):
""" Return a list of all affected domain and subdomains """
results = set()
dotted_domain = ("." + self.domain) if self.domain else None
for website in self.websites:
for subdomain in website['subdomains']:
if self.domain is None or subdomain == self.domain or \
(self.include_subdomains and subdomain.endswith(dotted_domain)):
results.add(subdomain)
# sort them by lenght so the shortest domain is the first
results = sorted(list(results), key=lambda item: len(item))
return results | python | def get_affected_domains(self):
""" Return a list of all affected domain and subdomains """
results = set()
dotted_domain = ("." + self.domain) if self.domain else None
for website in self.websites:
for subdomain in website['subdomains']:
if self.domain is None or subdomain == self.domain or \
(self.include_subdomains and subdomain.endswith(dotted_domain)):
results.add(subdomain)
# sort them by lenght so the shortest domain is the first
results = sorted(list(results), key=lambda item: len(item))
return results | [
"def",
"get_affected_domains",
"(",
"self",
")",
":",
"results",
"=",
"set",
"(",
")",
"dotted_domain",
"=",
"(",
"\".\"",
"+",
"self",
".",
"domain",
")",
"if",
"self",
".",
"domain",
"else",
"None",
"for",
"website",
"in",
"self",
".",
"websites",
":",
"for",
"subdomain",
"in",
"website",
"[",
"'subdomains'",
"]",
":",
"if",
"self",
".",
"domain",
"is",
"None",
"or",
"subdomain",
"==",
"self",
".",
"domain",
"or",
"(",
"self",
".",
"include_subdomains",
"and",
"subdomain",
".",
"endswith",
"(",
"dotted_domain",
")",
")",
":",
"results",
".",
"add",
"(",
"subdomain",
")",
"# sort them by lenght so the shortest domain is the first",
"results",
"=",
"sorted",
"(",
"list",
"(",
"results",
")",
",",
"key",
"=",
"lambda",
"item",
":",
"len",
"(",
"item",
")",
")",
"return",
"results"
] | Return a list of all affected domain and subdomains | [
"Return",
"a",
"list",
"of",
"all",
"affected",
"domain",
"and",
"subdomains"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/tossl.py#L76-L88 |
248,399 | dariosky/wfcli | wfcli/tossl.py | WebfactionWebsiteToSsl.secured_apps_copy | def secured_apps_copy(self, apps):
""" Given the http app list of a website, return what should be in the secure version """
return [[app_name, path] for app_name, path in apps if
app_name not in (self.LETSENCRYPT_VERIFY_APP_NAME,)] | python | def secured_apps_copy(self, apps):
""" Given the http app list of a website, return what should be in the secure version """
return [[app_name, path] for app_name, path in apps if
app_name not in (self.LETSENCRYPT_VERIFY_APP_NAME,)] | [
"def",
"secured_apps_copy",
"(",
"self",
",",
"apps",
")",
":",
"return",
"[",
"[",
"app_name",
",",
"path",
"]",
"for",
"app_name",
",",
"path",
"in",
"apps",
"if",
"app_name",
"not",
"in",
"(",
"self",
".",
"LETSENCRYPT_VERIFY_APP_NAME",
",",
")",
"]"
] | Given the http app list of a website, return what should be in the secure version | [
"Given",
"the",
"http",
"app",
"list",
"of",
"a",
"website",
"return",
"what",
"should",
"be",
"in",
"the",
"secure",
"version"
] | 87a9ed30dbd456f801135a55099f0541b0614ccb | https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/tossl.py#L212-L215 |
Subsets and Splits