repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._offload_service_containers
def _offload_service_containers(self, service): """ :param service: :return: """ if not isinstance(service, Service): raise TypeError("service must be an instance of Service") if service.containers: for key in list(service.containers.keys()): ...
python
def _offload_service_containers(self, service): """ :param service: :return: """ if not isinstance(service, Service): raise TypeError("service must be an instance of Service") if service.containers: for key in list(service.containers.keys()): ...
[ "def", "_offload_service_containers", "(", "self", ",", "service", ")", ":", "if", "not", "isinstance", "(", "service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must be an instance of Service\"", ")", "if", "service", ".", "containers", ":",...
:param service: :return:
[ ":", "param", "service", ":", ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L588-L599
train
Offload the containers of a service.
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._load_service_cargo
def _load_service_cargo(self, service, inject_configs, use_cache=False): """ :param service: :return None: """ if not isinstance(service, Service): raise TypeError("service must of an instance of Service") repository = "{0}/{1}".format(service.repository, ser...
python
def _load_service_cargo(self, service, inject_configs, use_cache=False): """ :param service: :return None: """ if not isinstance(service, Service): raise TypeError("service must of an instance of Service") repository = "{0}/{1}".format(service.repository, ser...
[ "def", "_load_service_cargo", "(", "self", ",", "service", ",", "inject_configs", ",", "use_cache", "=", "False", ")", ":", "if", "not", "isinstance", "(", "service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must of an instance of Service\""...
:param service: :return None:
[ ":", "param", "service", ":", ":", "return", "None", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L601-L635
train
Loads the service s cargo.
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._load_service_containers
def _load_service_containers(self, service, configs, use_cache): """ :param service: :return: """ if not isinstance(service, Service): raise TypeError("service must of an instance of Service") if not service.containers: container_name = self._cont...
python
def _load_service_containers(self, service, configs, use_cache): """ :param service: :return: """ if not isinstance(service, Service): raise TypeError("service must of an instance of Service") if not service.containers: container_name = self._cont...
[ "def", "_load_service_containers", "(", "self", ",", "service", ",", "configs", ",", "use_cache", ")", ":", "if", "not", "isinstance", "(", "service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must of an instance of Service\"", ")", "if", "...
:param service: :return:
[ ":", "param", "service", ":", ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L637-L661
train
Loads the service containers.
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._update_container_host_config
def _update_container_host_config(self, service): """ :param service: :return None: """ if not isinstance(service, Service): raise TypeError("service must be an instance of Service") if service.dependencies: self._load_dependency_containers(servi...
python
def _update_container_host_config(self, service): """ :param service: :return None: """ if not isinstance(service, Service): raise TypeError("service must be an instance of Service") if service.dependencies: self._load_dependency_containers(servi...
[ "def", "_update_container_host_config", "(", "self", ",", "service", ")", ":", "if", "not", "isinstance", "(", "service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must be an instance of Service\"", ")", "if", "service", ".", "dependencies", ...
:param service: :return None:
[ ":", "param", "service", ":", ":", "return", "None", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L663-L679
train
Updates the host config of a container.
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._request_auth
def _request_auth(self, registry): """ self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None): """ if registry: if registry.auth: registry.auth.load_dockercfg() try:...
python
def _request_auth(self, registry): """ self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None): """ if registry: if registry.auth: registry.auth.load_dockercfg() try:...
[ "def", "_request_auth", "(", "self", ",", "registry", ")", ":", "if", "registry", ":", "if", "registry", ".", "auth", ":", "registry", ".", "auth", ".", "load_dockercfg", "(", ")", "try", ":", "self", ".", "_client_session", ".", "login", "(", "username"...
self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None):
[ "self", "username", "password", "=", "None", "email", "=", "None", "registry", "=", "None", "reauth", "=", "False", "insecure_registry", "=", "False", "dockercfg_path", "=", "None", ")", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L718-L736
train
Request auth for a specific user
uogbuji/versa
tools/py/reader/__init__.py
statement_prep
def statement_prep(link): ''' Prepare a statement into a triple ready for rdflib ''' from rdflib import URIRef, Literal from rdflib import BNode s, p, o = link[:3] if not isinstance(s, BNode): s = URIRef(s) p = URIRef(p) if not isinstance(o, BNode): o = URIRef(o) if isinstance(o, I) ...
python
def statement_prep(link): ''' Prepare a statement into a triple ready for rdflib ''' from rdflib import URIRef, Literal from rdflib import BNode s, p, o = link[:3] if not isinstance(s, BNode): s = URIRef(s) p = URIRef(p) if not isinstance(o, BNode): o = URIRef(o) if isinstance(o, I) ...
[ "def", "statement_prep", "(", "link", ")", ":", "from", "rdflib", "import", "URIRef", ",", "Literal", "from", "rdflib", "import", "BNode", "s", ",", "p", ",", "o", "=", "link", "[", ":", "3", "]", "if", "not", "isinstance", "(", "s", ",", "BNode", ...
Prepare a statement into a triple ready for rdflib
[ "Prepare", "a", "statement", "into", "a", "triple", "ready", "for", "rdflib" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/reader/__init__.py#L6-L16
train
Prepare a statement into a triple ready for rdflib
jpulec/django-protractor
protractor/management/commands/protractor.py
Command.teardown_databases
def teardown_databases(self, old_config, options): """ Destroys all the non-mirror databases. """ if len(old_config) > 1: old_names, mirrors = old_config else: old_names = old_config for connection, old_name, destroy in old_names: if de...
python
def teardown_databases(self, old_config, options): """ Destroys all the non-mirror databases. """ if len(old_config) > 1: old_names, mirrors = old_config else: old_names = old_config for connection, old_name, destroy in old_names: if de...
[ "def", "teardown_databases", "(", "self", ",", "old_config", ",", "options", ")", ":", "if", "len", "(", "old_config", ")", ">", "1", ":", "old_names", ",", "mirrors", "=", "old_config", "else", ":", "old_names", "=", "old_config", "for", "connection", ","...
Destroys all the non-mirror databases.
[ "Destroys", "all", "the", "non", "-", "mirror", "databases", "." ]
3857d651612fd988ff0ab17264d367db5345664a
https://github.com/jpulec/django-protractor/blob/3857d651612fd988ff0ab17264d367db5345664a/protractor/management/commands/protractor.py#L114-L124
train
Destroys all the non - mirror databases.
mardix/Mocha
mocha/extras/jinja_helpers.py
oembed
def oembed(url, class_=""): """ Create OEmbed link {{ url | oembed }} :param url: :param class_: :return: """ o = "<a href=\"{url}\" class=\"oembed {class_}\" ></a>".format(url=url, class_=class_) return Markup(o)
python
def oembed(url, class_=""): """ Create OEmbed link {{ url | oembed }} :param url: :param class_: :return: """ o = "<a href=\"{url}\" class=\"oembed {class_}\" ></a>".format(url=url, class_=class_) return Markup(o)
[ "def", "oembed", "(", "url", ",", "class_", "=", "\"\"", ")", ":", "o", "=", "\"<a href=\\\"{url}\\\" class=\\\"oembed {class_}\\\" ></a>\"", ".", "format", "(", "url", "=", "url", ",", "class_", "=", "class_", ")", "return", "Markup", "(", "o", ")" ]
Create OEmbed link {{ url | oembed }} :param url: :param class_: :return:
[ "Create", "OEmbed", "link" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/jinja_helpers.py#L31-L42
train
Create OEmbed link
mardix/Mocha
mocha/extras/jinja_helpers.py
img_src
def img_src(url, class_="", responsive=False, lazy_load=False, id_=""): """ Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return: """ if not url.startswith("http://") and not url.startswith("https://...
python
def img_src(url, class_="", responsive=False, lazy_load=False, id_=""): """ Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return: """ if not url.startswith("http://") and not url.startswith("https://...
[ "def", "img_src", "(", "url", ",", "class_", "=", "\"\"", ",", "responsive", "=", "False", ",", "lazy_load", "=", "False", ",", "id_", "=", "\"\"", ")", ":", "if", "not", "url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "url", ".", ...
Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return:
[ "Create", "an", "image", "src" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/jinja_helpers.py#L45-L72
train
Create an image src tag
assamite/creamas
creamas/examples/spiro/spiro.py
give_dots_yield
def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(theta) + r_*math.cos((R-r) / r * theta) def y(theta): return (R-r) * math.sin(theta) - r_*math.sin((R-r) / r * theta) thet...
python
def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(theta) + r_*math.cos((R-r) / r * theta) def y(theta): return (R-r) * math.sin(theta) - r_*math.sin((R-r) / r * theta) thet...
[ "def", "give_dots_yield", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ")", ":", "def", "x", "(", "theta", ")", ":", "return", "(", "R", "-", "r", ")", "*", "math", ".", "cos", ...
Generate Spirograph dots without numpy using yield.
[ "Generate", "Spirograph", "dots", "without", "numpy", "using", "yield", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L14-L26
train
Generate Spirograph dots with numpy using yield.
assamite/creamas
creamas/examples/spiro/spiro.py
give_dots
def give_dots(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots with numpy. ''' thetas = np.arange(0, 2*PI*spins, resolution) Rr = R - r x = Rr * np.cos(thetas) + r_*np.cos(Rr / r * thetas) y = Rr * np.sin(thetas) - r_*np.sin(Rr / r * thetas) return x, y
python
def give_dots(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots with numpy. ''' thetas = np.arange(0, 2*PI*spins, resolution) Rr = R - r x = Rr * np.cos(thetas) + r_*np.cos(Rr / r * thetas) y = Rr * np.sin(thetas) - r_*np.sin(Rr / r * thetas) return x, y
[ "def", "give_dots", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ")", ":", "thetas", "=", "np", ".", "arange", "(", "0", ",", "2", "*", "PI", "*", "spins", ",", "resolution", ")"...
Generate Spirograph dots with numpy.
[ "Generate", "Spirograph", "dots", "with", "numpy", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L29-L36
train
Generate dots with numpy.
assamite/creamas
creamas/examples/spiro/spiro.py
spiro_image
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
python
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
[ "def", "spiro_image", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ",", "size", "=", "[", "32", ",", "32", "]", ")", ":", "x", ",", "y", "=", "give_dots", "(", "200", ",", "r",...
Create image with given Spirograph parameters using numpy and scipy.
[ "Create", "image", "with", "given", "Spirograph", "parameters", "using", "numpy", "and", "scipy", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L39-L53
train
Create image with given Spirograph parameters using numpy and scipy.
mardix/Mocha
mocha/extras/md.py
html
def html(text, lazy_images=False): """ To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the ...
python
def html(text, lazy_images=False): """ To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the ...
[ "def", "html", "(", "text", ",", "lazy_images", "=", "False", ")", ":", "extensions", "=", "[", "'markdown.extensions.nl2br'", ",", "'markdown.extensions.sane_lists'", ",", "'markdown.extensions.toc'", ",", "'markdown.extensions.tables'", ",", "OEmbedExtension", "(", ")...
To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the LazyImageExtension :return:
[ "To", "render", "a", "markdown", "format", "text", "into", "HTML", "." ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L66-L88
train
Render a markdown format text into HTML.
mardix/Mocha
mocha/extras/md.py
toc
def toc(text): """ Return a table of context list :param text: :return: """ extensions = ['markdown.extensions.toc'] mkd = markdown.Markdown(extensions=extensions) html = mkd.convert(text) return mkd.toc
python
def toc(text): """ Return a table of context list :param text: :return: """ extensions = ['markdown.extensions.toc'] mkd = markdown.Markdown(extensions=extensions) html = mkd.convert(text) return mkd.toc
[ "def", "toc", "(", "text", ")", ":", "extensions", "=", "[", "'markdown.extensions.toc'", "]", "mkd", "=", "markdown", ".", "Markdown", "(", "extensions", "=", "extensions", ")", "html", "=", "mkd", ".", "convert", "(", "text", ")", "return", "mkd", ".",...
Return a table of context list :param text: :return:
[ "Return", "a", "table", "of", "context", "list", ":", "param", "text", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L90-L99
train
Return a table of context list of text
mardix/Mocha
mocha/extras/md.py
extract_images
def extract_images(text): """ Extract all images in the content :param text: :return: """ extensions = [ExtractImagesExtension()] mkd = markdown.Markdown(extensions=extensions) html = mkd.convert(text) return mkd.images
python
def extract_images(text): """ Extract all images in the content :param text: :return: """ extensions = [ExtractImagesExtension()] mkd = markdown.Markdown(extensions=extensions) html = mkd.convert(text) return mkd.images
[ "def", "extract_images", "(", "text", ")", ":", "extensions", "=", "[", "ExtractImagesExtension", "(", ")", "]", "mkd", "=", "markdown", ".", "Markdown", "(", "extensions", "=", "extensions", ")", "html", "=", "mkd", ".", "convert", "(", "text", ")", "re...
Extract all images in the content :param text: :return:
[ "Extract", "all", "images", "in", "the", "content", ":", "param", "text", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L102-L111
train
Extract all images in the content
mardix/Mocha
mocha/extras/md.py
get_toc
def get_toc(text): """ Extract Table of Content of MD :param text: :return: """ mkd.convert(text) toc = mkd.toc mkd.reset() return toc
python
def get_toc(text): """ Extract Table of Content of MD :param text: :return: """ mkd.convert(text) toc = mkd.toc mkd.reset() return toc
[ "def", "get_toc", "(", "text", ")", ":", "mkd", ".", "convert", "(", "text", ")", "toc", "=", "mkd", ".", "toc", "mkd", ".", "reset", "(", ")", "return", "toc" ]
Extract Table of Content of MD :param text: :return:
[ "Extract", "Table", "of", "Content", "of", "MD", ":", "param", "text", ":", ":", "return", ":" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L197-L206
train
Extract Table of Content of MD
mardix/Mocha
mocha/extras/md.py
ExtractImagesTreeprocessor.run
def run(self, root): "Find all images and append to markdown.images. " self.markdown.images = [] for image in root.getiterator("img"): self.markdown.images.append(image.attrib["src"])
python
def run(self, root): "Find all images and append to markdown.images. " self.markdown.images = [] for image in root.getiterator("img"): self.markdown.images.append(image.attrib["src"])
[ "def", "run", "(", "self", ",", "root", ")", ":", "self", ".", "markdown", ".", "images", "=", "[", "]", "for", "image", "in", "root", ".", "getiterator", "(", "\"img\"", ")", ":", "self", ".", "markdown", ".", "images", ".", "append", "(", "image"...
Find all images and append to markdown.images.
[ "Find", "all", "images", "and", "append", "to", "markdown", ".", "images", "." ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L25-L29
train
Find all images and append to markdown. images.
jaraco/jaraco.collections
jaraco/collections.py
dict_map
def dict_map(function, dictionary): """ dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) Tr...
python
def dict_map(function, dictionary): """ dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) Tr...
[ "def", "dict_map", "(", "function", ",", "dictionary", ")", ":", "return", "dict", "(", "(", "key", ",", "function", "(", "value", ")", ")", "for", "key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ")" ]
dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) True
[ "dict_map", "is", "much", "like", "the", "built", "-", "in", "function", "map", ".", "It", "takes", "a", "dictionary", "and", "applys", "a", "function", "to", "the", "values", "of", "that", "dictionary", "returning", "a", "new", "dictionary", "with", "the"...
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L139-L149
train
This function is a built - in function map. It takes a dictionary and applies a function to the values of that dictionary and returns a new dictionary with the mapped values.
jaraco/jaraco.collections
jaraco/collections.py
sorted_items
def sorted_items(d, key=__identity, reverse=False): """ Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=...
python
def sorted_items(d, key=__identity, reverse=False): """ Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=...
[ "def", "sorted_items", "(", "d", ",", "key", "=", "__identity", ",", "reverse", "=", "False", ")", ":", "# wrap the key func so it operates on the first element of each item", "def", "pairkey_key", "(", "item", ")", ":", "return", "key", "(", "item", "[", "0", "...
Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=reverse_string)) (('foo', 20), ('bar', 42), ('baz', 10)) ...
[ "Return", "the", "items", "of", "the", "dictionary", "sorted", "by", "the", "keys" ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L269-L287
train
Return the items of the dictionary sorted by the keys
jaraco/jaraco.collections
jaraco/collections.py
invert_map
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceba...
python
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceba...
[ "def", "invert_map", "(", "map", ")", ":", "res", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "map", ".", "items", "(", ")", ")", "if", "not", "len", "(", "res", ")", "==", "len", "(", "map", ")", ":", "raise", ...
Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceback (most recent call last):...
[ "Given", "a", "dictionary", "return", "another", "dictionary", "with", "keys", "and", "values", "switched", ".", "If", "any", "of", "the", "values", "resolve", "to", "the", "same", "key", "raises", "a", "ValueError", "." ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L506-L525
train
Given a dictionary return another dictionary with keys and values switched.
jaraco/jaraco.collections
jaraco/collections.py
KeyTransformingDict.matching_key_for
def matching_key_for(self, key): """ Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found. """ try: return next(e_key for e_key in self.keys() if e_key == key) except StopIteration: raise KeyError(key)
python
def matching_key_for(self, key): """ Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found. """ try: return next(e_key for e_key in self.keys() if e_key == key) except StopIteration: raise KeyError(key)
[ "def", "matching_key_for", "(", "self", ",", "key", ")", ":", "try", ":", "return", "next", "(", "e_key", "for", "e_key", "in", "self", ".", "keys", "(", ")", "if", "e_key", "==", "key", ")", "except", "StopIteration", ":", "raise", "KeyError", "(", ...
Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found.
[ "Given", "a", "key", "return", "the", "actual", "key", "stored", "in", "self", "that", "matches", ".", "Raise", "KeyError", "if", "the", "key", "isn", "t", "found", "." ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L335-L343
train
Given a key return the actual key stored in self that matches.
cozy/python_cozy_management
cozy_management/backup.py
backup
def backup(backup_filename=None): ''' Backup a Cozy ''' timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) if not backup_filename: if not os.path.isdir(BACKUPS_PATH): print 'Need to create {}'.format(BACKUPS_PATH) os.makedirs(BACKUPS_PATH, 0700) ...
python
def backup(backup_filename=None): ''' Backup a Cozy ''' timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) if not backup_filename: if not os.path.isdir(BACKUPS_PATH): print 'Need to create {}'.format(BACKUPS_PATH) os.makedirs(BACKUPS_PATH, 0700) ...
[ "def", "backup", "(", "backup_filename", "=", "None", ")", ":", "timestamp", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d-%H-%M-%S\"", ",", "time", ".", "gmtime", "(", ")", ")", "if", "not", "backup_filename", ":", "if", "not", "os", ".", "path", ".", ...
Backup a Cozy
[ "Backup", "a", "Cozy" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/backup.py#L24-L52
train
Backup a Cozycozy object
cozy/python_cozy_management
cozy_management/backup.py
restore
def restore(backup_file): ''' Restore a Cozy backup_file: path to .tar.gz ''' if not os.path.isfile(backup_file) and not os.path.islink(backup_file): print 'Missing backup file: {}'.format(backup_file) else: couchdb_path = _get_couchdb_path() print 'Restore Cozy:...
python
def restore(backup_file): ''' Restore a Cozy backup_file: path to .tar.gz ''' if not os.path.isfile(backup_file) and not os.path.islink(backup_file): print 'Missing backup file: {}'.format(backup_file) else: couchdb_path = _get_couchdb_path() print 'Restore Cozy:...
[ "def", "restore", "(", "backup_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "backup_file", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "backup_file", ")", ":", "print", "'Missing backup file: {}'", ".", "format", "("...
Restore a Cozy backup_file: path to .tar.gz
[ "Restore", "a", "Cozy", "backup_file", ":", "path", "to", ".", "tar", ".", "gz" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/backup.py#L55-L76
train
Restore a CozyMacroEntry from a file.
projectshift/shift-boiler
boiler/cli/db.py
get_config
def get_config(): """ Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it """ from boiler.migra...
python
def get_config(): """ Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it """ from boiler.migra...
[ "def", "get_config", "(", ")", ":", "from", "boiler", ".", "migrations", ".", "config", "import", "MigrationsConfig", "# used for errors", "map", "=", "dict", "(", "path", "=", "'MIGRATIONS_PATH'", ",", "db_url", "=", "'SQLALCHEMY_DATABASE_URI'", ",", "metadata", ...
Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it
[ "Prepare", "and", "return", "alembic", "config", "These", "configurations", "used", "to", "live", "in", "alembic", "config", "initialiser", "but", "that", "just", "tight", "coupling", ".", "Ideally", "we", "should", "move", "that", "to", "userspace", "and", "f...
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L10-L40
train
Prepare and return alembic config
projectshift/shift-boiler
boiler/cli/db.py
init
def init(): """ Initialize new migrations directory """ try: config = get_config() print(config.dir) alembic_command.init(config, config.dir, 'project') except CommandError as e: click.echo(red(str(e)))
python
def init(): """ Initialize new migrations directory """ try: config = get_config() print(config.dir) alembic_command.init(config, config.dir, 'project') except CommandError as e: click.echo(red(str(e)))
[ "def", "init", "(", ")", ":", "try", ":", "config", "=", "get_config", "(", ")", "print", "(", "config", ".", "dir", ")", "alembic_command", ".", "init", "(", "config", ",", "config", ".", "dir", ",", "'project'", ")", "except", "CommandError", "as", ...
Initialize new migrations directory
[ "Initialize", "new", "migrations", "directory" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L59-L66
train
Initialize new migrations directory
projectshift/shift-boiler
boiler/cli/db.py
revision
def revision(revision, path, branch_label, splice, head, sql, autogenerate, message): """ Create new revision file """ alembic_command.revision( config=get_config(), rev_id=revision, version_path=path, branch_label=branch_label, splice=splice, head=head, s...
python
def revision(revision, path, branch_label, splice, head, sql, autogenerate, message): """ Create new revision file """ alembic_command.revision( config=get_config(), rev_id=revision, version_path=path, branch_label=branch_label, splice=splice, head=head, s...
[ "def", "revision", "(", "revision", ",", "path", ",", "branch_label", ",", "splice", ",", "head", ",", "sql", ",", "autogenerate", ",", "message", ")", ":", "alembic_command", ".", "revision", "(", "config", "=", "get_config", "(", ")", ",", "rev_id", "=...
Create new revision file
[ "Create", "new", "revision", "file" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L78-L90
train
Create a new revision file
projectshift/shift-boiler
boiler/cli/db.py
merge
def merge(revision, branch_label, message, list_revisions=''): """ Merge two revision together, create new revision file """ alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
python
def merge(revision, branch_label, message, list_revisions=''): """ Merge two revision together, create new revision file """ alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
[ "def", "merge", "(", "revision", ",", "branch_label", ",", "message", ",", "list_revisions", "=", "''", ")", ":", "alembic_command", ".", "merge", "(", "config", "=", "get_config", "(", ")", ",", "revisions", "=", "list_revisions", ",", "message", "=", "me...
Merge two revision together, create new revision file
[ "Merge", "two", "revision", "together", "create", "new", "revision", "file" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L121-L129
train
Merge two revision together create new revision file
projectshift/shift-boiler
boiler/cli/db.py
up
def up(tag, sql, revision): """ Upgrade to revision """ alembic_command.upgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def up(tag, sql, revision): """ Upgrade to revision """ alembic_command.upgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "up", "(", "tag", ",", "sql", ",", "revision", ")", ":", "alembic_command", ".", "upgrade", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Upgrade to revision
[ "Upgrade", "to", "revision" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L136-L143
train
Upgrades the current version of the current page to the given revision.
projectshift/shift-boiler
boiler/cli/db.py
down
def down(tag, sql, revision): """ Downgrade to revision """ alembic_command.downgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def down(tag, sql, revision): """ Downgrade to revision """ alembic_command.downgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "down", "(", "tag", ",", "sql", ",", "revision", ")", ":", "alembic_command", ".", "downgrade", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Downgrade to revision
[ "Downgrade", "to", "revision" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L150-L157
train
Downgrade to revision
projectshift/shift-boiler
boiler/cli/db.py
history
def history(verbose, range): """ List revision changesets chronologically """ alembic_command.history( config=get_config(), rev_range=range, verbose=verbose )
python
def history(verbose, range): """ List revision changesets chronologically """ alembic_command.history( config=get_config(), rev_range=range, verbose=verbose )
[ "def", "history", "(", "verbose", ",", "range", ")", ":", "alembic_command", ".", "history", "(", "config", "=", "get_config", "(", ")", ",", "rev_range", "=", "range", ",", "verbose", "=", "verbose", ")" ]
List revision changesets chronologically
[ "List", "revision", "changesets", "chronologically" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L173-L179
train
List revision changesets chronologically
projectshift/shift-boiler
boiler/cli/db.py
heads
def heads(resolve, verbose): """ Show available heads """ alembic_command.heads( config=get_config(), verbose=verbose, resolve_dependencies=resolve )
python
def heads(resolve, verbose): """ Show available heads """ alembic_command.heads( config=get_config(), verbose=verbose, resolve_dependencies=resolve )
[ "def", "heads", "(", "resolve", ",", "verbose", ")", ":", "alembic_command", ".", "heads", "(", "config", "=", "get_config", "(", ")", ",", "verbose", "=", "verbose", ",", "resolve_dependencies", "=", "resolve", ")" ]
Show available heads
[ "Show", "available", "heads" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L185-L191
train
Show available heads
projectshift/shift-boiler
boiler/cli/db.py
stamp
def stamp(revision, sql, tag): """ Stamp db to given revision without migrating """ alembic_command.stamp( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def stamp(revision, sql, tag): """ Stamp db to given revision without migrating """ alembic_command.stamp( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "stamp", "(", "revision", ",", "sql", ",", "tag", ")", ":", "alembic_command", ".", "stamp", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Stamp db to given revision without migrating
[ "Stamp", "db", "to", "given", "revision", "without", "migrating" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L218-L225
train
Stamp the database to given revision without migrating.
Kortemme-Lab/klab
klab/db/sqlalchemy_interface.py
row_to_dict
def row_to_dict(r, keep_relationships = False): '''Converts an SQLAlchemy record to a Python dict. We assume that _sa_instance_state exists and is the only value we do not care about. If DeclarativeBase is passed then all DeclarativeBase objects (e.g. those created by relationships) are also removed. '''...
python
def row_to_dict(r, keep_relationships = False): '''Converts an SQLAlchemy record to a Python dict. We assume that _sa_instance_state exists and is the only value we do not care about. If DeclarativeBase is passed then all DeclarativeBase objects (e.g. those created by relationships) are also removed. '''...
[ "def", "row_to_dict", "(", "r", ",", "keep_relationships", "=", "False", ")", ":", "d", "=", "{", "}", "if", "not", "keep_relationships", ":", "# only returns the table columns", "t", "=", "r", ".", "__table__", "for", "c", "in", "[", "c", ".", "name", "...
Converts an SQLAlchemy record to a Python dict. We assume that _sa_instance_state exists and is the only value we do not care about. If DeclarativeBase is passed then all DeclarativeBase objects (e.g. those created by relationships) are also removed.
[ "Converts", "an", "SQLAlchemy", "record", "to", "a", "Python", "dict", ".", "We", "assume", "that", "_sa_instance_state", "exists", "and", "is", "the", "only", "value", "we", "do", "not", "care", "about", ".", "If", "DeclarativeBase", "is", "passed", "then",...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L48-L61
train
Converts an SQLAlchemy record to a Python dict.
Kortemme-Lab/klab
klab/db/sqlalchemy_interface.py
get_or_create_in_transaction
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): ''' Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing re...
python
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): ''' Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing re...
[ "def", "get_or_create_in_transaction", "(", "tsession", ",", "model", ",", "values", ",", "missing_columns", "=", "[", "]", ",", "variable_columns", "=", "[", "]", ",", "updatable_columns", "=", "[", "]", ",", "only_use_supplied_columns", "=", "False", ",", "r...
Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing record, to create a new database record. :param tsession: An SQLAlchemy transactioned session :param model: The name of the SQLAlchemy class representing the table :param values: A di...
[ "Uses", "the", "SQLAlchemy", "model", "to", "retrieve", "an", "existing", "record", "based", "on", "the", "supplied", "field", "values", "or", "if", "there", "is", "no", "existing", "record", "to", "create", "a", "new", "database", "record", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L74-L137
train
This function is used to retrieve an existing record based on the supplied field values or create a new record based on the supplied field values.
Kortemme-Lab/klab
klab/db/sqlalchemy_interface.py
get_or_create_in_transaction_wrapper
def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): '''This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling...
python
def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): '''This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling...
[ "def", "get_or_create_in_transaction_wrapper", "(", "tsession", ",", "model", ",", "values", ",", "missing_columns", "=", "[", "]", ",", "variable_columns", "=", "[", "]", ",", "updatable_columns", "=", "[", "]", ",", "only_use_supplied_columns", "=", "False", "...
This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling the database API. Switch out calls to get_or_create_in_transaction to get_or_create_in_transaction_wrapper in the suspected functions to determine where the pain lies.
[ "This", "function", "can", "be", "used", "to", "determine", "which", "calling", "method", "is", "spending", "time", "in", "get_or_create_in_transaction", "when", "profiling", "the", "database", "API", ".", "Switch", "out", "calls", "to", "get_or_create_in_transactio...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L140-L143
train
This function is used to determine which calling method is spending time in get_or_create_in_transaction when profiling the database API.
assamite/creamas
creamas/rules/agent.py
RuleAgent.set_weight
def set_weight(self, rule, weight): """Set weight for rule in :attr:`R`. Adds the rule if it is not in :attr:`R`. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to set weight ({}) is not subclass " "of {} or {}.".fo...
python
def set_weight(self, rule, weight): """Set weight for rule in :attr:`R`. Adds the rule if it is not in :attr:`R`. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to set weight ({}) is not subclass " "of {} or {}.".fo...
[ "def", "set_weight", "(", "self", ",", "rule", ",", "weight", ")", ":", "if", "not", "issubclass", "(", "rule", ".", "__class__", ",", "(", "Rule", ",", "RuleLeaf", ")", ")", ":", "raise", "TypeError", "(", "\"Rule to set weight ({}) is not subclass \"", "\"...
Set weight for rule in :attr:`R`. Adds the rule if it is not in :attr:`R`.
[ "Set", "weight", "for", "rule", "in", ":", "attr", ":", "R", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L53-L66
train
Set the weight for rule in the internal list.
assamite/creamas
creamas/rules/agent.py
RuleAgent.get_weight
def get_weight(self, rule): """Get weight for rule. If rule is not in :attr:`R`, returns ``None``. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to get weight ({}) is not subclass " "of {} or {}.".format(rule, Rule...
python
def get_weight(self, rule): """Get weight for rule. If rule is not in :attr:`R`, returns ``None``. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to get weight ({}) is not subclass " "of {} or {}.".format(rule, Rule...
[ "def", "get_weight", "(", "self", ",", "rule", ")", ":", "if", "not", "issubclass", "(", "rule", ".", "__class__", ",", "(", "Rule", ",", "RuleLeaf", ")", ")", ":", "raise", "TypeError", "(", "\"Rule to get weight ({}) is not subclass \"", "\"of {} or {}.\"", ...
Get weight for rule. If rule is not in :attr:`R`, returns ``None``.
[ "Get", "weight", "for", "rule", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L68-L80
train
Get weight for rule.
assamite/creamas
creamas/rules/agent.py
RuleAgent.add_rule
def add_rule(self, rule, weight): """Add rule to :attr:`R` with initial weight. :param rule: rule to be added :type rule: `~creamas.core.rule.Rule` :param float weight: initial weight for the rule :raises TypeError: if rule is not subclass of :py:class:`Rule` :returns: `...
python
def add_rule(self, rule, weight): """Add rule to :attr:`R` with initial weight. :param rule: rule to be added :type rule: `~creamas.core.rule.Rule` :param float weight: initial weight for the rule :raises TypeError: if rule is not subclass of :py:class:`Rule` :returns: `...
[ "def", "add_rule", "(", "self", ",", "rule", ",", "weight", ")", ":", "if", "not", "issubclass", "(", "rule", ".", "__class__", ",", "(", "Rule", ",", "RuleLeaf", ")", ")", ":", "raise", "TypeError", "(", "\"Rule to add ({}) must be derived from {} or {}.\"", ...
Add rule to :attr:`R` with initial weight. :param rule: rule to be added :type rule: `~creamas.core.rule.Rule` :param float weight: initial weight for the rule :raises TypeError: if rule is not subclass of :py:class:`Rule` :returns: ``True`` if rule was successfully added, other...
[ "Add", "rule", "to", ":", "attr", ":", "R", "with", "initial", "weight", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L82-L100
train
Adds a rule to the list of available rules.
assamite/creamas
creamas/rules/agent.py
RuleAgent.remove_rule
def remove_rule(self, rule): """Remove rule from :attr:`R` and its corresponding weight from :attr:`W`. :param rule: rule to remove :type rule: :class:`~creamas.rules.rule.Rule` or :class:`~creamas.rules.rule.RuleLeaf` :raises TypeError: If ru...
python
def remove_rule(self, rule): """Remove rule from :attr:`R` and its corresponding weight from :attr:`W`. :param rule: rule to remove :type rule: :class:`~creamas.rules.rule.Rule` or :class:`~creamas.rules.rule.RuleLeaf` :raises TypeError: If ru...
[ "def", "remove_rule", "(", "self", ",", "rule", ")", ":", "if", "not", "issubclass", "(", "rule", ".", "__class__", ",", "(", "Rule", ",", "RuleLeaf", ")", ")", ":", "raise", "TypeError", "(", "\"Rule to remove ({}) is not subclass of {} or {}.\"", ".", "forma...
Remove rule from :attr:`R` and its corresponding weight from :attr:`W`. :param rule: rule to remove :type rule: :class:`~creamas.rules.rule.Rule` or :class:`~creamas.rules.rule.RuleLeaf` :raises TypeError: If rule is not derived from :class:`Rule` or ...
[ "Remove", "rule", "from", ":", "attr", ":", "R", "and", "its", "corresponding", "weight", "from", ":", "attr", ":", "W", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L102-L126
train
Removes a rule from the internal list R and its corresponding weight from the internal list W.
assamite/creamas
creamas/rules/agent.py
RuleAgent.evaluate
def evaluate(self, artifact): r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evalu...
python
def evaluate(self, artifact): r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evalu...
[ "def", "evaluate", "(", "self", ",", "artifact", ")", ":", "s", "=", "0", "w", "=", "0.0", "if", "len", "(", "self", ".", "R", ")", "==", "0", ":", "return", "0.0", ",", "None", "for", "i", "in", "range", "(", "len", "(", "self", ".", "R", ...
r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evaluation of the artifact, in [-1,1], and ...
[ "r", "Evaluate", "artifact", "with", "agent", "s", "current", "rules", "and", "weights", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L129-L167
train
r Evaluates the given artifact with agent s current rules and weights.
TheGhouls/oct
oct/results/report.py
ReportResults._init_dates
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
python
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
[ "def", "_init_dates", "(", "self", ")", ":", "if", "self", ".", "total_transactions", "==", "0", ":", "return", "None", "self", ".", "epoch_start", "=", "Result", ".", "select", "(", "Result", ".", "epoch", ")", ".", "order_by", "(", "Result", ".", "ep...
Initialize all dates properties
[ "Initialize", "all", "dates", "properties" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L29-L37
train
Initialize all dates properties
TheGhouls/oct
oct/results/report.py
ReportResults._init_dataframes
def _init_dataframes(self): """Initialise the main dataframe for the results and the custom timers dataframes """ df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC", db.get_conn()) self._get_all_tim...
python
def _init_dataframes(self): """Initialise the main dataframe for the results and the custom timers dataframes """ df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC", db.get_conn()) self._get_all_tim...
[ "def", "_init_dataframes", "(", "self", ")", ":", "df", "=", "pd", ".", "read_sql_query", "(", "\"SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC\"", ",", "db", ".", "get_conn", "(", ")", ")", "self", ".", "_get_all_timers", "(", "d...
Initialise the main dataframe for the results and the custom timers dataframes
[ "Initialise", "the", "main", "dataframe", "for", "the", "results", "and", "the", "custom", "timers", "dataframes" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L39-L56
train
Initialise the main dataframe for the results and the custom timers dataframes
TheGhouls/oct
oct/results/report.py
ReportResults._get_all_timers
def _get_all_timers(self, dataframe): """Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results """ s = dataframe['custom_timers'].apply(json.loads) s.index = dataframe['epoch'] for index, value i...
python
def _get_all_timers(self, dataframe): """Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results """ s = dataframe['custom_timers'].apply(json.loads) s.index = dataframe['epoch'] for index, value i...
[ "def", "_get_all_timers", "(", "self", ",", "dataframe", ")", ":", "s", "=", "dataframe", "[", "'custom_timers'", "]", ".", "apply", "(", "json", ".", "loads", ")", "s", ".", "index", "=", "dataframe", "[", "'epoch'", "]", "for", "index", ",", "value",...
Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results
[ "Get", "all", "timers", "and", "set", "them", "in", "the", "_timers_values", "property" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L58-L72
train
Get all timers and set them in the _timers_values property
TheGhouls/oct
oct/results/report.py
ReportResults._get_processed_dataframe
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dat...
python
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dat...
[ "def", "_get_processed_dataframe", "(", "self", ",", "dataframe", ")", ":", "dataframe", ".", "index", "=", "pd", ".", "to_datetime", "(", "dataframe", "[", "'epoch'", "]", ",", "unit", "=", "'s'", ",", "utc", "=", "True", ")", "del", "dataframe", "[", ...
Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict
[ "Generate", "required", "dataframe", "for", "results", "from", "raw", "dataframe" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L74-L91
train
Generate required dataframe for results from original dataframe
TheGhouls/oct
oct/results/report.py
ReportResults._init_turrets
def _init_turrets(self): """Setup data from database """ for turret in Turret.select(): self.turrets.append(turret.to_dict())
python
def _init_turrets(self): """Setup data from database """ for turret in Turret.select(): self.turrets.append(turret.to_dict())
[ "def", "_init_turrets", "(", "self", ")", ":", "for", "turret", "in", "Turret", ".", "select", "(", ")", ":", "self", ".", "turrets", ".", "append", "(", "turret", ".", "to_dict", "(", ")", ")" ]
Setup data from database
[ "Setup", "data", "from", "database" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L93-L97
train
Setup data from database
TheGhouls/oct
oct/results/report.py
ReportResults.compile_results
def compile_results(self): """Compile all results for the current test """ self._init_dataframes() self.total_transactions = len(self.main_results['raw']) self._init_dates()
python
def compile_results(self): """Compile all results for the current test """ self._init_dataframes() self.total_transactions = len(self.main_results['raw']) self._init_dates()
[ "def", "compile_results", "(", "self", ")", ":", "self", ".", "_init_dataframes", "(", ")", "self", ".", "total_transactions", "=", "len", "(", "self", ".", "main_results", "[", "'raw'", "]", ")", "self", ".", "_init_dates", "(", ")" ]
Compile all results for the current test
[ "Compile", "all", "results", "for", "the", "current", "test" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L99-L105
train
Compile all results for the current testset
Kortemme-Lab/klab
klab/bio/kabsch.py
centroid
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
python
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
[ "def", "centroid", "(", "X", ")", ":", "C", "=", "np", ".", "sum", "(", "X", ",", "axis", "=", "0", ")", "/", "len", "(", "X", ")", "return", "C" ]
Calculate the centroid from a matrix X
[ "Calculate", "the", "centroid", "from", "a", "matrix", "X" ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/kabsch.py#L30-L35
train
Calculate the centroid from a matrix X
Kortemme-Lab/klab
klab/bio/kabsch.py
bakan_bahar_ensemble_align
def bakan_bahar_ensemble_align(coords, tolerance = 0.001, verbose = False ): ''' input: a list of coordinates in the format: [ [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 1 [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 2 # etc. ] ''' rmsd_tolerance = float("in...
python
def bakan_bahar_ensemble_align(coords, tolerance = 0.001, verbose = False ): ''' input: a list of coordinates in the format: [ [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 1 [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 2 # etc. ] ''' rmsd_tolerance = float("in...
[ "def", "bakan_bahar_ensemble_align", "(", "coords", ",", "tolerance", "=", "0.001", ",", "verbose", "=", "False", ")", ":", "rmsd_tolerance", "=", "float", "(", "\"inf\"", ")", "average_struct_coords", "=", "np", ".", "array", "(", "random", ".", "choice", "...
input: a list of coordinates in the format: [ [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 1 [ (x, y, z), (x, y, z), (x, y, z) ], # atoms in model 2 # etc. ]
[ "input", ":", "a", "list", "of", "coordinates", "in", "the", "format", ":", "[", "[", "(", "x", "y", "z", ")", "(", "x", "y", "z", ")", "(", "x", "y", "z", ")", "]", "#", "atoms", "in", "model", "1", "[", "(", "x", "y", "z", ")", "(", "...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/kabsch.py#L82-L102
train
aligns a list of coordinates with the Bakan - Bahar model
Apstra/aeon-venos
pylib/aeon/utils/__init__.py
get_device
def get_device(target=None, user='admin', passwd='admin', nos_only=False): """ Automatically determine device type based on device interrogation. :param target: IP address or hostname of target :param user: Username to login to target :param passwd: Password to login to target :param nos_only: O...
python
def get_device(target=None, user='admin', passwd='admin', nos_only=False): """ Automatically determine device type based on device interrogation. :param target: IP address or hostname of target :param user: Username to login to target :param passwd: Password to login to target :param nos_only: O...
[ "def", "get_device", "(", "target", "=", "None", ",", "user", "=", "'admin'", ",", "passwd", "=", "'admin'", ",", "nos_only", "=", "False", ")", ":", "dev_table", "=", "{", "'nxos'", ":", "aeon", ".", "nxos", ".", "device", ".", "Device", ",", "'eos'...
Automatically determine device type based on device interrogation. :param target: IP address or hostname of target :param user: Username to login to target :param passwd: Password to login to target :param nos_only: Only check for device nos and return as string, do not return device object :return:...
[ "Automatically", "determine", "device", "type", "based", "on", "device", "interrogation", ".", ":", "param", "target", ":", "IP", "address", "or", "hostname", "of", "target", ":", "param", "user", ":", "Username", "to", "login", "to", "target", ":", "param",...
4d4f73d5904831ddc78c30922a8a226c90cf7d90
https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/utils/__init__.py#L20-L91
train
Get a specific device object from the given target.
eventbrite/rebar
src/rebar/validators.py
StateValidatorFormMixin.is_valid
def is_valid(self, *states): """Returns True if no errors are thrown for the specified state.""" # if no state is specified, fallback to the base Form's is_valid if not states: return super(StateValidatorFormMixin, self).is_valid() return all(self.state_validators[state].is...
python
def is_valid(self, *states): """Returns True if no errors are thrown for the specified state.""" # if no state is specified, fallback to the base Form's is_valid if not states: return super(StateValidatorFormMixin, self).is_valid() return all(self.state_validators[state].is...
[ "def", "is_valid", "(", "self", ",", "*", "states", ")", ":", "# if no state is specified, fallback to the base Form's is_valid", "if", "not", "states", ":", "return", "super", "(", "StateValidatorFormMixin", ",", "self", ")", ".", "is_valid", "(", ")", "return", ...
Returns True if no errors are thrown for the specified state.
[ "Returns", "True", "if", "no", "errors", "are", "thrown", "for", "the", "specified", "state", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L42-L50
train
Returns True if no errors are thrown for the specified state.
eventbrite/rebar
src/rebar/validators.py
StateValidator.is_valid
def is_valid(self, instance): """Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called. """ errors = self.errors(instance) if...
python
def is_valid(self, instance): """Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called. """ errors = self.errors(instance) if...
[ "def", "is_valid", "(", "self", ",", "instance", ")", ":", "errors", "=", "self", ".", "errors", "(", "instance", ")", "if", "isinstance", "(", "errors", ",", "list", ")", ":", "return", "not", "any", "(", "errors", ")", "return", "not", "bool", "(",...
Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called.
[ "Return", "True", "if", "no", "errors", "are", "raised", "when", "validating", "instance", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L80-L93
train
Return True if the instance is valid.
eventbrite/rebar
src/rebar/validators.py
StateValidator._validate
def _validate(self, data): """Helper to run validators on the field data.""" errors = {} # if the validator is not enabled, return the empty error dict if not self._enabled: return errors for field in self.validators: field_errors = [] for...
python
def _validate(self, data): """Helper to run validators on the field data.""" errors = {} # if the validator is not enabled, return the empty error dict if not self._enabled: return errors for field in self.validators: field_errors = [] for...
[ "def", "_validate", "(", "self", ",", "data", ")", ":", "errors", "=", "{", "}", "# if the validator is not enabled, return the empty error dict", "if", "not", "self", ".", "_enabled", ":", "return", "errors", "for", "field", "in", "self", ".", "validators", ":"...
Helper to run validators on the field data.
[ "Helper", "to", "run", "validators", "on", "the", "field", "data", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L95-L118
train
Helper to run validators on the field data.
eventbrite/rebar
src/rebar/validators.py
StateValidator.errors
def errors(self, instance): """Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be cal...
python
def errors(self, instance): """Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be cal...
[ "def", "errors", "(", "self", ",", "instance", ")", ":", "if", "isinstance", "(", "instance", ",", "dict", ")", ":", "return", "self", ".", "_validate", "(", "instance", ")", "elif", "isinstance", "(", "instance", ",", "forms", ".", "BaseForm", ")", ":...
Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be called if the form is bound. ...
[ "Run", "all", "field", "validators", "and", "return", "a", "dict", "of", "errors", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L120-L173
train
Run all field validators and return a dict of errors.
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/relational.py
queryset_formatter
def queryset_formatter(queryset): """ This is used for custom detail fields returning a QuerySet of admin objects. """ return Markup( base_list_formatter( None, [ '<a href="{}">{}</a>'.format(u.get_admin_url(_external=True), u) for u in...
python
def queryset_formatter(queryset): """ This is used for custom detail fields returning a QuerySet of admin objects. """ return Markup( base_list_formatter( None, [ '<a href="{}">{}</a>'.format(u.get_admin_url(_external=True), u) for u in...
[ "def", "queryset_formatter", "(", "queryset", ")", ":", "return", "Markup", "(", "base_list_formatter", "(", "None", ",", "[", "'<a href=\"{}\">{}</a>'", ".", "format", "(", "u", ".", "get_admin_url", "(", "_external", "=", "True", ")", ",", "u", ")", "for",...
This is used for custom detail fields returning a QuerySet of admin objects.
[ "This", "is", "used", "for", "custom", "detail", "fields", "returning", "a", "QuerySet", "of", "admin", "objects", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/relational.py#L8-L21
train
This is used for custom detail fields returning a QuerySet of admin objects.
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/relational.py
qs_field
def qs_field( model_class, field, filters=None, formatter=queryset_formatter, manager_name='objects', ): """ Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ...
python
def qs_field( model_class, field, filters=None, formatter=queryset_formatter, manager_name='objects', ): """ Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ...
[ "def", "qs_field", "(", "model_class", ",", "field", ",", "filters", "=", "None", ",", "formatter", "=", "queryset_formatter", ",", "manager_name", "=", "'objects'", ",", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "{", "}", "def", "_",...
Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ------- class MyModel(ModelView): details_extra_columns = [ ('courses_owned', 'Courses (Owner of)'), ] ...
[ "Show", "computed", "fields", "based", "on", "QuerySet", "s", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/relational.py#L24-L57
train
Show computed fields based on QuerySet s.
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM._get_pdb_id
def _get_pdb_id(self, elem, **kwargs): '''If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.''' id = elem.attrib['ID'] if self.restrict_to_transmembrane_proteins: tmp = elem.attrib['TMP'] ...
python
def _get_pdb_id(self, elem, **kwargs): '''If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.''' id = elem.attrib['ID'] if self.restrict_to_transmembrane_proteins: tmp = elem.attrib['TMP'] ...
[ "def", "_get_pdb_id", "(", "self", ",", "elem", ",", "*", "*", "kwargs", ")", ":", "id", "=", "elem", ".", "attrib", "[", "'ID'", "]", "if", "self", ".", "restrict_to_transmembrane_proteins", ":", "tmp", "=", "elem", ".", "attrib", "[", "'TMP'", "]", ...
If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.
[ "If", "self", ".", "restrict_to_transmembrane_proteins", "is", "False", "then", "this", "adds", "all", "ids", "to", "self", ".", "ids", ".", "Otherwise", "only", "transmembrane", "protein", "ids", "are", "added", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L61-L70
train
Get the PDB ID from the XML element.
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM.get_pdb_id_map
def get_pdb_id_map(self): ''' Returns a dict mapping PDB IDs to: i) their number of associated records, if self.restrict_to_transmembrane_proteins is False; ii) the type of transmembrane protein if self.restrict_to_transmembrane_proteins is True. At the time of writing...
python
def get_pdb_id_map(self): ''' Returns a dict mapping PDB IDs to: i) their number of associated records, if self.restrict_to_transmembrane_proteins is False; ii) the type of transmembrane protein if self.restrict_to_transmembrane_proteins is True. At the time of writing...
[ "def", "get_pdb_id_map", "(", "self", ")", ":", "self", ".", "ids", "=", "{", "}", "context", "=", "etree", ".", "iterparse", "(", "io", ".", "BytesIO", "(", "self", ".", "xml_contents", ")", ",", "events", "=", "(", "'end'", ",", ")", ",", "tag", ...
Returns a dict mapping PDB IDs to: i) their number of associated records, if self.restrict_to_transmembrane_proteins is False; ii) the type of transmembrane protein if self.restrict_to_transmembrane_proteins is True. At the time of writing this (2014-12-03), there were 106,094...
[ "Returns", "a", "dict", "mapping", "PDB", "IDs", "to", ":", "i", ")", "their", "number", "of", "associated", "records", "if", "self", ".", "restrict_to_transmembrane_proteins", "is", "False", ";", "ii", ")", "the", "type", "of", "transmembrane", "protein", "...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L78-L87
train
Returns a dict mapping PDB IDs to PDB IDs.
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM.get_membrane_xml
def get_membrane_xml(self, pdb_id): ''' Returns the <MEMBRANE> tag XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_membrane_x...
python
def get_membrane_xml(self, pdb_id): ''' Returns the <MEMBRANE> tag XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_membrane_x...
[ "def", "get_membrane_xml", "(", "self", ",", "pdb_id", ")", ":", "self", ".", "tmp_string", "=", "None", "context", "=", "etree", ".", "iterparse", "(", "io", ".", "BytesIO", "(", "self", ".", "xml_contents", ")", ",", "events", "=", "(", "'end'", ",",...
Returns the <MEMBRANE> tag XML for pdb_id if the tag exists.
[ "Returns", "the", "<MEMBRANE", ">", "tag", "XML", "for", "pdb_id", "if", "the", "tag", "exists", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L100-L107
train
Returns the XML for the MEBRANE tag for pdb_id if the tag exists.
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM.get_xml
def get_xml(self, pdb_id): ''' Returns the XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_xml, pdb_id = pdb_id.upper()) ...
python
def get_xml(self, pdb_id): ''' Returns the XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_xml, pdb_id = pdb_id.upper()) ...
[ "def", "get_xml", "(", "self", ",", "pdb_id", ")", ":", "self", ".", "tmp_string", "=", "None", "context", "=", "etree", ".", "iterparse", "(", "io", ".", "BytesIO", "(", "self", ".", "xml_contents", ")", ",", "events", "=", "(", "'end'", ",", ")", ...
Returns the XML for pdb_id if the tag exists.
[ "Returns", "the", "XML", "for", "pdb_id", "if", "the", "tag", "exists", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L117-L124
train
Returns the XML for pdb_id if the tag exists.
uogbuji/versa
tools/py/driver/mongo.py
connection.copy
def copy(self, contents=True): '''Create a copy of this model, optionally without contents (i.e. just configuration)''' cp = connection(collection=self._db_coll, baseiri=self._baseiri) if contents: cp.add_many(self._relationships) return cp
python
def copy(self, contents=True): '''Create a copy of this model, optionally without contents (i.e. just configuration)''' cp = connection(collection=self._db_coll, baseiri=self._baseiri) if contents: cp.add_many(self._relationships) return cp
[ "def", "copy", "(", "self", ",", "contents", "=", "True", ")", ":", "cp", "=", "connection", "(", "collection", "=", "self", ".", "_db_coll", ",", "baseiri", "=", "self", ".", "_baseiri", ")", "if", "contents", ":", "cp", ".", "add_many", "(", "self"...
Create a copy of this model, optionally without contents (i.e. just configuration)
[ "Create", "a", "copy", "of", "this", "model", "optionally", "without", "contents", "(", "i", ".", "e", ".", "just", "configuration", ")" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L74-L78
train
Create a copy of this model optionally without contents ( i. e. just configuration )
uogbuji/versa
tools/py/driver/mongo.py
connection.size
def size(self): '''Return the number of links in the model''' count = 0 cursor = self._db_coll.find() for item in cursor: if item['origin'] == '@_abbreviations': continue count += len(item['rels']) return count
python
def size(self): '''Return the number of links in the model''' count = 0 cursor = self._db_coll.find() for item in cursor: if item['origin'] == '@_abbreviations': continue count += len(item['rels']) return count
[ "def", "size", "(", "self", ")", ":", "count", "=", "0", "cursor", "=", "self", ".", "_db_coll", ".", "find", "(", ")", "for", "item", "in", "cursor", ":", "if", "item", "[", "'origin'", "]", "==", "'@_abbreviations'", ":", "continue", "count", "+=",...
Return the number of links in the model
[ "Return", "the", "number", "of", "links", "in", "the", "model" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L96-L104
train
Return the number of links in the model
uogbuji/versa
tools/py/driver/mongo.py
connection.match
def match(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) t...
python
def match(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) t...
[ "def", "match", "(", "self", ",", "origin", "=", "None", ",", "rel", "=", "None", ",", "target", "=", "None", ",", "attrs", "=", "None", ",", "include_ids", "=", "False", ")", ":", "abbrevs", "=", "self", ".", "_abbreviations", "(", ")", "index", "...
Iterator over relationship IDs that match a pattern of components origin - (optional) origin of the relationship (similar to an RDF subject). If omitted any origin will be matched. rel - (optional) type IRI of the relationship (similar to an RDF predicate). If omitted any relationship will be matched. ...
[ "Iterator", "over", "relationship", "IDs", "that", "match", "a", "pattern", "of", "components" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L121-L165
train
Yields the set of identifiers that match a pattern of components.
uogbuji/versa
tools/py/driver/mongo.py
connection.multimatch
def multimatch(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of...
python
def multimatch(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of...
[ "def", "multimatch", "(", "self", ",", "origin", "=", "None", ",", "rel", "=", "None", ",", "target", "=", "None", ",", "attrs", "=", "None", ",", "include_ids", "=", "False", ")", ":", "raise", "NotImplementedError", "origin", "=", "origin", "if", "or...
Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of values. If omitted any origin will be matched. rel - (optional) type IRI of the relationship (simila...
[ "Iterator", "over", "relationship", "IDs", "that", "match", "a", "pattern", "of", "components", "with", "multiple", "options", "provided", "for", "each", "component" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L167-L198
train
Iterator over relationship IDs that match a pattern of components with multiple options provided for each component.
uogbuji/versa
tools/py/driver/mongo.py
connection.add
def add(self, origin, rel, target, attrs=None): ''' Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), ...
python
def add(self, origin, rel, target, attrs=None): ''' Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), ...
[ "def", "add", "(", "self", ",", "origin", ",", "rel", ",", "target", ",", "attrs", "=", "None", ")", ":", "if", "not", "origin", ":", "raise", "ValueError", "(", "'Relationship origin cannot be null'", ")", "if", "not", "rel", ":", "raise", "ValueError", ...
Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object attrs - optional...
[ "Add", "one", "relationship", "to", "the", "model" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L200-L232
train
Add one relationship to the model
uogbuji/versa
tools/py/driver/mongo.py
connection.remove
def remove(self, index): ''' Delete one or more relationship, by index, from the extent index - either a single index or a list of indices ''' raise NotImplementedError if hasattr(index, '__iter__'): ind = set(index) else: ind = [index] ...
python
def remove(self, index): ''' Delete one or more relationship, by index, from the extent index - either a single index or a list of indices ''' raise NotImplementedError if hasattr(index, '__iter__'): ind = set(index) else: ind = [index] ...
[ "def", "remove", "(", "self", ",", "index", ")", ":", "raise", "NotImplementedError", "if", "hasattr", "(", "index", ",", "'__iter__'", ")", ":", "ind", "=", "set", "(", "index", ")", "else", ":", "ind", "=", "[", "index", "]", "# Rebuild relationships, ...
Delete one or more relationship, by index, from the extent index - either a single index or a list of indices
[ "Delete", "one", "or", "more", "relationship", "by", "index", "from", "the", "extent" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L260-L273
train
Removes one or more relationship by index from the extent
uogbuji/versa
tools/py/driver/mongo.py
connection._abbreviate
def _abbreviate(self, rid): ''' Abbreviate a relationship or resource ID target for efficient storage in the DB. Works only with a prefix/suffix split of hierarchical HTTP-like IRIs, e.g. 'http://example.org/spam/eggs' becomes something like '{a23}eggs' and afterward there will b...
python
def _abbreviate(self, rid): ''' Abbreviate a relationship or resource ID target for efficient storage in the DB. Works only with a prefix/suffix split of hierarchical HTTP-like IRIs, e.g. 'http://example.org/spam/eggs' becomes something like '{a23}eggs' and afterward there will b...
[ "def", "_abbreviate", "(", "self", ",", "rid", ")", ":", "if", "not", "isinstance", "(", "rid", ",", "str", ")", "or", "not", "iri", ".", "matches_uri_syntax", "(", "rid", ")", ":", "return", "rid", "head", ",", "tail", "=", "rid", ".", "rsplit", "...
Abbreviate a relationship or resource ID target for efficient storage in the DB. Works only with a prefix/suffix split of hierarchical HTTP-like IRIs, e.g. 'http://example.org/spam/eggs' becomes something like '{a23}eggs' and afterward there will be an entry in the prefix map from 'a23' to 'http...
[ "Abbreviate", "a", "relationship", "or", "resource", "ID", "target", "for", "efficient", "storage", "in", "the", "DB", ".", "Works", "only", "with", "a", "prefix", "/", "suffix", "split", "of", "hierarchical", "HTTP", "-", "like", "IRIs", "e", ".", "g", ...
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L296-L323
train
Abbreviate a relationship or resource ID target for efficient storage.
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.act
async def act(self): '''Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details. ''' # Learn from domain artifacts. self.age += 1 self.added_last = False self.learn_from_domain(method=self.env_learning_method, ...
python
async def act(self): '''Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details. ''' # Learn from domain artifacts. self.age += 1 self.added_last = False self.learn_from_domain(method=self.env_learning_method, ...
[ "async", "def", "act", "(", "self", ")", ":", "# Learn from domain artifacts.", "self", ".", "age", "+=", "1", "self", ".", "added_last", "=", "False", "self", ".", "learn_from_domain", "(", "method", "=", "self", ".", "env_learning_method", ",", "amount", "...
Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details.
[ "Agent", "s", "main", "method", "to", "create", "new", "spirographs", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L213-L246
train
Create new spirograph and train the SOM with the invented environment.
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.learn_from_domain
def learn_from_domain(self, method='random', amount=10): '''Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples c...
python
def learn_from_domain(self, method='random', amount=10): '''Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples c...
[ "def", "learn_from_domain", "(", "self", ",", "method", "=", "'random'", ",", "amount", "=", "10", ")", ":", "if", "method", "==", "'none'", ":", "return", "arts", "=", "self", ".", "env", ".", "artifacts", "if", "len", "(", "arts", ")", "==", "0", ...
Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples closest artifacts based on spirograph generation artifacts. :...
[ "Learn", "SOM", "from", "artifacts", "introduced", "to", "the", "environment", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L248-L279
train
Learn SOM from artifacts introduced to the environment.
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.plot_distances
def plot_distances(self, mean_dist, distances, indeces): '''Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs. ''' from matplotlib import pyplot as plt x = np.arange(len(distances)) y = [mean_dist for i in x] fig, ax = plt.subp...
python
def plot_distances(self, mean_dist, distances, indeces): '''Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs. ''' from matplotlib import pyplot as plt x = np.arange(len(distances)) y = [mean_dist for i in x] fig, ax = plt.subp...
[ "def", "plot_distances", "(", "self", ",", "mean_dist", ",", "distances", ",", "indeces", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "x", "=", "np", ".", "arange", "(", "len", "(", "distances", ")", ")", "y", "=", "[", "mean_dist"...
Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs.
[ "Plot", "distances", "of", "the", "generated", "spirographs", "w", ".", "r", ".", "t", ".", "the", "previously", "generated", "spirogaphs", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L353-L383
train
Plot distances of the generated spirographs w. r. t. the previously generated spirogaphs.
inveniosoftware/invenio-pidrelations
invenio_pidrelations/ext.py
InvenioPIDRelations.init_app
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['invenio-pidrelations'] = _InvenioPIDRelationsState(app)
python
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['invenio-pidrelations'] = _InvenioPIDRelationsState(app)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "init_config", "(", "app", ")", "app", ".", "extensions", "[", "'invenio-pidrelations'", "]", "=", "_InvenioPIDRelationsState", "(", "app", ")" ]
Flask application initialization.
[ "Flask", "application", "initialization", "." ]
a49f3725cf595b663c5b04814280b231f88bc333
https://github.com/inveniosoftware/invenio-pidrelations/blob/a49f3725cf595b663c5b04814280b231f88bc333/invenio_pidrelations/ext.py#L54-L57
train
Initialize the Flask application.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
get_qtls_matrix
def get_qtls_matrix(qtl_matrix, matrix, inputfile): """Extract for each position the LOD value obtained and save it in a matrix. This assumes that the first 4 columns are identical accross all mqo files (ie: the Group, Position and Locus are the same). This assumption should hold true if the files w...
python
def get_qtls_matrix(qtl_matrix, matrix, inputfile): """Extract for each position the LOD value obtained and save it in a matrix. This assumes that the first 4 columns are identical accross all mqo files (ie: the Group, Position and Locus are the same). This assumption should hold true if the files w...
[ "def", "get_qtls_matrix", "(", "qtl_matrix", ",", "matrix", ",", "inputfile", ")", ":", "trait_name", "=", "inputfile", ".", "split", "(", "')_'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'.mqo'", ")", "[", "0", "]", "matrix", "=", "list", ...
Extract for each position the LOD value obtained and save it in a matrix. This assumes that the first 4 columns are identical accross all mqo files (ie: the Group, Position and Locus are the same). This assumption should hold true if the files were generated from the same map. :arg qtl_matrix, ...
[ "Extract", "for", "each", "position", "the", "LOD", "value", "obtained", "and", "save", "it", "in", "a", "matrix", ".", "This", "assumes", "that", "the", "first", "4", "columns", "are", "identical", "accross", "all", "mqo", "files", "(", "ie", ":", "the"...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L38-L71
train
This function extracts for each position the LOD value obtained and saves it in a matrix.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
get_map_matrix
def get_map_matrix(inputfile): """ Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. """ matrix = read_input_file(inputfile) output = [] for row in matrix: if row[3]: output.append...
python
def get_map_matrix(inputfile): """ Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map. """ matrix = read_input_file(inputfile) output = [] for row in matrix: if row[3]: output.append...
[ "def", "get_map_matrix", "(", "inputfile", ")", ":", "matrix", "=", "read_input_file", "(", "inputfile", ")", "output", "=", "[", "]", "for", "row", "in", "matrix", ":", "if", "row", "[", "3", "]", ":", "output", ".", "append", "(", "[", "row", "[", ...
Return the matrix representation of the genetic map. :arg inputfile: the path to the input file from which to retrieve the genetic map.
[ "Return", "the", "matrix", "representation", "of", "the", "genetic", "map", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L74-L86
train
Returns the matrix representation of the genetic map.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
get_qtls_from_mapqtl_data
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
python
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
[ "def", "get_qtls_from_mapqtl_data", "(", "matrix", ",", "threshold", ",", "inputfile", ")", ":", "trait_name", "=", "inputfile", ".", "split", "(", "')_'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'.mqo'", ")", "[", "0", "]", "qtls", "=", "[...
Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective the presence of a QTL. :arg inputfile, name of the inputfile in...
[ "Extract", "the", "QTLs", "found", "by", "MapQTL", "reading", "its", "file", ".", "This", "assume", "that", "there", "is", "only", "one", "QTL", "per", "linkage", "group", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L89-L123
train
Extract the QTLs found by MapQTL reading its file.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.valid_file
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ return not os.path.isdir(filename) \ and os.path.basename(filename).startswith('Session ') \ and filename.endswith('....
python
def valid_file(cls, filename): """ Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check. """ return not os.path.isdir(filename) \ and os.path.basename(filename).startswith('Session ') \ and filename.endswith('....
[ "def", "valid_file", "(", "cls", ",", "filename", ")", ":", "return", "not", "os", ".", "path", ".", "isdir", "(", "filename", ")", "and", "os", ".", "path", ".", "basename", "(", "filename", ")", ".", "startswith", "(", "'Session '", ")", "and", "fi...
Check if the provided file is a valid file for this plugin. :arg filename: the path to the file to check.
[ "Check", "if", "the", "provided", "file", "is", "a", "valid", "file", "for", "this", "plugin", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L144-L152
train
Check if the provided file is a valid file for this plugin.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.get_files
def get_files(cls, folder, session_id=''): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to t...
python
def get_files(cls, folder, session_id=''): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to t...
[ "def", "get_files", "(", "cls", ",", "folder", ",", "session_id", "=", "''", ")", ":", "filelist", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return", "filelist", "if", "sess...
Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to those with this session identifier in their name...
[ "Retrieve", "the", "list", "of", "files", "the", "plugin", "can", "work", "on", ".", "Find", "this", "list", "based", "on", "the", "files", "name", "files", "extension", "or", "even", "actually", "by", "reading", "in", "the", "file", ".", "If", "a", "s...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L155-L180
train
Retrieve the list of files that can be used to check the MapQTL output.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.get_session_identifiers
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the pa...
python
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the pa...
[ "def", "get_session_identifiers", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ")", ":", "sessions", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return...
Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the path to the input file to use
[ "Retrieve", "the", "list", "of", "session", "identifiers", "contained", "in", "the", "data", "on", "the", "folder", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L183-L202
train
Retrieve the list of session identifiers contained in the check folder.
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.convert_inputfiles
def convert_inputfiles(cls, folder=None, inputfile=None, session=None, lod_threshold=None, qtls_file='qtls.csv', matrix_file='qtls_matrix.csv', ...
python
def convert_inputfiles(cls, folder=None, inputfile=None, session=None, lod_threshold=None, qtls_file='qtls.csv', matrix_file='qtls_matrix.csv', ...
[ "def", "convert_inputfiles", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ",", "session", "=", "None", ",", "lod_threshold", "=", "None", ",", "qtls_file", "=", "'qtls.csv'", ",", "matrix_file", "=", "'qtls_matrix.csv'", ",", "map_f...
Convert the input files present in the given folder or inputfile. This method creates the matrix representation of the QTLs results providing for each marker position the LOD value found for each trait as well as a representation of the genetic map used in the experiment. ...
[ "Convert", "the", "input", "files", "present", "in", "the", "given", "folder", "or", "inputfile", ".", "This", "method", "creates", "the", "matrix", "representation", "of", "the", "QTLs", "results", "providing", "for", "each", "marker", "position", "the", "LOD...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L205-L304
train
This method converts the input files present in the given folder or inputfile into a genetic map.
Kortemme-Lab/klab
klab/general/strutil.py
parse_range
def parse_range(s, range_separator = '-'): ''' Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014. ''' return reduce(lambda x,y: x+y, (map(lambda r: (range(int(r.split(range_separator)[0]), int(r.split(range_sep...
python
def parse_range(s, range_separator = '-'): ''' Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014. ''' return reduce(lambda x,y: x+y, (map(lambda r: (range(int(r.split(range_separator)[0]), int(r.split(range_sep...
[ "def", "parse_range", "(", "s", ",", "range_separator", "=", "'-'", ")", ":", "return", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "(", "map", "(", "lambda", "r", ":", "(", "range", "(", "int", "(", "r", ".", "split", "(",...
Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014.
[ "Parses", "the", "string", "s", "which", "contains", "indices", "and", "ranges", "and", "returns", "the", "explicit", "list", "of", "integers", "defined", "by", "s", ".", "Written", "by", "Laurens", "Kraal", "2014", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L15-L19
train
Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014. Written by Laurens Kraal 2014. Written by Laurens Kraal 2014. Written by Laurens Kraal 2014. Written by Laurens Kraal 2014. Written by Laurens Kraal 20...
Kortemme-Lab/klab
klab/general/strutil.py
parse_range_pairs
def parse_range_pairs(s, range_separator = '-', convert_to_tuple = True): ''' Based on parse_range but instead returns a list of lists with the ranges. A single index n is returned as a range (n, n) whereas a range m-n is returned as (m, n) if m <= n, else (n, m). ''' result = map(sorted, map...
python
def parse_range_pairs(s, range_separator = '-', convert_to_tuple = True): ''' Based on parse_range but instead returns a list of lists with the ranges. A single index n is returned as a range (n, n) whereas a range m-n is returned as (m, n) if m <= n, else (n, m). ''' result = map(sorted, map...
[ "def", "parse_range_pairs", "(", "s", ",", "range_separator", "=", "'-'", ",", "convert_to_tuple", "=", "True", ")", ":", "result", "=", "map", "(", "sorted", ",", "map", "(", "lambda", "r", ":", "(", "int", "(", "r", ".", "split", "(", "range_separato...
Based on parse_range but instead returns a list of lists with the ranges. A single index n is returned as a range (n, n) whereas a range m-n is returned as (m, n) if m <= n, else (n, m).
[ "Based", "on", "parse_range", "but", "instead", "returns", "a", "list", "of", "lists", "with", "the", "ranges", ".", "A", "single", "index", "n", "is", "returned", "as", "a", "range", "(", "n", "n", ")", "whereas", "a", "range", "m", "-", "n", "is", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L22-L33
train
Based on parse_range but instead returns a list of lists with the ranges.
Kortemme-Lab/klab
klab/general/strutil.py
merge_range_pairs
def merge_range_pairs(prs): '''Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.''' new_prs = [] sprs = [sorted(p) for p in prs] sprs = sorted(sprs) merged = False x = 0 while x < len(sprs): newx = x + 1 new_pair = list(sprs[x]) ...
python
def merge_range_pairs(prs): '''Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.''' new_prs = [] sprs = [sorted(p) for p in prs] sprs = sorted(sprs) merged = False x = 0 while x < len(sprs): newx = x + 1 new_pair = list(sprs[x]) ...
[ "def", "merge_range_pairs", "(", "prs", ")", ":", "new_prs", "=", "[", "]", "sprs", "=", "[", "sorted", "(", "p", ")", "for", "p", "in", "prs", "]", "sprs", "=", "sorted", "(", "sprs", ")", "merged", "=", "False", "x", "=", "0", "while", "x", "...
Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.
[ "Takes", "in", "a", "list", "of", "pairs", "specifying", "ranges", "and", "returns", "a", "sorted", "list", "of", "merged", "sorted", "ranges", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L36-L54
train
Takes in a list of pairs specifying ranges and returns a sorted list of merged sorted ranges.
Kortemme-Lab/klab
klab/general/strutil.py
split_pdb_residue
def split_pdb_residue(s): '''Splits a PDB residue into the numeric and insertion code components.''' if s.isdigit(): return (int(s), ' ') else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
python
def split_pdb_residue(s): '''Splits a PDB residue into the numeric and insertion code components.''' if s.isdigit(): return (int(s), ' ') else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
[ "def", "split_pdb_residue", "(", "s", ")", ":", "if", "s", ".", "isdigit", "(", ")", ":", "return", "(", "int", "(", "s", ")", ",", "' '", ")", "else", ":", "assert", "(", "s", "[", ":", "-", "1", "]", ".", "isdigit", "(", ")", ")", "return",...
Splits a PDB residue into the numeric and insertion code components.
[ "Splits", "a", "PDB", "residue", "into", "the", "numeric", "and", "insertion", "code", "components", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L57-L63
train
Splits a PDB residue into the numeric and insertion code components.
Kortemme-Lab/klab
klab/general/strutil.py
merge_pdb_range_pairs
def merge_pdb_range_pairs(prs): '''Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges. This works as above but we have to split the residues into pairs as "1A" > "19". ''' new_prs = [] sprs = [sorted((split_pdb_resi...
python
def merge_pdb_range_pairs(prs): '''Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges. This works as above but we have to split the residues into pairs as "1A" > "19". ''' new_prs = [] sprs = [sorted((split_pdb_resi...
[ "def", "merge_pdb_range_pairs", "(", "prs", ")", ":", "new_prs", "=", "[", "]", "sprs", "=", "[", "sorted", "(", "(", "split_pdb_residue", "(", "p", "[", "0", "]", ")", ",", "split_pdb_residue", "(", "p", "[", "1", "]", ")", ")", ")", "for", "p", ...
Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges. This works as above but we have to split the residues into pairs as "1A" > "19".
[ "Takes", "in", "a", "list", "of", "PDB", "residue", "IDs", "(", "including", "insertion", "codes", ")", "specifying", "ranges", "and", "returns", "a", "sorted", "list", "of", "merged", "sorted", "ranges", ".", "This", "works", "as", "above", "but", "we", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L66-L87
train
Takes in a list of PDB residue IDs including insertion codes and returns a sorted list of merged ranges.
brunato/lograptor
lograptor/utils.py
do_chunked_gzip
def do_chunked_gzip(infh, outfh, filename): """ A memory-friendly way of compressing the data. """ import gzip gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh) if infh.closed: infh = open(infh.name, 'r') else: infh.seek(0) readsize = 0 sys.stdout.w...
python
def do_chunked_gzip(infh, outfh, filename): """ A memory-friendly way of compressing the data. """ import gzip gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh) if infh.closed: infh = open(infh.name, 'r') else: infh.seek(0) readsize = 0 sys.stdout.w...
[ "def", "do_chunked_gzip", "(", "infh", ",", "outfh", ",", "filename", ")", ":", "import", "gzip", "gzfh", "=", "gzip", ".", "GzipFile", "(", "'rawlogs'", ",", "mode", "=", "'wb'", ",", "fileobj", "=", "outfh", ")", "if", "infh", ".", "closed", ":", "...
A memory-friendly way of compressing the data.
[ "A", "memory", "-", "friendly", "way", "of", "compressing", "the", "data", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L42-L75
train
A memory - friendly way of compressing the data.
brunato/lograptor
lograptor/utils.py
mail_message
def mail_message(smtp_server, message, from_address, rcpt_addresses): """ Send mail using smtp. """ if smtp_server[0] == '/': # Sending the message with local sendmail p = os.popen(smtp_server, 'w') p.write(message) p.close() else: # Sending the message using ...
python
def mail_message(smtp_server, message, from_address, rcpt_addresses): """ Send mail using smtp. """ if smtp_server[0] == '/': # Sending the message with local sendmail p = os.popen(smtp_server, 'w') p.write(message) p.close() else: # Sending the message using ...
[ "def", "mail_message", "(", "smtp_server", ",", "message", ",", "from_address", ",", "rcpt_addresses", ")", ":", "if", "smtp_server", "[", "0", "]", "==", "'/'", ":", "# Sending the message with local sendmail", "p", "=", "os", ".", "popen", "(", "smtp_server", ...
Send mail using smtp.
[ "Send", "mail", "using", "smtp", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L78-L93
train
Send a message using the SMTP server
brunato/lograptor
lograptor/utils.py
get_value_unit
def get_value_unit(value, unit, prefix): """ Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round. """ prefixes = ('', 'K', 'M', 'G', 'T') if len(unit): if...
python
def get_value_unit(value, unit, prefix): """ Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round. """ prefixes = ('', 'K', 'M', 'G', 'T') if len(unit): if...
[ "def", "get_value_unit", "(", "value", ",", "unit", ",", "prefix", ")", ":", "prefixes", "=", "(", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ")", "if", "len", "(", "unit", ")", ":", "if", "unit", "[", ":", "1", "]", "in", "prefixes"...
Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round.
[ "Return", "a", "human", "-", "readable", "value", "with", "unit", "specification", ".", "Try", "to", "transform", "the", "unit", "prefix", "to", "the", "one", "passed", "as", "parameter", ".", "When", "transform", "to", "higher", "prefix", "apply", "nearest"...
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L96-L124
train
Return a human - readable value with unit specification.
brunato/lograptor
lograptor/utils.py
htmlsafe
def htmlsafe(unsafe): """ Escapes all x(ht)ml control characters. """ unsafe = unsafe.replace('&', '&amp;') unsafe = unsafe.replace('<', '&lt;') unsafe = unsafe.replace('>', '&gt;') return unsafe
python
def htmlsafe(unsafe): """ Escapes all x(ht)ml control characters. """ unsafe = unsafe.replace('&', '&amp;') unsafe = unsafe.replace('<', '&lt;') unsafe = unsafe.replace('>', '&gt;') return unsafe
[ "def", "htmlsafe", "(", "unsafe", ")", ":", "unsafe", "=", "unsafe", ".", "replace", "(", "'&'", ",", "'&amp;'", ")", "unsafe", "=", "unsafe", ".", "replace", "(", "'<'", ",", "'&lt;'", ")", "unsafe", "=", "unsafe", ".", "replace", "(", "'>'", ",", ...
Escapes all x(ht)ml control characters.
[ "Escapes", "all", "x", "(", "ht", ")", "ml", "control", "characters", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L127-L134
train
Returns a string that can be used as an HTML snippet.
brunato/lograptor
lograptor/utils.py
get_fmt_results
def get_fmt_results(results, limit=5, sep='::', fmt=None): """ Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements ...
python
def get_fmt_results(results, limit=5, sep='::', fmt=None): """ Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements ...
[ "def", "get_fmt_results", "(", "results", ",", "limit", "=", "5", ",", "sep", "=", "'::'", ",", "fmt", "=", "None", ")", ":", "result_list", "=", "[", "]", "for", "key", "in", "sorted", "(", "results", ",", "key", "=", "lambda", "x", ":", "results"...
Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements of the key if a fmt parameter is passed.
[ "Return", "a", "list", "of", "formatted", "strings", "representation", "on", "a", "result", "dictionary", ".", "The", "elements", "of", "the", "key", "are", "divided", "by", "a", "separator", "string", ".", "The", "result", "is", "appended", "after", "the", ...
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L137-L164
train
Returns a list of formatted strings representation on a result dictionary.
brunato/lograptor
lograptor/utils.py
safe_expand
def safe_expand(template, mapping): """ Safe string template expansion. Raises an error if the provided substitution mapping has circularities. """ for _ in range(len(mapping) + 1): _template = template template = string.Template(template).safe_substitute(mapping) if template == ...
python
def safe_expand(template, mapping): """ Safe string template expansion. Raises an error if the provided substitution mapping has circularities. """ for _ in range(len(mapping) + 1): _template = template template = string.Template(template).safe_substitute(mapping) if template == ...
[ "def", "safe_expand", "(", "template", ",", "mapping", ")", ":", "for", "_", "in", "range", "(", "len", "(", "mapping", ")", "+", "1", ")", ":", "_template", "=", "template", "template", "=", "string", ".", "Template", "(", "template", ")", ".", "saf...
Safe string template expansion. Raises an error if the provided substitution mapping has circularities.
[ "Safe", "string", "template", "expansion", ".", "Raises", "an", "error", "if", "the", "provided", "substitution", "mapping", "has", "circularities", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L186-L196
train
Safe string template expansion.
brunato/lograptor
lograptor/utils.py
protected_property
def protected_property(func): """ Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined. """ if func.__name__.startswith('_'): raise ValueError("%r: Cannot decorate a protecte...
python
def protected_property(func): """ Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined. """ if func.__name__.startswith('_'): raise ValueError("%r: Cannot decorate a protecte...
[ "def", "protected_property", "(", "func", ")", ":", "if", "func", ".", "__name__", ".", "startswith", "(", "'_'", ")", ":", "raise", "ValueError", "(", "\"%r: Cannot decorate a protected method!\"", "%", "func", ")", "@", "property", "@", "wraps", "(", "func",...
Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined.
[ "Class", "method", "decorator", "that", "creates", "a", "property", "that", "returns", "the", "protected", "attribute", "or", "the", "value", "returned", "by", "the", "wrapped", "method", "if", "the", "protected", "attribute", "is", "not", "defined", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L214-L231
train
A protected property decorator that creates a property that returns the protected attribute or the value returned by the wrapped method.
brunato/lograptor
lograptor/utils.py
open_resource
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
python
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
[ "def", "open_resource", "(", "source", ")", ":", "try", ":", "return", "open", "(", "source", ",", "mode", "=", "'rb'", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "err", ":", "try", ":", "resource", "=", "urlopen", "(", "source", ")", ...
Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL.
[ "Opens", "a", "resource", "in", "binary", "reading", "mode", ".", "Wraps", "the", "resource", "with", "a", "context", "manager", "when", "it", "doesn", "t", "have", "one", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L255-L279
train
Opens a resource in binary reading mode.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig.devices
def devices(self, value): """ { "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"} """ if value is None: self._devices = None elif isinstance(value, list): results = [] delimiter = ':' ...
python
def devices(self, value): """ { "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"} """ if value is None: self._devices = None elif isinstance(value, list): results = [] delimiter = ':' ...
[ "def", "devices", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_devices", "=", "None", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "results", "=", "[", "]", "delimiter", "=", "':'", "for", "dev...
{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}
[ "{", "PathOnHost", ":", "/", "dev", "/", "deviceName", "PathInContainer", ":", "/", "dev", "/", "deviceName", "CgroupPermissions", ":", "mrw", "}" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L238-L280
train
Set the _devices attribute of the object.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig.log_config
def log_config(self, value): """ { "Type": "<driver_name>", "Config": {"key1": "val1"}} """ if not isinstance(value, dict): raise TypeError("log_config must be a dict. {0} was passed".format(value)) config = value.get('config') driver_type = value.get('t...
python
def log_config(self, value): """ { "Type": "<driver_name>", "Config": {"key1": "val1"}} """ if not isinstance(value, dict): raise TypeError("log_config must be a dict. {0} was passed".format(value)) config = value.get('config') driver_type = value.get('t...
[ "def", "log_config", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"log_config must be a dict. {0} was passed\"", ".", "format", "(", "value", ")", ")", "config", "=", "value...
{ "Type": "<driver_name>", "Config": {"key1": "val1"}}
[ "{", "Type", ":", "<driver_name", ">", "Config", ":", "{", "key1", ":", "val1", "}}" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L303-L325
train
Set the log_config of the log entry.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig.port_bindings
def port_bindings(self, value): """ { u'8080/tcp': [ { u'host_port': u'8080', u'host_ip': u'' } ] } """ if isinstance(value, (list, dict)): ...
python
def port_bindings(self, value): """ { u'8080/tcp': [ { u'host_port': u'8080', u'host_ip': u'' } ] } """ if isinstance(value, (list, dict)): ...
[ "def", "port_bindings", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "dict", ")", ")", ":", "self", ".", "_port_bindings", "=", "self", ".", "_convert_port_bindings", "(", "value", ")", "elif", "value", ...
{ u'8080/tcp': [ { u'host_port': u'8080', u'host_ip': u'' } ] }
[ "{", "u", "8080", "/", "tcp", ":", "[", "{", "u", "host_port", ":", "u", "8080", "u", "host_ip", ":", "u", "}", "]", "}" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L418-L434
train
Set the port bindings of the related user s log entry.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig.extra_hosts
def extra_hosts(self, value): """ :param value: :return None: """ if value is None: self._extra_hosts = value elif isinstance(value, list): # TODO: better validation self._extra_hosts = value elif isinstance(value, dict): ...
python
def extra_hosts(self, value): """ :param value: :return None: """ if value is None: self._extra_hosts = value elif isinstance(value, list): # TODO: better validation self._extra_hosts = value elif isinstance(value, dict): ...
[ "def", "extra_hosts", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_extra_hosts", "=", "value", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "# TODO: better validation", "self", ".", "_extra_hosts", "="...
:param value: :return None:
[ ":", "param", "value", ":", ":", "return", "None", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L525-L548
train
Set the _extra_hosts attribute of the object.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig.volumes_from
def volumes_from(self, value): """ :param value: :return: """ volumes_from = [] if isinstance(value, list): for volume_from in value: if not isinstance(volume_from, six.string_types): raise TypeError("each bind must be a st...
python
def volumes_from(self, value): """ :param value: :return: """ volumes_from = [] if isinstance(value, list): for volume_from in value: if not isinstance(volume_from, six.string_types): raise TypeError("each bind must be a st...
[ "def", "volumes_from", "(", "self", ",", "value", ")", ":", "volumes_from", "=", "[", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "volume_from", "in", "value", ":", "if", "not", "isinstance", "(", "volume_from", ",", "six", "."...
:param value: :return:
[ ":", "param", "value", ":", ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L568-L592
train
Set the internal _volumes_from field of the object.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig._convert_volume_from
def _convert_volume_from(self, volume_from): """ :param volume_from: :return: """ if ':' in volume_from: container, permissions = volume_from.split(':') else: container = volume_from permissions = 'rw' if permissions not in ('r...
python
def _convert_volume_from(self, volume_from): """ :param volume_from: :return: """ if ':' in volume_from: container, permissions = volume_from.split(':') else: container = volume_from permissions = 'rw' if permissions not in ('r...
[ "def", "_convert_volume_from", "(", "self", ",", "volume_from", ")", ":", "if", "':'", "in", "volume_from", ":", "container", ",", "permissions", "=", "volume_from", ".", "split", "(", "':'", ")", "else", ":", "container", "=", "volume_from", "permissions", ...
:param volume_from: :return:
[ ":", "param", "volume_from", ":", ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L605-L619
train
Convert a volume_from string to a key - value string.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig._create_dns_list
def _create_dns_list(self, dns): """ :param dns: :return: """ if not dns: return None dns_list = [] if isinstance(dns, six.string_types): if is_valid_ip(dns): dns_list.append(dns) else: raise Va...
python
def _create_dns_list(self, dns): """ :param dns: :return: """ if not dns: return None dns_list = [] if isinstance(dns, six.string_types): if is_valid_ip(dns): dns_list.append(dns) else: raise Va...
[ "def", "_create_dns_list", "(", "self", ",", "dns", ")", ":", "if", "not", "dns", ":", "return", "None", "dns_list", "=", "[", "]", "if", "isinstance", "(", "dns", ",", "six", ".", "string_types", ")", ":", "if", "is_valid_ip", "(", "dns", ")", ":", ...
:param dns: :return:
[ ":", "param", "dns", ":", ":", "return", ":" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L621-L646
train
Create a list of DNS entries for a given DNS entry.
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
HostConfig._convert_port_bindings
def _convert_port_bindings(self, value): """ "PortBindings": { "6379/tcp": [ { "HostIp": "", "HostPort": "6379" } ] } """ converted = {} if not value: return conve...
python
def _convert_port_bindings(self, value): """ "PortBindings": { "6379/tcp": [ { "HostIp": "", "HostPort": "6379" } ] } """ converted = {} if not value: return conve...
[ "def", "_convert_port_bindings", "(", "self", ",", "value", ")", ":", "converted", "=", "{", "}", "if", "not", "value", ":", "return", "converted", "if", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "self", ".", "_convert_port_bindings_...
"PortBindings": { "6379/tcp": [ { "HostIp": "", "HostPort": "6379" } ] }
[ "PortBindings", ":", "{", "6379", "/", "tcp", ":", "[", "{", "HostIp", ":", "HostPort", ":", "6379", "}", "]", "}" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L715-L761
train
Convert port bindings to a dict.
TheGhouls/oct
oct/core/devices.py
forwarder
def forwarder(frontend, backend): """Simple pub/sub forwarder :param int frontend: fontend zeromq port :param int backend: backend zeromq port """ try: context = zmq.Context() front_sub = context.socket(zmq.SUB) front_sub.bind("tcp://*:%d" % frontend) front_sub.set...
python
def forwarder(frontend, backend): """Simple pub/sub forwarder :param int frontend: fontend zeromq port :param int backend: backend zeromq port """ try: context = zmq.Context() front_sub = context.socket(zmq.SUB) front_sub.bind("tcp://*:%d" % frontend) front_sub.set...
[ "def", "forwarder", "(", "frontend", ",", "backend", ")", ":", "try", ":", "context", "=", "zmq", ".", "Context", "(", ")", "front_sub", "=", "context", ".", "socket", "(", "zmq", ".", "SUB", ")", "front_sub", ".", "bind", "(", "\"tcp://*:%d\"", "%", ...
Simple pub/sub forwarder :param int frontend: fontend zeromq port :param int backend: backend zeromq port
[ "Simple", "pub", "/", "sub", "forwarder" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/devices.py#L7-L31
train
Simple pub and sub forwarder for frontend and backend
TheGhouls/oct
oct/core/devices.py
streamer
def streamer(frontend, backend): """Simple push/pull streamer :param int frontend: fontend zeromq port :param int backend: backend zeromq port """ try: context = zmq.Context() front_pull = context.socket(zmq.PULL) front_pull.set_hwm(0) front_pull.bind("tcp://*:%d" %...
python
def streamer(frontend, backend): """Simple push/pull streamer :param int frontend: fontend zeromq port :param int backend: backend zeromq port """ try: context = zmq.Context() front_pull = context.socket(zmq.PULL) front_pull.set_hwm(0) front_pull.bind("tcp://*:%d" %...
[ "def", "streamer", "(", "frontend", ",", "backend", ")", ":", "try", ":", "context", "=", "zmq", ".", "Context", "(", ")", "front_pull", "=", "context", ".", "socket", "(", "zmq", ".", "PULL", ")", "front_pull", ".", "set_hwm", "(", "0", ")", "front_...
Simple push/pull streamer :param int frontend: fontend zeromq port :param int backend: backend zeromq port
[ "Simple", "push", "/", "pull", "streamer" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/core/devices.py#L34-L57
train
Simple push streamer