Unnamed: 0
int64
0
10k
repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
5
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
100
30.3k
language
stringclasses
1 value
func_code_string
stringlengths
100
30.3k
func_code_tokens
stringlengths
138
33.2k
func_documentation_string
stringlengths
1
15k
func_documentation_tokens
stringlengths
5
5.14k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
8,300
ultrabug/py3status
py3status/parse_config.py
ConfigParser.unicode_escape_sequence_fix
def unicode_escape_sequence_fix(self, value): """ It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394 ...
python
def unicode_escape_sequence_fix(self, value): """ It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394 ...
['def', 'unicode_escape_sequence_fix', '(', 'self', ',', 'value', ')', ':', 'def', 'fix_fn', '(', 'match', ')', ':', "# we don't escape an escaped backslash", 'if', 'match', '.', 'group', '(', '0', ')', '==', 'r"\\\\"', ':', 'return', 'r"\\\\"', 'return', 'match', '.', 'group', '(', '0', ')', '.', 'encode', '(', '"utf-...
It is possible to define unicode characters in the config either as the actual utf-8 character or using escape sequences the following all will show the Greek delta character. Δ \N{GREEK CAPITAL LETTER DELTA} \U00000394 \u0394
['It', 'is', 'possible', 'to', 'define', 'unicode', 'characters', 'in', 'the', 'config', 'either', 'as', 'the', 'actual', 'utf', '-', '8', 'character', 'or', 'using', 'escape', 'sequences', 'the', 'following', 'all', 'will', 'show', 'the', 'Greek', 'delta', 'character', '.', 'Δ', '\\', 'N', '{', 'GREEK', 'CAPITAL', 'LE...
train
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/parse_config.py#L305-L319
8,301
jldantas/libmft
libmft/attribute.py
_from_binary_idx_root
def _from_binary_idx_root(cls, binary_stream): """See base class.""" ''' Attribute type - 4 Collation rule - 4 Bytes per index record - 4 Clusters per index record - 1 Padding - 3 ''' attr_type, collation_rule, b_per_idx_r, c_per_idx_r = cls._REPR.unpack(binary_stream[:cl...
python
def _from_binary_idx_root(cls, binary_stream): """See base class.""" ''' Attribute type - 4 Collation rule - 4 Bytes per index record - 4 Clusters per index record - 1 Padding - 3 ''' attr_type, collation_rule, b_per_idx_r, c_per_idx_r = cls._REPR.unpack(binary_stream[:cl...
['def', '_from_binary_idx_root', '(', 'cls', ',', 'binary_stream', ')', ':', "''' Attribute type - 4\n Collation rule - 4\n Bytes per index record - 4\n Clusters per index record - 1\n Padding - 3\n '''", 'attr_type', ',', 'collation_rule', ',', 'b_per_idx_r', ',', 'c_per_idx_r', '=', 'cl...
See base class.
['See', 'base', 'class', '.']
train
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/attribute.py#L1352-L1380
8,302
sveetch/boussole
boussole/compiler.py
SassCompileHelper.write_content
def write_content(self, content, destination): """ Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. ...
python
def write_content(self, content, destination): """ Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. ...
['def', 'write_content', '(', 'self', ',', 'content', ',', 'destination', ')', ':', 'directory', '=', 'os', '.', 'path', '.', 'dirname', '(', 'destination', ')', 'if', 'directory', 'and', 'not', 'os', '.', 'path', '.', 'exists', '(', 'directory', ')', ':', 'os', '.', 'makedirs', '(', 'directory', ')', 'with', 'io', '.'...
Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. destination (str): Destination path for target file. Ret...
['Write', 'given', 'content', 'to', 'destination', 'path', '.']
train
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/compiler.py#L82-L104
8,303
guzzle/guzzle_sphinx_theme
guzzle_sphinx_theme/__init__.py
create_sitemap
def create_sitemap(app, exception): """Generates the sitemap.xml from the collected HTML page links""" if (not app.config['html_theme_options'].get('base_url', '') or exception is not None or not app.sitemap_links): return filename = app.outdir + "/sitemap.xml" print("Gene...
python
def create_sitemap(app, exception): """Generates the sitemap.xml from the collected HTML page links""" if (not app.config['html_theme_options'].get('base_url', '') or exception is not None or not app.sitemap_links): return filename = app.outdir + "/sitemap.xml" print("Gene...
['def', 'create_sitemap', '(', 'app', ',', 'exception', ')', ':', 'if', '(', 'not', 'app', '.', 'config', '[', "'html_theme_options'", ']', '.', 'get', '(', "'base_url'", ',', "''", ')', 'or', 'exception', 'is', 'not', 'None', 'or', 'not', 'app', '.', 'sitemap_links', ')', ':', 'return', 'filename', '=', 'app', '.', 'o...
Generates the sitemap.xml from the collected HTML page links
['Generates', 'the', 'sitemap', '.', 'xml', 'from', 'the', 'collected', 'HTML', 'page', 'links']
train
https://github.com/guzzle/guzzle_sphinx_theme/blob/eefd45b79383b1b4aab1607444e41366fd1348a6/guzzle_sphinx_theme/__init__.py#L30-L47
8,304
huyingxi/Synonyms
synonyms/utils.py
any2unicode
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
python
def any2unicode(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, unicode): return text return unicode(text, encoding, errors=errors)
['def', 'any2unicode', '(', 'text', ',', 'encoding', '=', "'utf8'", ',', 'errors', '=', "'strict'", ')', ':', 'if', 'isinstance', '(', 'text', ',', 'unicode', ')', ':', 'return', 'text', 'return', 'unicode', '(', 'text', ',', 'encoding', ',', 'errors', '=', 'errors', ')']
Convert a string (bytestring in `encoding` or unicode), to unicode.
['Convert', 'a', 'string', '(', 'bytestring', 'in', 'encoding', 'or', 'unicode', ')', 'to', 'unicode', '.']
train
https://github.com/huyingxi/Synonyms/blob/fe7450d51d9ad825fdba86b9377da9dc76ae26a4/synonyms/utils.py#L233-L237
8,305
Kronuz/pyScss
yapps2.py
Parser._scan
def _scan(self, type): """ Returns the matched text, and moves to the next token """ tok = self._scanner.token(self._pos, frozenset([type])) if tok[2] != type: err = SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type)) err.p...
python
def _scan(self, type): """ Returns the matched text, and moves to the next token """ tok = self._scanner.token(self._pos, frozenset([type])) if tok[2] != type: err = SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to find " + type)) err.p...
['def', '_scan', '(', 'self', ',', 'type', ')', ':', 'tok', '=', 'self', '.', '_scanner', '.', 'token', '(', 'self', '.', '_pos', ',', 'frozenset', '(', '[', 'type', ']', ')', ')', 'if', 'tok', '[', '2', ']', '!=', 'type', ':', 'err', '=', 'SyntaxError', '(', '"SyntaxError[@ char %s: %s]"', '%', '(', 'repr', '(', 'tok'...
Returns the matched text, and moves to the next token
['Returns', 'the', 'matched', 'text', 'and', 'moves', 'to', 'the', 'next', 'token']
train
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L875-L885
8,306
quantumlib/Cirq
cirq/study/visualize.py
plot_state_histogram
def plot_state_histogram(result: trial_result.TrialResult) -> np.ndarray: """Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a singl...
python
def plot_state_histogram(result: trial_result.TrialResult) -> np.ndarray: """Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a singl...
['def', 'plot_state_histogram', '(', 'result', ':', 'trial_result', '.', 'TrialResult', ')', '->', 'np', '.', 'ndarray', ':', '# pyplot import is deferred because it requires a system dependency', "# (python3-tk) that `python -m pip install cirq` can't handle for the user.", '# This allows cirq to be usable without pyt...
Plot the state histogram from a single result with repetitions. States is a bitstring representation of all the qubit states in a single result. Currently this function assumes each measurement gate applies to only a single qubit. Args: result: The trial results to plot. Returns: ...
['Plot', 'the', 'state', 'histogram', 'from', 'a', 'single', 'result', 'with', 'repetitions', '.']
train
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/study/visualize.py#L22-L66
8,307
ribozz/sphinx-argparse
sphinxarg/markdown.py
block_quote
def block_quote(node): """ A block quote """ o = nodes.block_quote() o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
python
def block_quote(node): """ A block quote """ o = nodes.block_quote() o.line = node.sourcepos[0][0] for n in MarkDown(node): o += n return o
['def', 'block_quote', '(', 'node', ')', ':', 'o', '=', 'nodes', '.', 'block_quote', '(', ')', 'o', '.', 'line', '=', 'node', '.', 'sourcepos', '[', '0', ']', '[', '0', ']', 'for', 'n', 'in', 'MarkDown', '(', 'node', ')', ':', 'o', '+=', 'n', 'return', 'o']
A block quote
['A', 'block', 'quote']
train
https://github.com/ribozz/sphinx-argparse/blob/178672cd5c846440ff7ecd695e3708feea13e4b4/sphinxarg/markdown.py#L214-L222
8,308
pycontribs/pyrax
pyrax/cloudmonitoring.py
CloudMonitorCheck.get
def get(self): """Reloads the check with its current values.""" new = self.manager.get(self) if new: self._add_details(new._info)
python
def get(self): """Reloads the check with its current values.""" new = self.manager.get(self) if new: self._add_details(new._info)
['def', 'get', '(', 'self', ')', ':', 'new', '=', 'self', '.', 'manager', '.', 'get', '(', 'self', ')', 'if', 'new', ':', 'self', '.', '_add_details', '(', 'new', '.', '_info', ')']
Reloads the check with its current values.
['Reloads', 'the', 'check', 'with', 'its', 'current', 'values', '.']
train
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L789-L793
8,309
sorgerlab/indra
indra/sources/bel/rdf_processor.py
BelRdfProcessor.get_degenerate_statements
def get_degenerate_statements(self): """Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts. """ logger.info("Checking for 'degenerate' statements...\n") # Get rules of type protein X -> activity Y q_stmts = prefixes + """ ...
python
def get_degenerate_statements(self): """Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts. """ logger.info("Checking for 'degenerate' statements...\n") # Get rules of type protein X -> activity Y q_stmts = prefixes + """ ...
['def', 'get_degenerate_statements', '(', 'self', ')', ':', 'logger', '.', 'info', '(', '"Checking for \'degenerate\' statements...\\n"', ')', '# Get rules of type protein X -> activity Y', 'q_stmts', '=', 'prefixes', '+', '"""\n SELECT ?stmt\n WHERE {\n ?stmt a belvoc:Statement .\n...
Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts.
['Get', 'all', 'degenerate', 'BEL', 'statements', '.']
train
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/bel/rdf_processor.py#L774-L827
8,310
APSL/puput
puput/urls.py
get_entry_url
def get_entry_url(entry, blog_page, root_page): """ Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page. """ if root_page == blog_page: return reverse('entry_page_serve', kwargs={ 'year': entry.date.s...
python
def get_entry_url(entry, blog_page, root_page): """ Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page. """ if root_page == blog_page: return reverse('entry_page_serve', kwargs={ 'year': entry.date.s...
['def', 'get_entry_url', '(', 'entry', ',', 'blog_page', ',', 'root_page', ')', ':', 'if', 'root_page', '==', 'blog_page', ':', 'return', 'reverse', '(', "'entry_page_serve'", ',', 'kwargs', '=', '{', "'year'", ':', 'entry', '.', 'date', '.', 'strftime', '(', "'%Y'", ')', ',', "'month'", ':', 'entry', '.', 'date', '.',...
Get the entry url given and entry page a blog page instances. It will use an url or another depending if blog_page is the root page.
['Get', 'the', 'entry', 'url', 'given', 'and', 'entry', 'page', 'a', 'blog', 'page', 'instances', '.', 'It', 'will', 'use', 'an', 'url', 'or', 'another', 'depending', 'if', 'blog_page', 'is', 'the', 'root', 'page', '.']
train
https://github.com/APSL/puput/blob/c3294f6bb0dd784f881ce9e3089cbf40d0528e47/puput/urls.py#L63-L88
8,311
gplepage/vegas
setup.py
build_py.run
def run(self): """ Append version number to vegas/__init__.py """ with open('src/vegas/__init__.py', 'a') as vfile: vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION) _build_py.run(self)
python
def run(self): """ Append version number to vegas/__init__.py """ with open('src/vegas/__init__.py', 'a') as vfile: vfile.write("\n__version__ = '%s'\n" % VEGAS_VERSION) _build_py.run(self)
['def', 'run', '(', 'self', ')', ':', 'with', 'open', '(', "'src/vegas/__init__.py'", ',', "'a'", ')', 'as', 'vfile', ':', 'vfile', '.', 'write', '(', '"\\n__version__ = \'%s\'\\n"', '%', 'VEGAS_VERSION', ')', '_build_py', '.', 'run', '(', 'self', ')']
Append version number to vegas/__init__.py
['Append', 'version', 'number', 'to', 'vegas', '/', '__init__', '.', 'py']
train
https://github.com/gplepage/vegas/blob/537aaa35938d521bbf7479b2be69170b9282f544/setup.py#L43-L47
8,312
BerkeleyAutomation/autolab_core
autolab_core/random_variables.py
RandomVariable._preallocate_samples
def _preallocate_samples(self): """Preallocate samples for faster adaptive sampling. """ self.prealloc_samples_ = [] for i in range(self.num_prealloc_samples_): self.prealloc_samples_.append(self.sample())
python
def _preallocate_samples(self): """Preallocate samples for faster adaptive sampling. """ self.prealloc_samples_ = [] for i in range(self.num_prealloc_samples_): self.prealloc_samples_.append(self.sample())
['def', '_preallocate_samples', '(', 'self', ')', ':', 'self', '.', 'prealloc_samples_', '=', '[', ']', 'for', 'i', 'in', 'range', '(', 'self', '.', 'num_prealloc_samples_', ')', ':', 'self', '.', 'prealloc_samples_', '.', 'append', '(', 'self', '.', 'sample', '(', ')', ')']
Preallocate samples for faster adaptive sampling.
['Preallocate', 'samples', 'for', 'faster', 'adaptive', 'sampling', '.']
train
https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/random_variables.py#L30-L35
8,313
manns/pyspread
pyspread/src/gui/_toolbars.py
AttributesToolbar.OnTextColor
def OnTextColor(self, event): """Text color choice event handler""" color = event.GetValue().GetRGB() post_command_event(self, self.TextColorMsg, color=color)
python
def OnTextColor(self, event): """Text color choice event handler""" color = event.GetValue().GetRGB() post_command_event(self, self.TextColorMsg, color=color)
['def', 'OnTextColor', '(', 'self', ',', 'event', ')', ':', 'color', '=', 'event', '.', 'GetValue', '(', ')', '.', 'GetRGB', '(', ')', 'post_command_event', '(', 'self', ',', 'self', '.', 'TextColorMsg', ',', 'color', '=', 'color', ')']
Text color choice event handler
['Text', 'color', 'choice', 'event', 'handler']
train
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_toolbars.py#L1008-L1013
8,314
sailthru/sailthru-python-client
sailthru/sailthru_client.py
SailthruClient.stats_list
def stats_list(self, list=None, date=None, headers=None): """ Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat """ data = {'stat': 'list'} if list is not None: data['list'] = list ...
python
def stats_list(self, list=None, date=None, headers=None): """ Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat """ data = {'stat': 'list'} if list is not None: data['list'] = list ...
['def', 'stats_list', '(', 'self', ',', 'list', '=', 'None', ',', 'date', '=', 'None', ',', 'headers', '=', 'None', ')', ':', 'data', '=', '{', "'stat'", ':', "'list'", '}', 'if', 'list', 'is', 'not', 'None', ':', 'data', '[', "'list'", ']', '=', 'list', 'if', 'date', 'is', 'not', 'None', ':', 'data', '[', "'date'", ']...
Retrieve information about your subscriber counts on a particular list, on a particular day. http://docs.sailthru.com/api/stat
['Retrieve', 'information', 'about', 'your', 'subscriber', 'counts', 'on', 'a', 'particular', 'list', 'on', 'a', 'particular', 'day', '.', 'http', ':', '//', 'docs', '.', 'sailthru', '.', 'com', '/', 'api', '/', 'stat']
train
https://github.com/sailthru/sailthru-python-client/blob/22aa39ba0c5bddd7b8743e24ada331128c0f4f54/sailthru/sailthru_client.py#L517-L527
8,315
markpasc/pywhich
pywhich.py
identify_filepath
def identify_filepath(arg, real_path=None, show_directory=None, find_source=None, hide_init=None): """Discover and return the disk file path of the Python module named in `arg` by importing the module and returning its ``__file__`` attribute. If `find_source` is `True`, the named module is a ``pyc`` or...
python
def identify_filepath(arg, real_path=None, show_directory=None, find_source=None, hide_init=None): """Discover and return the disk file path of the Python module named in `arg` by importing the module and returning its ``__file__`` attribute. If `find_source` is `True`, the named module is a ``pyc`` or...
['def', 'identify_filepath', '(', 'arg', ',', 'real_path', '=', 'None', ',', 'show_directory', '=', 'None', ',', 'find_source', '=', 'None', ',', 'hide_init', '=', 'None', ')', ':', 'mod', '=', 'identify_module', '(', 'arg', ')', '# raises ModuleNotFound', 'try', ':', 'filename', '=', 'mod', '.', '__file__', 'except', ...
Discover and return the disk file path of the Python module named in `arg` by importing the module and returning its ``__file__`` attribute. If `find_source` is `True`, the named module is a ``pyc`` or ``pyo`` file, and a corresponding ``.py`` file exists on disk, the path to the ``.py`` file is return...
['Discover', 'and', 'return', 'the', 'disk', 'file', 'path', 'of', 'the', 'Python', 'module', 'named', 'in', 'arg', 'by', 'importing', 'the', 'module', 'and', 'returning', 'its', '__file__', 'attribute', '.']
train
https://github.com/markpasc/pywhich/blob/2c7cbe0d8a6789ede48c53f263872ceac5b67ca3/pywhich.py#L33-L80
8,316
saltstack/salt
salt/modules/k8s.py
_kput
def _kput(url, data): ''' put any object in kubernetes based on URL ''' # Prepare headers headers = {"Content-Type": "application/json"} # Make request ret = http.query(url, method='PUT', header_dict=headers, data=salt.utils.json.dumps(...
python
def _kput(url, data): ''' put any object in kubernetes based on URL ''' # Prepare headers headers = {"Content-Type": "application/json"} # Make request ret = http.query(url, method='PUT', header_dict=headers, data=salt.utils.json.dumps(...
['def', '_kput', '(', 'url', ',', 'data', ')', ':', '# Prepare headers', 'headers', '=', '{', '"Content-Type"', ':', '"application/json"', '}', '# Make request', 'ret', '=', 'http', '.', 'query', '(', 'url', ',', 'method', '=', "'PUT'", ',', 'header_dict', '=', 'headers', ',', 'data', '=', 'salt', '.', 'utils', '.', 'j...
put any object in kubernetes based on URL
['put', 'any', 'object', 'in', 'kubernetes', 'based', 'on', 'URL']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/k8s.py#L88-L102
8,317
saltstack/salt
salt/modules/mac_service.py
enabled
def enabled(name, runas=None): ''' Check if the specified service is enabled :param str name: The name of the service to look up :param str runas: User to run launchctl commands :return: True if the specified service enabled, otherwise False :rtype: bool CLI Example: .. code-block::...
python
def enabled(name, runas=None): ''' Check if the specified service is enabled :param str name: The name of the service to look up :param str runas: User to run launchctl commands :return: True if the specified service enabled, otherwise False :rtype: bool CLI Example: .. code-block::...
['def', 'enabled', '(', 'name', ',', 'runas', '=', 'None', ')', ':', "# Try to list the service. If it can't be listed, it's not enabled", 'try', ':', 'list_', '(', 'name', '=', 'name', ',', 'runas', '=', 'runas', ')', 'return', 'True', 'except', 'CommandExecutionError', ':', 'return', 'False']
Check if the specified service is enabled :param str name: The name of the service to look up :param str runas: User to run launchctl commands :return: True if the specified service enabled, otherwise False :rtype: bool CLI Example: .. code-block:: bash salt '*' service.enabled org...
['Check', 'if', 'the', 'specified', 'service', 'is', 'enabled']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_service.py#L571-L593
8,318
mrcagney/gtfstk
gtfstk/routes.py
build_route_timetable
def build_route_timetable( feed: "Feed", route_id: str, dates: List[str] ) -> DataFrame: """ Return a timetable for the given route and dates. Parameters ---------- feed : Feed route_id : string ID of a route in ``feed.routes`` dates : string or list A YYYYMMDD date stri...
python
def build_route_timetable( feed: "Feed", route_id: str, dates: List[str] ) -> DataFrame: """ Return a timetable for the given route and dates. Parameters ---------- feed : Feed route_id : string ID of a route in ``feed.routes`` dates : string or list A YYYYMMDD date stri...
['def', 'build_route_timetable', '(', 'feed', ':', '"Feed"', ',', 'route_id', ':', 'str', ',', 'dates', ':', 'List', '[', 'str', ']', ')', '->', 'DataFrame', ':', 'dates', '=', 'feed', '.', 'restrict_dates', '(', 'dates', ')', 'if', 'not', 'dates', ':', 'return', 'pd', '.', 'DataFrame', '(', ')', 't', '=', 'pd', '.', '...
Return a timetable for the given route and dates. Parameters ---------- feed : Feed route_id : string ID of a route in ``feed.routes`` dates : string or list A YYYYMMDD date string or list thereof Returns ------- DataFrame The columns are all those in ``feed.tri...
['Return', 'a', 'timetable', 'for', 'the', 'given', 'route', 'and', 'dates', '.']
train
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/routes.py#L772-L832
8,319
tjcsl/cslbot
cslbot/helpers/orm.py
setup_db
def setup_db(session, botconfig, confdir): """Sets up the database.""" Base.metadata.create_all(session.connection()) # If we're creating a fresh db, we don't need to worry about migrations. if not session.get_bind().has_table('alembic_version'): conf_obj = config.Config() conf_obj.set_m...
python
def setup_db(session, botconfig, confdir): """Sets up the database.""" Base.metadata.create_all(session.connection()) # If we're creating a fresh db, we don't need to worry about migrations. if not session.get_bind().has_table('alembic_version'): conf_obj = config.Config() conf_obj.set_m...
['def', 'setup_db', '(', 'session', ',', 'botconfig', ',', 'confdir', ')', ':', 'Base', '.', 'metadata', '.', 'create_all', '(', 'session', '.', 'connection', '(', ')', ')', "# If we're creating a fresh db, we don't need to worry about migrations.", 'if', 'not', 'session', '.', 'get_bind', '(', ')', '.', 'has_table', '...
Sets up the database.
['Sets', 'up', 'the', 'database', '.']
train
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/orm.py#L36-L50
8,320
playpauseandstop/rororo
rororo/schemas/validators.py
extend_with_default
def extend_with_default(validator_class: Any) -> Any: """Append defaults from schema to instance need to be validated. :param validator_class: Apply the change for given validator class. """ validate_properties = validator_class.VALIDATORS['properties'] def set_defaults(validator: Any, ...
python
def extend_with_default(validator_class: Any) -> Any: """Append defaults from schema to instance need to be validated. :param validator_class: Apply the change for given validator class. """ validate_properties = validator_class.VALIDATORS['properties'] def set_defaults(validator: Any, ...
['def', 'extend_with_default', '(', 'validator_class', ':', 'Any', ')', '->', 'Any', ':', 'validate_properties', '=', 'validator_class', '.', 'VALIDATORS', '[', "'properties'", ']', 'def', 'set_defaults', '(', 'validator', ':', 'Any', ',', 'properties', ':', 'dict', ',', 'instance', ':', 'dict', ',', 'schema', ':', 'di...
Append defaults from schema to instance need to be validated. :param validator_class: Apply the change for given validator class.
['Append', 'defaults', 'from', 'schema', 'to', 'instance', 'need', 'to', 'be', 'validated', '.']
train
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/validators.py#L33-L53
8,321
pydata/xarray
xarray/core/resample_cftime.py
_adjust_bin_edges
def _adjust_bin_edges(datetime_bins, offset, closed, index, labels): """This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with ...
python
def _adjust_bin_edges(datetime_bins, offset, closed, index, labels): """This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with ...
['def', '_adjust_bin_edges', '(', 'datetime_bins', ',', 'offset', ',', 'closed', ',', 'index', ',', 'labels', ')', ':', 'is_super_daily', '=', '(', 'isinstance', '(', 'offset', ',', '(', 'MonthEnd', ',', 'QuarterEnd', ',', 'YearEnd', ')', ')', 'or', '(', 'isinstance', '(', 'offset', ',', 'Day', ')', 'and', 'offset', '....
This is required for determining the bin edges resampling with daily frequencies greater than one day, month end, and year end frequencies. Consider the following example. Let's say you want to downsample the time series with the following coordinates to month end frequency: CFTimeIndex([2000-01-...
['This', 'is', 'required', 'for', 'determining', 'the', 'bin', 'edges', 'resampling', 'with', 'daily', 'frequencies', 'greater', 'than', 'one', 'day', 'month', 'end', 'and', 'year', 'end', 'frequencies', '.']
train
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/resample_cftime.py#L167-L212
8,322
ckan/ckan-service-provider
ckanserviceprovider/db.py
mark_job_as_errored
def mark_job_as_errored(job_id, error_object): """Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value i...
python
def mark_job_as_errored(job_id, error_object): """Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value i...
['def', 'mark_job_as_errored', '(', 'job_id', ',', 'error_object', ')', ':', 'update_dict', '=', '{', '"status"', ':', '"error"', ',', '"error"', ':', 'error_object', ',', '"finished_timestamp"', ':', 'datetime', '.', 'datetime', '.', 'now', '(', ')', ',', '}', '_update_job', '(', 'job_id', ',', 'update_dict', ')']
Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value is a string
['Mark', 'a', 'job', 'as', 'failed', 'with', 'an', 'error', '.']
train
https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L397-L413
8,323
ArchiveTeam/wpull
wpull/database/sqltable.py
BaseSQLURLTable._session
def _session(self): """Provide a transactional scope around a series of operations.""" # Taken from the session docs. session = self._session_maker() try: yield session session.commit() except: session.rollback() raise final...
python
def _session(self): """Provide a transactional scope around a series of operations.""" # Taken from the session docs. session = self._session_maker() try: yield session session.commit() except: session.rollback() raise final...
['def', '_session', '(', 'self', ')', ':', '# Taken from the session docs.', 'session', '=', 'self', '.', '_session_maker', '(', ')', 'try', ':', 'yield', 'session', 'session', '.', 'commit', '(', ')', 'except', ':', 'session', '.', 'rollback', '(', ')', 'raise', 'finally', ':', 'session', '.', 'close', '(', ')']
Provide a transactional scope around a series of operations.
['Provide', 'a', 'transactional', 'scope', 'around', 'a', 'series', 'of', 'operations', '.']
train
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/database/sqltable.py#L30-L41
8,324
pantsbuild/pants
src/python/pants/engine/objects.py
Serializable.is_serializable
def is_serializable(obj): """Return `True` if the given object conforms to the Serializable protocol. :rtype: bool """ if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
python
def is_serializable(obj): """Return `True` if the given object conforms to the Serializable protocol. :rtype: bool """ if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
['def', 'is_serializable', '(', 'obj', ')', ':', 'if', 'inspect', '.', 'isclass', '(', 'obj', ')', ':', 'return', 'Serializable', '.', 'is_serializable_type', '(', 'obj', ')', 'return', 'isinstance', '(', 'obj', ',', 'Serializable', ')', 'or', 'hasattr', '(', 'obj', ',', "'_asdict'", ')']
Return `True` if the given object conforms to the Serializable protocol. :rtype: bool
['Return', 'True', 'if', 'the', 'given', 'object', 'conforms', 'to', 'the', 'Serializable', 'protocol', '.']
train
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/objects.py#L74-L81
8,325
F5Networks/f5-common-python
f5/bigip/tm/security/firewall.py
Rule.update
def update(self, **kwargs): """We need to implement the custom exclusive parameter check.""" self._check_exclusive_parameters(**kwargs) return super(Rule, self)._update(**kwargs)
python
def update(self, **kwargs): """We need to implement the custom exclusive parameter check.""" self._check_exclusive_parameters(**kwargs) return super(Rule, self)._update(**kwargs)
['def', 'update', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'self', '.', '_check_exclusive_parameters', '(', '*', '*', 'kwargs', ')', 'return', 'super', '(', 'Rule', ',', 'self', ')', '.', '_update', '(', '*', '*', 'kwargs', ')']
We need to implement the custom exclusive parameter check.
['We', 'need', 'to', 'implement', 'the', 'custom', 'exclusive', 'parameter', 'check', '.']
train
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/security/firewall.py#L159-L162
8,326
richardkiss/pycoin
pycoin/ecdsa/Generator.py
Generator.verify
def verify(self, public_pair, val, sig): """ :param: public_pair: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve :param: val: an integer value :param: sig: a pair of integers ``(r, s)`` representing an ecdsa signature :returns: True if and only if the signature ``sig``...
python
def verify(self, public_pair, val, sig): """ :param: public_pair: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve :param: val: an integer value :param: sig: a pair of integers ``(r, s)`` representing an ecdsa signature :returns: True if and only if the signature ``sig``...
['def', 'verify', '(', 'self', ',', 'public_pair', ',', 'val', ',', 'sig', ')', ':', 'order', '=', 'self', '.', '_order', 'r', ',', 's', '=', 'sig', 'if', 'r', '<', '1', 'or', 'r', '>=', 'order', 'or', 's', '<', '1', 'or', 's', '>=', 'order', ':', 'return', 'False', 's_inverse', '=', 'self', '.', 'inverse', '(', 's', '...
:param: public_pair: a :class:`Point <pycoin.ecdsa.Point.Point>` on the curve :param: val: an integer value :param: sig: a pair of integers ``(r, s)`` representing an ecdsa signature :returns: True if and only if the signature ``sig`` is a valid signature of ``val`` using ``public_p...
[':', 'param', ':', 'public_pair', ':', 'a', ':', 'class', ':', 'Point', '<pycoin', '.', 'ecdsa', '.', 'Point', '.', 'Point', '>', 'on', 'the', 'curve', ':', 'param', ':', 'val', ':', 'an', 'integer', 'value', ':', 'param', ':', 'sig', ':', 'a', 'pair', 'of', 'integers', '(', 'r', 's', ')', 'representing', 'an', 'ecdsa...
train
https://github.com/richardkiss/pycoin/blob/1e8d0d9fe20ce0347b97847bb529cd1bd84c7442/pycoin/ecdsa/Generator.py#L139-L157
8,327
sendgrid/sendgrid-python
sendgrid/helpers/mail/attachment.py
Attachment.file_content
def file_content(self, value): """The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string """ if isinstance(value, FileContent): self._file_content = value else: self...
python
def file_content(self, value): """The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string """ if isinstance(value, FileContent): self._file_content = value else: self...
['def', 'file_content', '(', 'self', ',', 'value', ')', ':', 'if', 'isinstance', '(', 'value', ',', 'FileContent', ')', ':', 'self', '.', '_file_content', '=', 'value', 'else', ':', 'self', '.', '_file_content', '=', 'FileContent', '(', 'value', ')']
The Base64 encoded content of the attachment :param value: The Base64 encoded content of the attachment :type value: FileContent, string
['The', 'Base64', 'encoded', 'content', 'of', 'the', 'attachment']
train
https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/sendgrid/helpers/mail/attachment.py#L73-L82
8,328
yougov/pmxbot
pmxbot/logging.py
MongoDBLogger._add_recent
def _add_recent(self, doc, logged_id): "Keep a tab on the most recent message for each channel" spec = dict(channel=doc['channel']) doc['ref'] = logged_id doc.pop('_id') self._recent.replace_one(spec, doc, upsert=True)
python
def _add_recent(self, doc, logged_id): "Keep a tab on the most recent message for each channel" spec = dict(channel=doc['channel']) doc['ref'] = logged_id doc.pop('_id') self._recent.replace_one(spec, doc, upsert=True)
['def', '_add_recent', '(', 'self', ',', 'doc', ',', 'logged_id', ')', ':', 'spec', '=', 'dict', '(', 'channel', '=', 'doc', '[', "'channel'", ']', ')', 'doc', '[', "'ref'", ']', '=', 'logged_id', 'doc', '.', 'pop', '(', "'_id'", ')', 'self', '.', '_recent', '.', 'replace_one', '(', 'spec', ',', 'doc', ',', 'upsert', '...
Keep a tab on the most recent message for each channel
['Keep', 'a', 'tab', 'on', 'the', 'most', 'recent', 'message', 'for', 'each', 'channel']
train
https://github.com/yougov/pmxbot/blob/5da84a3258a0fd73cb35b60e39769a5d7bfb2ba7/pmxbot/logging.py#L256-L261
8,329
aacanakin/glim
glim/utils.py
copytree
def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (l...
python
def copytree(src, dst, symlinks=False, ignore=None): """ Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (l...
['def', 'copytree', '(', 'src', ',', 'dst', ',', 'symlinks', '=', 'False', ',', 'ignore', '=', 'None', ')', ':', 'if', 'not', 'os', '.', 'path', '.', 'exists', '(', 'dst', ')', ':', 'os', '.', 'mkdir', '(', 'dst', ')', 'try', ':', 'for', 'item', 'in', 'os', '.', 'listdir', '(', 'src', ')', ':', 's', '=', 'os', '.', 'pa...
Function recursively copies from directory to directory. Args ---- src (string): the full path of source directory dst (string): the full path of destination directory symlinks (boolean): the switch for tracking symlinks ignore (list): the ignore list
['Function', 'recursively', 'copies', 'from', 'directory', 'to', 'directory', '.']
train
https://github.com/aacanakin/glim/blob/71a20ac149a1292c0d6c1dc7414985ea51854f7a/glim/utils.py#L84-L106
8,330
aio-libs/aiohttp
aiohttp/client_reqrep.py
ClientRequest.update_host
def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.host: raise InvalidURL(url) # basic auth info username, password = url.user, url.password if username: self.auth = h...
python
def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.host: raise InvalidURL(url) # basic auth info username, password = url.user, url.password if username: self.auth = h...
['def', 'update_host', '(', 'self', ',', 'url', ':', 'URL', ')', '->', 'None', ':', '# get host/port', 'if', 'not', 'url', '.', 'host', ':', 'raise', 'InvalidURL', '(', 'url', ')', '# basic auth info', 'username', ',', 'password', '=', 'url', '.', 'user', ',', 'url', '.', 'password', 'if', 'username', ':', 'self', '.',...
Update destination host, port and connection type (ssl).
['Update', 'destination', 'host', 'port', 'and', 'connection', 'type', '(', 'ssl', ')', '.']
train
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/client_reqrep.py#L296-L305
8,331
rapidpro/expressions
python/temba_expressions/functions/excel.py
_unicode
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
python
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
['def', '_unicode', '(', 'ctx', ',', 'text', ')', ':', 'text', '=', 'conversions', '.', 'to_string', '(', 'text', ',', 'ctx', ')', 'if', 'len', '(', 'text', ')', '==', '0', ':', 'raise', 'ValueError', '(', '"Text can\'t be empty"', ')', 'return', 'ord', '(', 'text', '[', '0', ']', ')']
Returns a numeric code for the first character in a text string
['Returns', 'a', 'numeric', 'code', 'for', 'the', 'first', 'character', 'in', 'a', 'text', 'string']
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L137-L144
8,332
MacHu-GWU/crawl_zillow-project
crawl_zillow/spider.py
get_html
def get_html(url, headers=None, timeout=None, errors="strict", wait_time=None, driver=None, zillow_only=False, cache_only=False, zillow_first=False, cache_first=False, random=False, ...
python
def get_html(url, headers=None, timeout=None, errors="strict", wait_time=None, driver=None, zillow_only=False, cache_only=False, zillow_first=False, cache_first=False, random=False, ...
['def', 'get_html', '(', 'url', ',', 'headers', '=', 'None', ',', 'timeout', '=', 'None', ',', 'errors', '=', '"strict"', ',', 'wait_time', '=', 'None', ',', 'driver', '=', 'None', ',', 'zillow_only', '=', 'False', ',', 'cache_only', '=', 'False', ',', 'zillow_first', '=', 'False', ',', 'cache_first', '=', 'False', ','...
Use Google Cached Url. :param cache_only: if True, then real zillow site will never be used. :param driver: selenium browser driver。
['Use', 'Google', 'Cached', 'Url', '.']
train
https://github.com/MacHu-GWU/crawl_zillow-project/blob/c6d7ca8e4c80e7e7e963496433ef73df1413c16e/crawl_zillow/spider.py#L85-L148
8,333
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.update_flags
def update_flags(self, idlist, flags): """ A thin back compat wrapper around build_update(flags=X) """ return self.update_bugs(idlist, self.build_update(flags=flags))
python
def update_flags(self, idlist, flags): """ A thin back compat wrapper around build_update(flags=X) """ return self.update_bugs(idlist, self.build_update(flags=flags))
['def', 'update_flags', '(', 'self', ',', 'idlist', ',', 'flags', ')', ':', 'return', 'self', '.', 'update_bugs', '(', 'idlist', ',', 'self', '.', 'build_update', '(', 'flags', '=', 'flags', ')', ')']
A thin back compat wrapper around build_update(flags=X)
['A', 'thin', 'back', 'compat', 'wrapper', 'around', 'build_update', '(', 'flags', '=', 'X', ')']
train
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1345-L1349
8,334
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
FormattedEventsHandler.on_message
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket m...
python
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket m...
['def', 'on_message', '(', 'self', ',', 'message', ')', ':', 'log', '.', 'debug', '(', "'Got websocket message %s'", ',', 'message', ')', 'if', 'message', '==', "'websocket client ready'", ':', 'if', 'self', '.', 'connected', ':', '# TBD: Add ability to run commands in this branch', 'log', '.', 'debug', '(', "'Websocke...
Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream.
['Listens', 'for', 'a', 'websocket', 'client', 'ready', 'message', '.', 'Once', 'that', 'message', 'is', 'received', 'an', 'asynchronous', 'job', 'is', 'stated', 'that', 'yields', 'messages', 'to', 'the', 'client', '.', 'These', 'messages', 'make', 'up', 'salt', 's', 'real', 'time', 'event', 'stream', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L391-L429
8,335
blockstack/blockstack-core
blockstack/lib/subdomains.py
SubdomainDB.get_all_subdomains
def get_all_subdomains(self, offset=None, count=None, min_sequence=None, cur=None): """ Get and all subdomain names, optionally over a range """ get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}'.format(self.subdomain_table) args = () if min_sequence is not No...
python
def get_all_subdomains(self, offset=None, count=None, min_sequence=None, cur=None): """ Get and all subdomain names, optionally over a range """ get_cmd = 'SELECT DISTINCT fully_qualified_subdomain FROM {}'.format(self.subdomain_table) args = () if min_sequence is not No...
['def', 'get_all_subdomains', '(', 'self', ',', 'offset', '=', 'None', ',', 'count', '=', 'None', ',', 'min_sequence', '=', 'None', ',', 'cur', '=', 'None', ')', ':', 'get_cmd', '=', "'SELECT DISTINCT fully_qualified_subdomain FROM {}'", '.', 'format', '(', 'self', '.', 'subdomain_table', ')', 'args', '=', '(', ')', 'i...
Get and all subdomain names, optionally over a range
['Get', 'and', 'all', 'subdomain', 'names', 'optionally', 'over', 'a', 'range']
train
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1095-L1127
8,336
odlgroup/odl
odl/space/npy_tensors.py
NumpyTensorSpace.available_dtypes
def available_dtypes(): """Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used. """ all_...
python
def available_dtypes(): """Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used. """ all_...
['def', 'available_dtypes', '(', ')', ':', 'all_dtypes', '=', '[', ']', 'for', 'lst', 'in', 'np', '.', 'sctypes', '.', 'values', '(', ')', ':', 'for', 'dtype', 'in', 'lst', ':', 'if', 'dtype', 'not', 'in', '(', 'np', '.', 'object', ',', 'np', '.', 'void', ')', ':', 'all_dtypes', '.', 'append', '(', 'np', '.', 'dtype', ...
Return the set of data types available in this implementation. Notes ----- This is all dtypes available in Numpy. See ``numpy.sctypes`` for more information. The available dtypes may depend on the specific system used.
['Return', 'the', 'set', 'of', 'data', 'types', 'available', 'in', 'this', 'implementation', '.']
train
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/npy_tensors.py#L469-L487
8,337
tadeck/onetimepass
onetimepass/__init__.py
valid_hotp
def valid_hotp( token, secret, last=1, trials=1000, digest_method=hashlib.sha1, token_length=6, ): """Check if given token is valid for given secret. Return interval number that was successful, or False if not found. :param token: token being checked :typ...
python
def valid_hotp( token, secret, last=1, trials=1000, digest_method=hashlib.sha1, token_length=6, ): """Check if given token is valid for given secret. Return interval number that was successful, or False if not found. :param token: token being checked :typ...
['def', 'valid_hotp', '(', 'token', ',', 'secret', ',', 'last', '=', '1', ',', 'trials', '=', '1000', ',', 'digest_method', '=', 'hashlib', '.', 'sha1', ',', 'token_length', '=', '6', ',', ')', ':', 'if', 'not', '_is_possible_token', '(', 'token', ',', 'token_length', '=', 'token_length', ')', ':', 'return', 'False', '...
Check if given token is valid for given secret. Return interval number that was successful, or False if not found. :param token: token being checked :type token: int or str :param secret: secret for which token is checked :type secret: str :param last: last used interval (start checking with ne...
['Check', 'if', 'given', 'token', 'is', 'valid', 'for', 'given', 'secret', '.', 'Return', 'interval', 'number', 'that', 'was', 'successful', 'or', 'False', 'if', 'not', 'found', '.']
train
https://github.com/tadeck/onetimepass/blob/ee4b4e1700089757594a5ffee5f24408c864ad00/onetimepass/__init__.py#L173-L218
8,338
openstack/proliantutils
proliantutils/ipa_hw_manager/hardware_manager.py
ProliantHardwareManager.create_configuration
def create_configuration(self, node, ports): """Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing ...
python
def create_configuration(self, node, ports): """Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing ...
['def', 'create_configuration', '(', 'self', ',', 'node', ',', 'ports', ')', ':', 'target_raid_config', '=', 'node', '.', 'get', '(', "'target_raid_config'", ',', '{', '}', ')', '.', 'copy', '(', ')', 'return', 'hpssa_manager', '.', 'create_configuration', '(', 'raid_config', '=', 'target_raid_config', ')']
Create RAID configuration on the bare metal. This method creates the desired RAID configuration as read from node['target_raid_config']. :param node: A dictionary of the node object :param ports: A list of dictionaries containing information of ports for the node :r...
['Create', 'RAID', 'configuration', 'on', 'the', 'bare', 'metal', '.']
train
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ipa_hw_manager/hardware_manager.py#L55-L79
8,339
keans/lmnotify
lmnotify/lmnotify.py
LaMetricManager.get_display
def get_display(self): """ returns information about the display, including brightness, screensaver etc. """ log.debug("getting display information...") cmd, url = DEVICE_URLS["get_display"] return self._exec(cmd, url)
python
def get_display(self): """ returns information about the display, including brightness, screensaver etc. """ log.debug("getting display information...") cmd, url = DEVICE_URLS["get_display"] return self._exec(cmd, url)
['def', 'get_display', '(', 'self', ')', ':', 'log', '.', 'debug', '(', '"getting display information..."', ')', 'cmd', ',', 'url', '=', 'DEVICE_URLS', '[', '"get_display"', ']', 'return', 'self', '.', '_exec', '(', 'cmd', ',', 'url', ')']
returns information about the display, including brightness, screensaver etc.
['returns', 'information', 'about', 'the', 'display', 'including', 'brightness', 'screensaver', 'etc', '.']
train
https://github.com/keans/lmnotify/blob/b0a5282a582e5090852dc20fea8a135ca258d0d3/lmnotify/lmnotify.py#L341-L348
8,340
rmed/pyemtmad
pyemtmad/api/geo.py
GeoApi.get_groups
def get_groups(self, **kwargs): """Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error. """ # Endpoint parameters ...
python
def get_groups(self, **kwargs): """Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error. """ # Endpoint parameters ...
['def', 'get_groups', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', '# Endpoint parameters', 'params', '=', '{', "'cultureInfo'", ':', 'util', '.', 'language_code', '(', 'kwargs', '.', 'get', '(', "'lang'", ')', ')', '}', '# Request', 'result', '=', 'self', '.', 'make_request', '(', "'geo'", ',', "'get_groups'", ',',...
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
['Obtain', 'line', 'types', 'and', 'details', '.']
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L67-L90
8,341
O365/python-o365
O365/excel.py
Range._get_range
def _get_range(self, endpoint, *args, method='GET', **kwargs): """ Helper that returns another range""" if args: url = self.build_url(self._endpoints.get(endpoint).format(*args)) else: url = self.build_url(self._endpoints.get(endpoint)) if not kwargs: ...
python
def _get_range(self, endpoint, *args, method='GET', **kwargs): """ Helper that returns another range""" if args: url = self.build_url(self._endpoints.get(endpoint).format(*args)) else: url = self.build_url(self._endpoints.get(endpoint)) if not kwargs: ...
['def', '_get_range', '(', 'self', ',', 'endpoint', ',', '*', 'args', ',', 'method', '=', "'GET'", ',', '*', '*', 'kwargs', ')', ':', 'if', 'args', ':', 'url', '=', 'self', '.', 'build_url', '(', 'self', '.', '_endpoints', '.', 'get', '(', 'endpoint', ')', '.', 'format', '(', '*', 'args', ')', ')', 'else', ':', 'url', ...
Helper that returns another range
['Helper', 'that', 'returns', 'another', 'range']
train
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L638-L652
8,342
jantman/webhook2lambda2sqs
webhook2lambda2sqs/terraform_runner.py
TerraformRunner.destroy
def destroy(self, stream=False): """ Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) args = ['-refresh=true', '-force', '.'] logger.warning('Running terraform des...
python
def destroy(self, stream=False): """ Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) args = ['-refresh=true', '-force', '.'] logger.warning('Running terraform des...
['def', 'destroy', '(', 'self', ',', 'stream', '=', 'False', ')', ':', 'self', '.', '_setup_tf', '(', 'stream', '=', 'stream', ')', 'args', '=', '[', "'-refresh=true'", ',', "'-force'", ',', "'.'", ']', 'logger', '.', 'warning', '(', "'Running terraform destroy: %s'", ',', "' '", '.', 'join', '(', 'args', ')', ')', 'ou...
Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool
['Run', 'a', 'terraform', 'destroy']
train
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/terraform_runner.py#L259-L273
8,343
mongodb/mongo-python-driver
pymongo/mongo_client.py
MongoClient._cache_index
def _cache_index(self, dbname, collection, index, cache_for): """Add an index to the index cache for ensure_index operations.""" now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now with self.__index_cache_lock: if dbname not in self.__index_...
python
def _cache_index(self, dbname, collection, index, cache_for): """Add an index to the index cache for ensure_index operations.""" now = datetime.datetime.utcnow() expire = datetime.timedelta(seconds=cache_for) + now with self.__index_cache_lock: if dbname not in self.__index_...
['def', '_cache_index', '(', 'self', ',', 'dbname', ',', 'collection', ',', 'index', ',', 'cache_for', ')', ':', 'now', '=', 'datetime', '.', 'datetime', '.', 'utcnow', '(', ')', 'expire', '=', 'datetime', '.', 'timedelta', '(', 'seconds', '=', 'cache_for', ')', '+', 'now', 'with', 'self', '.', '__index_cache_lock', ':...
Add an index to the index cache for ensure_index operations.
['Add', 'an', 'index', 'to', 'the', 'index', 'cache', 'for', 'ensure_index', 'operations', '.']
train
https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L737-L753
8,344
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.score
def score(self, periods=None): """Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array ...
python
def score(self, periods=None): """Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array ...
['def', 'score', '(', 'self', ',', 'periods', '=', 'None', ')', ':', 'periods', '=', 'np', '.', 'asarray', '(', 'periods', ')', 'return', 'self', '.', '_score', '(', 'periods', '.', 'ravel', '(', ')', ')', '.', 'reshape', '(', 'periods', '.', 'shape', ')']
Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array of normalized powers (between 0 and 1) for...
['Compute', 'the', 'periodogram', 'for', 'the', 'given', 'period', 'or', 'periods']
train
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L129-L144
8,345
allenai/allennlp
allennlp/commands/__init__.py
main
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
python
def main(prog: str = None, subcommand_overrides: Dict[str, Subcommand] = {}) -> None: """ The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unle...
['def', 'main', '(', 'prog', ':', 'str', '=', 'None', ',', 'subcommand_overrides', ':', 'Dict', '[', 'str', ',', 'Subcommand', ']', '=', '{', '}', ')', '->', 'None', ':', '# pylint: disable=dangerous-default-value', 'parser', '=', 'ArgumentParserWithDefaults', '(', 'description', '=', '"Run AllenNLP"', ',', 'usage', '=...
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp`` codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't work for them, unless you use the ``--include-package`` flag.
['The', ':', 'mod', ':', '~allennlp', '.', 'run', 'command', 'only', 'knows', 'about', 'the', 'registered', 'classes', 'in', 'the', 'allennlp', 'codebase', '.', 'In', 'particular', 'once', 'you', 'start', 'creating', 'your', 'own', 'Model', 's', 'and', 'so', 'forth', 'it', 'won', 't', 'work', 'for', 'them', 'unless', '...
train
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/commands/__init__.py#L52-L104
8,346
pybel/pybel
src/pybel/parser/parse_bel.py
BELParser.handle_nested_relation
def handle_nested_relation(self, line: str, position: int, tokens: ParseResults): """Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning """ if not self.allow_nested: raise NestedRelationWarn...
python
def handle_nested_relation(self, line: str, position: int, tokens: ParseResults): """Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning """ if not self.allow_nested: raise NestedRelationWarn...
['def', 'handle_nested_relation', '(', 'self', ',', 'line', ':', 'str', ',', 'position', ':', 'int', ',', 'tokens', ':', 'ParseResults', ')', ':', 'if', 'not', 'self', '.', 'allow_nested', ':', 'raise', 'NestedRelationWarning', '(', 'self', '.', 'get_line_number', '(', ')', ',', 'line', ',', 'position', ')', 'self', '....
Handle nested statements. If :code:`allow_nested` is False, raises a ``NestedRelationWarning``. :raises: NestedRelationWarning
['Handle', 'nested', 'statements', '.']
train
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/parser/parse_bel.py#L630-L651
8,347
tilde-lab/tilde
tilde/berlinium/cubicspline.py
NaturalCubicSpline._findSegment
def _findSegment(self, x): ''' :param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment ''' iLeft = 0 iRight = len(self.xData) - 1 while True: if iRight - iLeft <= 1: return iLef...
python
def _findSegment(self, x): ''' :param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment ''' iLeft = 0 iRight = len(self.xData) - 1 while True: if iRight - iLeft <= 1: return iLef...
['def', '_findSegment', '(', 'self', ',', 'x', ')', ':', 'iLeft', '=', '0', 'iRight', '=', 'len', '(', 'self', '.', 'xData', ')', '-', '1', 'while', 'True', ':', 'if', 'iRight', '-', 'iLeft', '<=', '1', ':', 'return', 'iLeft', 'i', '=', '(', 'iRight', '+', 'iLeft', ')', '/', '2', 'if', 'x', '<', 'self', '.', 'xData', '...
:param x: x value to place in segment defined by the xData (instantiation) :return: The lower index in the segment
[':', 'param', 'x', ':', 'x', 'value', 'to', 'place', 'in', 'segment', 'defined', 'by', 'the', 'xData', '(', 'instantiation', ')', ':', 'return', ':', 'The', 'lower', 'index', 'in', 'the', 'segment']
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/cubicspline.py#L240-L254
8,348
graphql-python/graphql-core-next
graphql/validation/rules/overlapping_fields_can_be_merged.py
do_types_conflict
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: """Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List...
python
def do_types_conflict(type1: GraphQLOutputType, type2: GraphQLOutputType) -> bool: """Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List...
['def', 'do_types_conflict', '(', 'type1', ':', 'GraphQLOutputType', ',', 'type2', ':', 'GraphQLOutputType', ')', '->', 'bool', ':', 'if', 'is_list_type', '(', 'type1', ')', ':', 'return', '(', 'do_types_conflict', '(', 'cast', '(', 'GraphQLList', ',', 'type1', ')', '.', 'of_type', ',', 'cast', '(', 'GraphQLList', ',',...
Check whether two types conflict Two types conflict if both types could not apply to a value simultaneously. Composite types are ignored as their individual field types will be compared later recursively. However List and Non-Null types must match.
['Check', 'whether', 'two', 'types', 'conflict']
train
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/overlapping_fields_can_be_merged.py#L613-L642
8,349
Josef-Friedrich/phrydy
phrydy/mediafile.py
MediaFile.update
def update(self, dict): """Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted ...
python
def update(self, dict): """Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted ...
['def', 'update', '(', 'self', ',', 'dict', ')', ':', 'for', 'field', 'in', 'self', '.', 'sorted_fields', '(', ')', ':', 'if', 'field', 'in', 'dict', ':', 'if', 'dict', '[', 'field', ']', 'is', 'None', ':', 'delattr', '(', 'self', ',', 'field', ')', 'else', ':', 'setattr', '(', 'self', ',', 'field', ',', 'dict', '[', '...
Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted from the `MediaFile`.
['Set', 'all', 'field', 'values', 'from', 'a', 'dictionary', '.']
train
https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/mediafile.py#L1587-L1600
8,350
Miserlou/Zappa
zappa/letsencrypt.py
parse_csr
def parse_csr(): """ Parse certificate signing request for domains """ LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') out = subprocess.check_outp...
python
def parse_csr(): """ Parse certificate signing request for domains """ LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') out = subprocess.check_outp...
['def', 'parse_csr', '(', ')', ':', 'LOGGER', '.', 'info', '(', '"Parsing CSR..."', ')', 'cmd', '=', '[', "'openssl'", ',', "'req'", ',', "'-in'", ',', 'os', '.', 'path', '.', 'join', '(', 'gettempdir', '(', ')', ',', "'domain.csr'", ')', ',', "'-noout'", ',', "'-text'", ']', 'devnull', '=', 'open', '(', 'os', '.', 'de...
Parse certificate signing request for domains
['Parse', 'certificate', 'signing', 'request', 'for', 'domains']
train
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L164-L187
8,351
LudovicRousseau/pyscard
smartcard/wx/CardAndReaderTreePanel.py
CardAndReaderTreePanel.OnDestroy
def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers if hasattr(self, 'cardmonitor'): self.cardmonitor.deleteObserver(self.cardtreecardobserver) if hasattr(self, 'readermonitor'): self.readermonitor.deleteObserver(self.readertreere...
python
def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers if hasattr(self, 'cardmonitor'): self.cardmonitor.deleteObserver(self.cardtreecardobserver) if hasattr(self, 'readermonitor'): self.readermonitor.deleteObserver(self.readertreere...
['def', 'OnDestroy', '(', 'self', ',', 'event', ')', ':', '# deregister observers', 'if', 'hasattr', '(', 'self', ',', "'cardmonitor'", ')', ':', 'self', '.', 'cardmonitor', '.', 'deleteObserver', '(', 'self', '.', 'cardtreecardobserver', ')', 'if', 'hasattr', '(', 'self', ',', "'readermonitor'", ')', ':', 'self', '.',...
Called on panel destruction.
['Called', 'on', 'panel', 'destruction', '.']
train
https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/wx/CardAndReaderTreePanel.py#L410-L418
8,352
avinassh/haxor
hackernews/__init__.py
HackerNews.get_user
def get_user(self, user_id, expand=False): """Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id ...
python
def get_user(self, user_id, expand=False): """Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id ...
['def', 'get_user', '(', 'self', ',', 'user_id', ',', 'expand', '=', 'False', ')', ':', 'url', '=', 'urljoin', '(', 'self', '.', 'user_url', ',', 'F"{user_id}.json"', ')', 'response', '=', 'self', '.', '_get_sync', '(', 'url', ')', 'if', 'not', 'response', ':', 'raise', 'InvalidUserID', 'user', '=', 'User', '(', 'respo...
Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id of a Hacker News user. expand (bool): Flag...
['Returns', 'Hacker', 'News', 'User', 'object', '.']
train
https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L223-L266
8,353
scdoshi/django-bits
bits/gis.py
gprmc_to_degdec
def gprmc_to_degdec(lat, latDirn, lng, lngDirn): """Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.""" x = float(lat[0:2]) + float(lat[2:]) / 60 y = float(lng[0:3]) + float(lng[3:]) / 60 if latDirn == 'S': x = -x if lngDirn == 'W': y = -y return x, y
python
def gprmc_to_degdec(lat, latDirn, lng, lngDirn): """Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.""" x = float(lat[0:2]) + float(lat[2:]) / 60 y = float(lng[0:3]) + float(lng[3:]) / 60 if latDirn == 'S': x = -x if lngDirn == 'W': y = -y return x, y
['def', 'gprmc_to_degdec', '(', 'lat', ',', 'latDirn', ',', 'lng', ',', 'lngDirn', ')', ':', 'x', '=', 'float', '(', 'lat', '[', '0', ':', '2', ']', ')', '+', 'float', '(', 'lat', '[', '2', ':', ']', ')', '/', '60', 'y', '=', 'float', '(', 'lng', '[', '0', ':', '3', ']', ')', '+', 'float', '(', 'lng', '[', '3', ':', ']...
Converts GPRMC formats (Decimal Minutes) to Degrees Decimal.
['Converts', 'GPRMC', 'formats', '(', 'Decimal', 'Minutes', ')', 'to', 'Degrees', 'Decimal', '.']
train
https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/gis.py#L15-L25
8,354
horazont/aioxmpp
aioxmpp/roster/service.py
RosterClient.import_from_json
def import_from_json(self, data): """ Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. ...
python
def import_from_json(self, data): """ Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. ...
['def', 'import_from_json', '(', 'self', ',', 'data', ')', ':', 'self', '.', 'version', '=', 'data', '.', 'get', '(', '"ver"', ',', 'None', ')', 'self', '.', 'items', '.', 'clear', '(', ')', 'self', '.', 'groups', '.', 'clear', '(', ')', 'for', 'jid', ',', 'data', 'in', 'data', '.', 'get', '(', '"items"', ',', '{', '}'...
Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. Also, no data is transferred to the server; this met...
['Replace', 'the', 'current', 'roster', 'with', 'the', ':', 'meth', ':', 'export_as_json', '-', 'compatible', 'dictionary', 'in', 'data', '.']
train
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/roster/service.py#L587-L609
8,355
shi-cong/PYSTUDY
PYSTUDY/processlib.py
create_process
def create_process(daemon, name, callback, *callbackParams): """创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象 """ bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams) ...
python
def create_process(daemon, name, callback, *callbackParams): """创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象 """ bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams) ...
['def', 'create_process', '(', 'daemon', ',', 'name', ',', 'callback', ',', '*', 'callbackParams', ')', ':', 'bp', '=', 'Process', '(', 'daemon', '=', 'daemon', ',', 'name', '=', 'name', ',', 'target', '=', 'callback', ',', 'args', '=', 'callbackParams', ')', 'return', 'bp']
创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象
['创建进程', ':', 'param', 'daemon', ':', 'True主进程关闭而关闭', 'False主进程必须等待子进程结束', ':', 'param', 'name', ':', '进程名称', ':', 'param', 'callback', ':', '回调函数', ':', 'param', 'callbackParams', ':', '回调函数参数', ':', 'return', ':', '返回一个进程对象']
train
https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/processlib.py#L8-L17
8,356
saltstack/salt
salt/utils/data.py
encode_dict
def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data): if isinstance(key, tuple)...
python
def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data): if isinstance(key, tuple)...
['def', 'encode_dict', '(', 'data', ',', 'encoding', '=', 'None', ',', 'errors', '=', "'strict'", ',', 'keep', '=', 'False', ',', 'preserve_dict_class', '=', 'False', ',', 'preserve_tuples', '=', 'False', ')', ':', 'rv', '=', 'data', '.', '__class__', '(', ')', 'if', 'preserve_dict_class', 'else', '{', '}', 'for', 'key...
Encode all string values to bytes
['Encode', 'all', 'string', 'values', 'to', 'bytes']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L370-L418
8,357
lago-project/lago
lago/config.py
_get_configs_path
def _get_configs_path(): """Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files """ paths...
python
def _get_configs_path(): """Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files """ paths...
['def', '_get_configs_path', '(', ')', ':', 'paths', '=', '[', ']', 'xdg_paths', '=', '[', 'path', 'for', 'path', 'in', 'base_dirs', '.', 'load_config_paths', '(', "'lago'", ',', "'lago.conf'", ')', ']', 'paths', '.', 'extend', '(', '[', 'path', 'for', 'path', 'in', 'CONFS_PATH', 'if', 'os', '.', 'path', '.', 'exists',...
Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files
['Get', 'a', 'list', 'of', 'possible', 'configuration', 'files', 'from', 'the', 'following', 'sources', ':', '1', '.', 'All', 'files', 'that', 'exists', 'in', 'constants', '.', 'CONFS_PATH', '.', '2', '.', 'All', 'XDG', 'standard', 'config', 'files', 'for', 'lago', '.', 'conf', 'in', 'reversed', 'order', 'of', 'importa...
train
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/config.py#L30-L49
8,358
pydata/xarray
xarray/core/variable.py
Variable.pad_with_fill_value
def pad_with_fill_value(self, pad_widths=None, fill_value=dtypes.NA, **pad_widths_kwargs): """ Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the ...
python
def pad_with_fill_value(self, pad_widths=None, fill_value=dtypes.NA, **pad_widths_kwargs): """ Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the ...
['def', 'pad_with_fill_value', '(', 'self', ',', 'pad_widths', '=', 'None', ',', 'fill_value', '=', 'dtypes', '.', 'NA', ',', '*', '*', 'pad_widths_kwargs', ')', ':', 'pad_widths', '=', 'either_dict_or_kwargs', '(', 'pad_widths', ',', 'pad_widths_kwargs', ',', "'pad'", ')', 'if', 'fill_value', 'is', 'dtypes', '.', 'NA'...
Return a new Variable with paddings. Parameters ---------- pad_width: Mapping of the form {dim: (before, after)} Number of values padded to the edges of each dimension. **pad_widths_kwargs: Keyword argument for pad_widths
['Return', 'a', 'new', 'Variable', 'with', 'paddings', '.']
train
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/variable.py#L1023-L1074
8,359
sjkingo/python-freshdesk
freshdesk/v1/api.py
ContactAPI.list_contacts
def list_contacts(self, **kwargs): """ List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered ...
python
def list_contacts(self, **kwargs): """ List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered ...
['def', 'list_contacts', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'url', '=', "'contacts.json?'", 'if', "'query'", 'in', 'kwargs', '.', 'keys', '(', ')', ':', 'filter_query', '=', 'kwargs', '.', 'pop', '(', "'query'", ')', 'url', '=', 'url', '+', '"query={}"', '.', 'format', '(', 'filter_query', ')', 'if', "'sta...
List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered by name such as; letter=Prenit ...
['List', 'all', 'contacts', 'optionally', 'filtered', 'by', 'a', 'query', '.', 'Specify', 'filters', 'as', 'query', 'keyword', 'argument', 'such', 'as', ':', 'query', '=', 'email', 'is', 'abc@xyz', '.', 'com', 'query', '=', 'mobile', 'is', '1234567890', 'query', '=', 'phone', 'is', '1234567890']
train
https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v1/api.py#L81-L113
8,360
dnanexus/dx-toolkit
src/python/dxpy/api.py
org_find_projects
def org_find_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindProjects """ return DXHTTPRequest('/%s/findProjects...
python
def org_find_projects(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindProjects """ return DXHTTPRequest('/%s/findProjects...
['def', 'org_find_projects', '(', 'object_id', ',', 'input_params', '=', '{', '}', ',', 'always_retry', '=', 'True', ',', '*', '*', 'kwargs', ')', ':', 'return', 'DXHTTPRequest', '(', "'/%s/findProjects'", '%', 'object_id', ',', 'input_params', ',', 'always_retry', '=', 'always_retry', ',', '*', '*', 'kwargs', ')']
Invokes the /org-xxxx/findProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindProjects
['Invokes', 'the', '/', 'org', '-', 'xxxx', '/', 'findProjects', 'API', 'method', '.']
train
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L875-L881
8,361
aliyun/aliyun-log-python-sdk
aliyun/log/logclient.py
LogClient.copy_data
def copy_data(self, project, logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, batch_size=None, compress=None, new_topic=None, new_source=None): """ copy data from one logstore to another one ...
python
def copy_data(self, project, logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, batch_size=None, compress=None, new_topic=None, new_source=None): """ copy data from one logstore to another one ...
['def', 'copy_data', '(', 'self', ',', 'project', ',', 'logstore', ',', 'from_time', ',', 'to_time', '=', 'None', ',', 'to_client', '=', 'None', ',', 'to_project', '=', 'None', ',', 'to_logstore', '=', 'None', ',', 'shard_list', '=', 'None', ',', 'batch_size', '=', 'None', ',', 'compress', '=', 'None', ',', 'new_topic'...
copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side. :type project: string :param project: project name :type logstore: string :param logstore: logstore name :type from_time: string/int ...
['copy', 'data', 'from', 'one', 'logstore', 'to', 'another', 'one', '(', 'could', 'be', 'the', 'same', 'or', 'in', 'different', 'region', ')', 'the', 'time', 'is', 'log', 'received', 'time', 'on', 'server', 'side', '.', ':', 'type', 'project', ':', 'string', ':', 'param', 'project', ':', 'project', 'name', ':', 'type',...
train
https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/logclient.py#L2390-L2439
8,362
DinoTools/python-ssdeep
src/ssdeep/__init__.py
hash
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isins...
python
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isins...
['def', 'hash', '(', 'buf', ',', 'encoding', '=', '"utf-8"', ')', ':', 'if', 'isinstance', '(', 'buf', ',', 'six', '.', 'text_type', ')', ':', 'buf', '=', 'buf', '.', 'encode', '(', 'encoding', ')', 'if', 'not', 'isinstance', '(', 'buf', ',', 'six', '.', 'binary_type', ')', ':', 'raise', 'TypeError', '(', '"Argument mu...
Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes
['Compute', 'the', 'fuzzy', 'hash', 'of', 'a', 'buffer']
train
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L191-L217
8,363
mgedmin/findimports
findimports.py
ModuleGraph.printImportedNames
def printImportedNames(self): """Produce a report of imported names.""" for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".join(imp.name for imp in module.imported_names))
python
def printImportedNames(self): """Produce a report of imported names.""" for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".join(imp.name for imp in module.imported_names))
['def', 'printImportedNames', '(', 'self', ')', ':', 'for', 'module', 'in', 'self', '.', 'listModules', '(', ')', ':', 'print', '(', '"%s:"', '%', 'module', '.', 'modname', ')', 'print', '(', '" %s"', '%', '"\\n "', '.', 'join', '(', 'imp', '.', 'name', 'for', 'imp', 'in', 'module', '.', 'imported_names', ')', ')']
Produce a report of imported names.
['Produce', 'a', 'report', 'of', 'imported', 'names', '.']
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L701-L705
8,364
ebroecker/canmatrix
src/canmatrix/log.py
setup_logger
def setup_logger(): # type: () -> logging.Logger """Setup the root logger. Return the logger instance for possible further setting and use. To be used from CLI scripts only. """ formatter = logging.Formatter( fmt='%(levelname)s - %(module)s - %(message)s') handler = logging.StreamHandler(...
python
def setup_logger(): # type: () -> logging.Logger """Setup the root logger. Return the logger instance for possible further setting and use. To be used from CLI scripts only. """ formatter = logging.Formatter( fmt='%(levelname)s - %(module)s - %(message)s') handler = logging.StreamHandler(...
['def', 'setup_logger', '(', ')', ':', '# type: () -> logging.Logger', 'formatter', '=', 'logging', '.', 'Formatter', '(', 'fmt', '=', "'%(levelname)s - %(module)s - %(message)s'", ')', 'handler', '=', 'logging', '.', 'StreamHandler', '(', ')', 'handler', '.', 'setFormatter', '(', 'formatter', ')', 'logger', '=', 'logg...
Setup the root logger. Return the logger instance for possible further setting and use. To be used from CLI scripts only.
['Setup', 'the', 'root', 'logger', '.', 'Return', 'the', 'logger', 'instance', 'for', 'possible', 'further', 'setting', 'and', 'use', '.']
train
https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/log.py#L31-L45
8,365
batiste/django-page-cms
pages/admin/views.py
get_content
def get_content(request, page_id, content_id): """Get the content for a particular page""" content = Content.objects.get(pk=content_id) return HttpResponse(content.body)
python
def get_content(request, page_id, content_id): """Get the content for a particular page""" content = Content.objects.get(pk=content_id) return HttpResponse(content.body)
['def', 'get_content', '(', 'request', ',', 'page_id', ',', 'content_id', ')', ':', 'content', '=', 'Content', '.', 'objects', '.', 'get', '(', 'pk', '=', 'content_id', ')', 'return', 'HttpResponse', '(', 'content', '.', 'body', ')']
Get the content for a particular page
['Get', 'the', 'content', 'for', 'a', 'particular', 'page']
train
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/admin/views.py#L181-L184
8,366
wesyoung/pyzyre
czmq/_czmq_ctypes.py
Zdir.fprint
def fprint(self, file, indent): """ Print contents of directory to open stream """ return lib.zdir_fprint(self._as_parameter_, coerce_py_file(file), indent)
python
def fprint(self, file, indent): """ Print contents of directory to open stream """ return lib.zdir_fprint(self._as_parameter_, coerce_py_file(file), indent)
['def', 'fprint', '(', 'self', ',', 'file', ',', 'indent', ')', ':', 'return', 'lib', '.', 'zdir_fprint', '(', 'self', '.', '_as_parameter_', ',', 'coerce_py_file', '(', 'file', ')', ',', 'indent', ')']
Print contents of directory to open stream
['Print', 'contents', 'of', 'directory', 'to', 'open', 'stream']
train
https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L2007-L2011
8,367
Opentrons/opentrons
api/src/opentrons/data_storage/database.py
reset
def reset(): """ Unmount and remove the sqlite database (used in robot reset) """ if os.path.exists(database_path): os.remove(database_path) # Not an os.path.join because it is a suffix to the full filename journal_path = database_path + '-journal' if os.path.exists(journal_path): os...
python
def reset(): """ Unmount and remove the sqlite database (used in robot reset) """ if os.path.exists(database_path): os.remove(database_path) # Not an os.path.join because it is a suffix to the full filename journal_path = database_path + '-journal' if os.path.exists(journal_path): os...
['def', 'reset', '(', ')', ':', 'if', 'os', '.', 'path', '.', 'exists', '(', 'database_path', ')', ':', 'os', '.', 'remove', '(', 'database_path', ')', '# Not an os.path.join because it is a suffix to the full filename', 'journal_path', '=', 'database_path', '+', "'-journal'", 'if', 'os', '.', 'path', '.', 'exists', '(...
Unmount and remove the sqlite database (used in robot reset)
['Unmount', 'and', 'remove', 'the', 'sqlite', 'database', '(', 'used', 'in', 'robot', 'reset', ')']
train
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/data_storage/database.py#L206-L213
8,368
MIT-LCP/wfdb-python
wfdb/processing/qrs.py
XQRS._is_qrs
def _is_qrs(self, peak_num, backsearch=False): """ Check whether a peak is a qrs complex. It is classified as qrs if it: - Comes after the refractory period - Passes qrs threshold - Is not a t-wave (check it if the peak is close to the previous qrs). Pa...
python
def _is_qrs(self, peak_num, backsearch=False): """ Check whether a peak is a qrs complex. It is classified as qrs if it: - Comes after the refractory period - Passes qrs threshold - Is not a t-wave (check it if the peak is close to the previous qrs). Pa...
['def', '_is_qrs', '(', 'self', ',', 'peak_num', ',', 'backsearch', '=', 'False', ')', ':', 'i', '=', 'self', '.', 'peak_inds_i', '[', 'peak_num', ']', 'if', 'backsearch', ':', 'qrs_thr', '=', 'self', '.', 'qrs_thr', '/', '2', 'else', ':', 'qrs_thr', '=', 'self', '.', 'qrs_thr', 'if', '(', 'i', '-', 'self', '.', 'last_...
Check whether a peak is a qrs complex. It is classified as qrs if it: - Comes after the refractory period - Passes qrs threshold - Is not a t-wave (check it if the peak is close to the previous qrs). Parameters ---------- peak_num : int The ...
['Check', 'whether', 'a', 'peak', 'is', 'a', 'qrs', 'complex', '.', 'It', 'is', 'classified', 'as', 'qrs', 'if', 'it', ':', '-', 'Comes', 'after', 'the', 'refractory', 'period', '-', 'Passes', 'qrs', 'threshold', '-', 'Is', 'not', 'a', 't', '-', 'wave', '(', 'check', 'it', 'if', 'the', 'peak', 'is', 'close', 'to', 'the...
train
https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/processing/qrs.py#L363-L393
8,369
petrjasek/eve-elastic
eve_elastic/helpers.py
_chunk_actions
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): """ Split actions into chunks by number or size, serialize them into strings in the process. """ bulk_actions = [] size, action_count = 0, 0 for action, data in actions: action = serializer.dumps(action) cu...
python
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): """ Split actions into chunks by number or size, serialize them into strings in the process. """ bulk_actions = [] size, action_count = 0, 0 for action, data in actions: action = serializer.dumps(action) cu...
['def', '_chunk_actions', '(', 'actions', ',', 'chunk_size', ',', 'max_chunk_bytes', ',', 'serializer', ')', ':', 'bulk_actions', '=', '[', ']', 'size', ',', 'action_count', '=', '0', ',', '0', 'for', 'action', ',', 'data', 'in', 'actions', ':', 'action', '=', 'serializer', '.', 'dumps', '(', 'action', ')', 'cur_size',...
Split actions into chunks by number or size, serialize them into strings in the process.
['Split', 'actions', 'into', 'chunks', 'by', 'number', 'or', 'size', 'serialize', 'them', 'into', 'strings', 'in', 'the', 'process', '.']
train
https://github.com/petrjasek/eve-elastic/blob/f146f31b348d22ac5559cf78717b3bb02efcb2d7/eve_elastic/helpers.py#L51-L79
8,370
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py
PostProcessor.forward
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
python
def forward(self, x, boxes): """ Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: ...
['def', 'forward', '(', 'self', ',', 'x', ',', 'boxes', ')', ':', 'class_logits', ',', 'box_regression', '=', 'x', 'class_prob', '=', 'F', '.', 'softmax', '(', 'class_logits', ',', '-', '1', ')', '# TODO think about a representation of batch of boxes', 'image_shapes', '=', '[', 'box', '.', 'size', 'for', 'box', 'in', '...
Arguments: x (tuple[tensor, tensor]): x contains the class logits and the box_regression from the model. boxes (list[BoxList]): bounding boxes that are used as reference, one for ech image Returns: results (list[BoxList]): one BoxList for each...
['Arguments', ':', 'x', '(', 'tuple', '[', 'tensor', 'tensor', ']', ')', ':', 'x', 'contains', 'the', 'class', 'logits', 'and', 'the', 'box_regression', 'from', 'the', 'model', '.', 'boxes', '(', 'list', '[', 'BoxList', ']', ')', ':', 'bounding', 'boxes', 'that', 'are', 'used', 'as', 'reference', 'one', 'for', 'ech', '...
train
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py#L43-L84
8,371
mitodl/pylti
pylti/common.py
LTIBase.name
def name(self): # pylint: disable=no-self-use """ Name returns user's name or user's email or user_id :return: best guess of name to use to greet user """ if 'lis_person_sourcedid' in self.session: return self.session['lis_person_sourcedid'] elif 'lis_person_...
python
def name(self): # pylint: disable=no-self-use """ Name returns user's name or user's email or user_id :return: best guess of name to use to greet user """ if 'lis_person_sourcedid' in self.session: return self.session['lis_person_sourcedid'] elif 'lis_person_...
['def', 'name', '(', 'self', ')', ':', '# pylint: disable=no-self-use', 'if', "'lis_person_sourcedid'", 'in', 'self', '.', 'session', ':', 'return', 'self', '.', 'session', '[', "'lis_person_sourcedid'", ']', 'elif', "'lis_person_contact_email_primary'", 'in', 'self', '.', 'session', ':', 'return', 'self', '.', 'sessio...
Name returns user's name or user's email or user_id :return: best guess of name to use to greet user
['Name', 'returns', 'user', 's', 'name', 'or', 'user', 's', 'email', 'or', 'user_id', ':', 'return', ':', 'best', 'guess', 'of', 'name', 'to', 'use', 'to', 'greet', 'user']
train
https://github.com/mitodl/pylti/blob/18a608282e0d5bc941beb2eaaeea3b7ad484b399/pylti/common.py#L473-L485
8,372
couchbase/couchbase-python-client
couchbase/result.py
SubdocResult.exists
def exists(self, path_or_index): """ Checks if a path exists in the document. This is meant to be used for a corresponding :meth:`~couchbase.subdocument.exists` request. :param path_or_index: The path (or index) to check :return: `True` if the path exists, `False` if the path do...
python
def exists(self, path_or_index): """ Checks if a path exists in the document. This is meant to be used for a corresponding :meth:`~couchbase.subdocument.exists` request. :param path_or_index: The path (or index) to check :return: `True` if the path exists, `False` if the path do...
['def', 'exists', '(', 'self', ',', 'path_or_index', ')', ':', 'result', '=', 'self', '.', '_resolve', '(', 'path_or_index', ')', 'if', 'not', 'result', '[', '0', ']', ':', 'return', 'True', 'elif', 'E', '.', 'SubdocPathNotFoundError', '.', '_can_derive', '(', 'result', '[', '0', ']', ')', ':', 'return', 'False', 'else...
Checks if a path exists in the document. This is meant to be used for a corresponding :meth:`~couchbase.subdocument.exists` request. :param path_or_index: The path (or index) to check :return: `True` if the path exists, `False` if the path does not exist :raise: An exception if the serv...
['Checks', 'if', 'a', 'path', 'exists', 'in', 'the', 'document', '.', 'This', 'is', 'meant', 'to', 'be', 'used', 'for', 'a', 'corresponding', ':', 'meth', ':', '~couchbase', '.', 'subdocument', '.', 'exists', 'request', '.']
train
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/result.py#L135-L151
8,373
PSPC-SPAC-buyandsell/von_agent
von_agent/agent/holder_prover.py
HolderProver.open
async def open(self) -> 'HolderProver': """ Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object """ LOGGER.debug('HolderProver.ope...
python
async def open(self) -> 'HolderProver': """ Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object """ LOGGER.debug('HolderProver.ope...
['async', 'def', 'open', '(', 'self', ')', '->', "'HolderProver'", ':', 'LOGGER', '.', 'debug', '(', "'HolderProver.open >>>'", ')', 'await', 'super', '(', ')', '.', 'open', '(', ')', 'if', 'self', '.', 'cfg', '.', 'get', '(', "'parse-cache-on-open'", ',', 'False', ')', ':', 'Caches', '.', 'parse', '(', 'self', '.', 'd...
Explicit entry. Perform ancestor opening operations, then parse cache from archive if so configured, and synchronize revocation registry to tails tree content. :return: current object
['Explicit', 'entry', '.', 'Perform', 'ancestor', 'opening', 'operations', 'then', 'parse', 'cache', 'from', 'archive', 'if', 'so', 'configured', 'and', 'synchronize', 'revocation', 'registry', 'to', 'tails', 'tree', 'content', '.']
train
https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/holder_prover.py#L494-L513
8,374
msiemens/tinydb
tinydb/database.py
Table.insert
def insert(self, document): """ Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID """ doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._wri...
python
def insert(self, document): """ Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID """ doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._wri...
['def', 'insert', '(', 'self', ',', 'document', ')', ':', 'doc_id', '=', 'self', '.', '_get_doc_id', '(', 'document', ')', 'data', '=', 'self', '.', '_read', '(', ')', 'data', '[', 'doc_id', ']', '=', 'dict', '(', 'document', ')', 'self', '.', '_write', '(', 'data', ')', 'return', 'doc_id']
Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID
['Insert', 'a', 'new', 'document', 'into', 'the', 'table', '.']
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L449-L462
8,375
wummel/dosage
scripts/order-symlinks.py
create_symlinks
def create_symlinks(d): """Create new symbolic links in output directory.""" data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in da...
python
def create_symlinks(d): """Create new symbolic links in output directory.""" data = loadJson(d) outDir = prepare_output(d) unseen = data["pages"].keys() while len(unseen) > 0: latest = work = unseen[0] while work in unseen: unseen.remove(work) if "prev" in da...
['def', 'create_symlinks', '(', 'd', ')', ':', 'data', '=', 'loadJson', '(', 'd', ')', 'outDir', '=', 'prepare_output', '(', 'd', ')', 'unseen', '=', 'data', '[', '"pages"', ']', '.', 'keys', '(', ')', 'while', 'len', '(', 'unseen', ')', '>', '0', ':', 'latest', '=', 'work', '=', 'unseen', '[', '0', ']', 'while', 'work...
Create new symbolic links in output directory.
['Create', 'new', 'symbolic', 'links', 'in', 'output', 'directory', '.']
train
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/scripts/order-symlinks.py#L34-L59
8,376
gorakhargosh/pathtools
scripts/nosy.py
filter_paths
def filter_paths(pathnames, patterns=None, ignore_patterns=None): """Filters from a set of paths based on acceptable patterns and ignorable patterns.""" result = [] if patterns is None: patterns = ['*'] if ignore_patterns is None: ignore_patterns = [] for pathname in pathnames: ...
python
def filter_paths(pathnames, patterns=None, ignore_patterns=None): """Filters from a set of paths based on acceptable patterns and ignorable patterns.""" result = [] if patterns is None: patterns = ['*'] if ignore_patterns is None: ignore_patterns = [] for pathname in pathnames: ...
['def', 'filter_paths', '(', 'pathnames', ',', 'patterns', '=', 'None', ',', 'ignore_patterns', '=', 'None', ')', ':', 'result', '=', '[', ']', 'if', 'patterns', 'is', 'None', ':', 'patterns', '=', '[', "'*'", ']', 'if', 'ignore_patterns', 'is', 'None', ':', 'ignore_patterns', '=', '[', ']', 'for', 'pathname', 'in', 'p...
Filters from a set of paths based on acceptable patterns and ignorable patterns.
['Filters', 'from', 'a', 'set', 'of', 'paths', 'based', 'on', 'acceptable', 'patterns', 'and', 'ignorable', 'patterns', '.']
train
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/scripts/nosy.py#L47-L58
8,377
gisce/heman
heman/auth/__init__.py
check_contract_allowed
def check_contract_allowed(func): """Check if Contract is allowed by token """ @wraps(func) def decorator(*args, **kwargs): contract = kwargs.get('contract') if (contract and current_user.is_authenticated() and not current_user.allowed(contract)): return curre...
python
def check_contract_allowed(func): """Check if Contract is allowed by token """ @wraps(func) def decorator(*args, **kwargs): contract = kwargs.get('contract') if (contract and current_user.is_authenticated() and not current_user.allowed(contract)): return curre...
['def', 'check_contract_allowed', '(', 'func', ')', ':', '@', 'wraps', '(', 'func', ')', 'def', 'decorator', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'contract', '=', 'kwargs', '.', 'get', '(', "'contract'", ')', 'if', '(', 'contract', 'and', 'current_user', '.', 'is_authenticated', '(', ')', 'and', 'not', ...
Check if Contract is allowed by token
['Check', 'if', 'Contract', 'is', 'allowed', 'by', 'token']
train
https://github.com/gisce/heman/blob/cf09fca09953f12454b2910ddfa9d7586709657b/heman/auth/__init__.py#L16-L26
8,378
raiden-network/raiden
tools/scenario-player/scenario_player/utils.py
HTTPExecutor.start
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Merged copy paste from the inheritance chain with modified stdout/err behaviour """ if self.pre_start_check(): # Some other executor (or process) is running with same config: raise AlreadyRunning(self) ...
python
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Merged copy paste from the inheritance chain with modified stdout/err behaviour """ if self.pre_start_check(): # Some other executor (or process) is running with same config: raise AlreadyRunning(self) ...
['def', 'start', '(', 'self', ',', 'stdout', '=', 'subprocess', '.', 'PIPE', ',', 'stderr', '=', 'subprocess', '.', 'PIPE', ')', ':', 'if', 'self', '.', 'pre_start_check', '(', ')', ':', '# Some other executor (or process) is running with same config:', 'raise', 'AlreadyRunning', '(', 'self', ')', 'if', 'self', '.', 'p...
Merged copy paste from the inheritance chain with modified stdout/err behaviour
['Merged', 'copy', 'paste', 'from', 'the', 'inheritance', 'chain', 'with', 'modified', 'stdout', '/', 'err', 'behaviour']
train
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/utils.py#L97-L128
8,379
aio-libs/aiohttp_admin
aiohttp_admin/backends/sa.py
PGResource.get_type_of_fields
def get_type_of_fields(fields, table): """ Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list o...
python
def get_type_of_fields(fields, table): """ Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list o...
['def', 'get_type_of_fields', '(', 'fields', ',', 'table', ')', ':', 'if', 'not', 'fields', ':', 'fields', '=', 'table', '.', 'primary_key', 'actual_fields', '=', '[', 'field', 'for', 'field', 'in', 'table', '.', 'c', '.', 'items', '(', ')', 'if', 'field', '[', '0', ']', 'in', 'fields', ']', 'data_type_fields', '=', '{...
Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list of the tuples `(field_name, fields_type)`
['Return', 'data', 'types', 'of', 'fields', 'that', 'are', 'in', 'table', '.', 'If', 'a', 'given', 'parameter', 'is', 'empty', 'return', 'primary', 'key', '.']
train
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L58-L80
8,380
senaite/senaite.core
bika/lims/content/analysisrequest.py
AnalysisRequest.Description
def Description(self): """Returns searchable data as Description""" descr = " ".join((self.getId(), self.aq_parent.Title())) return safe_unicode(descr).encode('utf-8')
python
def Description(self): """Returns searchable data as Description""" descr = " ".join((self.getId(), self.aq_parent.Title())) return safe_unicode(descr).encode('utf-8')
['def', 'Description', '(', 'self', ')', ':', 'descr', '=', '" "', '.', 'join', '(', '(', 'self', '.', 'getId', '(', ')', ',', 'self', '.', 'aq_parent', '.', 'Title', '(', ')', ')', ')', 'return', 'safe_unicode', '(', 'descr', ')', '.', 'encode', '(', "'utf-8'", ')']
Returns searchable data as Description
['Returns', 'searchable', 'data', 'as', 'Description']
train
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/analysisrequest.py#L1423-L1426
8,381
petl-developers/petl
petl/transform/selects.py
selectnone
def selectnone(table, field, complement=False): """Select rows where the given field is `None`.""" return select(table, field, lambda v: v is None, complement=complement)
python
def selectnone(table, field, complement=False): """Select rows where the given field is `None`.""" return select(table, field, lambda v: v is None, complement=complement)
['def', 'selectnone', '(', 'table', ',', 'field', ',', 'complement', '=', 'False', ')', ':', 'return', 'select', '(', 'table', ',', 'field', ',', 'lambda', 'v', ':', 'v', 'is', 'None', ',', 'complement', '=', 'complement', ')']
Select rows where the given field is `None`.
['Select', 'rows', 'where', 'the', 'given', 'field', 'is', 'None', '.']
train
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/transform/selects.py#L356-L359
8,382
Morrolan/surrealism
surrealism.py
__process_sentence
def __process_sentence(sentence_tuple, counts): """pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts: """ sentence = sentence_tuple[2] # now we start replacing words one type at a time... sentence = __replace_verbs(sen...
python
def __process_sentence(sentence_tuple, counts): """pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts: """ sentence = sentence_tuple[2] # now we start replacing words one type at a time... sentence = __replace_verbs(sen...
['def', '__process_sentence', '(', 'sentence_tuple', ',', 'counts', ')', ':', 'sentence', '=', 'sentence_tuple', '[', '2', ']', '# now we start replacing words one type at a time...', 'sentence', '=', '__replace_verbs', '(', 'sentence', ',', 'counts', ')', 'sentence', '=', '__replace_nouns', '(', 'sentence', ',', 'coun...
pull the actual sentence from the tuple (tuple contains additional data such as ID) :param _sentence_tuple: :param counts:
['pull', 'the', 'actual', 'sentence', 'from', 'the', 'tuple', '(', 'tuple', 'contains', 'additional', 'data', 'such', 'as', 'ID', ')', ':', 'param', '_sentence_tuple', ':', ':', 'param', 'counts', ':']
train
https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L521-L559
8,383
alvarogzp/telegram-bot-framework
bot/action/standard/chatsettings/__init__.py
ChatSettings.list
def list(self): """ :rtype: list(setting_name, value, default_value, is_set, is_supported) """ settings = [] for setting in _SETTINGS: value = self.get(setting) is_set = self.is_set(setting) default_value = self.get_default_value(setting) ...
python
def list(self): """ :rtype: list(setting_name, value, default_value, is_set, is_supported) """ settings = [] for setting in _SETTINGS: value = self.get(setting) is_set = self.is_set(setting) default_value = self.get_default_value(setting) ...
['def', 'list', '(', 'self', ')', ':', 'settings', '=', '[', ']', 'for', 'setting', 'in', '_SETTINGS', ':', 'value', '=', 'self', '.', 'get', '(', 'setting', ')', 'is_set', '=', 'self', '.', 'is_set', '(', 'setting', ')', 'default_value', '=', 'self', '.', 'get_default_value', '(', 'setting', ')', 'is_supported', '=', ...
:rtype: list(setting_name, value, default_value, is_set, is_supported)
[':', 'rtype', ':', 'list', '(', 'setting_name', 'value', 'default_value', 'is_set', 'is_supported', ')']
train
https://github.com/alvarogzp/telegram-bot-framework/blob/7b597a415c1901901c677976cb13100fc3083107/bot/action/standard/chatsettings/__init__.py#L42-L60
8,384
sernst/cauldron
cauldron/environ/modes.py
remove
def remove(mode_id: str) -> bool: """ Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed. """ had_mode = has(mode_id) if had_mode:...
python
def remove(mode_id: str) -> bool: """ Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed. """ had_mode = has(mode_id) if had_mode:...
['def', 'remove', '(', 'mode_id', ':', 'str', ')', '->', 'bool', ':', 'had_mode', '=', 'has', '(', 'mode_id', ')', 'if', 'had_mode', ':', '_current_modes', '.', 'remove', '(', 'mode_id', ')', 'return', 'had_mode']
Removes the specified mode identifier from the active modes and returns whether or not a remove operation was carried out. If the mode identifier is not in the currently active modes, it does need to be removed.
['Removes', 'the', 'specified', 'mode', 'identifier', 'from', 'the', 'active', 'modes', 'and', 'returns', 'whether', 'or', 'not', 'a', 'remove', 'operation', 'was', 'carried', 'out', '.', 'If', 'the', 'mode', 'identifier', 'is', 'not', 'in', 'the', 'currently', 'active', 'modes', 'it', 'does', 'need', 'to', 'be', 'remo...
train
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/environ/modes.py#L31-L43
8,385
bwohlberg/sporco
sporco/util.py
combineblocks
def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to...
python
def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to...
['def', 'combineblocks', '(', 'blks', ',', 'imgsz', ',', 'stpsz', '=', 'None', ',', 'fn', '=', 'np', '.', 'median', ')', ':', '# Construct a vectorized append function', 'def', 'listapp', '(', 'x', ',', 'y', ')', ':', 'x', '.', 'append', '(', 'y', ')', 'veclistapp', '=', 'np', '.', 'vectorize', '(', 'listapp', ',', 'ot...
Combine blocks from an ndarray to reconstruct ndarray signal. Parameters ---------- blks : ndarray nd array of blocks of a signal imgsz : tuple tuple of the signal size stpsz : tuple, optional (default None, corresponds to steps of 1) tuple of step sizes between neighboring blocks...
['Combine', 'blocks', 'from', 'an', 'ndarray', 'to', 'reconstruct', 'ndarray', 'signal', '.']
train
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L379-L429
8,386
tensorflow/tensor2tensor
tensor2tensor/layers/modalities.py
softmax_average_pooling_class_label_top
def softmax_average_pooling_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "sof...
python
def softmax_average_pooling_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "sof...
['def', 'softmax_average_pooling_class_label_top', '(', 'body_output', ',', 'targets', ',', 'model_hparams', ',', 'vocab_size', ')', ':', 'del', 'targets', '# unused arg', 'with', 'tf', '.', 'variable_scope', '(', '"softmax_average_pooling_onehot_class_label_modality_%d_%d"', '%', '(', 'vocab_size', ',', 'model_hparams...
Loss for class label.
['Loss', 'for', 'class', 'label', '.']
train
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L1062-L1073
8,387
pantsbuild/pants
src/python/pants/backend/codegen/thrift/java/thrift_defaults.py
ThriftDefaults.namespace_map
def namespace_map(self, target): """Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: d...
python
def namespace_map(self, target): """Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: d...
['def', 'namespace_map', '(', 'self', ',', 'target', ')', ':', 'self', '.', '_check_target', '(', 'target', ')', 'return', 'target', '.', 'namespace_map', 'or', 'self', '.', '_default_namespace_map']
Returns the namespace_map used for Thrift generation. :param target: The target to extract the namespace_map from. :type target: :class:`pants.backend.codegen.targets.java_thrift_library.JavaThriftLibrary` :returns: The namespaces to remap (old to new). :rtype: dictionary
['Returns', 'the', 'namespace_map', 'used', 'for', 'Thrift', 'generation', '.']
train
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/codegen/thrift/java/thrift_defaults.py#L62-L71
8,388
ASKIDA/Selenium2LibraryExtension
src/Selenium2LibraryExtension/keywords/__init__.py
_keywords.element_height_should_be
def element_height_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected height. Expected height should be in pixels. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | expected | expected height | 600 |""" self._...
python
def element_height_should_be(self, locator, expected): """Verifies the element identified by `locator` has the expected height. Expected height should be in pixels. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | expected | expected height | 600 |""" self._...
['def', 'element_height_should_be', '(', 'self', ',', 'locator', ',', 'expected', ')', ':', 'self', '.', '_info', '(', '"Verifying element \'%s\' height is \'%s\'"', '%', '(', 'locator', ',', 'expected', ')', ')', 'self', '.', '_check_element_size', '(', 'locator', ',', "'height'", ',', 'expected', ')']
Verifies the element identified by `locator` has the expected height. Expected height should be in pixels. | *Argument* | *Description* | *Example* | | locator | Selenium 2 element locator | id=my_id | | expected | expected height | 600 |
['Verifies', 'the', 'element', 'identified', 'by', 'locator', 'has', 'the', 'expected', 'height', '.', 'Expected', 'height', 'should', 'be', 'in', 'pixels', '.']
train
https://github.com/ASKIDA/Selenium2LibraryExtension/blob/5ca3fa776063c6046dff317cb2575e4772d7541f/src/Selenium2LibraryExtension/keywords/__init__.py#L217-L226
8,389
Karaage-Cluster/karaage
karaage/plugins/kgapplications/views/base.py
StateMachine._next
def _next(self, request, application, roles, next_config): """ Continue the state machine at given state. """ # we only support state changes for POST requests if request.method == "POST": key = None # If next state is a transition, process it while True: ...
python
def _next(self, request, application, roles, next_config): """ Continue the state machine at given state. """ # we only support state changes for POST requests if request.method == "POST": key = None # If next state is a transition, process it while True: ...
['def', '_next', '(', 'self', ',', 'request', ',', 'application', ',', 'roles', ',', 'next_config', ')', ':', '# we only support state changes for POST requests', 'if', 'request', '.', 'method', '==', '"POST"', ':', 'key', '=', 'None', '# If next state is a transition, process it', 'while', 'True', ':', '# We do not ex...
Continue the state machine at given state.
['Continue', 'the', 'state', 'machine', 'at', 'given', 'state', '.']
train
https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/base.py#L253-L291
8,390
emencia/emencia-django-forum
forum/forms/crispies.py
category_helper
def category_helper(form_tag=True): """ Category's form layout helper """ helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag helper.layout = Layout( Row( Column( 'title', css...
python
def category_helper(form_tag=True): """ Category's form layout helper """ helper = FormHelper() helper.form_action = '.' helper.attrs = {'data_abide': ''} helper.form_tag = form_tag helper.layout = Layout( Row( Column( 'title', css...
['def', 'category_helper', '(', 'form_tag', '=', 'True', ')', ':', 'helper', '=', 'FormHelper', '(', ')', 'helper', '.', 'form_action', '=', "'.'", 'helper', '.', 'attrs', '=', '{', "'data_abide'", ':', "''", '}', 'helper', '.', 'form_tag', '=', 'form_tag', 'helper', '.', 'layout', '=', 'Layout', '(', 'Row', '(', 'Colu...
Category's form layout helper
['Category', 's', 'form', 'layout', 'helper']
train
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L9-L53
8,391
HacKanCuBa/passphrase-py
passphrase/calc.py
password_length_needed
def password_length_needed(entropybits: Union[int, float], chars: str) -> int: """Calculate the length of a password for a given entropy and chars.""" if not isinstance(entropybits, (int, float)): raise TypeError('entropybits can only be int or float') if entropybits < 0: raise ValueError('e...
python
def password_length_needed(entropybits: Union[int, float], chars: str) -> int: """Calculate the length of a password for a given entropy and chars.""" if not isinstance(entropybits, (int, float)): raise TypeError('entropybits can only be int or float') if entropybits < 0: raise ValueError('e...
['def', 'password_length_needed', '(', 'entropybits', ':', 'Union', '[', 'int', ',', 'float', ']', ',', 'chars', ':', 'str', ')', '->', 'int', ':', 'if', 'not', 'isinstance', '(', 'entropybits', ',', '(', 'int', ',', 'float', ')', ')', ':', 'raise', 'TypeError', '(', "'entropybits can only be int or float'", ')', 'if',...
Calculate the length of a password for a given entropy and chars.
['Calculate', 'the', 'length', 'of', 'a', 'password', 'for', 'a', 'given', 'entropy', 'and', 'chars', '.']
train
https://github.com/HacKanCuBa/passphrase-py/blob/219d6374338ed9a1475b4f09b0d85212376f11e0/passphrase/calc.py#L87-L100
8,392
photo/openphoto-python
trovebox/api/api_album.py
ApiAlbums.list
def list(self, **kwds): """ Endpoint: /albums/list.json Returns a list of Album objects. """ albums = self._client.get("/albums/list.json", **kwds)["result"] albums = self._result_to_list(albums) return [Album(self._client, album) for album in albums]
python
def list(self, **kwds): """ Endpoint: /albums/list.json Returns a list of Album objects. """ albums = self._client.get("/albums/list.json", **kwds)["result"] albums = self._result_to_list(albums) return [Album(self._client, album) for album in albums]
['def', 'list', '(', 'self', ',', '*', '*', 'kwds', ')', ':', 'albums', '=', 'self', '.', '_client', '.', 'get', '(', '"/albums/list.json"', ',', '*', '*', 'kwds', ')', '[', '"result"', ']', 'albums', '=', 'self', '.', '_result_to_list', '(', 'albums', ')', 'return', '[', 'Album', '(', 'self', '.', '_client', ',', 'alb...
Endpoint: /albums/list.json Returns a list of Album objects.
['Endpoint', ':', '/', 'albums', '/', 'list', '.', 'json']
train
https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/api/api_album.py#L12-L20
8,393
ianmiell/shutit
shutit_class.py
ShutIt.do_list_modules
def do_list_modules(self, long_output=None,sort_order=None): """Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by mo...
python
def do_list_modules(self, long_output=None,sort_order=None): """Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by mo...
['def', 'do_list_modules', '(', 'self', ',', 'long_output', '=', 'None', ',', 'sort_order', '=', 'None', ')', ':', 'shutit_global', '.', 'shutit_global_object', '.', 'yield_to_draw', '(', ')', 'cfg', '=', 'self', '.', 'cfg', '# list of module ids and other details', '# will also contain column headers', 'table_list', '...
Display a list of loaded modules. Config items: - shutit.list_modules['long'] If set, also print each module's run order value - shutit.list_modules['sort'] Select the column by which the list is ordered: - id: sort the list by module id - run_order: sort the list by module run order The ...
['Display', 'a', 'list', 'of', 'loaded', 'modules', '.']
train
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3241-L3335
8,394
googleapis/google-cloud-python
firestore/google/cloud/firestore_v1beta1/watch.py
Watch._on_rpc_done
def _on_rpc_done(self, future): """Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancel...
python
def _on_rpc_done(self, future): """Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancel...
['def', '_on_rpc_done', '(', 'self', ',', 'future', ')', ':', '_LOGGER', '.', 'info', '(', '"RPC termination has signaled manager shutdown."', ')', 'future', '=', '_maybe_wrap_exception', '(', 'future', ')', 'thread', '=', 'threading', '.', 'Thread', '(', 'name', '=', '_RPC_ERROR_THREAD_NAME', ',', 'target', '=', 'self...
Triggered whenever the underlying RPC terminates without recovery. This is typically triggered from one of two threads: the background consumer thread (when calling ``recv()`` produces a non-recoverable error) or the grpc management thread (when cancelling the RPC). This method is *non...
['Triggered', 'whenever', 'the', 'underlying', 'RPC', 'terminates', 'without', 'recovery', '.']
train
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/watch.py#L293-L310
8,395
saltstack/salt
salt/modules/vsphere.py
_create_adapter_type
def _create_adapter_type(network_adapter, adapter_type, network_adapter_label=''): ''' Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual ethernet card information network_adapter None or VirtualEthernet object adapter_type String, type...
python
def _create_adapter_type(network_adapter, adapter_type, network_adapter_label=''): ''' Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual ethernet card information network_adapter None or VirtualEthernet object adapter_type String, type...
['def', '_create_adapter_type', '(', 'network_adapter', ',', 'adapter_type', ',', 'network_adapter_label', '=', "''", ')', ':', 'log', '.', 'trace', '(', "'Configuring virtual machine network '", "'adapter adapter_type=%s'", ',', 'adapter_type', ')', 'if', 'adapter_type', 'in', '[', "'vmxnet'", ',', "'vmxnet2'", ',', "...
Returns a vim.vm.device.VirtualEthernetCard object specifying a virtual ethernet card information network_adapter None or VirtualEthernet object adapter_type String, type of adapter network_adapter_label string, network adapter name
['Returns', 'a', 'vim', '.', 'vm', '.', 'device', '.', 'VirtualEthernetCard', 'object', 'specifying', 'a', 'virtual', 'ethernet', 'card', 'information']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L7646-L7690
8,396
DataDog/integrations-core
datadog_checks_base/datadog_checks/base/checks/libs/thread_pool.py
PoolWorker.run
def run(self): """Process the work unit, or wait for sentinel to exit""" while True: self.running = True workunit = self._workq.get() if is_sentinel(workunit): # Got sentinel break # Run the job / sequence worku...
python
def run(self): """Process the work unit, or wait for sentinel to exit""" while True: self.running = True workunit = self._workq.get() if is_sentinel(workunit): # Got sentinel break # Run the job / sequence worku...
['def', 'run', '(', 'self', ')', ':', 'while', 'True', ':', 'self', '.', 'running', '=', 'True', 'workunit', '=', 'self', '.', '_workq', '.', 'get', '(', ')', 'if', 'is_sentinel', '(', 'workunit', ')', ':', '# Got sentinel', 'break', '# Run the job / sequence', 'workunit', '.', 'process', '(', ')', 'self', '.', 'runnin...
Process the work unit, or wait for sentinel to exit
['Process', 'the', 'work', 'unit', 'or', 'wait', 'for', 'sentinel', 'to', 'exit']
train
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/libs/thread_pool.py#L56-L67
8,397
KeplerGO/K2fov
K2fov/K2onSilicon.py
onSiliconCheckList
def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a list of positions.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) mask = (dist < 90.) out = np.zeros(len(dist), dtype=bool) out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[ma...
python
def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a list of positions.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) mask = (dist < 90.) out = np.zeros(len(dist), dtype=bool) out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[ma...
['def', 'onSiliconCheckList', '(', 'ra_deg', ',', 'dec_deg', ',', 'FovObj', ',', 'padding_pix', '=', 'DEFAULT_PADDING', ')', ':', 'dist', '=', 'angSepVincenty', '(', 'FovObj', '.', 'ra0_deg', ',', 'FovObj', '.', 'dec0_deg', ',', 'ra_deg', ',', 'dec_deg', ')', 'mask', '=', '(', 'dist', '<', '90.', ')', 'out', '=', 'np',...
Check a list of positions.
['Check', 'a', 'list', 'of', 'positions', '.']
train
https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L96-L102
8,398
kwikteam/phy
phy/cluster/views/correlogram.py
CorrelogramView.set_bin_window
def set_bin_window(self, bin_size=None, window_size=None): """Set the bin and window sizes.""" bin_size = bin_size or self.bin_size window_size = window_size or self.window_size assert 1e-6 < bin_size < 1e3 assert 1e-6 < window_size < 1e3 assert bin_size < window_size ...
python
def set_bin_window(self, bin_size=None, window_size=None): """Set the bin and window sizes.""" bin_size = bin_size or self.bin_size window_size = window_size or self.window_size assert 1e-6 < bin_size < 1e3 assert 1e-6 < window_size < 1e3 assert bin_size < window_size ...
['def', 'set_bin_window', '(', 'self', ',', 'bin_size', '=', 'None', ',', 'window_size', '=', 'None', ')', ':', 'bin_size', '=', 'bin_size', 'or', 'self', '.', 'bin_size', 'window_size', '=', 'window_size', 'or', 'self', '.', 'window_size', 'assert', '1e-6', '<', 'bin_size', '<', '1e3', 'assert', '1e-6', '<', 'window_s...
Set the bin and window sizes.
['Set', 'the', 'bin', 'and', 'window', 'sizes', '.']
train
https://github.com/kwikteam/phy/blob/7e9313dc364304b7d2bd03b92938347343703003/phy/cluster/views/correlogram.py#L56-L67
8,399
ethereum/py-evm
eth/db/diff.py
DBDiff.join
def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff': """ Join several DBDiff objects into a single DBDiff object. In case of a conflict, changes in diffs that come later in ``diffs`` will overwrite changes from earlier changes. """ tracker = DBDiffTracker() for ...
python
def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff': """ Join several DBDiff objects into a single DBDiff object. In case of a conflict, changes in diffs that come later in ``diffs`` will overwrite changes from earlier changes. """ tracker = DBDiffTracker() for ...
['def', 'join', '(', 'cls', ',', 'diffs', ':', 'Iterable', '[', "'DBDiff'", ']', ')', '->', "'DBDiff'", ':', 'tracker', '=', 'DBDiffTracker', '(', ')', 'for', 'diff', 'in', 'diffs', ':', 'diff', '.', 'apply_to', '(', 'tracker', ')', 'return', 'tracker', '.', 'diff', '(', ')']
Join several DBDiff objects into a single DBDiff object. In case of a conflict, changes in diffs that come later in ``diffs`` will overwrite changes from earlier changes.
['Join', 'several', 'DBDiff', 'objects', 'into', 'a', 'single', 'DBDiff', 'object', '.']
train
https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/diff.py#L211-L221