repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
cjw85/myriad
myriad/managers.py
https://github.com/cjw85/myriad/blob/518124d431bf5cd2a7853489eb9c95d849d12346/myriad/managers.py#L38-L64
def make_server(function, port, authkey, qsize=None): """Create a manager containing input and output queues, and a function to map inputs over. A connecting client can read the stored function, apply it to items in the input queue and post back to the output queue :param function: function to appl...
[ "def", "make_server", "(", "function", ",", "port", ",", "authkey", ",", "qsize", "=", "None", ")", ":", "QueueManager", ".", "register", "(", "'get_job_q'", ",", "callable", "=", "partial", "(", "return_arg", ",", "Queue", "(", "maxsize", "=", "qsize", ...
Create a manager containing input and output queues, and a function to map inputs over. A connecting client can read the stored function, apply it to items in the input queue and post back to the output queue :param function: function to apply to inputs :param port: port over which to server :p...
[ "Create", "a", "manager", "containing", "input", "and", "output", "queues", "and", "a", "function", "to", "map", "inputs", "over", ".", "A", "connecting", "client", "can", "read", "the", "stored", "function", "apply", "it", "to", "items", "in", "the", "inp...
python
train
41.925926
rwl/godot
godot/ui/graph_view_model.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L269-L300
def save_as(self, info): """ Handles saving the current model to file. """ if not info.initialized: return # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "save as", wildcard = "Graphviz Files (*.dot, *.xdo...
[ "def", "save_as", "(", "self", ",", "info", ")", ":", "if", "not", "info", ".", "initialized", ":", "return", "# retval = self.edit_traits(parent=info.ui.control, view=\"file_view\")", "dlg", "=", "FileDialog", "(", "action", "=", "\"save as\"", ",", "wildcard"...
Handles saving the current model to file.
[ "Handles", "saving", "the", "current", "model", "to", "file", "." ]
python
test
29.40625
icgood/pymap
pymap/parsing/specials/flag.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/flag.py#L93-L95
def get_system_flags() -> FrozenSet[Flag]: """Return the set of implemented system flags.""" return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
[ "def", "get_system_flags", "(", ")", "->", "FrozenSet", "[", "Flag", "]", ":", "return", "frozenset", "(", "{", "Seen", ",", "Recent", ",", "Deleted", ",", "Flagged", ",", "Answered", ",", "Draft", "}", ")" ]
Return the set of implemented system flags.
[ "Return", "the", "set", "of", "implemented", "system", "flags", "." ]
python
train
55.333333
titusjan/argos
argos/qt/treeitems.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L253-L261
def removeChild(self, position): """ Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it. """ assert 0 <= position <= len(self.childItems), \ "position should be 0 < {} <= {}".format(position, len(self.child...
[ "def", "removeChild", "(", "self", ",", "position", ")", ":", "assert", "0", "<=", "position", "<=", "len", "(", "self", ".", "childItems", ")", ",", "\"position should be 0 < {} <= {}\"", ".", "format", "(", "position", ",", "len", "(", "self", ".", "chil...
Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it.
[ "Removes", "the", "child", "at", "the", "position", "position", "Calls", "the", "child", "item", "finalize", "to", "close", "its", "resources", "before", "removing", "it", "." ]
python
train
44.777778
apache/airflow
airflow/configuration.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/configuration.py#L59-L72
def expand_env_var(env_var): """ Expands (potentially nested) env vars by repeatedly applying `expandvars` and `expanduser` until interpolation stops having any effect. """ if not env_var: return env_var while True: interpolated = os.path.expanduser(os.path.expandvars(str(env...
[ "def", "expand_env_var", "(", "env_var", ")", ":", "if", "not", "env_var", ":", "return", "env_var", "while", "True", ":", "interpolated", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "expandvars", "(", "str", "(", "env_var", ...
Expands (potentially nested) env vars by repeatedly applying `expandvars` and `expanduser` until interpolation stops having any effect.
[ "Expands", "(", "potentially", "nested", ")", "env", "vars", "by", "repeatedly", "applying", "expandvars", "and", "expanduser", "until", "interpolation", "stops", "having", "any", "effect", "." ]
python
test
30.785714
dpkp/kafka-python
kafka/consumer/fetcher.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/consumer/fetcher.py#L568-L627
def _handle_offset_response(self, future, response): """Callback for the response of the list offset call above. Arguments: future (Future): the future to update based on response response (OffsetResponse): response from the server Raises: AssertionError: if...
[ "def", "_handle_offset_response", "(", "self", ",", "future", ",", "response", ")", ":", "timestamp_offset_map", "=", "{", "}", "for", "topic", ",", "part_data", "in", "response", ".", "topics", ":", "for", "partition_info", "in", "part_data", ":", "partition"...
Callback for the response of the list offset call above. Arguments: future (Future): the future to update based on response response (OffsetResponse): response from the server Raises: AssertionError: if response does not match partition
[ "Callback", "for", "the", "response", "of", "the", "list", "offset", "call", "above", "." ]
python
train
55.066667
zetaops/pyoko
pyoko/db/schema_update.py
https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/db/schema_update.py#L218-L248
def create_index(self, model, waiting_models): """ Creates search indexes. Args: model: model to execute waiting_models: if riak can't return response immediately, model is taken to queue. After first execution session, method is executed with waiting models ...
[ "def", "create_index", "(", "self", ",", "model", ",", "waiting_models", ")", ":", "bucket_name", "=", "model", ".", "_get_bucket_name", "(", ")", "bucket_type", "=", "client", ".", "bucket_type", "(", "settings", ".", "DEFAULT_BUCKET_TYPE", ")", "index_name", ...
Creates search indexes. Args: model: model to execute waiting_models: if riak can't return response immediately, model is taken to queue. After first execution session, method is executed with waiting models and controlled. And be ensured that all given models ar...
[ "Creates", "search", "indexes", "." ]
python
train
45.935484
JukeboxPipeline/jukebox-core
src/jukeboxcore/reftrack.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L530-L562
def wrap(cls, root, refobjinter, refobjects): """Wrap the given refobjects in a :class:`Reftrack` instance and set the right parents This is the preferred method for creating refobjects. Because you cannot set the parent of a :class:`Reftrack` before the parent has been wrapped itselfed...
[ "def", "wrap", "(", "cls", ",", "root", ",", "refobjinter", ",", "refobjects", ")", ":", "tracks", "=", "[", "]", "for", "r", "in", "refobjects", ":", "track", "=", "cls", "(", "root", "=", "root", ",", "refobjinter", "=", "refobjinter", ",", "refobj...
Wrap the given refobjects in a :class:`Reftrack` instance and set the right parents This is the preferred method for creating refobjects. Because you cannot set the parent of a :class:`Reftrack` before the parent has been wrapped itselfed. :param root: the root that groups all reftrack...
[ "Wrap", "the", "given", "refobjects", "in", "a", ":", "class", ":", "Reftrack", "instance", "and", "set", "the", "right", "parents" ]
python
train
39.848485
joke2k/faker
faker/providers/lorem/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/lorem/__init__.py#L96-L125
def paragraph( self, nb_sentences=3, variable_nb_sentences=True, ext_word_list=None): """ :returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' ...
[ "def", "paragraph", "(", "self", ",", "nb_sentences", "=", "3", ",", "variable_nb_sentences", "=", "True", ",", "ext_word_list", "=", "None", ")", ":", "if", "nb_sentences", "<=", "0", ":", "return", "''", "if", "variable_nb_sentences", ":", "nb_sentences", ...
:returns: A single paragraph. For example: 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' Keyword arguments: :param nb_sentences: around how many sentences the paragraph should contain :param variable_nb_sentences: set to false ...
[ ":", "returns", ":", "A", "single", "paragraph", ".", "For", "example", ":", "Sapiente", "sunt", "omnis", ".", "Ut", "pariatur", "ad", "autem", "ducimus", "et", ".", "Voluptas", "rem", "voluptas", "sint", "modi", "dolorem", "amet", "." ]
python
train
35.166667
Robpol86/sphinxcontrib-versioning
sphinxcontrib/versioning/git.py
https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L393-L457
def commit_and_push(local_root, remote, versions): """Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository. :raise CalledProcessError: Unhandled git command failure. :raise GitError: Conflicting changes made in remote by other client and bad git config ...
[ "def", "commit_and_push", "(", "local_root", ",", "remote", ",", "versions", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "current_branch", "=", "run_command", "(", "local_root", ",", "[", "'git'", ",", "'rev-parse'", ",", "'--abb...
Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository. :raise CalledProcessError: Unhandled git command failure. :raise GitError: Conflicting changes made in remote by other client and bad git config for commits. :param str local_root: Local path to git...
[ "Commit", "changed", "new", "and", "deleted", "files", "in", "the", "repo", "and", "attempt", "to", "push", "the", "branch", "to", "the", "remote", "repository", "." ]
python
train
43.861538
jedie/DragonPy
boot_dragonpy.py
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1901-L1912
def _get_python_cmd(self): """ return the python executable in the virtualenv. Try first sys.executable but use fallbacks. """ file_names = ["pypy.exe", "python.exe", "python"] executable = sys.executable if executable is not None: executable = os.path...
[ "def", "_get_python_cmd", "(", "self", ")", ":", "file_names", "=", "[", "\"pypy.exe\"", ",", "\"python.exe\"", ",", "\"python\"", "]", "executable", "=", "sys", ".", "executable", "if", "executable", "is", "not", "None", ":", "executable", "=", "os", ".", ...
return the python executable in the virtualenv. Try first sys.executable but use fallbacks.
[ "return", "the", "python", "executable", "in", "the", "virtualenv", ".", "Try", "first", "sys", ".", "executable", "but", "use", "fallbacks", "." ]
python
train
35.25
tanghaibao/goatools
goatools/wr_tbl.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/wr_tbl.py#L231-L247
def mk_fmtfld(nt_item, joinchr=" ", eol="\n"): """Given a namedtuple, return a format_field string.""" fldstrs = [] # Default formats based on fieldname fld2fmt = { 'hdrgo' : lambda f: "{{{FLD}:1,}}".format(FLD=f), 'dcnt' : lambda f: "{{{FLD}:6,}}".format(FLD=f), 'level' : lambda...
[ "def", "mk_fmtfld", "(", "nt_item", ",", "joinchr", "=", "\" \"", ",", "eol", "=", "\"\\n\"", ")", ":", "fldstrs", "=", "[", "]", "# Default formats based on fieldname", "fld2fmt", "=", "{", "'hdrgo'", ":", "lambda", "f", ":", "\"{{{FLD}:1,}}\"", ".", "forma...
Given a namedtuple, return a format_field string.
[ "Given", "a", "namedtuple", "return", "a", "format_field", "string", "." ]
python
train
38.647059
jazzband/django-ddp
dddp/accounts/ddp.py
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/accounts/ddp.py#L197-L213
def update(self, selector, update, options=None): """Update user data.""" # we're ignoring the `options` argument at this time del options user = get_object( self.model, selector['_id'], pk=this.user_id, ) profile_update = self.deserialize_profile(...
[ "def", "update", "(", "self", ",", "selector", ",", "update", ",", "options", "=", "None", ")", ":", "# we're ignoring the `options` argument at this time", "del", "options", "user", "=", "get_object", "(", "self", ".", "model", ",", "selector", "[", "'_id'", ...
Update user data.
[ "Update", "user", "data", "." ]
python
test
34.176471
YosaiProject/yosai
yosai/core/session/session.py
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/session/session.py#L989-L994
def create_exposed_session(self, session, key=None, context=None): """ :type session: SimpleSession """ # shiro ignores key and context parameters return DelegatingSession(self, SessionKey(session.session_id))
[ "def", "create_exposed_session", "(", "self", ",", "session", ",", "key", "=", "None", ",", "context", "=", "None", ")", ":", "# shiro ignores key and context parameters", "return", "DelegatingSession", "(", "self", ",", "SessionKey", "(", "session", ".", "session...
:type session: SimpleSession
[ ":", "type", "session", ":", "SimpleSession" ]
python
train
40.833333
hydraplatform/hydra-base
hydra_base/db/model.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L1695-L1700
def roles(self): """Return a set with all roles granted to the user.""" roles = [] for ur in self.roleusers: roles.append(ur.role) return set(roles)
[ "def", "roles", "(", "self", ")", ":", "roles", "=", "[", "]", "for", "ur", "in", "self", ".", "roleusers", ":", "roles", ".", "append", "(", "ur", ".", "role", ")", "return", "set", "(", "roles", ")" ]
Return a set with all roles granted to the user.
[ "Return", "a", "set", "with", "all", "roles", "granted", "to", "the", "user", "." ]
python
train
31.166667
blockstack/blockstack-core
blockstack/lib/nameset/namedb.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/namedb.py#L1779-L1865
def commit_state_create( self, nameop, current_block_number ): """ Commit a state-creation operation (works for name_registration, namespace_reveal, name_import). Returns the sequence of dicts of fields to serialize. DO NOT CALL THIS DIRECTLY """ # have to have...
[ "def", "commit_state_create", "(", "self", ",", "nameop", ",", "current_block_number", ")", ":", "# have to have read-write disposition ", "if", "self", ".", "disposition", "!=", "DISPOSITION_RW", ":", "log", ".", "error", "(", "\"FATAL: borrowing violation: not a read-wr...
Commit a state-creation operation (works for name_registration, namespace_reveal, name_import). Returns the sequence of dicts of fields to serialize. DO NOT CALL THIS DIRECTLY
[ "Commit", "a", "state", "-", "creation", "operation", "(", "works", "for", "name_registration", "namespace_reveal", "name_import", ")", "." ]
python
train
39.83908
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/setuptools/ssl_support.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/ssl_support.py#L230-L241
def find_ca_bundle(): """Return an existing CA bundle path, or None""" if os.name=='nt': return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', ...
[ "def", "find_ca_bundle", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "return", "get_win_certfile", "(", ")", "else", ":", "for", "cert_path", "in", "cert_paths", ":", "if", "os", ".", "path", ".", "isfile", "(", "cert_path", ")", ":", ...
Return an existing CA bundle path, or None
[ "Return", "an", "existing", "CA", "bundle", "path", "or", "None" ]
python
test
33.5
spacetelescope/stsci.tools
lib/stsci/tools/clipboard_helper.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/clipboard_helper.py#L19-L27
def ch_handler(offset=0, length=-1, **kw): """ Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLIPBOARD. """ global _lastSel offset = int(offset) length = int(length) if length < 0: length = len(_lastSel) return _lastSel[offs...
[ "def", "ch_handler", "(", "offset", "=", "0", ",", "length", "=", "-", "1", ",", "*", "*", "kw", ")", ":", "global", "_lastSel", "offset", "=", "int", "(", "offset", ")", "length", "=", "int", "(", "length", ")", "if", "length", "<", "0", ":", ...
Handle standard PRIMARY clipboard access. Note that offset and length are passed as strings. This differs from CLIPBOARD.
[ "Handle", "standard", "PRIMARY", "clipboard", "access", ".", "Note", "that", "offset", "and", "length", "are", "passed", "as", "strings", ".", "This", "differs", "from", "CLIPBOARD", "." ]
python
train
36.555556
eddiejessup/spatious
spatious/vector.py
https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L297-L317
def disk_pick_polar(n=1, rng=None): """Return vectors uniformly picked on the unit disk. The unit disk is the space enclosed by the unit circle. Vectors are in a polar representation. Parameters ---------- n: integer Number of points to return. Returns ------- r: array, sha...
[ "def", "disk_pick_polar", "(", "n", "=", "1", ",", "rng", "=", "None", ")", ":", "if", "rng", "is", "None", ":", "rng", "=", "np", ".", "random", "a", "=", "np", ".", "zeros", "(", "[", "n", ",", "2", "]", ",", "dtype", "=", "np", ".", "flo...
Return vectors uniformly picked on the unit disk. The unit disk is the space enclosed by the unit circle. Vectors are in a polar representation. Parameters ---------- n: integer Number of points to return. Returns ------- r: array, shape (n, 2) Sample vectors.
[ "Return", "vectors", "uniformly", "picked", "on", "the", "unit", "disk", ".", "The", "unit", "disk", "is", "the", "space", "enclosed", "by", "the", "unit", "circle", ".", "Vectors", "are", "in", "a", "polar", "representation", "." ]
python
train
25.428571
pyupio/changelogs
changelogs/finder.py
https://github.com/pyupio/changelogs/blob/0cdb929ac4546c766cd7eef9ae4eb4baaa08f452/changelogs/finder.py#L46-L59
def contains_project_name(name, link): """ Checks if the given link `somewhat` contains the project name. :param name: str, project name :param link: str, link :return: bool, True if the link contains the project name """ def unclutter(string): # strip out all python references and r...
[ "def", "contains_project_name", "(", "name", ",", "link", ")", ":", "def", "unclutter", "(", "string", ")", ":", "# strip out all python references and remove all excessive characters", "string", "=", "string", ".", "lower", "(", ")", ".", "replace", "(", "\"_\"", ...
Checks if the given link `somewhat` contains the project name. :param name: str, project name :param link: str, link :return: bool, True if the link contains the project name
[ "Checks", "if", "the", "given", "link", "somewhat", "contains", "the", "project", "name", ".", ":", "param", "name", ":", "str", "project", "name", ":", "param", "link", ":", "str", "link", ":", "return", ":", "bool", "True", "if", "the", "link", "cont...
python
train
44.785714
siemens/django-mantis-stix-importer
mantis_stix_importer/importer.py
https://github.com/siemens/django-mantis-stix-importer/blob/20f5709e068101dad299f58134513d8873c91ba5/mantis_stix_importer/importer.py#L733-L751
def cybox_RAW_ft_handler(self, enrichment, fact, attr_info, add_fact_kargs): """ Handler for facts whose content is to be written to disk rather than stored in the database. We use it for all elements that contain the string 'Raw_' ('Raw_Header', 'Raw_Artifact', ...) """ ...
[ "def", "cybox_RAW_ft_handler", "(", "self", ",", "enrichment", ",", "fact", ",", "attr_info", ",", "add_fact_kargs", ")", ":", "# get the value", "raw_value", "=", "add_fact_kargs", "[", "'values'", "]", "[", "0", "]", "if", "len", "(", "raw_value", ")", ">=...
Handler for facts whose content is to be written to disk rather than stored in the database. We use it for all elements that contain the string 'Raw_' ('Raw_Header', 'Raw_Artifact', ...)
[ "Handler", "for", "facts", "whose", "content", "is", "to", "be", "written", "to", "disk", "rather", "than", "stored", "in", "the", "database", ".", "We", "use", "it", "for", "all", "elements", "that", "contain", "the", "string", "Raw_", "(", "Raw_Header", ...
python
train
43.526316
deepmind/pysc2
pysc2/lib/features.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/features.py#L536-L598
def parse_agent_interface_format( feature_screen=None, feature_minimap=None, rgb_screen=None, rgb_minimap=None, action_space=None, camera_width_world_units=None, use_feature_units=False, use_raw_units=False, use_unit_counts=False, use_camera_position=False): """Creates an Agent...
[ "def", "parse_agent_interface_format", "(", "feature_screen", "=", "None", ",", "feature_minimap", "=", "None", ",", "rgb_screen", "=", "None", ",", "rgb_minimap", "=", "None", ",", "action_space", "=", "None", ",", "camera_width_world_units", "=", "None", ",", ...
Creates an AgentInterfaceFormat object from keyword args. Convenient when using dictionaries or command-line arguments for config. Note that the feature_* and rgb_* properties define the respective spatial observation dimensions and accept: * None or 0 to disable that spatial observation. * A single...
[ "Creates", "an", "AgentInterfaceFormat", "object", "from", "keyword", "args", "." ]
python
train
33.15873
sorgerlab/indra
indra/sources/eidos/processor.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/eidos/processor.py#L287-L298
def time_context_from_ref(self, timex): """Return a time context object given a timex reference entry.""" # If the timex has a value set, it means that it refers to a DCT or # a TimeExpression e.g. "value": {"@id": "_:DCT_1"} and the parameters # need to be taken from there value...
[ "def", "time_context_from_ref", "(", "self", ",", "timex", ")", ":", "# If the timex has a value set, it means that it refers to a DCT or", "# a TimeExpression e.g. \"value\": {\"@id\": \"_:DCT_1\"} and the parameters", "# need to be taken from there", "value", "=", "timex", ".", "get"...
Return a time context object given a timex reference entry.
[ "Return", "a", "time", "context", "object", "given", "a", "timex", "reference", "entry", "." ]
python
train
44.916667
scot-dev/scot
scot/connectivity.py
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/connectivity.py#L174-L187
def S(self): """Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f) """ if self.c is None: raise RuntimeError('Cross-spectral density requires noise ' 'covariance matrix c.') H = self.H() # ...
[ "def", "S", "(", "self", ")", ":", "if", "self", ".", "c", "is", "None", ":", "raise", "RuntimeError", "(", "'Cross-spectral density requires noise '", "'covariance matrix c.'", ")", "H", "=", "self", ".", "H", "(", ")", "# TODO: can we do that more efficiently?",...
Cross-spectral density. .. math:: \mathbf{S}(f) = \mathbf{H}(f) \mathbf{C} \mathbf{H}'(f)
[ "Cross", "-", "spectral", "density", "." ]
python
train
36.857143
saltstack/salt
salt/cloud/clouds/proxmox.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L212-L221
def _get_vm_by_id(vmid, allDetails=False): ''' Retrieve a VM based on the ID. ''' for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=allDetails)): if six.text_type(vm_details['vmid']) == six.text_type(vmid): return vm_details log.info('VM with ID "%s" could...
[ "def", "_get_vm_by_id", "(", "vmid", ",", "allDetails", "=", "False", ")", ":", "for", "vm_name", ",", "vm_details", "in", "six", ".", "iteritems", "(", "get_resources_vms", "(", "includeConfig", "=", "allDetails", ")", ")", ":", "if", "six", ".", "text_ty...
Retrieve a VM based on the ID.
[ "Retrieve", "a", "VM", "based", "on", "the", "ID", "." ]
python
train
35
sdispater/orator
orator/orm/relations/belongs_to.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to.py#L41-L56
def add_constraints(self): """ Set the base constraints on the relation query. :rtype: None """ if self._constraints: foreign_key = getattr(self._parent, self._foreign_key, None) if foreign_key is None: self._query = None else:...
[ "def", "add_constraints", "(", "self", ")", ":", "if", "self", ".", "_constraints", ":", "foreign_key", "=", "getattr", "(", "self", ".", "_parent", ",", "self", ".", "_foreign_key", ",", "None", ")", "if", "foreign_key", "is", "None", ":", "self", ".", ...
Set the base constraints on the relation query. :rtype: None
[ "Set", "the", "base", "constraints", "on", "the", "relation", "query", "." ]
python
train
30.375
OLC-Bioinformatics/sipprverse
cgecore/utility.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L390-L405
def mkpath(filepath, permissions=0o777): """ This function executes a mkdir command for filepath and with permissions (octal number with leading 0 or string only) # eg. mkpath("path/to/file", "0o775") """ # Converting string of octal to integer, if string is given. if isinstance(permissions, str): ...
[ "def", "mkpath", "(", "filepath", ",", "permissions", "=", "0o777", ")", ":", "# Converting string of octal to integer, if string is given.", "if", "isinstance", "(", "permissions", ",", "str", ")", ":", "permissions", "=", "sum", "(", "[", "int", "(", "x", ")",...
This function executes a mkdir command for filepath and with permissions (octal number with leading 0 or string only) # eg. mkpath("path/to/file", "0o775")
[ "This", "function", "executes", "a", "mkdir", "command", "for", "filepath", "and", "with", "permissions", "(", "octal", "number", "with", "leading", "0", "or", "string", "only", ")", "#", "eg", ".", "mkpath", "(", "path", "/", "to", "/", "file", "0o775",...
python
train
42.375
arkottke/pysra
pysra/site.py
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L491-L511
def _calc_mod_reduc(self, strains, strain_ref, x_1, x_1_mean, x_2, x_2_mean, x_3, x_3_mean): """Compute the shear modulus reduction using Equation (1).""" ones = np.ones_like(strains) # Predictor x_4 = np.log(self._lab_consol_ratio) * ones x = np.c_[ones,...
[ "def", "_calc_mod_reduc", "(", "self", ",", "strains", ",", "strain_ref", ",", "x_1", ",", "x_1_mean", ",", "x_2", ",", "x_2_mean", ",", "x_3", ",", "x_3_mean", ")", ":", "ones", "=", "np", ".", "ones_like", "(", "strains", ")", "# Predictor", "x_4", "...
Compute the shear modulus reduction using Equation (1).
[ "Compute", "the", "shear", "modulus", "reduction", "using", "Equation", "(", "1", ")", "." ]
python
train
53.666667
valency/deeputils
deeputils/common.py
https://github.com/valency/deeputils/blob/27efd91668de0223ed8b07cfadf2151632521520/deeputils/common.py#L180-L196
def dict_remove_value(d, v): """ Recursively remove keys with a certain value from a dict :param d: the dictionary :param v: value which should be removed :return: formatted dictionary """ dd = dict() for key, value in d.items(): if not value == v: if isinstance(value...
[ "def", "dict_remove_value", "(", "d", ",", "v", ")", ":", "dd", "=", "dict", "(", ")", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "not", "value", "==", "v", ":", "if", "isinstance", "(", "value", ",", "dict", ")",...
Recursively remove keys with a certain value from a dict :param d: the dictionary :param v: value which should be removed :return: formatted dictionary
[ "Recursively", "remove", "keys", "with", "a", "certain", "value", "from", "a", "dict", ":", "param", "d", ":", "the", "dictionary", ":", "param", "v", ":", "value", "which", "should", "be", "removed", ":", "return", ":", "formatted", "dictionary" ]
python
valid
31.705882
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/events.py#L201-L208
def add_event(self, event, prepend=False): """ Adds an event to the manager. """ if prepend: self._events.insert(0, event) else: self._events.append(event)
[ "def", "add_event", "(", "self", ",", "event", ",", "prepend", "=", "False", ")", ":", "if", "prepend", ":", "self", ".", "_events", ".", "insert", "(", "0", ",", "event", ")", "else", ":", "self", ".", "_events", ".", "append", "(", "event", ")" ]
Adds an event to the manager.
[ "Adds", "an", "event", "to", "the", "manager", "." ]
python
train
26.5
tensorflow/tensor2tensor
tensor2tensor/models/research/glow_ops.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L404-L426
def add_edge_bias(x, filter_size): """Pad x and concatenates an edge bias across the depth of x. The edge bias can be thought of as a binary feature which is unity when the filter is being convolved over an edge and zero otherwise. Args: x: Input tensor, shape (NHWC) filter_size: filter_size to determ...
[ "def", "add_edge_bias", "(", "x", ",", "filter_size", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "if", "filter_size", "[", "0", "]", "==", "1", "and", "filter_size", "[", "1", "]", "==", "1", ":", "return", "x", "a",...
Pad x and concatenates an edge bias across the depth of x. The edge bias can be thought of as a binary feature which is unity when the filter is being convolved over an edge and zero otherwise. Args: x: Input tensor, shape (NHWC) filter_size: filter_size to determine padding. Returns: x_pad: Input...
[ "Pad", "x", "and", "concatenates", "an", "edge", "bias", "across", "the", "depth", "of", "x", "." ]
python
train
34.391304
heitzmann/gdspy
gdspy/__init__.py
https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L221-L243
def scale(self, scalex, scaley=None, center=(0, 0)): """ Scale this object. Parameters ---------- scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ...
[ "def", "scale", "(", "self", ",", "scalex", ",", "scaley", "=", "None", ",", "center", "=", "(", "0", ",", "0", ")", ")", ":", "c0", "=", "numpy", ".", "array", "(", "center", ")", "s", "=", "scalex", "if", "scaley", "is", "None", "else", "nump...
Scale this object. Parameters ---------- scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ``scalex``. center : array-like[2] Center point f...
[ "Scale", "this", "object", "." ]
python
train
30.304348
adamziel/python_translate
python_translate/loaders.py
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L127-L152
def flatten(self, messages, parent_key=''): """ Flattens an nested array of translations. The scheme used is: 'key' => array('key2' => array('key3' => 'value')) Becomes: 'key.key2.key3' => 'value' This function takes an array by reference and will modify it ...
[ "def", "flatten", "(", "self", ",", "messages", ",", "parent_key", "=", "''", ")", ":", "items", "=", "[", "]", "sep", "=", "'.'", "for", "k", ",", "v", "in", "list", "(", "messages", ".", "items", "(", ")", ")", ":", "new_key", "=", "\"{0}{1}{2}...
Flattens an nested array of translations. The scheme used is: 'key' => array('key2' => array('key3' => 'value')) Becomes: 'key.key2.key3' => 'value' This function takes an array by reference and will modify it @type messages: dict @param messages: The dict ...
[ "Flattens", "an", "nested", "array", "of", "translations", "." ]
python
train
34.307692
sprockets/sprockets.http
sprockets/http/runner.py
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/runner.py#L100-L133
def run(self, port_number, number_of_procs=0): """ Create the server and run the IOLoop. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the applic...
[ "def", "run", "(", "self", ",", "port_number", ",", "number_of_procs", "=", "0", ")", ":", "self", ".", "start_server", "(", "port_number", ",", "number_of_procs", ")", "iol", "=", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "try", ":", "self", ...
Create the server and run the IOLoop. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to...
[ "Create", "the", "server", "and", "run", "the", "IOLoop", "." ]
python
train
41.941176
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1792-L1804
def rotate(self, theta, around): """Rotate Compound around an arbitrary vector. Parameters ---------- theta : float The angle by which to rotate the Compound, in radians. around : np.ndarray, shape=(3,), dtype=float The vector about which to rotate the Co...
[ "def", "rotate", "(", "self", ",", "theta", ",", "around", ")", ":", "new_positions", "=", "_rotate", "(", "self", ".", "xyz_with_ports", ",", "theta", ",", "around", ")", "self", ".", "xyz_with_ports", "=", "new_positions" ]
Rotate Compound around an arbitrary vector. Parameters ---------- theta : float The angle by which to rotate the Compound, in radians. around : np.ndarray, shape=(3,), dtype=float The vector about which to rotate the Compound.
[ "Rotate", "Compound", "around", "an", "arbitrary", "vector", "." ]
python
train
33.846154
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_dataflash_logger.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_dataflash_logger.py#L243-L259
def tell_sender_to_start(self): '''send a start packet (if we haven't sent one in the last second)''' now = time.time() if now - self.time_last_start_packet_sent < 1: return self.time_last_start_packet_sent = now if self.log_settings.verbose: print("DFLog...
[ "def", "tell_sender_to_start", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "now", "-", "self", ".", "time_last_start_packet_sent", "<", "1", ":", "return", "self", ".", "time_last_start_packet_sent", "=", "now", "if", "self", "....
send a start packet (if we haven't sent one in the last second)
[ "send", "a", "start", "packet", "(", "if", "we", "haven", "t", "sent", "one", "in", "the", "last", "second", ")" ]
python
train
36.882353
go-macaroon-bakery/py-macaroon-bakery
macaroonbakery/bakery/_oven.py
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L153-L204
def macaroon_ops(self, macaroons): ''' This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. For macaroons minted with previous bakery versions, it always returns a single LoginOp operation. :param macaroons: :return: '''...
[ "def", "macaroon_ops", "(", "self", ",", "macaroons", ")", ":", "if", "len", "(", "macaroons", ")", "==", "0", ":", "raise", "ValueError", "(", "'no macaroons provided'", ")", "storage_id", ",", "ops", "=", "_decode_macaroon_id", "(", "macaroons", "[", "0", ...
This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. For macaroons minted with previous bakery versions, it always returns a single LoginOp operation. :param macaroons: :return:
[ "This", "method", "makes", "the", "oven", "satisfy", "the", "MacaroonOpStore", "protocol", "required", "by", "the", "Checker", "class", "." ]
python
train
37.730769
yero13/na3x
na3x/utils/converter.py
https://github.com/yero13/na3x/blob/b31ef801ea574081125020a7d0f9c4242f8f8b02/na3x/utils/converter.py#L65-L73
def df2list(df): """ Converts pandas.DataFrame values into list :param df: pandas.DataFrame :return: list """ for column in df: df[column] = df[column].astype(object).where(df[column].notnull(), None) return df.to_dict(orient='records')
[ "def", "df2list", "(", "df", ")", ":", "for", "column", "in", "df", ":", "df", "[", "column", "]", "=", "df", "[", "column", "]", ".", "astype", "(", "object", ")", ".", "where", "(", "df", "[", "column", "]", ".", "notnull", "(", ")", ",", "...
Converts pandas.DataFrame values into list :param df: pandas.DataFrame :return: list
[ "Converts", "pandas", ".", "DataFrame", "values", "into", "list", ":", "param", "df", ":", "pandas", ".", "DataFrame", ":", "return", ":", "list" ]
python
train
32.888889
adaptive-learning/proso-apps
proso_models/models.py
https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_models/models.py#L478-L505
def get_parents_graph(self, item_ids, language=None): """ Get a subgraph of items reachable from the given set of items through the 'parent' relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter ...
[ "def", "get_parents_graph", "(", "self", ",", "item_ids", ",", "language", "=", "None", ")", ":", "def", "_parents", "(", "item_ids", ")", ":", "if", "item_ids", "is", "None", ":", "items", "=", "Item", ".", "objects", ".", "filter", "(", "active", "="...
Get a subgraph of items reachable from the given set of items through the 'parent' relation. Args: item_ids (list): items which are taken as roots for the reachability language (str): if specified, filter out items which are not available in the given language ...
[ "Get", "a", "subgraph", "of", "items", "reachable", "from", "the", "given", "set", "of", "items", "through", "the", "parent", "relation", "." ]
python
train
44.892857
opencobra/memote
memote/support/annotation.py
https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/annotation.py#L167-L206
def generate_component_annotation_miriam_match(elements, component, db): """ Tabulate which MIRIAM databases the element's annotation match. If the relevant MIRIAM identifier is not in an element's annotation it is ignored. Parameters ---------- elements : list Elements of a model,...
[ "def", "generate_component_annotation_miriam_match", "(", "elements", ",", "component", ",", "db", ")", ":", "def", "is_faulty", "(", "annotation", ",", "key", ",", "pattern", ")", ":", "# Ignore missing annotation for this database.", "if", "key", "not", "in", "ann...
Tabulate which MIRIAM databases the element's annotation match. If the relevant MIRIAM identifier is not in an element's annotation it is ignored. Parameters ---------- elements : list Elements of a model, either metabolites or reactions. component : {"metabolites", "reactions"} ...
[ "Tabulate", "which", "MIRIAM", "databases", "the", "element", "s", "annotation", "match", "." ]
python
train
31.275
mdscruggs/ga
ga/chromosomes.py
https://github.com/mdscruggs/ga/blob/adac7a004e5e22d888e44ab39f313064c3803b38/ga/chromosomes.py#L12-L36
def create_random(cls, gene_length, n=1, gene_class=BinaryGene): """ Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromos...
[ "def", "create_random", "(", "cls", ",", "gene_length", ",", "n", "=", "1", ",", "gene_class", "=", "BinaryGene", ")", ":", "assert", "issubclass", "(", "gene_class", ",", "BaseGene", ")", "chromosomes", "=", "[", "]", "# when gene_length is scalar, convert to a...
Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes ...
[ "Create", "1", "or", "more", "chromosomes", "with", "randomly", "generated", "DNA", "." ]
python
train
36.92
saghul/evergreen
evergreen/patcher.py
https://github.com/saghul/evergreen/blob/22f22f45892f397c23c3e09e6ea1ad4c00b3add8/evergreen/patcher.py#L80-L125
def patch(**on): """Globally patches certain system modules to be 'cooperaive'. The keyword arguments afford some control over which modules are patched. If no keyword arguments are supplied, all possible modules are patched. If keywords are set to True, only the specified modules are patched. E.g., ...
[ "def", "patch", "(", "*", "*", "on", ")", ":", "accepted_args", "=", "set", "(", "(", "'select'", ",", "'socket'", ",", "'time'", ")", ")", "default_on", "=", "on", ".", "pop", "(", "\"all\"", ",", "None", ")", "for", "k", "in", "on", ".", "keys"...
Globally patches certain system modules to be 'cooperaive'. The keyword arguments afford some control over which modules are patched. If no keyword arguments are supplied, all possible modules are patched. If keywords are set to True, only the specified modules are patched. E.g., ``monkey_patch(socket...
[ "Globally", "patches", "certain", "system", "modules", "to", "be", "cooperaive", "." ]
python
train
40.934783
vanheeringen-lab/gimmemotifs
gimmemotifs/motif.py
https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/motif.py#L252-L266
def to_motevo(self): """Return motif formatted in MotEvo (TRANSFAC-like) format Returns ------- m : str String of motif in MotEvo format. """ m = "//\n" m += "NA {}\n".format(self.id) m += "P0\tA\tC\tG\tT\n" for i, row in enume...
[ "def", "to_motevo", "(", "self", ")", ":", "m", "=", "\"//\\n\"", "m", "+=", "\"NA {}\\n\"", ".", "format", "(", "self", ".", "id", ")", "m", "+=", "\"P0\\tA\\tC\\tG\\tT\\n\"", "for", "i", ",", "row", "in", "enumerate", "(", "self", ".", "pfm", ")", ...
Return motif formatted in MotEvo (TRANSFAC-like) format Returns ------- m : str String of motif in MotEvo format.
[ "Return", "motif", "formatted", "in", "MotEvo", "(", "TRANSFAC", "-", "like", ")", "format", "Returns", "-------", "m", ":", "str", "String", "of", "motif", "in", "MotEvo", "format", "." ]
python
train
28.866667
msmbuilder/msmbuilder
msmbuilder/lumping/pcca_plus.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L143-L180
def _optimize_A(self, A): """Find optimal transformation matrix A by minimization. Parameters ---------- A : ndarray The transformation matrix A. Returns ------- A : ndarray The transformation matrix. """ right_eigenvector...
[ "def", "_optimize_A", "(", "self", ",", "A", ")", ":", "right_eigenvectors", "=", "self", ".", "right_eigenvectors_", "[", ":", ",", ":", "self", ".", "n_macrostates", "]", "flat_map", ",", "square_map", "=", "get_maps", "(", "A", ")", "alpha", "=", "to_...
Find optimal transformation matrix A by minimization. Parameters ---------- A : ndarray The transformation matrix A. Returns ------- A : ndarray The transformation matrix.
[ "Find", "optimal", "transformation", "matrix", "A", "by", "minimization", "." ]
python
train
28.684211
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2257-L2268
def yield_lines(strs): """Yield non-empty/non-comment lines of a string or sequence""" if isinstance(strs, string_types): for s in strs.splitlines(): s = s.strip() # skip blank lines/comments if s and not s.startswith('#'): yield s else: fo...
[ "def", "yield_lines", "(", "strs", ")", ":", "if", "isinstance", "(", "strs", ",", "string_types", ")", ":", "for", "s", "in", "strs", ".", "splitlines", "(", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "# skip blank lines/comments", "if", "s", ...
Yield non-empty/non-comment lines of a string or sequence
[ "Yield", "non", "-", "empty", "/", "non", "-", "comment", "lines", "of", "a", "string", "or", "sequence" ]
python
test
32
gem/oq-engine
openquake/hazardlib/gsim/germany_2018.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/germany_2018.py#L70-L91
def _compute_mean(self, C, rup, dists, sites, imt): """ Returns the mean ground motion acceleration and velocity """ # Convert rhypo to rrup rrup = rhypo_to_rrup(dists.rhypo, rup.mag) mean = (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distanc...
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "rup", ",", "dists", ",", "sites", ",", "imt", ")", ":", "# Convert rhypo to rrup", "rrup", "=", "rhypo_to_rrup", "(", "dists", ".", "rhypo", ",", "rup", ".", "mag", ")", "mean", "=", "(", "self", "...
Returns the mean ground motion acceleration and velocity
[ "Returns", "the", "mean", "ground", "motion", "acceleration", "and", "velocity" ]
python
train
45.136364
necaris/python3-openid
openid/yadis/xri.py
https://github.com/necaris/python3-openid/blob/4911bbc196dfd6f9eda7155df9903d668720ecbf/openid/yadis/xri.py#L59-L64
def iriToURI(iri): """Transform an IRI to a URI by escaping unicode.""" # According to RFC 3987, section 3.1, "Mapping of IRIs to URIs" if isinstance(iri, bytes): iri = str(iri, encoding="utf-8") return iri.encode('ascii', errors='oid_percent_escape').decode()
[ "def", "iriToURI", "(", "iri", ")", ":", "# According to RFC 3987, section 3.1, \"Mapping of IRIs to URIs\"", "if", "isinstance", "(", "iri", ",", "bytes", ")", ":", "iri", "=", "str", "(", "iri", ",", "encoding", "=", "\"utf-8\"", ")", "return", "iri", ".", "...
Transform an IRI to a URI by escaping unicode.
[ "Transform", "an", "IRI", "to", "a", "URI", "by", "escaping", "unicode", "." ]
python
train
46.5
SuperCowPowers/chains
chains/utils/flow_utils.py
https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/utils/flow_utils.py#L112-L160
def _cts_or_stc(data): """Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?""" # UDP/TCP if data['transport']: # TCP flags if data['transport']['type'] == 'TCP': flags = data['transport']['flags'] # Syn/...
[ "def", "_cts_or_stc", "(", "data", ")", ":", "# UDP/TCP", "if", "data", "[", "'transport'", "]", ":", "# TCP flags", "if", "data", "[", "'transport'", "]", "[", "'type'", "]", "==", "'TCP'", ":", "flags", "=", "data", "[", "'transport'", "]", "[", "'fl...
Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?
[ "Does", "the", "data", "look", "like", "a", "Client", "to", "Server", "(", "cts", ")", "or", "Server", "to", "Client", "(", "stc", ")", "traffic?" ]
python
train
33.938776
LuminosoInsight/luminoso-api-client-python
luminoso_api/v4_json_stream.py
https://github.com/LuminosoInsight/luminoso-api-client-python/blob/3bedf2a454aee39214c11fbf556ead3eecc27881/luminoso_api/v4_json_stream.py#L149-L157
def _convert_date(date_string, date_format): """ Convert a date in a given format to epoch time. Mostly a wrapper for datetime's strptime. """ if date_format != 'epoch': return datetime.strptime(date_string, date_format).timestamp() else: return float(date_string)
[ "def", "_convert_date", "(", "date_string", ",", "date_format", ")", ":", "if", "date_format", "!=", "'epoch'", ":", "return", "datetime", ".", "strptime", "(", "date_string", ",", "date_format", ")", ".", "timestamp", "(", ")", "else", ":", "return", "float...
Convert a date in a given format to epoch time. Mostly a wrapper for datetime's strptime.
[ "Convert", "a", "date", "in", "a", "given", "format", "to", "epoch", "time", ".", "Mostly", "a", "wrapper", "for", "datetime", "s", "strptime", "." ]
python
test
32.888889
innolitics/dicom-numpy
dicom_numpy/combine_slices.py
https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L126-L153
def _validate_slices_form_uniform_grid(slice_datasets): ''' Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway. '''...
[ "def", "_validate_slices_form_uniform_grid", "(", "slice_datasets", ")", ":", "invariant_properties", "=", "[", "'Modality'", ",", "'SOPClassUID'", ",", "'SeriesInstanceUID'", ",", "'Rows'", ",", "'Columns'", ",", "'PixelSpacing'", ",", "'PixelRepresentation'", ",", "'B...
Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway.
[ "Perform", "various", "data", "checks", "to", "ensure", "that", "the", "list", "of", "slices", "form", "a", "evenly", "-", "spaced", "grid", "of", "data", ".", "Some", "of", "these", "checks", "are", "probably", "not", "required", "if", "the", "data", "f...
python
train
33.428571
joaopcanario/imports
imports/cli.py
https://github.com/joaopcanario/imports/blob/46db0d3d2aa55427027bf0e91d61a24d52730337/imports/cli.py#L13-L22
def main(path_dir, requirements_name): """Console script for imports.""" click.echo("\nWARNING: Uninstall libs it's at your own risk!") click.echo('\nREMINDER: After uninstall libs, update your requirements ' 'file.\nUse the `pip freeze > requirements.txt` command.') click.echo('\n\nList...
[ "def", "main", "(", "path_dir", ",", "requirements_name", ")", ":", "click", ".", "echo", "(", "\"\\nWARNING: Uninstall libs it's at your own risk!\"", ")", "click", ".", "echo", "(", "'\\nREMINDER: After uninstall libs, update your requirements '", "'file.\\nUse the `pip freez...
Console script for imports.
[ "Console", "script", "for", "imports", "." ]
python
train
46.9
fastai/fastai
fastai/torch_core.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L76-L85
def tensor(x:Any, *rest)->Tensor: "Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly." if len(rest): x = (x,)+rest # XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report if is_listy(x) and len(x)==0: return tensor(0) res = torch...
[ "def", "tensor", "(", "x", ":", "Any", ",", "*", "rest", ")", "->", "Tensor", ":", "if", "len", "(", "rest", ")", ":", "x", "=", "(", "x", ",", ")", "+", "rest", "# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report", "if", "is...
Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly.
[ "Like", "torch", ".", "as_tensor", "but", "handle", "lists", "too", "and", "can", "pass", "multiple", "vector", "elements", "directly", "." ]
python
train
52
boriel/zxbasic
basic.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/basic.py#L181-L185
def add_line(self, sentences, line_number=None): """ Add current line to the output. See self.line() for more info """ self.bytes += self.line(sentences, line_number)
[ "def", "add_line", "(", "self", ",", "sentences", ",", "line_number", "=", "None", ")", ":", "self", ".", "bytes", "+=", "self", ".", "line", "(", "sentences", ",", "line_number", ")" ]
Add current line to the output. See self.line() for more info
[ "Add", "current", "line", "to", "the", "output", ".", "See", "self", ".", "line", "()", "for", "more", "info" ]
python
train
38.8
materialsproject/pymatgen
pymatgen/io/abinit/works.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/works.py#L147-L167
def fetch_task_to_run(self): """ Returns the first task that is ready to run or None if no task can be submitted at present" Raises: `StopIteration` if all tasks are done. """ # All the tasks are done so raise an exception # that will be handled by th...
[ "def", "fetch_task_to_run", "(", "self", ")", ":", "# All the tasks are done so raise an exception", "# that will be handled by the client code.", "if", "all", "(", "task", ".", "is_completed", "for", "task", "in", "self", ")", ":", "raise", "StopIteration", "(", "\"All...
Returns the first task that is ready to run or None if no task can be submitted at present" Raises: `StopIteration` if all tasks are done.
[ "Returns", "the", "first", "task", "that", "is", "ready", "to", "run", "or", "None", "if", "no", "task", "can", "be", "submitted", "at", "present" ]
python
train
33.857143
GNS3/gns3-server
gns3server/compute/dynamips/nodes/ethernet_switch.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/dynamips/nodes/ethernet_switch.py#L292-L305
def set_port_settings(self, port_number, settings): """ Applies port settings to a specific port. :param port_number: port number to set the settings :param settings: port settings """ if settings["type"] == "access": yield from self.set_access_port(port_num...
[ "def", "set_port_settings", "(", "self", ",", "port_number", ",", "settings", ")", ":", "if", "settings", "[", "\"type\"", "]", "==", "\"access\"", ":", "yield", "from", "self", ".", "set_access_port", "(", "port_number", ",", "settings", "[", "\"vlan\"", "]...
Applies port settings to a specific port. :param port_number: port number to set the settings :param settings: port settings
[ "Applies", "port", "settings", "to", "a", "specific", "port", "." ]
python
train
41.857143
cytoscape/py2cytoscape
py2cytoscape/util/util_dataframe.py
https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/util/util_dataframe.py#L6-L49
def from_dataframe(df, source_col='source', target_col='target', interaction_col='interaction', name='From DataFrame', edge_attr_cols=[]): """ Utility to convert Pandas DataFrame object into Cytoscape.js JSON :pa...
[ "def", "from_dataframe", "(", "df", ",", "source_col", "=", "'source'", ",", "target_col", "=", "'target'", ",", "interaction_col", "=", "'interaction'", ",", "name", "=", "'From DataFrame'", ",", "edge_attr_cols", "=", "[", "]", ")", ":", "network", "=", "c...
Utility to convert Pandas DataFrame object into Cytoscape.js JSON :param df: Dataframe to convert. :param source_col: Name of source column. :param target_col: Name of target column. :param interaction_col: Name of interaction column. :param name: Name of network. :param edge_attr_cols: List co...
[ "Utility", "to", "convert", "Pandas", "DataFrame", "object", "into", "Cytoscape", ".", "js", "JSON" ]
python
train
32.75
liip/taxi
taxi/timesheet/entry.py
https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L540-L548
def append(self, x): """ Append the given element to the list and synchronize the textual representation. """ super(EntriesList, self).append(x) if self.entries_collection is not None: self.entries_collection.add_entry(self.date, x)
[ "def", "append", "(", "self", ",", "x", ")", ":", "super", "(", "EntriesList", ",", "self", ")", ".", "append", "(", "x", ")", "if", "self", ".", "entries_collection", "is", "not", "None", ":", "self", ".", "entries_collection", ".", "add_entry", "(", ...
Append the given element to the list and synchronize the textual representation.
[ "Append", "the", "given", "element", "to", "the", "list", "and", "synchronize", "the", "textual", "representation", "." ]
python
train
31.666667
log2timeline/plaso
plaso/parsers/winreg.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg.py#L127-L139
def _ParseKeyWithPlugin(self, parser_mediator, registry_key, plugin): """Parses the Registry key with a specific plugin. Args: parser_mediator (ParserMediator): parser mediator. registry_key (dfwinreg.WinRegistryKey): Windwos Registry key. plugin (WindowsRegistryPlugin): Windows Registry plug...
[ "def", "_ParseKeyWithPlugin", "(", "self", ",", "parser_mediator", ",", "registry_key", ",", "plugin", ")", ":", "try", ":", "plugin", ".", "UpdateChainAndProcess", "(", "parser_mediator", ",", "registry_key", ")", "except", "(", "IOError", ",", "dfwinreg_errors",...
Parses the Registry key with a specific plugin. Args: parser_mediator (ParserMediator): parser mediator. registry_key (dfwinreg.WinRegistryKey): Windwos Registry key. plugin (WindowsRegistryPlugin): Windows Registry plugin.
[ "Parses", "the", "Registry", "key", "with", "a", "specific", "plugin", "." ]
python
train
45.615385
ivanprjcts/sdklib
sdklib/http/renderers.py
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L52-L77
def guess_file_name_stream_type_header(args): """ Guess filename, file stream, file type, file header from args. :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). :return: filena...
[ "def", "guess_file_name_stream_type_header", "(", "args", ")", ":", "ftype", "=", "None", "fheader", "=", "None", "if", "isinstance", "(", "args", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "fname", ...
Guess filename, file stream, file type, file header from args. :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). :return: filename, file stream, file type, file header
[ "Guess", "filename", "file", "stream", "file", "type", "file", "header", "from", "args", "." ]
python
train
33.730769
ArchiveTeam/wpull
wpull/warc/format.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/warc/format.py#L94-L132
def compute_checksum(self, payload_offset: Optional[int]=None): '''Compute and add the checksum data to the record fields. This function also sets the content length. ''' if not self.block_file: self.fields['Content-Length'] = '0' return block_hasher = h...
[ "def", "compute_checksum", "(", "self", ",", "payload_offset", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "if", "not", "self", ".", "block_file", ":", "self", ".", "fields", "[", "'Content-Length'", "]", "=", "'0'", "return", "block_hasher", ...
Compute and add the checksum data to the record fields. This function also sets the content length.
[ "Compute", "and", "add", "the", "checksum", "data", "to", "the", "record", "fields", "." ]
python
train
32.666667
globus/globus-cli
globus_cli/helpers/version.py
https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/helpers/version.py#L53-L103
def print_version(): """ Print out the current version, and at least try to fetch the latest from PyPi to print alongside it. It may seem odd that this isn't in globus_cli.version , but it's done this way to separate concerns over printing the version from looking it up. """ latest, current...
[ "def", "print_version", "(", ")", ":", "latest", ",", "current", "=", "get_versions", "(", ")", "if", "latest", "is", "None", ":", "safeprint", "(", "(", "\"Installed Version: {0}\\n\"", "\"Failed to lookup latest version.\"", ")", ".", "format", "(", "current", ...
Print out the current version, and at least try to fetch the latest from PyPi to print alongside it. It may seem odd that this isn't in globus_cli.version , but it's done this way to separate concerns over printing the version from looking it up.
[ "Print", "out", "the", "current", "version", "and", "at", "least", "try", "to", "fetch", "the", "latest", "from", "PyPi", "to", "print", "alongside", "it", "." ]
python
train
37.823529
DLR-RM/RAFCON
source/rafcon/gui/controllers/states_editor.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/states_editor.py#L569-L579
def update_tab_label(self, state_m): """Update all tab labels :param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated """ state_identifier = self.get_state_identifier(state_m) if state_identifier not in self.tabs and state_identifier ...
[ "def", "update_tab_label", "(", "self", ",", "state_m", ")", ":", "state_identifier", "=", "self", ".", "get_state_identifier", "(", "state_m", ")", "if", "state_identifier", "not", "in", "self", ".", "tabs", "and", "state_identifier", "not", "in", "self", "."...
Update all tab labels :param rafcon.state_machine.states.state.State state_m: State model who's tab label is to be updated
[ "Update", "all", "tab", "labels" ]
python
train
54.454545
allenai/allennlp
allennlp/semparse/contexts/sql_context_utils.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/contexts/sql_context_utils.py#L26-L61
def initialize_valid_actions(grammar: Grammar, keywords_to_uppercase: List[str] = None) -> Dict[str, List[str]]: """ We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tabl...
[ "def", "initialize_valid_actions", "(", "grammar", ":", "Grammar", ",", "keywords_to_uppercase", ":", "List", "[", "str", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ":", "valid_actions", ":", "Dict", "[", "str", ...
We initialize the valid actions with the global actions. These include the valid actions that result from the grammar and also those that result from the tables provided. The keys represent the nonterminals in the grammar and the values are lists of the valid actions of that nonterminal.
[ "We", "initialize", "the", "valid", "actions", "with", "the", "global", "actions", ".", "These", "include", "the", "valid", "actions", "that", "result", "from", "the", "grammar", "and", "also", "those", "that", "result", "from", "the", "tables", "provided", ...
python
train
49.305556
programa-stic/barf-project
barf/core/reil/builder.py
https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L166-L171
def gen_nop(): """Return a NOP instruction. """ empty_reg = ReilEmptyOperand() return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg)
[ "def", "gen_nop", "(", ")", ":", "empty_reg", "=", "ReilEmptyOperand", "(", ")", "return", "ReilBuilder", ".", "build", "(", "ReilMnemonic", ".", "NOP", ",", "empty_reg", ",", "empty_reg", ",", "empty_reg", ")" ]
Return a NOP instruction.
[ "Return", "a", "NOP", "instruction", "." ]
python
train
30.333333
pazz/alot
alot/settings/manager.py
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/settings/manager.py#L515-L534
def represent_datetime(self, d): """ turns a given datetime obj into a string representation. This will: 1) look if a fixed 'timestamp_format' is given in the config 2) check if a 'timestamp_format' hook is defined 3) use :func:`~alot.helper.pretty_datetime` as fallback ...
[ "def", "represent_datetime", "(", "self", ",", "d", ")", ":", "fixed_format", "=", "self", ".", "get", "(", "'timestamp_format'", ")", "if", "fixed_format", ":", "rep", "=", "string_decode", "(", "d", ".", "strftime", "(", "fixed_format", ")", ",", "'UTF-8...
turns a given datetime obj into a string representation. This will: 1) look if a fixed 'timestamp_format' is given in the config 2) check if a 'timestamp_format' hook is defined 3) use :func:`~alot.helper.pretty_datetime` as fallback
[ "turns", "a", "given", "datetime", "obj", "into", "a", "string", "representation", ".", "This", "will", ":" ]
python
train
34.9
bxlab/bx-python
lib/bx/motif/pwm.py
https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx/motif/pwm.py#L51-L64
def create_from_other( Class, other, values=None ): """ Create a new Matrix with attributes taken from `other` but with the values taken from `values` if provided """ m = Class() m.alphabet = other.alphabet m.sorted_alphabet = other.sorted_alphabet m.char...
[ "def", "create_from_other", "(", "Class", ",", "other", ",", "values", "=", "None", ")", ":", "m", "=", "Class", "(", ")", "m", ".", "alphabet", "=", "other", ".", "alphabet", "m", ".", "sorted_alphabet", "=", "other", ".", "sorted_alphabet", "m", ".",...
Create a new Matrix with attributes taken from `other` but with the values taken from `values` if provided
[ "Create", "a", "new", "Matrix", "with", "attributes", "taken", "from", "other", "but", "with", "the", "values", "taken", "from", "values", "if", "provided" ]
python
train
33.285714
HDI-Project/RDT
rdt/transformers/__init__.py
https://github.com/HDI-Project/RDT/blob/b28fdd671a1d7fbd14983eefe0cfbd8d87ded92a/rdt/transformers/__init__.py#L13-L29
def load_data_table(table_name, meta_file, meta): """Return the contents and metadata of a given table. Args: table_name(str): Name of the table. meta_file(str): Path to the meta.json file. meta(dict): Contents of meta.json. Returns: tuple(pandas.DataFrame, dict) """ ...
[ "def", "load_data_table", "(", "table_name", ",", "meta_file", ",", "meta", ")", ":", "for", "table", "in", "meta", "[", "'tables'", "]", ":", "if", "table", "[", "'name'", "]", "==", "table_name", ":", "prefix", "=", "os", ".", "path", ".", "dirname",...
Return the contents and metadata of a given table. Args: table_name(str): Name of the table. meta_file(str): Path to the meta.json file. meta(dict): Contents of meta.json. Returns: tuple(pandas.DataFrame, dict)
[ "Return", "the", "contents", "and", "metadata", "of", "a", "given", "table", "." ]
python
train
32.588235
night-crawler/django-docker-helpers
django_docker_helpers/config/backends/redis_parser.py
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/backends/redis_parser.py#L72-L94
def inner_parser(self) -> BaseParser: """ Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain ...
[ "def", "inner_parser", "(", "self", ")", "->", "BaseParser", ":", "if", "self", ".", "_inner_parser", "is", "not", "None", ":", "return", "self", ".", "_inner_parser", "config", "=", "self", ".", "client", ".", "get", "(", "self", ".", "endpoint", ")", ...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageValueIsEmpty: if specified ``endpoint`` does not contain a config
[ "Prepares", "inner", "config", "parser", "for", "config", "stored", "at", "endpoint", "." ]
python
train
35.782609
wummel/linkchecker
linkcheck/checker/urlbase.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/urlbase.py#L70-L78
def url_norm (url, encoding=None): """Wrapper for url.url_norm() to convert UnicodeError in LinkCheckerError.""" try: return urlutil.url_norm(url, encoding=encoding) except UnicodeError: msg = _("URL has unparsable domain name: %(name)s") % \ {"name": sys.exc_info()[1]} ...
[ "def", "url_norm", "(", "url", ",", "encoding", "=", "None", ")", ":", "try", ":", "return", "urlutil", ".", "url_norm", "(", "url", ",", "encoding", "=", "encoding", ")", "except", "UnicodeError", ":", "msg", "=", "_", "(", "\"URL has unparsable domain na...
Wrapper for url.url_norm() to convert UnicodeError in LinkCheckerError.
[ "Wrapper", "for", "url", ".", "url_norm", "()", "to", "convert", "UnicodeError", "in", "LinkCheckerError", "." ]
python
train
38
casacore/python-casacore
casacore/tables/table.py
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1056-L1064
def getvarcol(self, columnname, startrow=0, nrow=-1, rowincr=1): """Get the contents of a column or part of it. It is similar to :func:`getcol`, but the result is returned as a dict of numpy arrays. It can deal with a column containing variable shaped arrays. """ return...
[ "def", "getvarcol", "(", "self", ",", "columnname", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "return", "self", ".", "_getvarcol", "(", "columnname", ",", "startrow", ",", "nrow", ",", "rowincr", ")" ]
Get the contents of a column or part of it. It is similar to :func:`getcol`, but the result is returned as a dict of numpy arrays. It can deal with a column containing variable shaped arrays.
[ "Get", "the", "contents", "of", "a", "column", "or", "part", "of", "it", "." ]
python
train
40.555556
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L1814-L1828
def DataProcessorsPost(self, parameters): """ Create a Data processor in CommonSense. If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string. ...
[ "def", "DataProcessorsPost", "(", "self", ",", "parameters", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/dataprocessors.json'", ",", "'POST'", ",", "parameters", "=", "parameters", ")", ":", "return", "True", "else", ":", "self", ".", "__error__",...
Create a Data processor in CommonSense. If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string. @param parameters (dictonary) - Dictionary containing the details...
[ "Create", "a", "Data", "processor", "in", "CommonSense", ".", "If", "DataProcessorsPost", "is", "successful", "the", "data", "processor", "and", "sensor", "details", "including", "its", "sensor_id", "can", "be", "obtained", "by", "a", "call", "to", "getResponse"...
python
train
57.333333
ajenhl/tacl
tacl/results.py
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L268-L278
def csv(self, fh): """Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object """ self._matches.to_csv(fh, encoding='utf-8', float_format='%d', index=False) ...
[ "def", "csv", "(", "self", ",", "fh", ")", ":", "self", ".", "_matches", ".", "to_csv", "(", "fh", ",", "encoding", "=", "'utf-8'", ",", "float_format", "=", "'%d'", ",", "index", "=", "False", ")", "return", "fh" ]
Writes the results data to `fh` in CSV format and returns `fh`. :param fh: file to write data to :type fh: file object :rtype: file object
[ "Writes", "the", "results", "data", "to", "fh", "in", "CSV", "format", "and", "returns", "fh", "." ]
python
train
29.636364
72squared/redpipe
redpipe/fields.py
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L312-L327
def encode(cls, value): """ the list it so it can be stored in redis. :param value: list :return: bytes """ try: coerced = [str(v) for v in value] if coerced == value: return ",".join(coerced).encode(cls._encoding) if len( ...
[ "def", "encode", "(", "cls", ",", "value", ")", ":", "try", ":", "coerced", "=", "[", "str", "(", "v", ")", "for", "v", "in", "value", "]", "if", "coerced", "==", "value", ":", "return", "\",\"", ".", "join", "(", "coerced", ")", ".", "encode", ...
the list it so it can be stored in redis. :param value: list :return: bytes
[ "the", "list", "it", "so", "it", "can", "be", "stored", "in", "redis", "." ]
python
train
27.0625
iotile/typedargs
typedargs/annotate.py
https://github.com/iotile/typedargs/blob/0a5091a664b9b4d836e091e9ba583e944f438fd8/typedargs/annotate.py#L250-L276
def annotated(func, name=None): """Mark a function as callable from the command line. This function is meant to be called as decorator. This function also initializes metadata about the function's arguments that is built up by the param decorator. Args: func (callable): The function that ...
[ "def", "annotated", "(", "func", ",", "name", "=", "None", ")", ":", "if", "hasattr", "(", "func", ",", "'metadata'", ")", ":", "if", "name", "is", "not", "None", ":", "func", ".", "metadata", "=", "AnnotatedMetadata", "(", "func", ",", "name", ")", ...
Mark a function as callable from the command line. This function is meant to be called as decorator. This function also initializes metadata about the function's arguments that is built up by the param decorator. Args: func (callable): The function that we wish to mark as callable ...
[ "Mark", "a", "function", "as", "callable", "from", "the", "command", "line", "." ]
python
test
28.962963
materialsproject/pymatgen
pymatgen/io/vasp/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L1900-L1914
def read_cs_g0_contribution(self): """ Parse the G0 contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. """ header_pattern = r'^\s+G\=0 CONTRIBUTION TO CHEMICAL SHIFT \(field along BDIR\)\s+$\n' \ ...
[ "def", "read_cs_g0_contribution", "(", "self", ")", ":", "header_pattern", "=", "r'^\\s+G\\=0 CONTRIBUTION TO CHEMICAL SHIFT \\(field along BDIR\\)\\s+$\\n'", "r'^\\s+-{50,}$\\n'", "r'^\\s+BDIR\\s+X\\s+Y\\s+Z\\s*$\\n'", "r'^\\s+-{50,}\\s*$\\n'", "row_pattern", "=", "r'(?:\\d+)\\s+'", "...
Parse the G0 contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list.
[ "Parse", "the", "G0", "contribution", "of", "NMR", "chemical", "shielding", "." ]
python
train
48.6
bgyori/pykqml
kqml/kqml_module.py
https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_module.py#L22-L75
def translate_argv(raw_args): """Enables conversion from system arguments. Parameters ---------- raw_args : list Arguments taken raw from the system input. Returns ------- kwargs : dict The input arguments formatted as a kwargs dict. To use as input, simply use `KQM...
[ "def", "translate_argv", "(", "raw_args", ")", ":", "kwargs", "=", "{", "}", "def", "get_parameter", "(", "param_str", ")", ":", "for", "i", ",", "a", "in", "enumerate", "(", "raw_args", ")", ":", "if", "a", "==", "param_str", ":", "assert", "len", "...
Enables conversion from system arguments. Parameters ---------- raw_args : list Arguments taken raw from the system input. Returns ------- kwargs : dict The input arguments formatted as a kwargs dict. To use as input, simply use `KQMLModule(**kwargs)`.
[ "Enables", "conversion", "from", "system", "arguments", "." ]
python
train
27.092593
materialsproject/pymatgen
pymatgen/analysis/chemenv/utils/math_utils.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/utils/math_utils.py#L65-L78
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
[ "def", "_factor_generator", "(", "n", ")", ":", "p", "=", "prime_factors", "(", "n", ")", "factors", "=", "{", "}", "for", "p1", "in", "p", ":", "try", ":", "factors", "[", "p1", "]", "+=", "1", "except", "KeyError", ":", "factors", "[", "p1", "]...
From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return:
[ "From", "a", "given", "natural", "integer", "returns", "the", "prime", "factors", "and", "their", "multiplicity", ":", "param", "n", ":", "Natural", "integer", ":", "return", ":" ]
python
train
23.357143
wavycloud/pyboto3
pyboto3/codedeploy.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/codedeploy.py#L640-L773
def create_deployment(applicationName=None, deploymentGroupName=None, revision=None, deploymentConfigName=None, description=None, ignoreApplicationStopFailures=None, targetInstances=None, autoRollbackConfiguration=None, updateOutdatedInstancesOnly=None, fileExistsBehavior=None): """ Deploys an application revis...
[ "def", "create_deployment", "(", "applicationName", "=", "None", ",", "deploymentGroupName", "=", "None", ",", "revision", "=", "None", ",", "deploymentConfigName", "=", "None", ",", "description", "=", "None", ",", "ignoreApplicationStopFailures", "=", "None", ",...
Deploys an application revision through the specified deployment group. See also: AWS API Documentation :example: response = client.create_deployment( applicationName='string', deploymentGroupName='string', revision={ 'revisionType': 'S3'|'GitHub', 's3Lo...
[ "Deploys", "an", "application", "revision", "through", "the", "specified", "deployment", "group", ".", "See", "also", ":", "AWS", "API", "Documentation", ":", "example", ":", "response", "=", "client", ".", "create_deployment", "(", "applicationName", "=", "stri...
python
train
53.477612
swistakm/python-gmaps
src/gmaps/geocoding.py
https://github.com/swistakm/python-gmaps/blob/ef3bdea6f02277200f21a09f99d4e2aebad762b9/src/gmaps/geocoding.py#L39-L65
def reverse(self, lat, lon, result_type=None, location_type=None, language=None, sensor=None): """Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude of queried point :param result_type: list of result_type for f...
[ "def", "reverse", "(", "self", ",", "lat", ",", "lon", ",", "result_type", "=", "None", ",", "location_type", "=", "None", ",", "language", "=", "None", ",", "sensor", "=", "None", ")", ":", "parameters", "=", "dict", "(", "latlng", "=", "\"%f,%f\"", ...
Reverse geocode with given latitude and longitude. :param lat: latitude of queried point :param lon: longitude of queried point :param result_type: list of result_type for filtered search. Accepted values: https://developers.google.com/maps/documentation/geocoding/intr...
[ "Reverse", "geocode", "with", "given", "latitude", "and", "longitude", "." ]
python
train
47.777778
jssimporter/python-jss
jss/jssobjects.py
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjects.py#L1068-L1089
def add_package(self, pkg, action_type="Install"): """Add a Package object to the policy with action=install. Args: pkg: A Package object to add. action_type (str, optional): One of "Install", "Cache", or "Install Cached". Defaults to "Install". """ ...
[ "def", "add_package", "(", "self", ",", "pkg", ",", "action_type", "=", "\"Install\"", ")", ":", "if", "isinstance", "(", "pkg", ",", "Package", ")", ":", "if", "action_type", "not", "in", "(", "\"Install\"", ",", "\"Cache\"", ",", "\"Install Cached\"", ")...
Add a Package object to the policy with action=install. Args: pkg: A Package object to add. action_type (str, optional): One of "Install", "Cache", or "Install Cached". Defaults to "Install".
[ "Add", "a", "Package", "object", "to", "the", "policy", "with", "action", "=", "install", "." ]
python
train
44
NetworkEng/fping.py
fping/fping.py
https://github.com/NetworkEng/fping.py/blob/991507889561aa6eb9ee2ad821adf460883a9c5d/fping/fping.py#L199-L211
def get_results(cmd): """ def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters ...
[ "def", "get_results", "(", "cmd", ")", ":", "try", ":", "return", "subprocess", ".", "check_output", "(", "cmd", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "return", "e", ".", "output" ]
def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters
[ "def", "get_results", "(", "cmd", ":", "list", ")", "-", ">", "str", ":", "return", "lines", "Get", "the", "ping", "results", "using", "fping", ".", ":", "param", "cmd", ":", "List", "-", "the", "fping", "command", "and", "its", "options", ":", "retu...
python
train
35.230769
mrstephenneal/pdfconduit
pdf/convert/img2pdf.py
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/img2pdf.py#L40-L45
def _image_loop(self): """Retrieve an iterable of images either with, or without a progress bar.""" if self.progress_bar and 'tqdm' in self.progress_bar.lower(): return tqdm(self.imgs, desc='Saving PNGs as flat PDFs', total=len(self.imgs), unit='PDFs') else: return self.i...
[ "def", "_image_loop", "(", "self", ")", ":", "if", "self", ".", "progress_bar", "and", "'tqdm'", "in", "self", ".", "progress_bar", ".", "lower", "(", ")", ":", "return", "tqdm", "(", "self", ".", "imgs", ",", "desc", "=", "'Saving PNGs as flat PDFs'", "...
Retrieve an iterable of images either with, or without a progress bar.
[ "Retrieve", "an", "iterable", "of", "images", "either", "with", "or", "without", "a", "progress", "bar", "." ]
python
train
53
numba/llvmlite
llvmlite/ir/builder.py
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L844-L850
def store_reg(self, value, reg_type, reg_name, name=''): """ Store an LLVM value inside a register Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax") """ ftype = types.FunctionType(types.VoidType(), [reg_type]) return self.asm(ftype, "", "{%s}" % ...
[ "def", "store_reg", "(", "self", ",", "value", ",", "reg_type", ",", "reg_name", ",", "name", "=", "''", ")", ":", "ftype", "=", "types", ".", "FunctionType", "(", "types", ".", "VoidType", "(", ")", ",", "[", "reg_type", "]", ")", "return", "self", ...
Store an LLVM value inside a register Example: store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax")
[ "Store", "an", "LLVM", "value", "inside", "a", "register", "Example", ":", "store_reg", "(", "Constant", "(", "IntType", "(", "32", ")", "0xAAAAAAAA", ")", "IntType", "(", "32", ")", "eax", ")" ]
python
train
49.142857
AmesCornish/buttersink
buttersink/SSHStore.py
https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/SSHStore.py#L301-L306
def deleteUnused(self): """ Delete any old snapshots in path, if not kept. """ if self.dryrun: self._client.listUnused() else: self._client.deleteUnused()
[ "def", "deleteUnused", "(", "self", ")", ":", "if", "self", ".", "dryrun", ":", "self", ".", "_client", ".", "listUnused", "(", ")", "else", ":", "self", ".", "_client", ".", "deleteUnused", "(", ")" ]
Delete any old snapshots in path, if not kept.
[ "Delete", "any", "old", "snapshots", "in", "path", "if", "not", "kept", "." ]
python
train
32.833333
Alignak-monitoring/alignak
alignak/objects/config.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2374-L2554
def is_correct(self): # pylint: disable=too-many-branches, too-many-statements, too-many-locals """Check if all elements got a good configuration :return: True if the configuration is correct else False :rtype: bool """ logger.info('Running pre-flight check on configuration dat...
[ "def", "is_correct", "(", "self", ")", ":", "# pylint: disable=too-many-branches, too-many-statements, too-many-locals", "logger", ".", "info", "(", "'Running pre-flight check on configuration data, initial state: %s'", ",", "self", ".", "conf_is_correct", ")", "valid", "=", "s...
Check if all elements got a good configuration :return: True if the configuration is correct else False :rtype: bool
[ "Check", "if", "all", "elements", "got", "a", "good", "configuration" ]
python
train
44.889503
DataDog/integrations-core
yarn/datadog_checks/yarn/yarn.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/yarn/datadog_checks/yarn/yarn.py#L321-L409
def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs): """ Query the given URL and return the JSON response """ service_check_tags = ['url:{}'.format(self._get_url_base(url))] + tags service_check_tags = list(set(service_check_tags)) if objec...
[ "def", "_rest_request_to_json", "(", "self", ",", "url", ",", "instance", ",", "object_path", ",", "tags", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "service_check_tags", "=", "[", "'url:{}'", ".", "format", "(", "self", ".", "_get_url_base", ...
Query the given URL and return the JSON response
[ "Query", "the", "given", "URL", "and", "return", "the", "JSON", "response" ]
python
train
36.955056
google/python-adb
adb/fastboot.py
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/fastboot.py#L140-L175
def _AcceptResponses(self, expected_header, info_cb, timeout_ms=None): """Accepts responses until the expected header or a FAIL. Args: expected_header: OKAY or DATA info_cb: Optional callback for text sent from the bootloader. timeout_ms: Timeout in milliseconds to wait fo...
[ "def", "_AcceptResponses", "(", "self", ",", "expected_header", ",", "info_cb", ",", "timeout_ms", "=", "None", ")", ":", "while", "True", ":", "response", "=", "self", ".", "usb", ".", "BulkRead", "(", "64", ",", "timeout_ms", "=", "timeout_ms", ")", "h...
Accepts responses until the expected header or a FAIL. Args: expected_header: OKAY or DATA info_cb: Optional callback for text sent from the bootloader. timeout_ms: Timeout in milliseconds to wait for each response. Raises: FastbootStateMismatch: Fastboot respon...
[ "Accepts", "responses", "until", "the", "expected", "header", "or", "a", "FAIL", "." ]
python
train
42.472222
schettino72/import-deps
import_deps/__init__.py
https://github.com/schettino72/import-deps/blob/311f2badd2c93f743d09664397f21e7eaa16e1f1/import_deps/__init__.py#L65-L75
def _get_fqn(cls, path): """get full qualified name as list of strings :return: (list - str) of path segments from top package to given path """ name_list = [path.stem] current_path = path # move to parent path until parent path is a python package while cls.is_pk...
[ "def", "_get_fqn", "(", "cls", ",", "path", ")", ":", "name_list", "=", "[", "path", ".", "stem", "]", "current_path", "=", "path", "# move to parent path until parent path is a python package", "while", "cls", ".", "is_pkg", "(", "current_path", ".", "parent", ...
get full qualified name as list of strings :return: (list - str) of path segments from top package to given path
[ "get", "full", "qualified", "name", "as", "list", "of", "strings", ":", "return", ":", "(", "list", "-", "str", ")", "of", "path", "segments", "from", "top", "package", "to", "given", "path" ]
python
train
43.272727
pymc-devs/pymc
pymc/StepMethods.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1216-L1230
def dimension(self): """Compute the dimension of the sampling space and identify the slices belonging to each stochastic. """ self.dim = 0 self._slices = {} for stochastic in self.stochastics: if isinstance(stochastic.value, np.matrix): p_len =...
[ "def", "dimension", "(", "self", ")", ":", "self", ".", "dim", "=", "0", "self", ".", "_slices", "=", "{", "}", "for", "stochastic", "in", "self", ".", "stochastics", ":", "if", "isinstance", "(", "stochastic", ".", "value", ",", "np", ".", "matrix",...
Compute the dimension of the sampling space and identify the slices belonging to each stochastic.
[ "Compute", "the", "dimension", "of", "the", "sampling", "space", "and", "identify", "the", "slices", "belonging", "to", "each", "stochastic", "." ]
python
train
39.866667
uw-it-aca/django-saferecipient-email-backend
saferecipient/__init__.py
https://github.com/uw-it-aca/django-saferecipient-email-backend/blob/8af20dece5a668d6bcad5dea75cc60871a4bd9fa/saferecipient/__init__.py#L56-L61
def _is_whitelisted(self, email): """Check if an email is in the whitelist. If there's no whitelist, it's assumed it's not whitelisted.""" return hasattr(settings, "SAFE_EMAIL_WHITELIST") and \ any(re.match(m, email) for m in settings.SAFE_EMAIL_WHITELIST)
[ "def", "_is_whitelisted", "(", "self", ",", "email", ")", ":", "return", "hasattr", "(", "settings", ",", "\"SAFE_EMAIL_WHITELIST\"", ")", "and", "any", "(", "re", ".", "match", "(", "m", ",", "email", ")", "for", "m", "in", "settings", ".", "SAFE_EMAIL_...
Check if an email is in the whitelist. If there's no whitelist, it's assumed it's not whitelisted.
[ "Check", "if", "an", "email", "is", "in", "the", "whitelist", ".", "If", "there", "s", "no", "whitelist", "it", "s", "assumed", "it", "s", "not", "whitelisted", "." ]
python
train
48
desbma/r128gain
r128gain/__init__.py
https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L71-L74
def format_ffmpeg_filter(name, params): """ Build a string to call a FFMpeg filter. """ return "%s=%s" % (name, ":".join("%s=%s" % (k, v) for k, v in params.items()))
[ "def", "format_ffmpeg_filter", "(", "name", ",", "params", ")", ":", "return", "\"%s=%s\"", "%", "(", "name", ",", "\":\"", ".", "join", "(", "\"%s=%s\"", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", ...
Build a string to call a FFMpeg filter.
[ "Build", "a", "string", "to", "call", "a", "FFMpeg", "filter", "." ]
python
train
46.75
Adyen/adyen-python-api-library
Adyen/client.py
https://github.com/Adyen/adyen-python-api-library/blob/928f6409ab6e2fac300b9fa29d89f3f508b23445/Adyen/client.py#L196-L309
def call_api(self, request_data, service, action, idempotency=False, **kwargs): """This will call the adyen api. username, password, merchant_account, and platform are pulled from root module level and or self object. AdyenResult will be returned on 200 response. Otherwise, an e...
[ "def", "call_api", "(", "self", ",", "request_data", ",", "service", ",", "action", ",", "idempotency", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "http_init", ":", "self", ".", "http_client", "=", "HTTPClient", "(", "se...
This will call the adyen api. username, password, merchant_account, and platform are pulled from root module level and or self object. AdyenResult will be returned on 200 response. Otherwise, an exception is raised. Args: request_data (dict): The dictionary of the request to...
[ "This", "will", "call", "the", "adyen", "api", ".", "username", "password", "merchant_account", "and", "platform", "are", "pulled", "from", "root", "module", "level", "and", "or", "self", "object", ".", "AdyenResult", "will", "be", "returned", "on", "200", "...
python
train
42.72807
seequent/vectormath
vectormath/vector.py
https://github.com/seequent/vectormath/blob/a2259fb82cf5a665170f50d216b11a738400d878/vectormath/vector.py#L303-L307
def cross(self, vec): """Cross product with another vector""" if not isinstance(vec, self.__class__): raise TypeError('Cross product operand must be a vector') return Vector3(0, 0, np.asscalar(np.cross(self, vec)))
[ "def", "cross", "(", "self", ",", "vec", ")", ":", "if", "not", "isinstance", "(", "vec", ",", "self", ".", "__class__", ")", ":", "raise", "TypeError", "(", "'Cross product operand must be a vector'", ")", "return", "Vector3", "(", "0", ",", "0", ",", "...
Cross product with another vector
[ "Cross", "product", "with", "another", "vector" ]
python
train
49.2
fermiPy/fermipy
fermipy/hpx_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/hpx_utils.py#L89-L95
def hpx_to_axes(h, npix): """ Generate a sequence of bin edge vectors corresponding to the axes of a HPX object.""" x = h.ebins z = np.arange(npix[-1] + 1) return x, z
[ "def", "hpx_to_axes", "(", "h", ",", "npix", ")", ":", "x", "=", "h", ".", "ebins", "z", "=", "np", ".", "arange", "(", "npix", "[", "-", "1", "]", "+", "1", ")", "return", "x", ",", "z" ]
Generate a sequence of bin edge vectors corresponding to the axes of a HPX object.
[ "Generate", "a", "sequence", "of", "bin", "edge", "vectors", "corresponding", "to", "the", "axes", "of", "a", "HPX", "object", "." ]
python
train
26
python-visualization/folium
folium/utilities.py
https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/utilities.py#L321-L340
def iter_coords(obj): """ Returns all the coordinate tuples from a geometry or feature. """ if isinstance(obj, (tuple, list)): coords = obj elif 'features' in obj: coords = [geom['geometry']['coordinates'] for geom in obj['features']] elif 'geometry' in obj: coords = obj...
[ "def", "iter_coords", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "tuple", ",", "list", ")", ")", ":", "coords", "=", "obj", "elif", "'features'", "in", "obj", ":", "coords", "=", "[", "geom", "[", "'geometry'", "]", "[", "'coor...
Returns all the coordinate tuples from a geometry or feature.
[ "Returns", "all", "the", "coordinate", "tuples", "from", "a", "geometry", "or", "feature", "." ]
python
train
29.05
ultrabug/py3status
py3status/util.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/util.py#L109-L139
def make_threshold_gradient(self, py3, thresholds, size=100): """ Given a thresholds list, creates a gradient list that covers the range of the thresholds. The number of colors in the gradient is limited by size. Because of how the range is split the exact number of colors in th...
[ "def", "make_threshold_gradient", "(", "self", ",", "py3", ",", "thresholds", ",", "size", "=", "100", ")", ":", "thresholds", "=", "sorted", "(", "thresholds", ")", "key", "=", "\"{}|{}\"", ".", "format", "(", "thresholds", ",", "size", ")", "try", ":",...
Given a thresholds list, creates a gradient list that covers the range of the thresholds. The number of colors in the gradient is limited by size. Because of how the range is split the exact number of colors in the gradient cannot be guaranteed.
[ "Given", "a", "thresholds", "list", "creates", "a", "gradient", "list", "that", "covers", "the", "range", "of", "the", "thresholds", ".", "The", "number", "of", "colors", "in", "the", "gradient", "is", "limited", "by", "size", ".", "Because", "of", "how", ...
python
train
37.580645
mitsei/dlkit
dlkit/handcar/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L3667-L3678
def _record_extension(self, bank_id, key, value): """ To structure a record extension property bean """ record_bean = { 'value': value, 'displayName': self._text_bean(key), 'description': self._text_bean(key), 'displayLabel': self._text_bea...
[ "def", "_record_extension", "(", "self", ",", "bank_id", ",", "key", ",", "value", ")", ":", "record_bean", "=", "{", "'value'", ":", "value", ",", "'displayName'", ":", "self", ".", "_text_bean", "(", "key", ")", ",", "'description'", ":", "self", ".", ...
To structure a record extension property bean
[ "To", "structure", "a", "record", "extension", "property", "bean" ]
python
train
32.833333
kalefranz/auxlib
auxlib/decorators.py
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L65-L147
def memoizemethod(method): """ Decorator to cause a method to cache it's results in self for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> class Foo (object): ... @memoizemethod ... ...
[ "def", "memoizemethod", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# NOTE: a __dict__ check is performed here rather than using the", "# built-in hasattr function ...
Decorator to cause a method to cache it's results in self for each combination of inputs and return the cached result on subsequent calls. Does not support named arguments or arg values that are not hashable. >>> class Foo (object): ... @memoizemethod ... def foo(self, x, y=0): ... prin...
[ "Decorator", "to", "cause", "a", "method", "to", "cache", "it", "s", "results", "in", "self", "for", "each", "combination", "of", "inputs", "and", "return", "the", "cached", "result", "on", "subsequent", "calls", ".", "Does", "not", "support", "named", "ar...
python
train
34.289157
planetlabs/es_fluent
es_fluent/builder.py
https://github.com/planetlabs/es_fluent/blob/74f8db3a1bf9aa1d54512cf2d5e0ec58ee2f4b1c/es_fluent/builder.py#L47-L55
def or_filter(self, filter_or_string, *args, **kwargs): """ Convenience method to delegate to the root_filter to generate an `or` clause. :return: :class:`~es_fluent.builder.QueryBuilder` """ self.root_filter.or_filter(filter_or_string, *args, **kwargs) return se...
[ "def", "or_filter", "(", "self", ",", "filter_or_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "root_filter", ".", "or_filter", "(", "filter_or_string", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self" ]
Convenience method to delegate to the root_filter to generate an `or` clause. :return: :class:`~es_fluent.builder.QueryBuilder`
[ "Convenience", "method", "to", "delegate", "to", "the", "root_filter", "to", "generate", "an", "or", "clause", "." ]
python
train
34.888889
angr/angr
angr/state_plugins/posix.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/posix.py#L355-L375
def get_fd(self, fd): """ Looks up the SimFileDescriptor associated with the given number (an AST). If the number is concrete and does not map to anything, return None. If the number is symbolic, constrain it to an open fd and create a new file for it. """ try: ...
[ "def", "get_fd", "(", "self", ",", "fd", ")", ":", "try", ":", "fd", "=", "self", ".", "state", ".", "solver", ".", "eval_one", "(", "fd", ")", "except", "SimSolverError", ":", "ideal", "=", "self", ".", "_pick_fd", "(", ")", "self", ".", "state", ...
Looks up the SimFileDescriptor associated with the given number (an AST). If the number is concrete and does not map to anything, return None. If the number is symbolic, constrain it to an open fd and create a new file for it.
[ "Looks", "up", "the", "SimFileDescriptor", "associated", "with", "the", "given", "number", "(", "an", "AST", ")", ".", "If", "the", "number", "is", "concrete", "and", "does", "not", "map", "to", "anything", "return", "None", ".", "If", "the", "number", "...
python
train
50.619048