repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
Yubico/python-pyhsm
pyhsm/tools/generate_keys.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/generate_keys.py#L42-L98
def parse_args(): """ Parse the command line arguments """ parser = argparse.ArgumentParser(description = "Generate secrets for YubiKeys using YubiHSM", add_help=True, formatter_class = argparse.ArgumentDefaultsHelpFormatter, ...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Generate secrets for YubiKeys using YubiHSM\"", ",", "add_help", "=", "True", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter",...
Parse the command line arguments
[ "Parse", "the", "command", "line", "arguments" ]
python
train
saltstack/salt
salt/modules/boto_rds.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_rds.py#L780-L819
def describe_parameter_group(name, Filters=None, MaxRecords=None, Marker=None, region=None, key=None, keyid=None, profile=None): ''' Returns a list of `DBParameterGroup` descriptions. CLI example to description of parameter group:: salt myminion boto_rds.describe_parame...
[ "def", "describe_parameter_group", "(", "name", ",", "Filters", "=", "None", ",", "MaxRecords", "=", "None", ",", "Marker", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ...
Returns a list of `DBParameterGroup` descriptions. CLI example to description of parameter group:: salt myminion boto_rds.describe_parameter_group parametergroupname\ region=us-east-1
[ "Returns", "a", "list", "of", "DBParameterGroup", "descriptions", ".", "CLI", "example", "to", "description", "of", "parameter", "group", "::" ]
python
train
resync/resync
resync/resource_list.py
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/resource_list.py#L162-L206
def compare(self, src): """Compare this ResourceList object with that specified as src. The parameter src must also be a ResourceList object, it is assumed to be the source, and the current object is the destination. This written to work for any objects in self and sc, provided that the...
[ "def", "compare", "(", "self", ",", "src", ")", ":", "dst_iter", "=", "iter", "(", "self", ".", "resources", ")", "src_iter", "=", "iter", "(", "src", ".", "resources", ")", "same", "=", "ResourceList", "(", ")", "updated", "=", "ResourceList", "(", ...
Compare this ResourceList object with that specified as src. The parameter src must also be a ResourceList object, it is assumed to be the source, and the current object is the destination. This written to work for any objects in self and sc, provided that the == operator can be used to...
[ "Compare", "this", "ResourceList", "object", "with", "that", "specified", "as", "src", "." ]
python
train
boakley/robotframework-lint
rflint/rflint.py
https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/rflint.py#L178-L184
def list_rules(self): """Print a list of all rules""" for rule in sorted(self.all_rules, key=lambda rule: rule.name): print(rule) if self.args.verbose: for line in rule.doc.split("\n"): print(" ", line)
[ "def", "list_rules", "(", "self", ")", ":", "for", "rule", "in", "sorted", "(", "self", ".", "all_rules", ",", "key", "=", "lambda", "rule", ":", "rule", ".", "name", ")", ":", "print", "(", "rule", ")", "if", "self", ".", "args", ".", "verbose", ...
Print a list of all rules
[ "Print", "a", "list", "of", "all", "rules" ]
python
valid
indico/indico-plugins
livesync/indico_livesync/util.py
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/util.py#L82-L85
def get_excluded_categories(): """Get excluded category IDs.""" from indico_livesync.plugin import LiveSyncPlugin return {int(x['id']) for x in LiveSyncPlugin.settings.get('excluded_categories')}
[ "def", "get_excluded_categories", "(", ")", ":", "from", "indico_livesync", ".", "plugin", "import", "LiveSyncPlugin", "return", "{", "int", "(", "x", "[", "'id'", "]", ")", "for", "x", "in", "LiveSyncPlugin", ".", "settings", ".", "get", "(", "'excluded_cat...
Get excluded category IDs.
[ "Get", "excluded", "category", "IDs", "." ]
python
train
Fantomas42/django-blog-zinnia
zinnia/url_shortener/__init__.py
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/url_shortener/__init__.py#L11-L26
def get_url_shortener(): """ Return the selected URL shortener backend. """ try: backend_module = import_module(URL_SHORTENER_BACKEND) backend = getattr(backend_module, 'backend') except (ImportError, AttributeError): warnings.warn('%s backend cannot be imported' % URL_SHORTE...
[ "def", "get_url_shortener", "(", ")", ":", "try", ":", "backend_module", "=", "import_module", "(", "URL_SHORTENER_BACKEND", ")", "backend", "=", "getattr", "(", "backend_module", ",", "'backend'", ")", "except", "(", "ImportError", ",", "AttributeError", ")", "...
Return the selected URL shortener backend.
[ "Return", "the", "selected", "URL", "shortener", "backend", "." ]
python
train
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L93-L111
def action_inactivate(self, ids): """Inactivate users.""" try: count = 0 for user_id in ids: user = _datastore.get_user(user_id) if user is None: raise ValueError(_("Cannot find user.")) if _datastore.deactivate_...
[ "def", "action_inactivate", "(", "self", ",", "ids", ")", ":", "try", ":", "count", "=", "0", "for", "user_id", "in", "ids", ":", "user", "=", "_datastore", ".", "get_user", "(", "user_id", ")", "if", "user", "is", "None", ":", "raise", "ValueError", ...
Inactivate users.
[ "Inactivate", "users", "." ]
python
train
childsish/sofia
sofia/execution_engines/workers/step_worker.py
https://github.com/childsish/sofia/blob/39b992f143e2610a62ad751568caa5ca9aaf0224/sofia/execution_engines/workers/step_worker.py#L4-L33
def step_worker(step, pipe, max_entities): """ All messages follow the form: <message>, <data> Valid messages -------------- run, <input_data> finalise, None next, None stop, None """ state = None while True: message, input = pipe.recv() if message == 'run': ...
[ "def", "step_worker", "(", "step", ",", "pipe", ",", "max_entities", ")", ":", "state", "=", "None", "while", "True", ":", "message", ",", "input", "=", "pipe", ".", "recv", "(", ")", "if", "message", "==", "'run'", ":", "state", "=", "step", ".", ...
All messages follow the form: <message>, <data> Valid messages -------------- run, <input_data> finalise, None next, None stop, None
[ "All", "messages", "follow", "the", "form", ":", "<message", ">", "<data", ">" ]
python
train
jrigden/pyPodcastParser
pyPodcastParser/Podcast.py
https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L403-L413
def set_owner(self): """Parses owner name and email then sets value""" owner = self.soup.find('itunes:owner') try: self.owner_name = owner.find('itunes:name').string except AttributeError: self.owner_name = None try: self.owner_email = owner.fi...
[ "def", "set_owner", "(", "self", ")", ":", "owner", "=", "self", ".", "soup", ".", "find", "(", "'itunes:owner'", ")", "try", ":", "self", ".", "owner_name", "=", "owner", ".", "find", "(", "'itunes:name'", ")", ".", "string", "except", "AttributeError",...
Parses owner name and email then sets value
[ "Parses", "owner", "name", "and", "email", "then", "sets", "value" ]
python
train
Diaoul/subliminal
subliminal/subtitle.py
https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/subtitle.py#L166-L182
def get_subtitle_path(video_path, language=None, extension='.srt'): """Get the subtitle path using the `video_path` and `language`. :param str video_path: path to the video. :param language: language of the subtitle to put in the path. :type language: :class:`~babelfish.language.Language` :param st...
[ "def", "get_subtitle_path", "(", "video_path", ",", "language", "=", "None", ",", "extension", "=", "'.srt'", ")", ":", "subtitle_root", "=", "os", ".", "path", ".", "splitext", "(", "video_path", ")", "[", "0", "]", "if", "language", ":", "subtitle_root",...
Get the subtitle path using the `video_path` and `language`. :param str video_path: path to the video. :param language: language of the subtitle to put in the path. :type language: :class:`~babelfish.language.Language` :param str extension: extension of the subtitle. :return: path of the subtitle. ...
[ "Get", "the", "subtitle", "path", "using", "the", "video_path", "and", "language", "." ]
python
train
biolink/ontobio
ontobio/sparql/sparql_ontol_utils.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sparql/sparql_ontol_utils.py#L231-L245
def fetchall_labels(ont): """ fetch all rdfs:label assertions for an ontology """ logging.info("fetching rdfs:labels for: "+ont) namedGraph = get_named_graph(ont) queryBody = querybody_label() query = """ SELECT * WHERE {{ GRAPH <{g}> {q} }} """.format(q=queryBody, g=namedGr...
[ "def", "fetchall_labels", "(", "ont", ")", ":", "logging", ".", "info", "(", "\"fetching rdfs:labels for: \"", "+", "ont", ")", "namedGraph", "=", "get_named_graph", "(", "ont", ")", "queryBody", "=", "querybody_label", "(", ")", "query", "=", "\"\"\"\n SELEC...
fetch all rdfs:label assertions for an ontology
[ "fetch", "all", "rdfs", ":", "label", "assertions", "for", "an", "ontology" ]
python
train
pymupdf/PyMuPDF
fitz/utils.py
https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L573-L582
def getRectArea(*args): """Calculate area of rectangle.\nparameter is one of 'px' (default), 'in', 'cm', or 'mm'.""" rect = args[0] if len(args) > 1: unit = args[1] else: unit = "px" u = {"px": (1,1), "in": (1.,72.), "cm": (2.54, 72.), "mm": (25.4, 72.)} f = (u[unit][0] / u[u...
[ "def", "getRectArea", "(", "*", "args", ")", ":", "rect", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "1", ":", "unit", "=", "args", "[", "1", "]", "else", ":", "unit", "=", "\"px\"", "u", "=", "{", "\"px\"", ":", "(", "...
Calculate area of rectangle.\nparameter is one of 'px' (default), 'in', 'cm', or 'mm'.
[ "Calculate", "area", "of", "rectangle", ".", "\\", "nparameter", "is", "one", "of", "px", "(", "default", ")", "in", "cm", "or", "mm", "." ]
python
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/launcher.py
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/launcher.py#L122-L140
def parse_args(self, args=None): """Parse the given arguments All commands should support executing a function, so you can use the arg Namespace like this:: launcher = Launcher() args, unknown = launcher.parse_args() args.func(args, unknown) # execute the command ...
[ "def", "parse_args", "(", "self", ",", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "return", "self", ".", "parser", ".", "parse_known_args", "(", "args", ")" ]
Parse the given arguments All commands should support executing a function, so you can use the arg Namespace like this:: launcher = Launcher() args, unknown = launcher.parse_args() args.func(args, unknown) # execute the command :param args: arguments to pass ...
[ "Parse", "the", "given", "arguments" ]
python
train
JasonKessler/scattertext
scattertext/TermDocMatrix.py
https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrix.py#L512-L523
def _get_scaled_f_score_from_counts(self, cat_word_counts, not_cat_word_counts, scaler_algo, beta=DEFAULT_BETA): ''' scaler = self._get_scaler_function(scaler_algo) p_word_given_category = cat_word_counts.astype(np.float64) / cat_word_counts.sum() ...
[ "def", "_get_scaled_f_score_from_counts", "(", "self", ",", "cat_word_counts", ",", "not_cat_word_counts", ",", "scaler_algo", ",", "beta", "=", "DEFAULT_BETA", ")", ":", "return", "ScaledFScore", ".", "get_scores", "(", "cat_word_counts", ",", "not_cat_word_counts", ...
scaler = self._get_scaler_function(scaler_algo) p_word_given_category = cat_word_counts.astype(np.float64) / cat_word_counts.sum() p_category_given_word = cat_word_counts.astype(np.float64) / (cat_word_counts + not_cat_word_counts) scores \ = self._computer_harmoic_mean_of_probabilit...
[ "scaler", "=", "self", ".", "_get_scaler_function", "(", "scaler_algo", ")", "p_word_given_category", "=", "cat_word_counts", ".", "astype", "(", "np", ".", "float64", ")", "/", "cat_word_counts", ".", "sum", "()", "p_category_given_word", "=", "cat_word_counts", ...
python
train
mbr/simplekv
simplekv/__init__.py
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L240-L251
def _get_filename(self, key, filename): """Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :me...
[ "def", "_get_filename", "(", "self", ",", "key", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "dest", ":", "return", "self", ".", "_get_file", "(", "key", ",", "dest", ")" ]
Write key to file. Either this method or :meth:`~simplekv.KeyValueStore._get_file` will be called by :meth:`~simplekv.KeyValueStore.get_file`. This method only accepts filenames and will open the file with a mode of ``wb``, then call :meth:`~simplekv.KeyValueStore._get_file`. :p...
[ "Write", "key", "to", "file", ".", "Either", "this", "method", "or", ":", "meth", ":", "~simplekv", ".", "KeyValueStore", ".", "_get_file", "will", "be", "called", "by", ":", "meth", ":", "~simplekv", ".", "KeyValueStore", ".", "get_file", ".", "This", "...
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/rst/heilman_sagae_2015.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/rst/heilman_sagae_2015.py#L254-L275
def get_nuclearity_type(child_types): """Returns the nuclearity type of an RST relation (i.e. 'multinuc', 'nucsat' or 'multisat') or 'edu' if the node is below the relation level. """ if 'text' in child_types and len(child_types) == 1: return NucType.edu assert 'nucleus' in child_types,...
[ "def", "get_nuclearity_type", "(", "child_types", ")", ":", "if", "'text'", "in", "child_types", "and", "len", "(", "child_types", ")", "==", "1", ":", "return", "NucType", ".", "edu", "assert", "'nucleus'", "in", "child_types", ",", "\"This is not a relational ...
Returns the nuclearity type of an RST relation (i.e. 'multinuc', 'nucsat' or 'multisat') or 'edu' if the node is below the relation level.
[ "Returns", "the", "nuclearity", "type", "of", "an", "RST", "relation", "(", "i", ".", "e", ".", "multinuc", "nucsat", "or", "multisat", ")", "or", "edu", "if", "the", "node", "is", "below", "the", "relation", "level", "." ]
python
train
facelessuser/bracex
bracex/__init__.py
https://github.com/facelessuser/bracex/blob/1fdf83e2bdfb939e78ba9966bcef80cd7a5c8534/bracex/__init__.py#L229-L234
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
[ "def", "combine", "(", "self", ",", "a", ",", "b", ")", ":", "for", "l", "in", "(", "a", ",", "b", ")", ":", "for", "x", "in", "l", ":", "yield", "x" ]
A generator that combines two iterables.
[ "A", "generator", "that", "combines", "two", "iterables", "." ]
python
train
senaite/senaite.core
bika/lims/browser/widgets/referenceresultswidget.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/referenceresultswidget.py#L126-L131
def folderitems(self): """TODO: Refactor to non-classic mode """ items = super(ReferenceResultsView, self).folderitems() self.categories.sort() return items
[ "def", "folderitems", "(", "self", ")", ":", "items", "=", "super", "(", "ReferenceResultsView", ",", "self", ")", ".", "folderitems", "(", ")", "self", ".", "categories", ".", "sort", "(", ")", "return", "items" ]
TODO: Refactor to non-classic mode
[ "TODO", ":", "Refactor", "to", "non", "-", "classic", "mode" ]
python
train
brainiak/brainiak
brainiak/factoranalysis/tfa.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/factoranalysis/tfa.py#L525-L567
def get_factors(self, unique_R, inds, centers, widths): """Calculate factors based on centers and widths Parameters ---------- unique_R : a list of array, Each element contains unique value in one dimension of scanner coordinate matrix R. inds : a list ...
[ "def", "get_factors", "(", "self", ",", "unique_R", ",", "inds", ",", "centers", ",", "widths", ")", ":", "F", "=", "np", ".", "zeros", "(", "(", "len", "(", "inds", "[", "0", "]", ")", ",", "self", ".", "K", ")", ")", "tfa_extension", ".", "fa...
Calculate factors based on centers and widths Parameters ---------- unique_R : a list of array, Each element contains unique value in one dimension of scanner coordinate matrix R. inds : a list of array, Each element contains the indices to reconstr...
[ "Calculate", "factors", "based", "on", "centers", "and", "widths" ]
python
train
cmbruns/pyopenvr
src/openvr/__init__.py
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L5250-L5255
def showMessageOverlay(self, pchText, pchCaption, pchButton0Text, pchButton1Text, pchButton2Text, pchButton3Text): """Show the message overlay. This will block and return you a result.""" fn = self.function_table.showMessageOverlay result = fn(pchText, pchCaption, pchButton0Text, pchButton1Text...
[ "def", "showMessageOverlay", "(", "self", ",", "pchText", ",", "pchCaption", ",", "pchButton0Text", ",", "pchButton1Text", ",", "pchButton2Text", ",", "pchButton3Text", ")", ":", "fn", "=", "self", ".", "function_table", ".", "showMessageOverlay", "result", "=", ...
Show the message overlay. This will block and return you a result.
[ "Show", "the", "message", "overlay", ".", "This", "will", "block", "and", "return", "you", "a", "result", "." ]
python
train
eaton-lab/toytree
toytree/Coords.py
https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/toytree/Coords.py#L75-L88
def update_fixed_order(self): "after pruning fixed order needs update to match new nnodes/ntips." # set tips order if fixing for multi-tree plotting (default None) fixed_order = self.ttree._fixed_order self.ttree_fixed_order = None self.ttree_fixed_idx = list(range(self.ttree.nti...
[ "def", "update_fixed_order", "(", "self", ")", ":", "# set tips order if fixing for multi-tree plotting (default None)", "fixed_order", "=", "self", ".", "ttree", ".", "_fixed_order", "self", ".", "ttree_fixed_order", "=", "None", "self", ".", "ttree_fixed_idx", "=", "l...
after pruning fixed order needs update to match new nnodes/ntips.
[ "after", "pruning", "fixed", "order", "needs", "update", "to", "match", "new", "nnodes", "/", "ntips", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex_bin_validate.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L412-L426
def interactive(self): """Run in interactive mode.""" while True: line = sys.stdin.readline().strip() if line == 'quit': sys.exit() elif line == 'validate': self.check_syntax() self.check_imports() self.c...
[ "def", "interactive", "(", "self", ")", ":", "while", "True", ":", "line", "=", "sys", ".", "stdin", ".", "readline", "(", ")", ".", "strip", "(", ")", "if", "line", "==", "'quit'", ":", "sys", ".", "exit", "(", ")", "elif", "line", "==", "'valid...
Run in interactive mode.
[ "Run", "in", "interactive", "mode", "." ]
python
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/streaming_pull_manager.py#L370-L399
def _get_initial_request(self): """Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon opening the subscription. Returns: google.cloud.pubsub_v1.types.StreamingPullRequest: A request suita...
[ "def", "_get_initial_request", "(", "self", ")", ":", "# Any ack IDs that are under lease management need to have their", "# deadline extended immediately.", "if", "self", ".", "_leaser", "is", "not", "None", ":", "# Explicitly copy the list, as it could be modified by another", "#...
Return the initial request for the RPC. This defines the initial request that must always be sent to Pub/Sub immediately upon opening the subscription. Returns: google.cloud.pubsub_v1.types.StreamingPullRequest: A request suitable for being the first request on the stre...
[ "Return", "the", "initial", "request", "for", "the", "RPC", "." ]
python
train
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1520-L1527
def unordered(x, y): """ Return True if x or y is a NaN and False otherwise. """ x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_unordered_p(x, y)
[ "def", "unordered", "(", "x", ",", "y", ")", ":", "x", "=", "BigFloat", ".", "_implicit_convert", "(", "x", ")", "y", "=", "BigFloat", ".", "_implicit_convert", "(", "y", ")", "return", "mpfr", ".", "mpfr_unordered_p", "(", "x", ",", "y", ")" ]
Return True if x or y is a NaN and False otherwise.
[ "Return", "True", "if", "x", "or", "y", "is", "a", "NaN", "and", "False", "otherwise", "." ]
python
train
eqcorrscan/EQcorrscan
eqcorrscan/utils/mag_calc.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/mag_calc.py#L328-L376
def _GSE2_PAZ_read(gsefile): """ Read the instrument response information from a GSE Poles and Zeros file. Formatted for files generated by the SEISAN program RESP. Format must be CAL2, not coded for any other format at the moment, contact the authors to add others in. :type gsefile: string ...
[ "def", "_GSE2_PAZ_read", "(", "gsefile", ")", ":", "with", "open", "(", "gsefile", ",", "'r'", ")", "as", "f", ":", "# First line should start with CAL2", "header", "=", "f", ".", "readline", "(", ")", "if", "not", "header", "[", "0", ":", "4", "]", "=...
Read the instrument response information from a GSE Poles and Zeros file. Formatted for files generated by the SEISAN program RESP. Format must be CAL2, not coded for any other format at the moment, contact the authors to add others in. :type gsefile: string :param gsefile: Path to GSE file ...
[ "Read", "the", "instrument", "response", "information", "from", "a", "GSE", "Poles", "and", "Zeros", "file", "." ]
python
train
wkentaro/fcn
fcn/initializers/weight.py
https://github.com/wkentaro/fcn/blob/a29e167b67b11418a06566ad1ddbbc6949575e05/fcn/initializers/weight.py#L6-L16
def _get_upsampling_filter(size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:size, :size] filter = (1 - abs(og[0] - center) / factor) * \ (1 - abs(o...
[ "def", "_get_upsampling_filter", "(", "size", ")", ":", "factor", "=", "(", "size", "+", "1", ")", "//", "2", "if", "size", "%", "2", "==", "1", ":", "center", "=", "factor", "-", "1", "else", ":", "center", "=", "factor", "-", "0.5", "og", "=", ...
Make a 2D bilinear kernel suitable for upsampling
[ "Make", "a", "2D", "bilinear", "kernel", "suitable", "for", "upsampling" ]
python
train
joesecurity/jbxapi
jbxapi.py
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L365-L373
def analysis_search(self, query): """ Lists the webids of the analyses that match the given query. Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id. """ response = self._post(self.apiurl + "/v2/analysis/search", data={'apikey': self.apikey, 'q':...
[ "def", "analysis_search", "(", "self", ",", "query", ")", ":", "response", "=", "self", ".", "_post", "(", "self", ".", "apiurl", "+", "\"/v2/analysis/search\"", ",", "data", "=", "{", "'apikey'", ":", "self", ".", "apikey", ",", "'q'", ":", "query", "...
Lists the webids of the analyses that match the given query. Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id.
[ "Lists", "the", "webids", "of", "the", "analyses", "that", "match", "the", "given", "query", "." ]
python
train
Metatab/metapack
metapack/cli/metaaws.py
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/cli/metaaws.py#L540-L548
def get_iam_account(l, args, user_name): """Return the local Account for a user name, by fetching User and looking up the arn. """ iam = get_resource(args, 'iam') user = iam.User(user_name) user.load() return l.find_or_new_account(user.arn)
[ "def", "get_iam_account", "(", "l", ",", "args", ",", "user_name", ")", ":", "iam", "=", "get_resource", "(", "args", ",", "'iam'", ")", "user", "=", "iam", ".", "User", "(", "user_name", ")", "user", ".", "load", "(", ")", "return", "l", ".", "fin...
Return the local Account for a user name, by fetching User and looking up the arn.
[ "Return", "the", "local", "Account", "for", "a", "user", "name", "by", "fetching", "User", "and", "looking", "up", "the", "arn", "." ]
python
train
jrief/djangocms-cascade
cmsplugin_cascade/segmentation/mixins.py
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/segmentation/mixins.py#L88-L159
def emulate_users(self, request): """ The list view """ def display_as_link(self, obj): try: identifier = getattr(user_model_admin, list_display_link)(obj) except AttributeError: identifier = admin.utils.lookup_field(list_display_li...
[ "def", "emulate_users", "(", "self", ",", "request", ")", ":", "def", "display_as_link", "(", "self", ",", "obj", ")", ":", "try", ":", "identifier", "=", "getattr", "(", "user_model_admin", ",", "list_display_link", ")", "(", "obj", ")", "except", "Attrib...
The list view
[ "The", "list", "view" ]
python
train
ltalirz/aiida-gudhi
aiida_gudhi/parsers/rips.py
https://github.com/ltalirz/aiida-gudhi/blob/81ebec782ddff3ab97a3e3242b809fec989fa4b9/aiida_gudhi/parsers/rips.py#L26-L69
def parse_with_retrieved(self, retrieved): """ Parse output data folder, store results in database. :param retrieved: a dictionary of retrieved nodes, where the key is the link name :returns: a tuple with two values ``(bool, node_list)``, where: * ``bool``...
[ "def", "parse_with_retrieved", "(", "self", ",", "retrieved", ")", ":", "from", "aiida", ".", "orm", ".", "data", ".", "singlefile", "import", "SinglefileData", "success", "=", "False", "node_list", "=", "[", "]", "# Check that the retrieved folder is there", "try...
Parse output data folder, store results in database. :param retrieved: a dictionary of retrieved nodes, where the key is the link name :returns: a tuple with two values ``(bool, node_list)``, where: * ``bool``: variable to tell if the parsing succeeded * ``node_...
[ "Parse", "output", "data", "folder", "store", "results", "in", "database", "." ]
python
train
google/apitools
apitools/base/py/encoding_helper.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/encoding_helper.py#L314-L345
def decode_field(self, field, value): """Decode the given JSON value. Args: field: a messages.Field for the field we're decoding. value: a python value we'd like to decode. Returns: A value suitable for assignment to field. """ for decoder in _GetF...
[ "def", "decode_field", "(", "self", ",", "field", ",", "value", ")", ":", "for", "decoder", "in", "_GetFieldCodecs", "(", "field", ",", "'decoder'", ")", ":", "result", "=", "decoder", "(", "field", ",", "value", ")", "value", "=", "result", ".", "valu...
Decode the given JSON value. Args: field: a messages.Field for the field we're decoding. value: a python value we'd like to decode. Returns: A value suitable for assignment to field.
[ "Decode", "the", "given", "JSON", "value", "." ]
python
train
f3at/feat
src/feat/common/error.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/common/error.py#L33-L45
def log_errors(function): """Logs the exceptions raised by the decorated function without interfering. For debugging purpose.""" def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except BaseException as e: handle_exception(None, e, "Exception in fun...
[ "def", "log_errors", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "BaseException", "as", "e", ":", "han...
Logs the exceptions raised by the decorated function without interfering. For debugging purpose.
[ "Logs", "the", "exceptions", "raised", "by", "the", "decorated", "function", "without", "interfering", ".", "For", "debugging", "purpose", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/multi_problem_v2.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/multi_problem_v2.py#L86-L89
def generate_data(self, *args, **kwargs): """Generates data for each problem.""" for p in self.problems: p.generate_data(*args, **kwargs)
[ "def", "generate_data", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "p", "in", "self", ".", "problems", ":", "p", ".", "generate_data", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Generates data for each problem.
[ "Generates", "data", "for", "each", "problem", "." ]
python
train
saltstack/salt
salt/utils/nacl.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L329-L350
def sealedbox_decrypt(data, **kwargs): ''' Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF...
[ "def", "sealedbox_decrypt", "(", "data", ",", "*", "*", "kwargs", ")", ":", "if", "data", "is", "None", ":", "return", "None", "# ensure data is in bytes", "data", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_bytes", "(", "data", ")", "sk", "=...
Decrypt data using a secret key that was encrypted using a public key with `nacl.sealedbox_encrypt`. CLI Examples: .. code-block:: bash salt-call nacl.sealedbox_decrypt pEXHQM6cuaF7A= salt-call --local nacl.sealedbox_decrypt data='pEXHQM6cuaF7A=' sk_file=/etc/salt/pki/master/nacl salt...
[ "Decrypt", "data", "using", "a", "secret", "key", "that", "was", "encrypted", "using", "a", "public", "key", "with", "nacl", ".", "sealedbox_encrypt", "." ]
python
train
ncc-tools/python-pa-api
paapi/paapi.py
https://github.com/ncc-tools/python-pa-api/blob/a27481dd323d282d0f4457586198d9faec896f11/paapi/paapi.py#L121-L143
def _query_api(self, method, url, fields=None, extra_headers=None, req_body=None): """ Abstracts http queries to the API """ with self.auth.authenticate() as token: logging.debug('PA Authentication returned token %s', token) headers = { 'Authorizat...
[ "def", "_query_api", "(", "self", ",", "method", ",", "url", ",", "fields", "=", "None", ",", "extra_headers", "=", "None", ",", "req_body", "=", "None", ")", ":", "with", "self", ".", "auth", ".", "authenticate", "(", ")", "as", "token", ":", "loggi...
Abstracts http queries to the API
[ "Abstracts", "http", "queries", "to", "the", "API" ]
python
train
ergoithz/browsepy
browsepy/__init__.py
https://github.com/ergoithz/browsepy/blob/1612a930ef220fae507e1b152c531707e555bd92/browsepy/__init__.py#L61-L73
def iter_cookie_browse_sorting(cookies): ''' Get sorting-cookie from cookies dictionary. :yields: tuple of path and sorting property :ytype: 2-tuple of strings ''' try: data = cookies.get('browse-sorting', 'e30=').encode('ascii') for path, prop in json.loads(base64.b64decode(dat...
[ "def", "iter_cookie_browse_sorting", "(", "cookies", ")", ":", "try", ":", "data", "=", "cookies", ".", "get", "(", "'browse-sorting'", ",", "'e30='", ")", ".", "encode", "(", "'ascii'", ")", "for", "path", ",", "prop", "in", "json", ".", "loads", "(", ...
Get sorting-cookie from cookies dictionary. :yields: tuple of path and sorting property :ytype: 2-tuple of strings
[ "Get", "sorting", "-", "cookie", "from", "cookies", "dictionary", "." ]
python
train
ClericPy/torequests
torequests/parsers.py
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/parsers.py#L167-L182
def ensure_list(obj): """ null obj -> return []; str, unicode, bytes, bytearray -> [obj]; else -> list(obj) """ if not obj: return [] elif isinstance(obj, (str, unicode, bytes, bytearray)): return [obj] elif hasattr(obj, '__iter_...
[ "def", "ensure_list", "(", "obj", ")", ":", "if", "not", "obj", ":", "return", "[", "]", "elif", "isinstance", "(", "obj", ",", "(", "str", ",", "unicode", ",", "bytes", ",", "bytearray", ")", ")", ":", "return", "[", "obj", "]", "elif", "hasattr",...
null obj -> return []; str, unicode, bytes, bytearray -> [obj]; else -> list(obj)
[ "null", "obj", "-", ">", "return", "[]", ";" ]
python
train
guaix-ucm/numina
numina/core/pipelineload.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipelineload.py#L65-L79
def load_mode(node): """Load one observing mdode""" obs_mode = ObservingMode() obs_mode.__dict__.update(node) # handle validator load_mode_validator(obs_mode, node) # handle builder load_mode_builder(obs_mode, node) # handle tagger: load_mode_tagger(obs_mode, node) return obs...
[ "def", "load_mode", "(", "node", ")", ":", "obs_mode", "=", "ObservingMode", "(", ")", "obs_mode", ".", "__dict__", ".", "update", "(", "node", ")", "# handle validator", "load_mode_validator", "(", "obs_mode", ",", "node", ")", "# handle builder", "load_mode_bu...
Load one observing mdode
[ "Load", "one", "observing", "mdode" ]
python
train
jrief/djangocms-cascade
cmsplugin_cascade/models.py
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/models.py#L371-L378
def assure_relation(cls, cms_page): """ Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage. """ try: cms_page.cascadepage except cls.DoesNotExist: cls.objects.create(extended_object=cms_page)
[ "def", "assure_relation", "(", "cls", ",", "cms_page", ")", ":", "try", ":", "cms_page", ".", "cascadepage", "except", "cls", ".", "DoesNotExist", ":", "cls", ".", "objects", ".", "create", "(", "extended_object", "=", "cms_page", ")" ]
Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage.
[ "Assure", "that", "we", "have", "a", "foreign", "key", "relation", "pointing", "from", "CascadePage", "onto", "CMSPage", "." ]
python
train
pschmitt/pyteleloisirs
pyteleloisirs/pyteleloisirs.py
https://github.com/pschmitt/pyteleloisirs/blob/d63610fd3729862455ac42afca440469f8063fba/pyteleloisirs/pyteleloisirs.py#L176-L232
async def async_get_program_guide(channel, no_cache=False, refresh_interval=4): ''' Get the program data for a channel ''' chan = await async_determine_channel(channel) now = datetime.datetime.now() max_cache_age = datetime.timedelta(hours=refresh_interval) if not no_cache and 'guide' in _CA...
[ "async", "def", "async_get_program_guide", "(", "channel", ",", "no_cache", "=", "False", ",", "refresh_interval", "=", "4", ")", ":", "chan", "=", "await", "async_determine_channel", "(", "channel", ")", "now", "=", "datetime", ".", "datetime", ".", "now", ...
Get the program data for a channel
[ "Get", "the", "program", "data", "for", "a", "channel" ]
python
train
vpelletier/pprofile
pprofile.py
https://github.com/vpelletier/pprofile/blob/51a36896727565faf23e5abccc9204e5f935fe1e/pprofile.py#L723-L732
def dump_stats(self, filename): """ Similar to profile.Profile.dump_stats - but different output format ! """ if _isCallgrindName(filename): with open(filename, 'w') as out: self.callgrind(out) else: with io.open(filename, 'w', errors='repl...
[ "def", "dump_stats", "(", "self", ",", "filename", ")", ":", "if", "_isCallgrindName", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "out", ":", "self", ".", "callgrind", "(", "out", ")", "else", ":", "with", "io"...
Similar to profile.Profile.dump_stats - but different output format !
[ "Similar", "to", "profile", ".", "Profile", ".", "dump_stats", "-", "but", "different", "output", "format", "!" ]
python
train
oemof/oemof.db
oemof/db/coastdat.py
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L92-L128
def fetch_raw_data(sql, connection, geometry): """ Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index. """ tmp_dc = {} weather_df = pd.DataFrame( connection.execute(sql).fetchall(), columns=[ 'gid', 'geom_point', 'geom_polygon', 'da...
[ "def", "fetch_raw_data", "(", "sql", ",", "connection", ",", "geometry", ")", ":", "tmp_dc", "=", "{", "}", "weather_df", "=", "pd", ".", "DataFrame", "(", "connection", ".", "execute", "(", "sql", ")", ".", "fetchall", "(", ")", ",", "columns", "=", ...
Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index.
[ "Fetch", "the", "coastdat2", "from", "the", "database", "adapt", "it", "to", "the", "local", "time", "zone", "and", "create", "a", "time", "index", "." ]
python
train
hellosign/hellosign-python-sdk
hellosign_sdk/hsclient.py
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/hsclient.py#L1076-L1154
def create_embedded_unclaimed_draft(self, test_mode=False, client_id=None, is_for_embedded_signing=False, requester_email_address=None, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, requesting_redirect_url=None, form_fields_per...
[ "def", "create_embedded_unclaimed_draft", "(", "self", ",", "test_mode", "=", "False", ",", "client_id", "=", "None", ",", "is_for_embedded_signing", "=", "False", ",", "requester_email_address", "=", "None", ",", "files", "=", "None", ",", "file_urls", "=", "No...
Creates a new Draft to be used for embedded requesting Args: test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False. client_id (str): Cli...
[ "Creates", "a", "new", "Draft", "to", "be", "used", "for", "embedded", "requesting" ]
python
train
saltstack/salt
salt/modules/libcloud_compute.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L531-L553
def delete_image(image_id, profile, **libcloud_kwargs): ''' Delete an image of a node :param image_id: Image to delete :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type li...
[ "def", "delete_image", "(", "image_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", ...
Delete an image of a node :param image_id: Image to delete :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash ...
[ "Delete", "an", "image", "of", "a", "node" ]
python
train
google/grr
grr/server/grr_response_server/gui/api_plugins/report_plugins/server_report_plugins.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/report_plugins/server_report_plugins.py#L82-L86
def _ExtractHuntIdFromPath(entry, event): """Extracts a Hunt ID from an APIAuditEntry's HTTP request path.""" match = re.match(r".*hunt/([^/]+).*", entry.http_request_path) if match: event.urn = "aff4:/hunts/{}".format(match.group(1))
[ "def", "_ExtractHuntIdFromPath", "(", "entry", ",", "event", ")", ":", "match", "=", "re", ".", "match", "(", "r\".*hunt/([^/]+).*\"", ",", "entry", ".", "http_request_path", ")", "if", "match", ":", "event", ".", "urn", "=", "\"aff4:/hunts/{}\"", ".", "form...
Extracts a Hunt ID from an APIAuditEntry's HTTP request path.
[ "Extracts", "a", "Hunt", "ID", "from", "an", "APIAuditEntry", "s", "HTTP", "request", "path", "." ]
python
train
push-things/django-th
th_rss/lib/feedsservice/feedsservice.py
https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_rss/lib/feedsservice/feedsservice.py#L21-L39
def datas(self): """ read the data from a given URL or path to a local file """ data = feedparser.parse(self.URL_TO_PARSE, agent=self.USER_AGENT) # when chardet says # >>> chardet.detect(data) # {'confidence': 0.99, 'encoding': 'utf-8'} # bozo says so...
[ "def", "datas", "(", "self", ")", ":", "data", "=", "feedparser", ".", "parse", "(", "self", ".", "URL_TO_PARSE", ",", "agent", "=", "self", ".", "USER_AGENT", ")", "# when chardet says", "# >>> chardet.detect(data)", "# {'confidence': 0.99, 'encoding': 'utf-8'}", "...
read the data from a given URL or path to a local file
[ "read", "the", "data", "from", "a", "given", "URL", "or", "path", "to", "a", "local", "file" ]
python
train
astropy/astropy-helpers
astropy_helpers/commands/build_ext.py
https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/commands/build_ext.py#L162-L206
def _check_cython_sources(self, extension): """ Where relevant, make sure that the .c files associated with .pyx modules are present (if building without Cython installed). """ # Determine the compiler we'll be using if self.compiler is None: compiler = get_d...
[ "def", "_check_cython_sources", "(", "self", ",", "extension", ")", ":", "# Determine the compiler we'll be using", "if", "self", ".", "compiler", "is", "None", ":", "compiler", "=", "get_default_compiler", "(", ")", "else", ":", "compiler", "=", "self", ".", "c...
Where relevant, make sure that the .c files associated with .pyx modules are present (if building without Cython installed).
[ "Where", "relevant", "make", "sure", "that", "the", ".", "c", "files", "associated", "with", ".", "pyx", "modules", "are", "present", "(", "if", "building", "without", "Cython", "installed", ")", "." ]
python
train
pypa/setuptools
setuptools/monkey.py
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/monkey.py#L104-L108
def _patch_distribution_metadata(): """Patch write_pkg_file and read_pkg_file for higher metadata standards""" for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'): new_val = getattr(setuptools.dist, attr) setattr(distutils.dist.DistributionMetadata, attr, new_val)
[ "def", "_patch_distribution_metadata", "(", ")", ":", "for", "attr", "in", "(", "'write_pkg_file'", ",", "'read_pkg_file'", ",", "'get_metadata_version'", ")", ":", "new_val", "=", "getattr", "(", "setuptools", ".", "dist", ",", "attr", ")", "setattr", "(", "d...
Patch write_pkg_file and read_pkg_file for higher metadata standards
[ "Patch", "write_pkg_file", "and", "read_pkg_file", "for", "higher", "metadata", "standards" ]
python
train
robotools/fontParts
Lib/fontParts/world.py
https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/world.py#L420-L435
def getFontsByFontInfoAttribute(self, *attributeValuePairs): """ Get a list of fonts that match the (attribute, value) combinations in ``attributeValuePairs``. :: >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20)) >>> subFonts = fonts.getFontsByFo...
[ "def", "getFontsByFontInfoAttribute", "(", "self", ",", "*", "attributeValuePairs", ")", ":", "found", "=", "self", "for", "attr", ",", "value", "in", "attributeValuePairs", ":", "found", "=", "self", ".", "_matchFontInfoAttributes", "(", "found", ",", "(", "a...
Get a list of fonts that match the (attribute, value) combinations in ``attributeValuePairs``. :: >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20)) >>> subFonts = fonts.getFontsByFontInfoAttribute(("xHeight", 20), ("descender", -150)) This will return a...
[ "Get", "a", "list", "of", "fonts", "that", "match", "the", "(", "attribute", "value", ")", "combinations", "in", "attributeValuePairs", "." ]
python
train
Jajcus/pyxmpp2
pyxmpp2/roster.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L886-L904
def remove_item(self, jid, callback = None, error_callback = None): """Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the...
[ "def", "remove_item", "(", "self", ",", "jid", ",", "callback", "=", "None", ",", "error_callback", "=", "None", ")", ":", "item", "=", "self", ".", "roster", "[", "jid", "]", "if", "jid", "not", "in", "self", ".", "roster", ":", "raise", "KeyError",...
Remove a contact from the roster. :Parameters: - `jid`: contact's jid - `callback`: function to call when the request succeeds. It should accept a single argument - a `RosterItem` describing the requested change - `error_callback`: function to cal...
[ "Remove", "a", "contact", "from", "the", "roster", "." ]
python
valid
deepmind/sonnet
sonnet/python/custom_getters/restore_initializer.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/custom_getters/restore_initializer.py#L26-L75
def restore_initializer(filename, name_fn=None, collection=tf.GraphKeys.GLOBAL_VARIABLES): """Custom getter to restore all variables with `snt.restore_initializer`. Args: filename: The filename of the checkpoint. name_fn: A function which can map the name of the variable requested. ...
[ "def", "restore_initializer", "(", "filename", ",", "name_fn", "=", "None", ",", "collection", "=", "tf", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ")", ":", "def", "_restore_initializer", "(", "getter", ",", "name", ",", "*", "args", ",", "*", "*", "kwar...
Custom getter to restore all variables with `snt.restore_initializer`. Args: filename: The filename of the checkpoint. name_fn: A function which can map the name of the variable requested. This allows restoring variables with values having different names in the checkpoint. collection: Only s...
[ "Custom", "getter", "to", "restore", "all", "variables", "with", "snt", ".", "restore_initializer", "." ]
python
train
saltstack/salt
salt/modules/yumpkg.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L156-L170
def _call_yum(args, **kwargs): ''' Call yum/dnf. ''' params = {'output_loglevel': 'trace', 'python_shell': False, 'env': salt.utils.environment.get_module_environment(globals())} params.update(kwargs) cmd = [] if salt.utils.systemd.has_scope(__context__) and __sal...
[ "def", "_call_yum", "(", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'output_loglevel'", ":", "'trace'", ",", "'python_shell'", ":", "False", ",", "'env'", ":", "salt", ".", "utils", ".", "environment", ".", "get_module_environment", "(...
Call yum/dnf.
[ "Call", "yum", "/", "dnf", "." ]
python
train
gabstopper/smc-python
smc/elements/other.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/other.py#L64-L83
def add_element(self, element): """ Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: elemen...
[ "def", "add_element", "(", "self", ",", "element", ")", ":", "element", "=", "element_resolver", "(", "element", ")", "self", ".", "make_request", "(", "ModificationFailed", ",", "method", "=", "'create'", ",", "resource", "=", "'category_add_element'", ",", "...
Element can be href or type :py:class:`smc.base.model.Element` :: >>> from smc.elements.other import Category >>> category = Category('foo') >>> category.add_element(Host('kali')) :param str,Element element: element to add to tag :raises: ModificationFailed:...
[ "Element", "can", "be", "href", "or", "type", ":", "py", ":", "class", ":", "smc", ".", "base", ".", "model", ".", "Element", "::" ]
python
train
Kortemme-Lab/pull_into_place
pull_into_place/structures.py
https://github.com/Kortemme-Lab/pull_into_place/blob/247f303100a612cc90cf31c86e4fe5052eb28c8d/pull_into_place/structures.py#L564-L572
def angle(array_of_xyzs): """ Calculates angle between three coordinate points (I could not find a package that does this but if one exists that would probably be better). Used for Angle constraints. """ ab = array_of_xyzs[0] - array_of_xyzs[1] cb = array_of_xyzs[2] - array_of_xyzs[1] retur...
[ "def", "angle", "(", "array_of_xyzs", ")", ":", "ab", "=", "array_of_xyzs", "[", "0", "]", "-", "array_of_xyzs", "[", "1", "]", "cb", "=", "array_of_xyzs", "[", "2", "]", "-", "array_of_xyzs", "[", "1", "]", "return", "np", ".", "arccos", "(", "(", ...
Calculates angle between three coordinate points (I could not find a package that does this but if one exists that would probably be better). Used for Angle constraints.
[ "Calculates", "angle", "between", "three", "coordinate", "points", "(", "I", "could", "not", "find", "a", "package", "that", "does", "this", "but", "if", "one", "exists", "that", "would", "probably", "be", "better", ")", ".", "Used", "for", "Angle", "const...
python
train
bwohlberg/sporco
sporco/admm/cbpdn.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L1733-L1748
def cnst_A0T(self, Y0): r"""Compute :math:`A_0^T \mathbf{y}_0` component of :math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`). """ # This calculation involves non-negligible computational cost. It # should be possible to disable relevant diagnostic information ...
[ "def", "cnst_A0T", "(", "self", ",", "Y0", ")", ":", "# This calculation involves non-negligible computational cost. It", "# should be possible to disable relevant diagnostic information", "# (dual residual) to avoid this cost.", "Y0f", "=", "sl", ".", "rfftn", "(", "Y0", ",", ...
r"""Compute :math:`A_0^T \mathbf{y}_0` component of :math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`).
[ "r", "Compute", ":", "math", ":", "A_0^T", "\\", "mathbf", "{", "y", "}", "_0", "component", "of", ":", "math", ":", "A^T", "\\", "mathbf", "{", "y", "}", "(", "see", ":", "meth", ":", ".", "ADMMTwoBlockCnstrnt", ".", "cnst_AT", ")", "." ]
python
train
ecell/ecell4
ecell4/util/ports.py
https://github.com/ecell/ecell4/blob/a4a1229661c39b2059adbbacae9090e5ba664e01/ecell4/util/ports.py#L377-L411
def load_sbml(filename): """ Load a model from a SBML file. Parameters ---------- filename : str The input SBML filename. Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume. ...
[ "def", "load_sbml", "(", "filename", ")", ":", "import", "libsbml", "document", "=", "libsbml", ".", "readSBML", "(", "filename", ")", "document", ".", "validateSBML", "(", ")", "num_errors", "=", "(", "document", ".", "getNumErrors", "(", "libsbml", ".", ...
Load a model from a SBML file. Parameters ---------- filename : str The input SBML filename. Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume.
[ "Load", "a", "model", "from", "a", "SBML", "file", "." ]
python
train
ajk8/hatchery
hatchery/project.py
https://github.com/ajk8/hatchery/blob/e068c9f5366d2c98225babb03d4cde36c710194f/hatchery/project.py#L45-L48
def package_has_version_file(package_name): """ Check to make sure _version.py is contained in the package """ version_file_path = helpers.package_file_path('_version.py', package_name) return os.path.isfile(version_file_path)
[ "def", "package_has_version_file", "(", "package_name", ")", ":", "version_file_path", "=", "helpers", ".", "package_file_path", "(", "'_version.py'", ",", "package_name", ")", "return", "os", ".", "path", ".", "isfile", "(", "version_file_path", ")" ]
Check to make sure _version.py is contained in the package
[ "Check", "to", "make", "sure", "_version", ".", "py", "is", "contained", "in", "the", "package" ]
python
train
bram85/topydo
topydo/lib/Config.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L337-L359
def priority_color(self, p_priority): """ Returns a dict with priorities as keys and color numbers as value. """ def _str_to_dict(p_string): pri_colors_dict = dict() for pri_color in p_string.split(','): pri, color = pri_color.split(':') ...
[ "def", "priority_color", "(", "self", ",", "p_priority", ")", ":", "def", "_str_to_dict", "(", "p_string", ")", ":", "pri_colors_dict", "=", "dict", "(", ")", "for", "pri_color", "in", "p_string", ".", "split", "(", "','", ")", ":", "pri", ",", "color", ...
Returns a dict with priorities as keys and color numbers as value.
[ "Returns", "a", "dict", "with", "priorities", "as", "keys", "and", "color", "numbers", "as", "value", "." ]
python
train
mediawiki-utilities/python-mwapi
mwapi/cli.py
https://github.com/mediawiki-utilities/python-mwapi/blob/7a653c29207ecd318ae4b369d398aed13f26951d/mwapi/cli.py#L16-L42
def do_login(session, for_what): """ Performs a login handshake with a user on the command-line. This method will handle all of the follow-up requests (e.g. capcha or two-factor). A login that requires two-factor looks like this:: >>> import mwapi.cli >>> import mwapi >>> mwap...
[ "def", "do_login", "(", "session", ",", "for_what", ")", ":", "# noqa", "username", ",", "password", "=", "request_username_password", "(", "for_what", ")", "try", ":", "session", ".", "login", "(", "username", ",", "password", ")", "except", "ClientInteractio...
Performs a login handshake with a user on the command-line. This method will handle all of the follow-up requests (e.g. capcha or two-factor). A login that requires two-factor looks like this:: >>> import mwapi.cli >>> import mwapi >>> mwapi.cli.do_login(mwapi.Session("https://en.wiki...
[ "Performs", "a", "login", "handshake", "with", "a", "user", "on", "the", "command", "-", "line", ".", "This", "method", "will", "handle", "all", "of", "the", "follow", "-", "up", "requests", "(", "e", ".", "g", ".", "capcha", "or", "two", "-", "facto...
python
train
pypa/pipenv
pipenv/patched/notpip/_internal/utils/misc.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/utils/misc.py#L1014-L1040
def protect_pip_from_modification_on_windows(modifying_pip): """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_info[0]), "pip{}.{}....
[ "def", "protect_pip_from_modification_on_windows", "(", "modifying_pip", ")", ":", "pip_names", "=", "[", "\"pip.exe\"", ",", "\"pip{}.exe\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ")", ",", "\"pip{}.{}.exe\"", ".", "format", "(", "*", ...
Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ...
[ "Protection", "of", "pip", ".", "exe", "from", "modification", "on", "Windows" ]
python
train
sendgrid/sendgrid-python
examples/helpers/mail_example.py
https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/examples/helpers/mail_example.py#L82-L92
def build_attachment1(): """Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md""" attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3I...
[ "def", "build_attachment1", "(", ")", ":", "attachment", "=", "Attachment", "(", ")", "attachment", ".", "content", "=", "(", "\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl\"", "\"Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\"", ")", "attachment", ".", "type", "=", "\"ap...
Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md
[ "Build", "attachment", "mock", ".", "Make", "sure", "your", "content", "is", "base64", "encoded", "before", "passing", "into", "attachment", ".", "content", ".", "Another", "example", ":", "https", ":", "//", "github", ".", "com", "/", "sendgrid", "/", "se...
python
train
AmesCornish/buttersink
buttersink/progress.py
https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/progress.py#L53-L80
def _display(self, sent, now, chunk, mbps): """ Display intermediate progress. """ if self.parent is not None: self.parent._display(self.parent.offset + sent, now, chunk, mbps) return elapsed = now - self.startTime if sent > 0 and self.total is not None and sent...
[ "def", "_display", "(", "self", ",", "sent", ",", "now", ",", "chunk", ",", "mbps", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "self", ".", "parent", ".", "_display", "(", "self", ".", "parent", ".", "offset", "+", "sent", "...
Display intermediate progress.
[ "Display", "intermediate", "progress", "." ]
python
train
inveniosoftware/invenio-github
invenio_github/api.py
https://github.com/inveniosoftware/invenio-github/blob/ec42fd6a06079310dcbe2c46d9fd79d5197bbe26/invenio_github/api.py#L224-L232
def check_sync(self): """Check if sync is required based on last sync date.""" # If refresh interval is not specified, we should refresh every time. expiration = utcnow() refresh_td = current_app.config.get('GITHUB_REFRESH_TIMEDELTA') if refresh_td: expiration -= refr...
[ "def", "check_sync", "(", "self", ")", ":", "# If refresh interval is not specified, we should refresh every time.", "expiration", "=", "utcnow", "(", ")", "refresh_td", "=", "current_app", ".", "config", ".", "get", "(", "'GITHUB_REFRESH_TIMEDELTA'", ")", "if", "refres...
Check if sync is required based on last sync date.
[ "Check", "if", "sync", "is", "required", "based", "on", "last", "sync", "date", "." ]
python
train
TkTech/Jawa
jawa/attributes/code.py
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attributes/code.py#L70-L91
def unpack(self, info): """ Read the CodeAttribute from the byte string `info`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param info: A byte string containing an unpa...
[ "def", "unpack", "(", "self", ",", "info", ")", ":", "self", ".", "max_stack", ",", "self", ".", "max_locals", ",", "c_len", "=", "info", ".", "unpack", "(", "'>HHI'", ")", "self", ".", "_code", "=", "info", ".", "read", "(", "c_len", ")", "# The e...
Read the CodeAttribute from the byte string `info`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param info: A byte string containing an unparsed CodeAttribute.
[ "Read", "the", "CodeAttribute", "from", "the", "byte", "string", "info", "." ]
python
train
ibis-project/ibis
ibis/sql/mysql/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/sql/mysql/client.py#L108-L141
def database(self, name=None): """Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db...
[ "def", "database", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "==", "self", ".", "current_database", "or", "(", "name", "is", "None", "and", "name", "!=", "self", ".", "current_database", ")", ":", "return", "self", ".", "database_c...
Connect to a database called `name`. Parameters ---------- name : str, optional The name of the database to connect to. If ``None``, return the database named ``self.current_database``. Returns ------- db : MySQLDatabase An :class:`ib...
[ "Connect", "to", "a", "database", "called", "name", "." ]
python
train
rwl/pylon
pylon/opf.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/opf.py#L243-L255
def _get_voltage_magnitude_var(self, buses, generators): """ Returns the voltage magnitude variable set. """ Vm = array([b.v_magnitude for b in buses]) # For buses with generators initialise Vm from gen data. for g in generators: Vm[g.bus._i] = g.v_magnitude ...
[ "def", "_get_voltage_magnitude_var", "(", "self", ",", "buses", ",", "generators", ")", ":", "Vm", "=", "array", "(", "[", "b", ".", "v_magnitude", "for", "b", "in", "buses", "]", ")", "# For buses with generators initialise Vm from gen data.", "for", "g", "in",...
Returns the voltage magnitude variable set.
[ "Returns", "the", "voltage", "magnitude", "variable", "set", "." ]
python
train
dnanexus/dx-toolkit
src/python/dxpy/bindings/dxproject.py
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxproject.py#L163-L181
def move_folder(self, folder, destination, **kwargs): """ :param folder: Full path to the folder to move :type folder: string :param destination: Full path to the destination folder that will contain *folder* :type destination: string Moves *folder* to reside in *destina...
[ "def", "move_folder", "(", "self", ",", "folder", ",", "destination", ",", "*", "*", "kwargs", ")", ":", "api_method", "=", "dxpy", ".", "api", ".", "container_move", "if", "isinstance", "(", "self", ",", "DXProject", ")", ":", "api_method", "=", "dxpy",...
:param folder: Full path to the folder to move :type folder: string :param destination: Full path to the destination folder that will contain *folder* :type destination: string Moves *folder* to reside in *destination* in the same project or container. All objects and subfolders...
[ ":", "param", "folder", ":", "Full", "path", "to", "the", "folder", "to", "move", ":", "type", "folder", ":", "string", ":", "param", "destination", ":", "Full", "path", "to", "the", "destination", "folder", "that", "will", "contain", "*", "folder", "*",...
python
train
astroduff/commah
commah/commah.py
https://github.com/astroduff/commah/blob/3ec70338c5123a053c79ddcf2cb3beac26bc9137/commah/commah.py#L349-L397
def calc_ab(zi, Mi, **cosmo): """ Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, ...
[ "def", "calc_ab", "(", "zi", ",", "Mi", ",", "*", "*", "cosmo", ")", ":", "# When zi = 0, the a_tilde becomes alpha and b_tilde becomes beta", "# Eqn 23 of Correa et al 2015a (analytically solve from Eqn 16 and 17)", "# Arbitray formation redshift, z_-2 in COM is more physically motivate...
Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0....
[ "Calculate", "growth", "rate", "indices", "a_tilde", "and", "b_tilde" ]
python
train
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_1/git/git_client_base.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_1/git/git_client_base.py#L2154-L2176
def update_pull_request(self, git_pull_request_to_update, repository_id, pull_request_id, project=None): """UpdatePullRequest. [Preview API] Update a pull request :param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content t...
[ "def", "update_pull_request", "(", "self", ",", "git_pull_request_to_update", ",", "repository_id", ",", "pull_request_id", ",", "project", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'...
UpdatePullRequest. [Preview API] Update a pull request :param :class:`<GitPullRequest> <azure.devops.v5_1.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content that should be updated. :param str repository_id: The repository ID of the pull request's target branch. ...
[ "UpdatePullRequest", ".", "[", "Preview", "API", "]", "Update", "a", "pull", "request", ":", "param", ":", "class", ":", "<GitPullRequest", ">", "<azure", ".", "devops", ".", "v5_1", ".", "git", ".", "models", ".", "GitPullRequest", ">", "git_pull_request_to...
python
train
google/grr
grr/core/grr_response_core/lib/communicator.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/communicator.py#L322-L399
def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3): """Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload...
[ "def", "EncodeMessages", "(", "self", ",", "message_list", ",", "result", ",", "destination", "=", "None", ",", "timestamp", "=", "None", ",", "api_version", "=", "3", ")", ":", "if", "api_version", "not", "in", "[", "3", "]", ":", "raise", "RuntimeError...
Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue which will be filled in. destination: The CN of the remote system...
[ "Accepts", "a", "list", "of", "messages", "and", "encodes", "for", "transmission", "." ]
python
train
chimera0/accel-brain-code
Automatic-Summarization/pysummarization/nlp_base.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Automatic-Summarization/pysummarization/nlp_base.py#L21-L26
def set_tokenizable_doc(self, value): ''' setter ''' if isinstance(value, TokenizableDoc): self.__tokenizable_doc = value else: raise TypeError()
[ "def", "set_tokenizable_doc", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "TokenizableDoc", ")", ":", "self", ".", "__tokenizable_doc", "=", "value", "else", ":", "raise", "TypeError", "(", ")" ]
setter
[ "setter" ]
python
train
apache/airflow
airflow/utils/log/gcs_task_handler.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/gcs_task_handler.py#L166-L177
def parse_gcs_url(gsurl): """ Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob. """ parsed_url = urlparse(gsurl) if not parsed_url.netloc: raise AirflowException('Please provide a bucket name...
[ "def", "parse_gcs_url", "(", "gsurl", ")", ":", "parsed_url", "=", "urlparse", "(", "gsurl", ")", "if", "not", "parsed_url", ".", "netloc", ":", "raise", "AirflowException", "(", "'Please provide a bucket name'", ")", "else", ":", "bucket", "=", "parsed_url", ...
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob.
[ "Given", "a", "Google", "Cloud", "Storage", "URL", "(", "gs", ":", "//", "<bucket", ">", "/", "<blob", ">", ")", "returns", "a", "tuple", "containing", "the", "corresponding", "bucket", "and", "blob", "." ]
python
test
openstack/networking-cisco
networking_cisco/apps/saf/server/cisco_dfa_rest.py
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L106-L119
def set_segmentid_range(self, orchestrator_id, segid_min, segid_max): """set segment id range in DCNM. """ url = self._segmentid_ranges_url payload = {'orchestratorId': orchestrator_id, 'segmentIdRanges': "%s-%s" % (segid_min, segid_max)} res = self._send_request('P...
[ "def", "set_segmentid_range", "(", "self", ",", "orchestrator_id", ",", "segid_min", ",", "segid_max", ")", ":", "url", "=", "self", ".", "_segmentid_ranges_url", "payload", "=", "{", "'orchestratorId'", ":", "orchestrator_id", ",", "'segmentIdRanges'", ":", "\"%s...
set segment id range in DCNM.
[ "set", "segment", "id", "range", "in", "DCNM", "." ]
python
train
swharden/PyOriginTools
PyOriginTools/highlevel.py
https://github.com/swharden/PyOriginTools/blob/536fb8e11234ffdc27e26b1800e0358179ca7d26/PyOriginTools/highlevel.py#L318-L405
def sheetToHTML(sheet): """ Put 2d numpy data into a temporary HTML file. This is a hack, copy/pasted from an earlier version of this software. It is very messy, but works great! Good enough for me. """ assert "SHEET" in str(type(sheet)) #data,names=None,units=None,bookName=None,sheetName=N...
[ "def", "sheetToHTML", "(", "sheet", ")", ":", "assert", "\"SHEET\"", "in", "str", "(", "type", "(", "sheet", ")", ")", "#data,names=None,units=None,bookName=None,sheetName=None,xCol=None", "#sheet=OR.SHEET()", "data", "=", "sheet", ".", "data", "names", "=", "sheet"...
Put 2d numpy data into a temporary HTML file. This is a hack, copy/pasted from an earlier version of this software. It is very messy, but works great! Good enough for me.
[ "Put", "2d", "numpy", "data", "into", "a", "temporary", "HTML", "file", ".", "This", "is", "a", "hack", "copy", "/", "pasted", "from", "an", "earlier", "version", "of", "this", "software", ".", "It", "is", "very", "messy", "but", "works", "great!", "Go...
python
train
nickmckay/LiPD-utilities
Python/lipd/timeseries.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/timeseries.py#L69-L78
def _extract_fund(l, _root): """ Creates flat funding dictionary. :param list l: Funding entries """ logger_ts.info("enter _extract_funding") for idx, i in enumerate(l): for k, v in i.items(): _root['funding' + str(idx + 1) + '_' + k] = v return _root
[ "def", "_extract_fund", "(", "l", ",", "_root", ")", ":", "logger_ts", ".", "info", "(", "\"enter _extract_funding\"", ")", "for", "idx", ",", "i", "in", "enumerate", "(", "l", ")", ":", "for", "k", ",", "v", "in", "i", ".", "items", "(", ")", ":",...
Creates flat funding dictionary. :param list l: Funding entries
[ "Creates", "flat", "funding", "dictionary", ".", ":", "param", "list", "l", ":", "Funding", "entries" ]
python
train
google/grr
grr/server/grr_response_server/maintenance_utils.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/maintenance_utils.py#L40-L83
def UploadSignedConfigBlob(content, aff4_path, client_context=None, limit=None, token=None): """Upload a signed blob into the datastore. Args: content: File content to upload. aff4_path: aff4 path to...
[ "def", "UploadSignedConfigBlob", "(", "content", ",", "aff4_path", ",", "client_context", "=", "None", ",", "limit", "=", "None", ",", "token", "=", "None", ")", ":", "if", "limit", "is", "None", ":", "limit", "=", "config", ".", "CONFIG", "[", "\"Datast...
Upload a signed blob into the datastore. Args: content: File content to upload. aff4_path: aff4 path to upload to. client_context: The configuration contexts to use. limit: The maximum size of the chunk to use. token: A security token. Raises: IOError: On failure to write.
[ "Upload", "a", "signed", "blob", "into", "the", "datastore", "." ]
python
train
pseudo-lang/pseudo
pseudo/api_translator.py
https://github.com/pseudo-lang/pseudo/blob/d0856d13e01a646156d3363f8c1bf352e6ea6315/pseudo/api_translator.py#L248-L287
def _expand_api(self, api, receiver, args, pseudo_type, equivalent): ''' the heart of api translation dsl function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg ''' if call...
[ "def", "_expand_api", "(", "self", ",", "api", ",", "receiver", ",", "args", ",", "pseudo_type", ",", "equivalent", ")", ":", "if", "callable", "(", "api", ")", ":", "if", "receiver", ":", "return", "api", "(", "receiver", ",", "*", "(", "args", "+",...
the heart of api translation dsl function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg
[ "the", "heart", "of", "api", "translation", "dsl" ]
python
train
sirfoga/pyhal
hal/meta/attributes.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/meta/attributes.py#L83-L93
def get_classes(self): """Finds classes in file :return: list of top-level classes """ instances = self._get_instances(ast.ClassDef) instances = [ PyClass(instance, self.package) for instance in instances ] return instances
[ "def", "get_classes", "(", "self", ")", ":", "instances", "=", "self", ".", "_get_instances", "(", "ast", ".", "ClassDef", ")", "instances", "=", "[", "PyClass", "(", "instance", ",", "self", ".", "package", ")", "for", "instance", "in", "instances", "]"...
Finds classes in file :return: list of top-level classes
[ "Finds", "classes", "in", "file" ]
python
train
rwl/pylon
pylon/dc_pf.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/dc_pf.py#L126-L159
def _get_v_angle(self, case, B, v_angle_guess, p_businj, iref): """ Calculates the voltage phase angles. """ buses = case.connected_buses pv_idxs = [bus._i for bus in buses if bus.type == PV] pq_idxs = [bus._i for bus in buses if bus.type == PQ] pvpq_idxs = pv_idxs + pq_...
[ "def", "_get_v_angle", "(", "self", ",", "case", ",", "B", ",", "v_angle_guess", ",", "p_businj", ",", "iref", ")", ":", "buses", "=", "case", ".", "connected_buses", "pv_idxs", "=", "[", "bus", ".", "_i", "for", "bus", "in", "buses", "if", "bus", "....
Calculates the voltage phase angles.
[ "Calculates", "the", "voltage", "phase", "angles", "." ]
python
train
pylast/pylast
src/pylast/__init__.py
https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L2671-L2678
def _retrieve_page(self, page_index): """Returns the node of matches to be processed""" params = self._get_params() params["page"] = str(page_index) doc = self._request(self._ws_prefix + ".search", True, params) return doc.getElementsByTagName(self._ws_prefix + "matches")[0]
[ "def", "_retrieve_page", "(", "self", ",", "page_index", ")", ":", "params", "=", "self", ".", "_get_params", "(", ")", "params", "[", "\"page\"", "]", "=", "str", "(", "page_index", ")", "doc", "=", "self", ".", "_request", "(", "self", ".", "_ws_pref...
Returns the node of matches to be processed
[ "Returns", "the", "node", "of", "matches", "to", "be", "processed" ]
python
train
LIVVkit/LIVVkit
livvkit/util/elements.py
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/elements.py#L261-L294
def image(title, desc, image_name, group=None, height=None): """ Builds an image element. Image elements are primarily created and then wrapped into an image gallery element. This is not required behavior, however and it's independent usage should be allowed depending on the behavior required. ...
[ "def", "image", "(", "title", ",", "desc", ",", "image_name", ",", "group", "=", "None", ",", "height", "=", "None", ")", ":", "ie", "=", "{", "'Type'", ":", "'Image'", ",", "'Title'", ":", "title", ",", "'Description'", ":", "desc", ",", "'Plot File...
Builds an image element. Image elements are primarily created and then wrapped into an image gallery element. This is not required behavior, however and it's independent usage should be allowed depending on the behavior required. The Javascript will search for the `image_name` in the component's ...
[ "Builds", "an", "image", "element", ".", "Image", "elements", "are", "primarily", "created", "and", "then", "wrapped", "into", "an", "image", "gallery", "element", ".", "This", "is", "not", "required", "behavior", "however", "and", "it", "s", "independent", ...
python
train
abingham/spor
src/spor/cli.py
https://github.com/abingham/spor/blob/673c8c36c99a4b9ea882f002bfb529f1eca89126/src/spor/cli.py#L191-L207
def status_handler(args): """usage: {program} status [<path>] Validate the anchors in the current repository. """ repo = _open_repo(args) for anchor_id, anchor in repo.items(): diff_lines = get_anchor_diff(anchor) if diff_lines: print('{} {}:{} out-of-date'.format( ...
[ "def", "status_handler", "(", "args", ")", ":", "repo", "=", "_open_repo", "(", "args", ")", "for", "anchor_id", ",", "anchor", "in", "repo", ".", "items", "(", ")", ":", "diff_lines", "=", "get_anchor_diff", "(", "anchor", ")", "if", "diff_lines", ":", ...
usage: {program} status [<path>] Validate the anchors in the current repository.
[ "usage", ":", "{", "program", "}", "status", "[", "<path", ">", "]" ]
python
train
Chilipp/psyplot
psyplot/plotter.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L2085-L2101
def _set_rc(self): """Method to set the rcparams and defaultParams for this plotter""" base_str = self._get_rc_strings() # to make sure that the '.' is not interpreted as a regex pattern, # we specify the pattern_base by ourselves pattern_base = map(lambda s: s.replace('.', '\.')...
[ "def", "_set_rc", "(", "self", ")", ":", "base_str", "=", "self", ".", "_get_rc_strings", "(", ")", "# to make sure that the '.' is not interpreted as a regex pattern,", "# we specify the pattern_base by ourselves", "pattern_base", "=", "map", "(", "lambda", "s", ":", "s"...
Method to set the rcparams and defaultParams for this plotter
[ "Method", "to", "set", "the", "rcparams", "and", "defaultParams", "for", "this", "plotter" ]
python
train
fermiPy/fermipy
fermipy/ltcube.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/ltcube.py#L239-L245
def create_empty(cls, tstart, tstop, fill=0.0, nside=64): """Create an empty livetime cube.""" cth_edges = np.linspace(0, 1.0, 41) domega = utils.edge_to_width(cth_edges) * 2.0 * np.pi hpx = HPX(nside, True, 'CEL', ebins=cth_edges) data = np.ones((len(cth_edges) - 1, hpx.npix)) *...
[ "def", "create_empty", "(", "cls", ",", "tstart", ",", "tstop", ",", "fill", "=", "0.0", ",", "nside", "=", "64", ")", ":", "cth_edges", "=", "np", ".", "linspace", "(", "0", ",", "1.0", ",", "41", ")", "domega", "=", "utils", ".", "edge_to_width",...
Create an empty livetime cube.
[ "Create", "an", "empty", "livetime", "cube", "." ]
python
train
singnet/snet-cli
snet_cli/commands.py
https://github.com/singnet/snet-cli/blob/1b5ac98cb9a64211c861ead9fcfe6208f2749032/snet_cli/commands.py#L541-L567
def list_my(self): """ Find organization that has the current identity as the owner or as the member """ org_list = self.call_contract_command("Registry", "listOrganizations", []) rez_owner = [] rez_member = [] for idx, org_id in enumerate(org_list): (found, org_id,...
[ "def", "list_my", "(", "self", ")", ":", "org_list", "=", "self", ".", "call_contract_command", "(", "\"Registry\"", ",", "\"listOrganizations\"", ",", "[", "]", ")", "rez_owner", "=", "[", "]", "rez_member", "=", "[", "]", "for", "idx", ",", "org_id", "...
Find organization that has the current identity as the owner or as the member
[ "Find", "organization", "that", "has", "the", "current", "identity", "as", "the", "owner", "or", "as", "the", "member" ]
python
train
polysquare/polysquare-generic-file-linter
polysquarelinter/spelling.py
https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/spelling.py#L129-L159
def _split_line_with_offsets(line): """Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punctuation from a line (so parenthesis preceded or succeeded by spaces, periods, etc) and then splitting on spaces. """ for delimiter in r...
[ "def", "_split_line_with_offsets", "(", "line", ")", ":", "for", "delimiter", "in", "re", ".", "finditer", "(", "r\"[\\.,:\\;](?![^\\s])\"", ",", "line", ")", ":", "span", "=", "delimiter", ".", "span", "(", ")", "line", "=", "line", "[", ":", "span", "[...
Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punctuation from a line (so parenthesis preceded or succeeded by spaces, periods, etc) and then splitting on spaces.
[ "Split", "a", "line", "by", "delimiter", "but", "yield", "tuples", "of", "word", "and", "offset", "." ]
python
train
ghukill/pyfc4
pyfc4/models.py
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L1455-L1474
def parents(self, as_resources=False): ''' method to return hierarchical parents of this resource Args: as_resources (bool): if True, opens each as appropriate resource type instead of return URI only Returns: (list): list of resources ''' parents = [o for s,p,o in self.rdf.graph.triples((None, se...
[ "def", "parents", "(", "self", ",", "as_resources", "=", "False", ")", ":", "parents", "=", "[", "o", "for", "s", ",", "p", ",", "o", "in", "self", ".", "rdf", ".", "graph", ".", "triples", "(", "(", "None", ",", "self", ".", "rdf", ".", "prefi...
method to return hierarchical parents of this resource Args: as_resources (bool): if True, opens each as appropriate resource type instead of return URI only Returns: (list): list of resources
[ "method", "to", "return", "hierarchical", "parents", "of", "this", "resource" ]
python
train
coins13/twins
twins/twins.py
https://github.com/coins13/twins/blob/d66cc850007a25f01812a9d8c7e3efe64a631ca2/twins/twins.py#L308-L331
def get_achievements_summary (self): """ 履修成績要約の取得 (累計)""" r = self.req("SIW0001200-flow") # XXX ret = {} k = "" for d in pq(r.text)("td"): if d.text is None: continue if k != "": # 全角英字ダメゼッタイ if k =...
[ "def", "get_achievements_summary", "(", "self", ")", ":", "r", "=", "self", ".", "req", "(", "\"SIW0001200-flow\"", ")", "# XXX", "ret", "=", "{", "}", "k", "=", "\"\"", "for", "d", "in", "pq", "(", "r", ".", "text", ")", "(", "\"td\"", ")", ":", ...
履修成績要約の取得 (累計)
[ "履修成績要約の取得", "(", "累計", ")" ]
python
train
BernardFW/bernard
src/bernard/storage/context/base.py
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/context/base.py#L125-L173
def inject(self, require: Optional[List[Text]] = None, fail: Text = 'missing_context', var_name: Text = 'context'): """ This is a decorator intended to be used on states (and actually only work on state handlers). The `require` argument is a ...
[ "def", "inject", "(", "self", ",", "require", ":", "Optional", "[", "List", "[", "Text", "]", "]", "=", "None", ",", "fail", ":", "Text", "=", "'missing_context'", ",", "var_name", ":", "Text", "=", "'context'", ")", ":", "def", "decorator", "(", "fu...
This is a decorator intended to be used on states (and actually only work on state handlers). The `require` argument is a list of keys to be checked in the context. If at least one of them is missing, then instead of calling the handler another method will be called. By default the meth...
[ "This", "is", "a", "decorator", "intended", "to", "be", "used", "on", "states", "(", "and", "actually", "only", "work", "on", "state", "handlers", ")", "." ]
python
train
learningequality/ricecooker
ricecooker/classes/nodes.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/classes/nodes.py#L134-L151
def process_files(self): """ Processes all the files associated with this Node. Files are downloaded if not present in the local storage. Creates and processes a NodeFile containing this Node's metadata. :return: A list of names of all the processed files. """ file_names ...
[ "def", "process_files", "(", "self", ")", ":", "file_names", "=", "[", "]", "for", "f", "in", "self", ".", "files", ":", "file_names", ".", "append", "(", "f", ".", "process_file", "(", ")", ")", "if", "not", "self", ".", "has_thumbnail", "(", ")", ...
Processes all the files associated with this Node. Files are downloaded if not present in the local storage. Creates and processes a NodeFile containing this Node's metadata. :return: A list of names of all the processed files.
[ "Processes", "all", "the", "files", "associated", "with", "this", "Node", ".", "Files", "are", "downloaded", "if", "not", "present", "in", "the", "local", "storage", ".", "Creates", "and", "processes", "a", "NodeFile", "containing", "this", "Node", "s", "met...
python
train
tomprince/txgithub
txgithub/api.py
https://github.com/tomprince/txgithub/blob/3bd5eebb25db013e2193e6a102a91049f356710d/txgithub/api.py#L256-L263
def getStatuses(self, repo_user, repo_name, sha): """ :param sha: Full sha to list the statuses from. :return: A defered with the result from GitHub. """ return self.api.makeRequest( ['repos', repo_user, repo_name, 'statuses', sha], method='GET')
[ "def", "getStatuses", "(", "self", ",", "repo_user", ",", "repo_name", ",", "sha", ")", ":", "return", "self", ".", "api", ".", "makeRequest", "(", "[", "'repos'", ",", "repo_user", ",", "repo_name", ",", "'statuses'", ",", "sha", "]", ",", "method", "...
:param sha: Full sha to list the statuses from. :return: A defered with the result from GitHub.
[ ":", "param", "sha", ":", "Full", "sha", "to", "list", "the", "statuses", "from", ".", ":", "return", ":", "A", "defered", "with", "the", "result", "from", "GitHub", "." ]
python
train
saltstack/salt
salt/states/saltsupport.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/saltsupport.py#L115-L139
def collected(self, group, filename=None, host=None, location=None, move=True, all=True): ''' Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return: ...
[ "def", "collected", "(", "self", ",", "group", ",", "filename", "=", "None", ",", "host", "=", "None", ",", "location", "=", "None", ",", "move", "=", "True", ",", "all", "=", "True", ")", ":", "ret", "=", "{", "'name'", ":", "'support.collected'", ...
Sync archives to a central place. :param name: :param group: :param filename: :param host: :param location: :param move: :param all: :return:
[ "Sync", "archives", "to", "a", "central", "place", "." ]
python
train
kensho-technologies/graphql-compiler
graphql_compiler/compiler/compiler_frontend.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/compiler_frontend.py#L217-L244
def _process_output_source_directive(schema, current_schema_type, ast, location, context, local_unique_directives): """Process the output_source directive, modifying the context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library ...
[ "def", "_process_output_source_directive", "(", "schema", ",", "current_schema_type", ",", "ast", ",", "location", ",", "context", ",", "local_unique_directives", ")", ":", "# The 'ast' variable is only for function signature uniformity, and is currently not used.", "output_source_...
Process the output_source directive, modifying the context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library locati...
[ "Process", "the", "output_source", "directive", "modifying", "the", "context", "as", "appropriate", "." ]
python
train
sdispater/orator
orator/migrations/migrator.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/migrations/migrator.py#L53-L69
def run_migration_list(self, path, migrations, pretend=False): """ Run a list of migrations. :type migrations: list :type pretend: bool """ if not migrations: self._note("<info>Nothing to migrate</info>") return batch = self._repository...
[ "def", "run_migration_list", "(", "self", ",", "path", ",", "migrations", ",", "pretend", "=", "False", ")", ":", "if", "not", "migrations", ":", "self", ".", "_note", "(", "\"<info>Nothing to migrate</info>\"", ")", "return", "batch", "=", "self", ".", "_re...
Run a list of migrations. :type migrations: list :type pretend: bool
[ "Run", "a", "list", "of", "migrations", "." ]
python
train
arista-eosplus/pyeapi
pyeapi/api/vrrp.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/vrrp.py#L626-L694
def set_secondary_ips(self, name, vrid, secondary_ips, run=True): """Configure the secondary_ip property of the vrrp Notes: set_secondary_ips takes a list of secondary ip addresses which are to be set on the virtal router. An empty list will remove any existing secon...
[ "def", "set_secondary_ips", "(", "self", ",", "name", ",", "vrid", ",", "secondary_ips", ",", "run", "=", "True", ")", ":", "cmds", "=", "[", "]", "# Get the current set of tracks defined for the vrrp", "curr_sec_ips", "=", "[", "]", "vrrps", "=", "self", ".",...
Configure the secondary_ip property of the vrrp Notes: set_secondary_ips takes a list of secondary ip addresses which are to be set on the virtal router. An empty list will remove any existing secondary ip addresses from the vrrp. A list containing addresses will...
[ "Configure", "the", "secondary_ip", "property", "of", "the", "vrrp" ]
python
train
macacajs/wd.py
macaca/asserters.py
https://github.com/macacajs/wd.py/blob/6d3c52060013e01a67cd52b68b5230b387427bad/macaca/asserters.py#L9-L22
def is_displayed(target): """Assert whether the target is displayed Args: target(WebElement): WebElement Object. Returns: Return True if the element is displayed or return False otherwise. """ is_displayed = getattr(target, 'is_displayed', None) if not is_displayed or not calla...
[ "def", "is_displayed", "(", "target", ")", ":", "is_displayed", "=", "getattr", "(", "target", ",", "'is_displayed'", ",", "None", ")", "if", "not", "is_displayed", "or", "not", "callable", "(", "is_displayed", ")", ":", "raise", "TypeError", "(", "'Target h...
Assert whether the target is displayed Args: target(WebElement): WebElement Object. Returns: Return True if the element is displayed or return False otherwise.
[ "Assert", "whether", "the", "target", "is", "displayed" ]
python
valid
cox-labs/perseuspy
perseuspy/dependent_peptides.py
https://github.com/cox-labs/perseuspy/blob/3809c1bd46512605f9e7ca7f97e026e4940ed604/perseuspy/dependent_peptides.py#L42-L51
def count(args): """ count occurences in a list of lists >>> count([['a','b'],['a']]) defaultdict(int, {'a' : 2, 'b' : 1}) """ counts = defaultdict(int) for arg in args: for item in arg: counts[item] = counts[item] + 1 return counts
[ "def", "count", "(", "args", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "for", "arg", "in", "args", ":", "for", "item", "in", "arg", ":", "counts", "[", "item", "]", "=", "counts", "[", "item", "]", "+", "1", "return", "counts" ]
count occurences in a list of lists >>> count([['a','b'],['a']]) defaultdict(int, {'a' : 2, 'b' : 1})
[ "count", "occurences", "in", "a", "list", "of", "lists", ">>>", "count", "(", "[[", "a", "b", "]", "[", "a", "]]", ")", "defaultdict", "(", "int", "{", "a", ":", "2", "b", ":", "1", "}", ")" ]
python
train
airspeed-velocity/asv
asv/extern/asizeof.py
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L740-L750
def _len_int(obj): '''Length of multi-precision int (aka long) in digits. ''' if obj: n, i = 1, abs(obj) if i > _digitmax: # no log(x[, base]) in Python 2.2 n += int(log(i) * _digitlog) else: # zero n = 0 return n
[ "def", "_len_int", "(", "obj", ")", ":", "if", "obj", ":", "n", ",", "i", "=", "1", ",", "abs", "(", "obj", ")", "if", "i", ">", "_digitmax", ":", "# no log(x[, base]) in Python 2.2", "n", "+=", "int", "(", "log", "(", "i", ")", "*", "_digitlog", ...
Length of multi-precision int (aka long) in digits.
[ "Length", "of", "multi", "-", "precision", "int", "(", "aka", "long", ")", "in", "digits", "." ]
python
train
juanifioren/django-oidc-provider
oidc_provider/lib/utils/token.py
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/token.py#L151-L167
def get_client_alg_keys(client): """ Takes a client and returns the set of keys associated with it. Returns a list of keys. """ if client.jwt_alg == 'RS256': keys = [] for rsakey in RSAKey.objects.all(): keys.append(jwk_RSAKey(key=importKey(rsakey.key), kid=rsakey.kid)) ...
[ "def", "get_client_alg_keys", "(", "client", ")", ":", "if", "client", ".", "jwt_alg", "==", "'RS256'", ":", "keys", "=", "[", "]", "for", "rsakey", "in", "RSAKey", ".", "objects", ".", "all", "(", ")", ":", "keys", ".", "append", "(", "jwk_RSAKey", ...
Takes a client and returns the set of keys associated with it. Returns a list of keys.
[ "Takes", "a", "client", "and", "returns", "the", "set", "of", "keys", "associated", "with", "it", ".", "Returns", "a", "list", "of", "keys", "." ]
python
train
IS-ENES-Data/esgf-pid
esgfpid/utils/logutils.py
https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/utils/logutils.py#L29-L38
def loginfo(logger, msg, *args, **kwargs): ''' Logs messages as INFO, unless esgfpid.defaults.LOG_INFO_TO_DEBUG, (then it logs messages as DEBUG). ''' if esgfpid.defaults.LOG_INFO_TO_DEBUG: logger.debug(msg, *args, **kwargs) else: logger.info(msg, *args, **kwargs)
[ "def", "loginfo", "(", "logger", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "esgfpid", ".", "defaults", ".", "LOG_INFO_TO_DEBUG", ":", "logger", ".", "debug", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ...
Logs messages as INFO, unless esgfpid.defaults.LOG_INFO_TO_DEBUG, (then it logs messages as DEBUG).
[ "Logs", "messages", "as", "INFO", "unless", "esgfpid", ".", "defaults", ".", "LOG_INFO_TO_DEBUG", "(", "then", "it", "logs", "messages", "as", "DEBUG", ")", "." ]
python
train