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
9,700
zalando/patroni
patroni/postgresql.py
Postgresql.restore_configuration_files
def restore_configuration_files(self): """ restore a previously saved postgresql.conf """ try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if no...
python
def restore_configuration_files(self): """ restore a previously saved postgresql.conf """ try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if no...
['def', 'restore_configuration_files', '(', 'self', ')', ':', 'try', ':', 'for', 'f', 'in', 'self', '.', '_configuration_to_save', ':', 'config_file', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', '_config_dir', ',', 'f', ')', 'backup_file', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', '_data_dir', '...
restore a previously saved postgresql.conf
['restore', 'a', 'previously', 'saved', 'postgresql', '.', 'conf']
train
https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postgresql.py#L1532-L1545
9,701
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/breakpoint.py
_BufferWatchCondition.remove
def remove(self, bw): """ Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed. """ try: self.__ranges.remove(bw) except ...
python
def remove(self, bw): """ Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed. """ try: self.__ranges.remove(bw) except ...
['def', 'remove', '(', 'self', ',', 'bw', ')', ':', 'try', ':', 'self', '.', '__ranges', '.', 'remove', '(', 'bw', ')', 'except', 'KeyError', ':', 'if', 'not', 'bw', '.', 'oneshot', ':', 'raise']
Removes a buffer watch identifier. @type bw: L{BufferWatch} @param bw: Buffer watch identifier. @raise KeyError: The buffer watch identifier was already removed.
['Removes', 'a', 'buffer', 'watch', 'identifier', '.']
train
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L1840-L1854
9,702
gwastro/pycbc
pycbc/workflow/minifollowups.py
setup_foreground_minifollowups
def setup_foreground_minifollowups(workflow, coinc_file, single_triggers, tmpltbank_file, insp_segs, insp_data_name, insp_anal_name, dax_output, out_dir, tags=None): """ Create plots that followup the Nth loudest coincident injection from a statmap produced HDF file...
python
def setup_foreground_minifollowups(workflow, coinc_file, single_triggers, tmpltbank_file, insp_segs, insp_data_name, insp_anal_name, dax_output, out_dir, tags=None): """ Create plots that followup the Nth loudest coincident injection from a statmap produced HDF file...
['def', 'setup_foreground_minifollowups', '(', 'workflow', ',', 'coinc_file', ',', 'single_triggers', ',', 'tmpltbank_file', ',', 'insp_segs', ',', 'insp_data_name', ',', 'insp_anal_name', ',', 'dax_output', ',', 'out_dir', ',', 'tags', '=', 'None', ')', ':', 'logging', '.', 'info', '(', "'Entering minifollowups module...
Create plots that followup the Nth loudest coincident injection from a statmap produced HDF file. Parameters ---------- workflow: pycbc.workflow.Workflow The core workflow instance we are populating coinc_file: single_triggers: list of pycbc.workflow.File A list cointaining the ...
['Create', 'plots', 'that', 'followup', 'the', 'Nth', 'loudest', 'coincident', 'injection', 'from', 'a', 'statmap', 'produced', 'HDF', 'file', '.']
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/minifollowups.py#L32-L123
9,703
asyncdef/apyio
apyio/__init__.py
StringIO
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
python
def StringIO(*args, **kwargs): """StringIO constructor shim for the async wrapper.""" raw = sync_io.StringIO(*args, **kwargs) return AsyncStringIOWrapper(raw)
['def', 'StringIO', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'raw', '=', 'sync_io', '.', 'StringIO', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', 'return', 'AsyncStringIOWrapper', '(', 'raw', ')']
StringIO constructor shim for the async wrapper.
['StringIO', 'constructor', 'shim', 'for', 'the', 'async', 'wrapper', '.']
train
https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L882-L885
9,704
sentinel-hub/sentinelhub-py
sentinelhub/download.py
_check_if_must_download
def _check_if_must_download(request_list, redownload): """ Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownlo...
python
def _check_if_must_download(request_list, redownload): """ Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownlo...
['def', '_check_if_must_download', '(', 'request_list', ',', 'redownload', ')', ':', 'for', 'request', 'in', 'request_list', ':', 'request', '.', 'will_download', '=', '(', 'request', '.', 'save_response', 'or', 'request', '.', 'return_data', ')', 'and', '(', 'not', 'request', '.', 'is_downloaded', '(', ')', 'or', 'red...
Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownload: tells whether to download the data again or not :type: bool
['Updates', 'request', '.', 'will_download', 'attribute', 'of', 'each', 'request', 'in', 'request_list', '.']
train
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L202-L215
9,705
HDI-Project/MLPrimitives
mlprimitives/candidates/dsp.py
SpectralMask.fit_freq_min_max
def fit_freq_min_max(self, training_signal): """Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_weight = sum(...
python
def fit_freq_min_max(self, training_signal): """Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_weight = sum(...
['def', 'fit_freq_min_max', '(', 'self', ',', 'training_signal', ')', ':', 'window_length', '=', 'len', '(', 'self', '.', 'window', ')', 'window_weight', '=', 'sum', '(', 'self', '.', 'window', ')', 'max_mask', '=', 'np', '.', 'zeros', '(', 'int', '(', 'window_length', '/', '2', ')', '+', '1', ')', 'min_mask', '=', 'np...
Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data
['Defines', 'a', 'spectral', 'mask', 'based', 'on', 'training', 'data', 'using', 'min', 'and', 'max', 'values', 'of', 'each', 'frequency', 'component', 'Args', ':', 'training_signal', ':', 'Training', 'data']
train
https://github.com/HDI-Project/MLPrimitives/blob/bf415f9f751724ff545a1156ddfd7524e320f469/mlprimitives/candidates/dsp.py#L79-L100
9,706
twisted/txaws
txaws/ec2/client.py
Parser.create_snapshot
def create_snapshot(self, xml_bytes): """Parse the XML returned by the C{CreateSnapshot} function. @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root element. @return: The L{Snapshot} instance created. TODO: ownerId, volumeSize, description. """ ...
python
def create_snapshot(self, xml_bytes): """Parse the XML returned by the C{CreateSnapshot} function. @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root element. @return: The L{Snapshot} instance created. TODO: ownerId, volumeSize, description. """ ...
['def', 'create_snapshot', '(', 'self', ',', 'xml_bytes', ')', ':', 'root', '=', 'XML', '(', 'xml_bytes', ')', 'snapshot_id', '=', 'root', '.', 'findtext', '(', '"snapshotId"', ')', 'volume_id', '=', 'root', '.', 'findtext', '(', '"volumeId"', ')', 'status', '=', 'root', '.', 'findtext', '(', '"status"', ')', 'start_ti...
Parse the XML returned by the C{CreateSnapshot} function. @param xml_bytes: XML bytes with a C{CreateSnapshotResponse} root element. @return: The L{Snapshot} instance created. TODO: ownerId, volumeSize, description.
['Parse', 'the', 'XML', 'returned', 'by', 'the', 'C', '{', 'CreateSnapshot', '}', 'function', '.']
train
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L868-L887
9,707
prometheus/client_python
prometheus_client/metrics_core.py
Metric.add_sample
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
python
def add_sample(self, name, labels, value, timestamp=None, exemplar=None): """Add a sample to the metric. Internal-only, do not use.""" self.samples.append(Sample(name, labels, value, timestamp, exemplar))
['def', 'add_sample', '(', 'self', ',', 'name', ',', 'labels', ',', 'value', ',', 'timestamp', '=', 'None', ',', 'exemplar', '=', 'None', ')', ':', 'self', '.', 'samples', '.', 'append', '(', 'Sample', '(', 'name', ',', 'labels', ',', 'value', ',', 'timestamp', ',', 'exemplar', ')', ')']
Add a sample to the metric. Internal-only, do not use.
['Add', 'a', 'sample', 'to', 'the', 'metric', '.']
train
https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics_core.py#L38-L42
9,708
edx/xblock-utils
xblockutils/studio_editable.py
StudioEditableXBlockMixin._make_field_info
def _make_field_info(self, field_name, field): """ Create the information that the template needs to render a form field for this field. """ supported_field_types = ( (Integer, 'integer'), (Float, 'float'), (Boolean, 'boolean'), (String, 's...
python
def _make_field_info(self, field_name, field): """ Create the information that the template needs to render a form field for this field. """ supported_field_types = ( (Integer, 'integer'), (Float, 'float'), (Boolean, 'boolean'), (String, 's...
['def', '_make_field_info', '(', 'self', ',', 'field_name', ',', 'field', ')', ':', 'supported_field_types', '=', '(', '(', 'Integer', ',', "'integer'", ')', ',', '(', 'Float', ',', "'float'", ')', ',', '(', 'Boolean', ',', "'boolean'", ')', ',', '(', 'String', ',', "'string'", ')', ',', '(', 'List', ',', "'list'", ')'...
Create the information that the template needs to render a form field for this field.
['Create', 'the', 'information', 'that', 'the', 'template', 'needs', 'to', 'render', 'a', 'form', 'field', 'for', 'this', 'field', '.']
train
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L100-L202
9,709
rackerlabs/rackspace-python-neutronclient
neutronclient/v2_0/client.py
Client.list_flavors
def list_flavors(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavors for a project.""" return self.list('flavors', self.flavors_path, retrieve_all, **_params)
python
def list_flavors(self, retrieve_all=True, **_params): """Fetches a list of all Neutron service flavors for a project.""" return self.list('flavors', self.flavors_path, retrieve_all, **_params)
['def', 'list_flavors', '(', 'self', ',', 'retrieve_all', '=', 'True', ',', '*', '*', '_params', ')', ':', 'return', 'self', '.', 'list', '(', "'flavors'", ',', 'self', '.', 'flavors_path', ',', 'retrieve_all', ',', '*', '*', '_params', ')']
Fetches a list of all Neutron service flavors for a project.
['Fetches', 'a', 'list', 'of', 'all', 'Neutron', 'service', 'flavors', 'for', 'a', 'project', '.']
train
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1643-L1646
9,710
theislab/scanpy
scanpy/queries/__init__.py
gene_coordinates
def gene_coordinates(host, org, gene, chr_exclude=[]) -> pd.DataFrame: """Retrieve gene coordinates for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. Can be used to control genome build. org : {{'hsapiens', 'mmusculus', '...
python
def gene_coordinates(host, org, gene, chr_exclude=[]) -> pd.DataFrame: """Retrieve gene coordinates for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. Can be used to control genome build. org : {{'hsapiens', 'mmusculus', '...
['def', 'gene_coordinates', '(', 'host', ',', 'org', ',', 'gene', ',', 'chr_exclude', '=', '[', ']', ')', '->', 'pd', '.', 'DataFrame', ':', 'try', ':', 'from', 'bioservices', 'import', 'biomart', 'except', 'ImportError', ':', 'raise', 'ImportError', '(', "'You need to install the `bioservices` module.'", ')', 'from', ...
Retrieve gene coordinates for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. Can be used to control genome build. org : {{'hsapiens', 'mmusculus', 'drerio'}} Organism to query. Currently available are human ('hsapiens'...
['Retrieve', 'gene', 'coordinates', 'for', 'specific', 'organism', 'through', 'BioMart', '.', 'Parameters', '----------', 'host', ':', '{{', 'www', '.', 'ensembl', '.', 'org', '...', '}}', 'A', 'valid', 'BioMart', 'host', 'URL', '.', 'Can', 'be', 'used', 'to', 'control', 'genome', 'build', '.', 'org', ':', '{{', 'hsapi...
train
https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/queries/__init__.py#L56-L108
9,711
moonlitesolutions/SolrClient
SolrClient/zk.py
ZK.copy_config
def copy_config(self, original, new): ''' Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param n...
python
def copy_config(self, original, new): ''' Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param n...
['def', 'copy_config', '(', 'self', ',', 'original', ',', 'new', ')', ':', 'if', 'not', 'self', '.', 'kz', '.', 'exists', '(', "'/configs/{}'", '.', 'format', '(', 'original', ')', ')', ':', 'raise', 'ZookeeperError', '(', '"Collection doesn\'t exist in Zookeeper. Current Collections are: {}"', '.', 'format', '(', 'sel...
Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param new str: New name of the ZK config.
['Copies', 'collection', 'configs', 'into', 'a', 'new', 'folder', '.', 'Can', 'be', 'used', 'to', 'create', 'new', 'collections', 'based', 'on', 'existing', 'configs', '.']
train
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/zk.py#L98-L111
9,712
insightindustry/validator-collection
validator_collection/validators.py
email
def email(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc532...
python
def email(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc532...
['def', 'email', '(', 'value', ',', 'allow_empty', '=', 'False', ',', '*', '*', 'kwargs', ')', ':', '# pylint: disable=too-many-branches,too-many-statements,R0914', 'if', 'not', 'value', 'and', 'not', 'allow_empty', ':', 'raise', 'errors', '.', 'EmptyValueError', '(', "'value (%s) was empty'", '%', 'value', ')', 'elif'...
Validate that ``value`` is a valid email address. .. note:: Email address validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of string parsing and regular expressions....
['Validate', 'that', 'value', 'is', 'a', 'valid', 'email', 'address', '.']
train
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2055-L2212
9,713
datastore/datastore
datastore/core/basic.py
SymlinkDatastore._follow_link
def _follow_link(self, value): '''Returns given `value` or, if it is a symlink, the `value` it names.''' seen_keys = set() while True: link_key = self._link_for_value(value) if not link_key: return value assert link_key not in seen_keys, 'circular symlink reference' seen_key...
python
def _follow_link(self, value): '''Returns given `value` or, if it is a symlink, the `value` it names.''' seen_keys = set() while True: link_key = self._link_for_value(value) if not link_key: return value assert link_key not in seen_keys, 'circular symlink reference' seen_key...
['def', '_follow_link', '(', 'self', ',', 'value', ')', ':', 'seen_keys', '=', 'set', '(', ')', 'while', 'True', ':', 'link_key', '=', 'self', '.', '_link_for_value', '(', 'value', ')', 'if', 'not', 'link_key', ':', 'return', 'value', 'assert', 'link_key', 'not', 'in', 'seen_keys', ',', "'circular symlink reference'", ...
Returns given `value` or, if it is a symlink, the `value` it names.
['Returns', 'given', 'value', 'or', 'if', 'it', 'is', 'a', 'symlink', 'the', 'value', 'it', 'names', '.']
train
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L739-L749
9,714
python-cmd2/cmd2
cmd2/utils.py
quote_string_if_needed
def quote_string_if_needed(arg: str) -> str: """ Quotes a string if it contains spaces and isn't already quoted """ if is_quoted(arg) or ' ' not in arg: return arg if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
python
def quote_string_if_needed(arg: str) -> str: """ Quotes a string if it contains spaces and isn't already quoted """ if is_quoted(arg) or ' ' not in arg: return arg if '"' in arg: quote = "'" else: quote = '"' return quote + arg + quote
['def', 'quote_string_if_needed', '(', 'arg', ':', 'str', ')', '->', 'str', ':', 'if', 'is_quoted', '(', 'arg', ')', 'or', "' '", 'not', 'in', 'arg', ':', 'return', 'arg', 'if', '\'"\'', 'in', 'arg', ':', 'quote', '=', '"\'"', 'else', ':', 'quote', '=', '\'"\'', 'return', 'quote', '+', 'arg', '+', 'quote']
Quotes a string if it contains spaces and isn't already quoted
['Quotes', 'a', 'string', 'if', 'it', 'contains', 'spaces', 'and', 'isn', 't', 'already', 'quoted']
train
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L46-L56
9,715
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py
PDFEmitter
def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return n...
python
def PDFEmitter(target, source, env): """Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file. """ def strip_suffixes(n): return n...
['def', 'PDFEmitter', '(', 'target', ',', 'source', ',', 'env', ')', ':', 'def', 'strip_suffixes', '(', 'n', ')', ':', 'return', 'not', 'SCons', '.', 'Util', '.', 'splitext', '(', 'str', '(', 'n', ')', ')', '[', '1', ']', 'in', '[', "'.aux'", ',', "'.log'", ']', 'source', '=', '[', 'src', 'for', 'src', 'in', 'source', ...
Strips any .aux or .log files from the input source list. These are created by the TeX Builder that in all likelihood was used to generate the .dvi file we're using as input, and we only care about the .dvi file.
['Strips', 'any', '.', 'aux', 'or', '.', 'log', 'files', 'from', 'the', 'input', 'source', 'list', '.', 'These', 'are', 'created', 'by', 'the', 'TeX', 'Builder', 'that', 'in', 'all', 'likelihood', 'was', 'used', 'to', 'generate', 'the', '.', 'dvi', 'file', 'we', 're', 'using', 'as', 'input', 'and', 'we', 'only', 'care'...
train
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/dvipdf.py#L82-L91
9,716
persephone-tools/persephone
persephone/datasets/bkw.py
pull_en_words
def pull_en_words() -> None: """ Fetches a repository containing English words. """ ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git" en_words_path = Path(config.EN_WORDS_PATH) if not en_words_path.is_file(): subprocess.run(["git", "clone", ENGLISH_WORDS_UR...
python
def pull_en_words() -> None: """ Fetches a repository containing English words. """ ENGLISH_WORDS_URL = "https://github.com/dwyl/english-words.git" en_words_path = Path(config.EN_WORDS_PATH) if not en_words_path.is_file(): subprocess.run(["git", "clone", ENGLISH_WORDS_UR...
['def', 'pull_en_words', '(', ')', '->', 'None', ':', 'ENGLISH_WORDS_URL', '=', '"https://github.com/dwyl/english-words.git"', 'en_words_path', '=', 'Path', '(', 'config', '.', 'EN_WORDS_PATH', ')', 'if', 'not', 'en_words_path', '.', 'is_file', '(', ')', ':', 'subprocess', '.', 'run', '(', '[', '"git"', ',', '"clone"',...
Fetches a repository containing English words.
['Fetches', 'a', 'repository', 'containing', 'English', 'words', '.']
train
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/datasets/bkw.py#L27-L34
9,717
ZELLMECHANIK-DRESDEN/dclab
dclab/rtdc_dataset/fmt_hierarchy.py
map_indices_parent2child
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
python
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
['def', 'map_indices_parent2child', '(', 'child', ',', 'parent_indices', ')', ':', 'parent', '=', 'child', '.', 'hparent', '# filters', 'pf', '=', 'parent', '.', 'filter', '.', 'all', '# indices in child', 'child_indices', '=', '[', ']', 'count', '=', '0', 'for', 'ii', 'in', 'range', '(', 'len', '(', 'pf', ')', ')', ':...
Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_indices: 1d ndarray child indices
['Map', 'parent', 'RTDCBase', 'event', 'indices', 'to', 'RTDC_Hierarchy']
train
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/rtdc_dataset/fmt_hierarchy.py#L362-L392
9,718
blockstack/blockstack-core
blockstack/lib/atlas.py
atlasdb_init
def atlasdb_init( path, zonefile_dir, db, peer_seeds, peer_blacklist, recover=False, validate=False): """ Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the pee...
python
def atlasdb_init( path, zonefile_dir, db, peer_seeds, peer_blacklist, recover=False, validate=False): """ Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the pee...
['def', 'atlasdb_init', '(', 'path', ',', 'zonefile_dir', ',', 'db', ',', 'peer_seeds', ',', 'peer_blacklist', ',', 'recover', '=', 'False', ',', 'validate', '=', 'False', ')', ':', 'global', 'ATLASDB_SQL', 'peer_table', '=', '{', '}', 'if', 'os', '.', 'path', '.', 'exists', '(', 'path', ')', ':', 'log', '.', 'debug', ...
Set up the atlas node: * create the db if it doesn't exist * go through all the names and verify that we have the *current* zonefiles * if we don't, queue them for fetching. * set up the peer db @db should be an instance of BlockstackDB @initial_peers should be a list of URLs Return the ne...
['Set', 'up', 'the', 'atlas', 'node', ':', '*', 'create', 'the', 'db', 'if', 'it', 'doesn', 't', 'exist', '*', 'go', 'through', 'all', 'the', 'names', 'and', 'verify', 'that', 'we', 'have', 'the', '*', 'current', '*', 'zonefiles', '*', 'if', 'we', 'don', 't', 'queue', 'them', 'for', 'fetching', '.', '*', 'set', 'up', '...
train
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1260-L1352
9,719
asweigart/pysimplevalidate
src/pysimplevalidate/__init__.py
validateState
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): """Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased s...
python
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): """Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased s...
['def', 'validateState', '(', 'value', ',', 'blank', '=', 'False', ',', 'strip', '=', 'None', ',', 'allowlistRegexes', '=', 'None', ',', 'blocklistRegexes', '=', 'None', ',', 'excMsg', '=', 'None', ',', 'returnStateName', '=', 'False', ')', ':', '# TODO - note that this is USA-centric. I should work on trying to make t...
Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased state name. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted....
['Raises', 'ValidationException', 'if', 'value', 'is', 'not', 'a', 'USA', 'state', '.', 'Returns', 'the', 'capitalized', 'state', 'abbreviation', 'unless', 'returnStateName', 'is', 'True', 'in', 'which', 'case', 'it', 'returns', 'the', 'titlecased', 'state', 'name', '.']
train
https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1235-L1279
9,720
google/grr
grr/server/grr_response_server/flow_utils.py
WaitForFlow
def WaitForFlow(flow_urn, token=None, timeout=DEFAULT_TIMEOUT, max_sleep_time=1, min_sleep_time=0.2, dampening_multiplier=0.9): """Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. ...
python
def WaitForFlow(flow_urn, token=None, timeout=DEFAULT_TIMEOUT, max_sleep_time=1, min_sleep_time=0.2, dampening_multiplier=0.9): """Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. ...
['def', 'WaitForFlow', '(', 'flow_urn', ',', 'token', '=', 'None', ',', 'timeout', '=', 'DEFAULT_TIMEOUT', ',', 'max_sleep_time', '=', '1', ',', 'min_sleep_time', '=', '0.2', ',', 'dampening_multiplier', '=', '0.9', ')', ':', 'start_time', '=', 'time', '.', 'time', '(', ')', 'sleep_time', '=', 'max_sleep_time', 'while'...
Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. token: The datastore access token. timeout: How long to wait before giving up, usually because the client has gone away. max_sleep_time: The initial and longest time to wait in between polls. ...
['Waits', 'for', 'a', 'flow', 'to', 'finish', 'polling', 'while', 'we', 'wait', '.']
train
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flow_utils.py#L88-L130
9,721
pandas-dev/pandas
pandas/core/frame.py
DataFrame.combine_first
def combine_first(self, other): """ Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the...
python
def combine_first(self, other): """ Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the...
['def', 'combine_first', '(', 'self', ',', 'other', ')', ':', 'import', 'pandas', '.', 'core', '.', 'computation', '.', 'expressions', 'as', 'expressions', 'def', 'extract_values', '(', 'arr', ')', ':', '# Does two things:', '# 1. maybe gets the values from the Series / Index', '# 2. convert datelike to i8', 'if', 'isi...
Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters -----...
['Update', 'null', 'elements', 'with', 'value', 'in', 'the', 'same', 'location', 'in', 'other', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L5332-L5406
9,722
delfick/harpoon
harpoon/ship/runner.py
Runner.create_container
def create_container(self, conf, detach, tty): """Create a single container""" name = conf.name image_name = conf.image_name if conf.tag is not NotSpecified: image_name = conf.image_name_with_tag container_name = conf.container_name with conf.assumed_role():...
python
def create_container(self, conf, detach, tty): """Create a single container""" name = conf.name image_name = conf.image_name if conf.tag is not NotSpecified: image_name = conf.image_name_with_tag container_name = conf.container_name with conf.assumed_role():...
['def', 'create_container', '(', 'self', ',', 'conf', ',', 'detach', ',', 'tty', ')', ':', 'name', '=', 'conf', '.', 'name', 'image_name', '=', 'conf', '.', 'image_name', 'if', 'conf', '.', 'tag', 'is', 'not', 'NotSpecified', ':', 'image_name', '=', 'conf', '.', 'image_name_with_tag', 'container_name', '=', 'conf', '.'...
Create a single container
['Create', 'a', 'single', 'container']
train
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/ship/runner.py#L226-L328
9,723
MacHu-GWU/angora-project
angora/math/img2waveform.py
img2wav
def img2wav(path, min_x, max_x, min_y, max_y, window_size=3): """Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> ...
python
def img2wav(path, min_x, max_x, min_y, max_y, window_size=3): """Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> ...
['def', 'img2wav', '(', 'path', ',', 'min_x', ',', 'max_x', ',', 'min_y', ',', 'max_y', ',', 'window_size', '=', '3', ')', ':', 'image', '=', 'Image', '.', 'open', '(', 'path', ')', '.', 'convert', '(', '"L"', ')', 'matrix', '=', 'np', '.', 'array', '(', 'image', ')', '[', ':', ':', '-', '1', ']', '# you can customize ...
Generate 1-D data ``y=f(x)`` from a black/white image. Suppose we have an image like that: .. image:: images/waveform.png :align: center Put some codes:: >>> from weatherlab.math.img2waveform import img2wav >>> import matplotlib.pyplot as plt >>> x, y = img2wav(r"testdata...
['Generate', '1', '-', 'D', 'data', 'y', '=', 'f', '(', 'x', ')', 'from', 'a', 'black', '/', 'white', 'image', '.']
train
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/img2waveform.py#L264-L327
9,724
stevearc/dql
dql/models.py
GlobalIndex.pformat
def pformat(self, consumed_capacity=None): """ Pretty format for insertion into table pformat """ consumed_capacity = consumed_capacity or {} lines = [] parts = ["GLOBAL", self.index_type, "INDEX", self.name] if self.status != "ACTIVE": parts.insert(0, "[%s]" % self.s...
python
def pformat(self, consumed_capacity=None): """ Pretty format for insertion into table pformat """ consumed_capacity = consumed_capacity or {} lines = [] parts = ["GLOBAL", self.index_type, "INDEX", self.name] if self.status != "ACTIVE": parts.insert(0, "[%s]" % self.s...
['def', 'pformat', '(', 'self', ',', 'consumed_capacity', '=', 'None', ')', ':', 'consumed_capacity', '=', 'consumed_capacity', 'or', '{', '}', 'lines', '=', '[', ']', 'parts', '=', '[', '"GLOBAL"', ',', 'self', '.', 'index_type', ',', '"INDEX"', ',', 'self', '.', 'name', ']', 'if', 'self', '.', 'status', '!=', '"ACTIV...
Pretty format for insertion into table pformat
['Pretty', 'format', 'for', 'insertion', 'into', 'table', 'pformat']
train
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L282-L305
9,725
bachya/pyairvisual
pyairvisual/supported.py
Supported.cities
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
python
async def cities(self, country: str, state: str) -> list: """Return a list of supported cities in a country/state.""" data = await self._request( 'get', 'cities', params={ 'state': state, 'country': country }) return [d['city'] for d in dat...
['async', 'def', 'cities', '(', 'self', ',', 'country', ':', 'str', ',', 'state', ':', 'str', ')', '->', 'list', ':', 'data', '=', 'await', 'self', '.', '_request', '(', "'get'", ',', "'cities'", ',', 'params', '=', '{', "'state'", ':', 'state', ',', "'country'", ':', 'country', '}', ')', 'return', '[', 'd', '[', "'cit...
Return a list of supported cities in a country/state.
['Return', 'a', 'list', 'of', 'supported', 'cities', 'in', 'a', 'country', '/', 'state', '.']
train
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/supported.py#L12-L19
9,726
mitsei/dlkit
dlkit/handcar/learning/managers.py
LearningManager.get_objective_bank_lookup_session
def get_objective_bank_lookup_session(self, *args, **kwargs): """Gets the OsidSession associated with the objective bank lookup service. return: (osid.learning.ObjectiveBankLookupSession) - an ObjectiveBankLookupSession raise: OperationFailed - unable to complete reques...
python
def get_objective_bank_lookup_session(self, *args, **kwargs): """Gets the OsidSession associated with the objective bank lookup service. return: (osid.learning.ObjectiveBankLookupSession) - an ObjectiveBankLookupSession raise: OperationFailed - unable to complete reques...
['def', 'get_objective_bank_lookup_session', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'if', 'not', 'self', '.', 'supports_objective_bank_lookup', '(', ')', ':', 'raise', 'Unimplemented', '(', ')', 'try', ':', 'from', '.', 'import', 'sessions', 'except', 'ImportError', ':', 'raise', 'OperationFa...
Gets the OsidSession associated with the objective bank lookup service. return: (osid.learning.ObjectiveBankLookupSession) - an ObjectiveBankLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_objective_bank_lookup() is ...
['Gets', 'the', 'OsidSession', 'associated', 'with', 'the', 'objective', 'bank', 'lookup', 'service', '.']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/managers.py#L2082-L2105
9,727
cggh/scikit-allel
allel/stats/diversity.py
tajima_d
def tajima_d(ac, pos=None, start=None, stop=None, min_sites=3): """Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant position...
python
def tajima_d(ac, pos=None, start=None, stop=None, min_sites=3): """Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant position...
['def', 'tajima_d', '(', 'ac', ',', 'pos', '=', 'None', ',', 'start', '=', 'None', ',', 'stop', '=', 'None', ',', 'min_sites', '=', '3', ')', ':', '# check inputs', 'if', 'not', 'hasattr', '(', 'ac', ',', "'count_segregating'", ')', ':', 'ac', '=', 'AlleleCountsArray', '(', 'ac', ',', 'copy', '=', 'False', ')', '# deal...
Calculate the value of Tajima's D over a given region. Parameters ---------- ac : array_like, int, shape (n_variants, n_alleles) Allele counts array. pos : array_like, int, shape (n_items,), optional Variant positions, using 1-based coordinates, in ascending order. start : int, opti...
['Calculate', 'the', 'value', 'of', 'Tajima', 's', 'D', 'over', 'a', 'given', 'region', '.']
train
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/diversity.py#L863-L954
9,728
saltstack/salt
salt/netapi/rest_tornado/saltnado.py
EventListener.clean_by_request
def clean_by_request(self, request): ''' Remove all futures that were waiting for request `request` since it is done waiting ''' if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: # timeout the future ...
python
def clean_by_request(self, request): ''' Remove all futures that were waiting for request `request` since it is done waiting ''' if request not in self.request_map: return for tag, matcher, future in self.request_map[request]: # timeout the future ...
['def', 'clean_by_request', '(', 'self', ',', 'request', ')', ':', 'if', 'request', 'not', 'in', 'self', '.', 'request_map', ':', 'return', 'for', 'tag', ',', 'matcher', ',', 'future', 'in', 'self', '.', 'request_map', '[', 'request', ']', ':', '# timeout the future', 'self', '.', '_timeout_future', '(', 'tag', ',', 'm...
Remove all futures that were waiting for request `request` since it is done waiting
['Remove', 'all', 'futures', 'that', 'were', 'waiting', 'for', 'request', 'request', 'since', 'it', 'is', 'done', 'waiting']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado.py#L302-L316
9,729
sorgerlab/indra
indra/explanation/model_checker.py
_get_signed_predecessors
def _get_signed_predecessors(im, node, polarity): """Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediat...
python
def _get_signed_predecessors(im, node, polarity): """Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediat...
['def', '_get_signed_predecessors', '(', 'im', ',', 'node', ',', 'polarity', ')', ':', 'signed_pred_list', '=', '[', ']', 'for', 'pred', 'in', 'im', '.', 'predecessors', '(', 'node', ')', ':', 'pred_edge', '=', '(', 'pred', ',', 'node', ')', 'yield', '(', 'pred', ',', '_get_edge_sign', '(', 'im', ',', 'pred_edge', ')',...
Get upstream nodes in the influence map. Return the upstream nodes along with the overall polarity of the path to that node by account for the polarity of the path to the given node and the polarity of the edge between the given node and its immediate predecessors. Parameters ---------- im...
['Get', 'upstream', 'nodes', 'in', 'the', 'influence', 'map', '.']
train
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L1009-L1037
9,730
bukun/TorCMS
torcms/script/autocrud/fetch_html_dic.py
__get_switch_arr
def __get_switch_arr(work_sheet, row_num): ''' if valud of the column of the row is `1`, it will be added to the array. ''' u_dic = [] for col_idx in FILTER_COLUMNS: cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value if cell_val in [1, '1']: # Appending the ...
python
def __get_switch_arr(work_sheet, row_num): ''' if valud of the column of the row is `1`, it will be added to the array. ''' u_dic = [] for col_idx in FILTER_COLUMNS: cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value if cell_val in [1, '1']: # Appending the ...
['def', '__get_switch_arr', '(', 'work_sheet', ',', 'row_num', ')', ':', 'u_dic', '=', '[', ']', 'for', 'col_idx', 'in', 'FILTER_COLUMNS', ':', 'cell_val', '=', 'work_sheet', '[', "'{0}{1}'", '.', 'format', '(', 'col_idx', ',', 'row_num', ')', ']', '.', 'value', 'if', 'cell_val', 'in', '[', '1', ',', "'1'", ']', ':', '...
if valud of the column of the row is `1`, it will be added to the array.
['if', 'valud', 'of', 'the', 'column', 'of', 'the', 'row', 'is', '1', 'it', 'will', 'be', 'added', 'to', 'the', 'array', '.']
train
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/script/autocrud/fetch_html_dic.py#L135-L146
9,731
hydraplatform/hydra-base
hydra_base/db/model.py
Network.add_node
def add_node(self, name, desc, layout, node_x, node_y): """ Add a node to a network. """ existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first() if existing_node is not None: raise HydraError("A node with name %s is alre...
python
def add_node(self, name, desc, layout, node_x, node_y): """ Add a node to a network. """ existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first() if existing_node is not None: raise HydraError("A node with name %s is alre...
['def', 'add_node', '(', 'self', ',', 'name', ',', 'desc', ',', 'layout', ',', 'node_x', ',', 'node_y', ')', ':', 'existing_node', '=', 'get_session', '(', ')', '.', 'query', '(', 'Node', ')', '.', 'filter', '(', 'Node', '.', 'name', '==', 'name', ',', 'Node', '.', 'network_id', '==', 'self', '.', 'id', ')', '.', 'firs...
Add a node to a network.
['Add', 'a', 'node', 'to', 'a', 'network', '.']
train
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/db/model.py#L885-L907
9,732
hermanschaaf/mafan
mafan/encoding.py
detect
def detect(filename, include_confidence=False): """ Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence) """ f = open(filename) detection = chardet.detect(f.r...
python
def detect(filename, include_confidence=False): """ Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence) """ f = open(filename) detection = chardet.detect(f.r...
['def', 'detect', '(', 'filename', ',', 'include_confidence', '=', 'False', ')', ':', 'f', '=', 'open', '(', 'filename', ')', 'detection', '=', 'chardet', '.', 'detect', '(', 'f', '.', 'read', '(', ')', ')', 'f', '.', 'close', '(', ')', 'encoding', '=', 'detection', '.', 'get', '(', "'encoding'", ')', 'confidence', '='...
Detect the encoding of a file. Returns only the predicted current encoding as a string. If `include_confidence` is True, Returns tuple containing: (str encoding, float confidence)
['Detect', 'the', 'encoding', 'of', 'a', 'file', '.']
train
https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/encoding.py#L67-L83
9,733
tensorpack/tensorpack
tensorpack/graph_builder/training.py
AsyncMultiGPUBuilder.call_for_each_tower
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
python
def call_for_each_tower(self, tower_fn): """ Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower. """ ps_device = 'cpu' if len(self.towers) >= 4 else 'gpu' raw_devic...
['def', 'call_for_each_tower', '(', 'self', ',', 'tower_fn', ')', ':', 'ps_device', '=', "'cpu'", 'if', 'len', '(', 'self', '.', 'towers', ')', '>=', '4', 'else', "'gpu'", 'raw_devices', '=', '[', "'/gpu:{}'", '.', 'format', '(', 'k', ')', 'for', 'k', 'in', 'self', '.', 'towers', ']', 'if', 'ps_device', '==', "'gpu'", ...
Call the function `tower_fn` under :class:`TowerContext` for each tower. Returns: a list, contains the return values of `tower_fn` on each tower.
['Call', 'the', 'function', 'tower_fn', 'under', ':', 'class', ':', 'TowerContext', 'for', 'each', 'tower', '.']
train
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/graph_builder/training.py#L369-L385
9,734
openatx/facebook-wda
wda/__init__.py
Client.source
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
python
def source(self, format='xml', accessible=False): """ Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json' """ if accessible: return self.http.get('/wda/accessibleSource').val...
['def', 'source', '(', 'self', ',', 'format', '=', "'xml'", ',', 'accessible', '=', 'False', ')', ':', 'if', 'accessible', ':', 'return', 'self', '.', 'http', '.', 'get', '(', "'/wda/accessibleSource'", ')', '.', 'value', 'return', 'self', '.', 'http', '.', 'get', '(', "'source?format='", '+', 'format', ')', '.', 'valu...
Args: format (str): only 'xml' and 'json' source types are supported accessible (bool): when set to true, format is always 'json'
['Args', ':', 'format', '(', 'str', ')', ':', 'only', 'xml', 'and', 'json', 'source', 'types', 'are', 'supported', 'accessible', '(', 'bool', ')', ':', 'when', 'set', 'to', 'true', 'format', 'is', 'always', 'json']
train
https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L229-L237
9,735
raghakot/keras-vis
vis/utils/utils.py
find_layer_idx
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
python
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
['def', 'find_layer_idx', '(', 'model', ',', 'layer_name', ')', ':', 'layer_idx', '=', 'None', 'for', 'idx', ',', 'layer', 'in', 'enumerate', '(', 'model', '.', 'layers', ')', ':', 'if', 'layer', '.', 'name', '==', 'layer_name', ':', 'layer_idx', '=', 'idx', 'break', 'if', 'layer_idx', 'is', 'None', ':', 'raise', 'Valu...
Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise.
['Looks', 'up', 'the', 'layer', 'index', 'corresponding', 'to', 'layer_name', 'from', 'model', '.']
train
https://github.com/raghakot/keras-vis/blob/668b0e11dab93f3487f23c17e07f40554a8939e9/vis/utils/utils.py#L136-L154
9,736
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.create_dcnm_in_nwk
def create_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM In Network and store the result in DB. """ tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_CREAT...
python
def create_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM In Network and store the result in DB. """ tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_CREAT...
['def', 'create_dcnm_in_nwk', '(', 'self', ',', 'tenant_id', ',', 'fw_dict', ',', 'is_fw_virt', '=', 'False', ')', ':', 'tenant_name', '=', 'fw_dict', '.', 'get', '(', "'tenant_name'", ')', 'ret', '=', 'self', '.', '_create_service_nwk', '(', 'tenant_id', ',', 'tenant_name', ',', "'in'", ')', 'if', 'ret', ':', 'res', '...
Create the DCNM In Network and store the result in DB.
['Create', 'the', 'DCNM', 'In', 'Network', 'and', 'store', 'the', 'result', 'in', 'DB', '.']
train
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1289-L1302
9,737
googleapis/dialogflow-python-client-v2
samples/knowledge_base_management.py
list_knowledge_bases
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print...
python
def list_knowledge_bases(project_id): """Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() project_path = client.project_path(project_id) print...
['def', 'list_knowledge_bases', '(', 'project_id', ')', ':', 'import', 'dialogflow_v2beta1', 'as', 'dialogflow', 'client', '=', 'dialogflow', '.', 'KnowledgeBasesClient', '(', ')', 'project_path', '=', 'client', '.', 'project_path', '(', 'project_id', ')', 'print', '(', "'Knowledge Bases for: {}'", '.', 'format', '(', ...
Lists the Knowledge bases belonging to a project. Args: project_id: The GCP project linked with the agent.
['Lists', 'the', 'Knowledge', 'bases', 'belonging', 'to', 'a', 'project', '.']
train
https://github.com/googleapis/dialogflow-python-client-v2/blob/8c9c8709222efe427b76c9c8fcc04a0c4a0760b5/samples/knowledge_base_management.py#L35-L47
9,738
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_viable_phone_number
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance ...
python
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance ...
['def', '_is_viable_phone_number', '(', 'number', ')', ':', 'if', 'len', '(', 'number', ')', '<', '_MIN_LENGTH_FOR_NSN', ':', 'return', 'False', 'match', '=', 'fullmatch', '(', '_VALID_PHONE_NUMBER_PATTERN', ',', 'number', ')', 'return', 'bool', '(', 'match', ')']
Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-numbe...
['Checks', 'to', 'see', 'if', 'a', 'string', 'could', 'possibly', 'be', 'a', 'phone', 'number', '.']
train
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L545-L563
9,739
welbornprod/colr
colr/progress_frames.py
BarSet.with_wrapper
def with_wrapper(self, wrapper=None, name=None): """ Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper. """ name...
python
def with_wrapper(self, wrapper=None, name=None): """ Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper. """ name...
['def', 'with_wrapper', '(', 'self', ',', 'wrapper', '=', 'None', ',', 'name', '=', 'None', ')', ':', 'name', '=', 'name', 'or', "'{}_custom_wrapper'", '.', 'format', '(', 'self', '.', 'name', ')', 'return', 'self', '.', '__class__', '(', 'self', '.', 'data', ',', 'name', '=', 'name', ',', 'wrapper', '=', 'wrapper', ')...
Copy this BarSet, and return a new BarSet with the specified name and wrapper. If no name is given, `{self.name}_custom_wrapper` is used. If no wrapper is given, the new BarSet will have no wrapper.
['Copy', 'this', 'BarSet', 'and', 'return', 'a', 'new', 'BarSet', 'with', 'the', 'specified', 'name', 'and', 'wrapper', '.', 'If', 'no', 'name', 'is', 'given', '{', 'self', '.', 'name', '}', '_custom_wrapper', 'is', 'used', '.', 'If', 'no', 'wrapper', 'is', 'given', 'the', 'new', 'BarSet', 'will', 'have', 'no', 'wrappe...
train
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L599-L606
9,740
yyuu/botornado
boto/mturk/connection.py
MTurkConnection._process_response
def _process_response(self, response, marker_elems=None): """ Helper to process the xml response from AWS """ body = response.read() #print body if '<Errors>' not in body: rs = ResultSet(marker_elems) h = handler.XmlHandler(rs, self) xm...
python
def _process_response(self, response, marker_elems=None): """ Helper to process the xml response from AWS """ body = response.read() #print body if '<Errors>' not in body: rs = ResultSet(marker_elems) h = handler.XmlHandler(rs, self) xm...
['def', '_process_response', '(', 'self', ',', 'response', ',', 'marker_elems', '=', 'None', ')', ':', 'body', '=', 'response', '.', 'read', '(', ')', '#print body', 'if', "'<Errors>'", 'not', 'in', 'body', ':', 'rs', '=', 'ResultSet', '(', 'marker_elems', ')', 'h', '=', 'handler', '.', 'XmlHandler', '(', 'rs', ',', 's...
Helper to process the xml response from AWS
['Helper', 'to', 'process', 'the', 'xml', 'response', 'from', 'AWS']
train
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/mturk/connection.py#L734-L746
9,741
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/vcenter.py
Vcenter.add_vcenter
def add_vcenter(self, **kwargs): """ Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function):...
python
def add_vcenter(self, **kwargs): """ Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function):...
['def', 'add_vcenter', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'vcenter', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"vcenter"', ',', 'xmlns', '=', '"urn:brocade.com:mgmt:brocade-vswitch"', ')', 'id', '=', 'ET', '.', 'SubElement', '(', 'vcenter'...
Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function): A function executed upon completion of the ...
['Add', 'vCenter', 'on', 'the', 'switch']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/vcenter.py#L40-L77
9,742
yangl1996/libpagure
libpagure/libpagure.py
Pagure.list_tags
def list_tags(self, pattern=None): """ List all tags made on this project. :param pattern: filters the starting letters of the return value :return: """ request_url = "{}tags".format(self.create_basic_url()) params = None if pattern: params = ...
python
def list_tags(self, pattern=None): """ List all tags made on this project. :param pattern: filters the starting letters of the return value :return: """ request_url = "{}tags".format(self.create_basic_url()) params = None if pattern: params = ...
['def', 'list_tags', '(', 'self', ',', 'pattern', '=', 'None', ')', ':', 'request_url', '=', '"{}tags"', '.', 'format', '(', 'self', '.', 'create_basic_url', '(', ')', ')', 'params', '=', 'None', 'if', 'pattern', ':', 'params', '=', '{', "'pattern'", ':', 'pattern', '}', 'return_value', '=', 'self', '.', '_call_api', '...
List all tags made on this project. :param pattern: filters the starting letters of the return value :return:
['List', 'all', 'tags', 'made', 'on', 'this', 'project', '.', ':', 'param', 'pattern', ':', 'filters', 'the', 'starting', 'letters', 'of', 'the', 'return', 'value', ':', 'return', ':']
train
https://github.com/yangl1996/libpagure/blob/dd96ed29142407463790c66ed321984a6ea7465a/libpagure/libpagure.py#L138-L151
9,743
WebarchivCZ/WA-KAT
src/wa_kat/connectors/seeder.py
_send_request
def _send_request(url_id, data=None, json=None, req_type=None): """ Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_t...
python
def _send_request(url_id, data=None, json=None, req_type=None): """ Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_t...
['def', '_send_request', '(', 'url_id', ',', 'data', '=', 'None', ',', 'json', '=', 'None', ',', 'req_type', '=', 'None', ')', ':', 'url', '=', 'settings', '.', 'SEEDER_INFO_URL', '%', 'url_id', 'if', 'not', 'req_type', ':', 'req_type', '=', 'requests', '.', 'get', 'resp', '=', 'req_type', '(', 'url', ',', 'data', '=',...
Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_type (fn, default None): Request method used to send/download the ...
['Send', 'request', 'to', 'Seeder', 's', 'API', '.']
train
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/connectors/seeder.py#L123-L155
9,744
bcbio/bcbio-nextgen
bcbio/heterogeneity/bubbletree.py
_is_possible_loh
def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None): """Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements. """ if _is_biallelic_snp(rec) and _passes_plus_...
python
def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None): """Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements. """ if _is_biallelic_snp(rec) and _passes_plus_...
['def', '_is_possible_loh', '(', 'rec', ',', 'vcf_rec', ',', 'params', ',', 'somatic_info', ',', 'use_status', '=', 'False', ',', 'max_normal_depth', '=', 'None', ')', ':', 'if', '_is_biallelic_snp', '(', 'rec', ')', 'and', '_passes_plus_germline', '(', 'rec', ',', 'use_status', '=', 'use_status', ')', ':', 'stats', '=...
Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements.
['Check', 'if', 'the', 'VCF', 'record', 'is', 'a', 'het', 'in', 'the', 'normal', 'with', 'sufficient', 'support', '.']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/heterogeneity/bubbletree.py#L358-L378
9,745
binbrain/OpenSesame
OpenSesame/keyring.py
OpenKeyring._auto_unlock_key_position
def _auto_unlock_key_position(self): """Find the open sesame password in the default keyring """ found_pos = None default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring) for pos in default_keyring_ids: item_attrs = gkr.item_get_attributes_sync(self.default_...
python
def _auto_unlock_key_position(self): """Find the open sesame password in the default keyring """ found_pos = None default_keyring_ids = gkr.list_item_ids_sync(self.default_keyring) for pos in default_keyring_ids: item_attrs = gkr.item_get_attributes_sync(self.default_...
['def', '_auto_unlock_key_position', '(', 'self', ')', ':', 'found_pos', '=', 'None', 'default_keyring_ids', '=', 'gkr', '.', 'list_item_ids_sync', '(', 'self', '.', 'default_keyring', ')', 'for', 'pos', 'in', 'default_keyring_ids', ':', 'item_attrs', '=', 'gkr', '.', 'item_get_attributes_sync', '(', 'self', '.', 'defa...
Find the open sesame password in the default keyring
['Find', 'the', 'open', 'sesame', 'password', 'in', 'the', 'default', 'keyring']
train
https://github.com/binbrain/OpenSesame/blob/e32c306385012646400ecb49fc65c64b14ce3a93/OpenSesame/keyring.py#L50-L61
9,746
blockstack/blockstack-core
blockstack/lib/nameset/db.py
namedb_get_names_owned_by_address
def namedb_get_names_owned_by_address( cur, address, current_block ): """ Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name. """ unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block ) ...
python
def namedb_get_names_owned_by_address( cur, address, current_block ): """ Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name. """ unexpired_fragment, unexpired_args = namedb_select_where_unexpired_names( current_block ) ...
['def', 'namedb_get_names_owned_by_address', '(', 'cur', ',', 'address', ',', 'current_block', ')', ':', 'unexpired_fragment', ',', 'unexpired_args', '=', 'namedb_select_where_unexpired_names', '(', 'current_block', ')', 'select_query', '=', '"SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id =...
Get the list of non-expired, non-revoked names owned by an address. Only works if there is a *singular* address for the name.
['Get', 'the', 'list', 'of', 'non', '-', 'expired', 'non', '-', 'revoked', 'names', 'owned', 'by', 'an', 'address', '.', 'Only', 'works', 'if', 'there', 'is', 'a', '*', 'singular', '*', 'address', 'for', 'the', 'name', '.']
train
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2245-L2266
9,747
Kronuz/pyScss
scss/source.py
SourceFile.from_string
def from_string(cls, string, relpath=None, encoding=None, is_sass=None): """Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". """ if isinstance(string, six.text_type): # Already decoded; we don't know what encodin...
python
def from_string(cls, string, relpath=None, encoding=None, is_sass=None): """Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...". """ if isinstance(string, six.text_type): # Already decoded; we don't know what encodin...
['def', 'from_string', '(', 'cls', ',', 'string', ',', 'relpath', '=', 'None', ',', 'encoding', '=', 'None', ',', 'is_sass', '=', 'None', ')', ':', 'if', 'isinstance', '(', 'string', ',', 'six', '.', 'text_type', ')', ':', "# Already decoded; we don't know what encoding to use for output,", '# though, so still check fo...
Read Sass source from the contents of a string. The origin is always None. `relpath` defaults to "string:...".
['Read', 'Sass', 'source', 'from', 'the', 'contents', 'of', 'a', 'string', '.']
train
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/source.py#L224-L256
9,748
Boudewijn26/gTTS-token
gtts_token/gtts_token.py
Token.calculate_token
def calculate_token(self, text, seed=None): """ Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch """ if seed is None: seed = self._ge...
python
def calculate_token(self, text, seed=None): """ Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch """ if seed is None: seed = self._ge...
['def', 'calculate_token', '(', 'self', ',', 'text', ',', 'seed', '=', 'None', ')', ':', 'if', 'seed', 'is', 'None', ':', 'seed', '=', 'self', '.', '_get_token_key', '(', ')', '[', 'first_seed', ',', 'second_seed', ']', '=', 'seed', '.', 'split', '(', '"."', ')', 'try', ':', 'd', '=', 'bytearray', '(', 'text', '.', 'en...
Calculate the request token (`tk`) of a string :param text: str The text to calculate a token for :param seed: str The seed to use. By default this is the number of hours since epoch
['Calculate', 'the', 'request', 'token', '(', 'tk', ')', 'of', 'a', 'string', ':', 'param', 'text', ':', 'str', 'The', 'text', 'to', 'calculate', 'a', 'token', 'for', ':', 'param', 'seed', ':', 'str', 'The', 'seed', 'to', 'use', '.', 'By', 'default', 'this', 'is', 'the', 'number', 'of', 'hours', 'since', 'epoch']
train
https://github.com/Boudewijn26/gTTS-token/blob/9a1bb569bcce1ec091bfd9586dd54f9c879e7d3c/gtts_token/gtts_token.py#L21-L49
9,749
Azure/azure-event-hubs-python
azure/eventhub/sender.py
Sender.open
def open(self): """ Open the Sender using the supplied conneciton. If the handler has previously been redirected, the redirect context will be used to create a new handler before opening it. :param connection: The underlying client shared connection. :type: connection: ~...
python
def open(self): """ Open the Sender using the supplied conneciton. If the handler has previously been redirected, the redirect context will be used to create a new handler before opening it. :param connection: The underlying client shared connection. :type: connection: ~...
['def', 'open', '(', 'self', ')', ':', 'self', '.', 'running', '=', 'True', 'if', 'self', '.', 'redirected', ':', 'self', '.', 'target', '=', 'self', '.', 'redirected', '.', 'address', 'self', '.', '_handler', '=', 'SendClient', '(', 'self', '.', 'target', ',', 'auth', '=', 'self', '.', 'client', '.', 'get_auth', '(', ...
Open the Sender using the supplied conneciton. If the handler has previously been redirected, the redirect context will be used to create a new handler before opening it. :param connection: The underlying client shared connection. :type: connection: ~uamqp.connection.Connection
['Open', 'the', 'Sender', 'using', 'the', 'supplied', 'conneciton', '.', 'If', 'the', 'handler', 'has', 'previously', 'been', 'redirected', 'the', 'redirect', 'context', 'will', 'be', 'used', 'to', 'create', 'a', 'new', 'handler', 'before', 'opening', 'it', '.']
train
https://github.com/Azure/azure-event-hubs-python/blob/737c5f966557ada2cf10fa0d8f3c19671ae96348/azure/eventhub/sender.py#L72-L95
9,750
frejanordsiek/hdf5storage
hdf5storage/utilities.py
set_attributes_all
def set_attributes_all(target, attributes, discard_others=True): """ Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying it in place if possible if it is already present) and optionally discarding all other Attributes not explicitly set. This function yields muc...
python
def set_attributes_all(target, attributes, discard_others=True): """ Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying it in place if possible if it is already present) and optionally discarding all other Attributes not explicitly set. This function yields muc...
['def', 'set_attributes_all', '(', 'target', ',', 'attributes', ',', 'discard_others', '=', 'True', ')', ':', 'attrs', '=', 'target', '.', 'attrs', 'existing', '=', 'dict', '(', 'attrs', '.', 'items', '(', ')', ')', '# Generate special dtype for string arrays.', 'if', 'sys', '.', 'hexversion', '>=', '0x03000000', ':', ...
Set Attributes in bulk and optionally discard others. Sets each Attribute in turn (modifying it in place if possible if it is already present) and optionally discarding all other Attributes not explicitly set. This function yields much greater performance than the required individual calls to ``set_att...
['Set', 'Attributes', 'in', 'bulk', 'and', 'optionally', 'discard', 'others', '.']
train
https://github.com/frejanordsiek/hdf5storage/blob/539275141dd3a4efbbbfd9bdb978f3ed59e3f05d/hdf5storage/utilities.py#L1537-L1599
9,751
bykof/billomapy
billomapy/billomapy.py
Billomapy.complete_delivery_note
def complete_delivery_note(self, delivery_note_id, complete_dict): """ Completes an delivery note :param complete_dict: the complete dict with the template id :param delivery_note_id: the delivery note id :return: Response """ return self._create_put_request( ...
python
def complete_delivery_note(self, delivery_note_id, complete_dict): """ Completes an delivery note :param complete_dict: the complete dict with the template id :param delivery_note_id: the delivery note id :return: Response """ return self._create_put_request( ...
['def', 'complete_delivery_note', '(', 'self', ',', 'delivery_note_id', ',', 'complete_dict', ')', ':', 'return', 'self', '.', '_create_put_request', '(', 'resource', '=', 'DELIVERY_NOTES', ',', 'billomat_id', '=', 'delivery_note_id', ',', 'command', '=', 'COMPLETE', ',', 'send_data', '=', 'complete_dict', ')']
Completes an delivery note :param complete_dict: the complete dict with the template id :param delivery_note_id: the delivery note id :return: Response
['Completes', 'an', 'delivery', 'note']
train
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L3564-L3577
9,752
bram85/topydo
topydo/ui/prompt/PromptCompleter.py
_dates
def _dates(p_word_before_cursor): """ Generator for date completion. """ to_absolute = lambda s: relative_date_to_date(s).isoformat() start_value_pos = p_word_before_cursor.find(':') + 1 value = p_word_before_cursor[start_value_pos:] for reldate in date_suggestions(): if not reldate.starts...
python
def _dates(p_word_before_cursor): """ Generator for date completion. """ to_absolute = lambda s: relative_date_to_date(s).isoformat() start_value_pos = p_word_before_cursor.find(':') + 1 value = p_word_before_cursor[start_value_pos:] for reldate in date_suggestions(): if not reldate.starts...
['def', '_dates', '(', 'p_word_before_cursor', ')', ':', 'to_absolute', '=', 'lambda', 's', ':', 'relative_date_to_date', '(', 's', ')', '.', 'isoformat', '(', ')', 'start_value_pos', '=', 'p_word_before_cursor', '.', 'find', '(', "':'", ')', '+', '1', 'value', '=', 'p_word_before_cursor', '[', 'start_value_pos', ':', ...
Generator for date completion.
['Generator', 'for', 'date', 'completion', '.']
train
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/prompt/PromptCompleter.py#L31-L42
9,753
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedset.py
SortedSet.copy
def copy(self): """Create a shallow copy of the sorted set.""" return self._fromset(set(self._set), key=self._key)
python
def copy(self): """Create a shallow copy of the sorted set.""" return self._fromset(set(self._set), key=self._key)
['def', 'copy', '(', 'self', ')', ':', 'return', 'self', '.', '_fromset', '(', 'set', '(', 'self', '.', '_set', ')', ',', 'key', '=', 'self', '.', '_key', ')']
Create a shallow copy of the sorted set.
['Create', 'a', 'shallow', 'copy', 'of', 'the', 'sorted', 'set', '.']
train
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedset.py#L168-L170
9,754
gawel/aiocron
aiocron/__init__.py
Cron.call_func
def call_func(self, *args, **kwargs): """Called. Take care of exceptions using gather""" asyncio.gather( self.cron(*args, **kwargs), loop=self.loop, return_exceptions=True ).add_done_callback(self.set_result)
python
def call_func(self, *args, **kwargs): """Called. Take care of exceptions using gather""" asyncio.gather( self.cron(*args, **kwargs), loop=self.loop, return_exceptions=True ).add_done_callback(self.set_result)
['def', 'call_func', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'asyncio', '.', 'gather', '(', 'self', '.', 'cron', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', ',', 'loop', '=', 'self', '.', 'loop', ',', 'return_exceptions', '=', 'True', ')', '.', 'add_done_callback', '(', 'self', '.', 'set_r...
Called. Take care of exceptions using gather
['Called', '.', 'Take', 'care', 'of', 'exceptions', 'using', 'gather']
train
https://github.com/gawel/aiocron/blob/949870b2f7fe1e10e4220f3243c9d4237255d203/aiocron/__init__.py#L83-L88
9,755
thautwarm/Redy
Redy/Collections/Traversal.py
reduce_by
def reduce_by(fn: Callable[[T1, T1], T1]) -> Callable[[ActualIterable[T1]], T1]: """ >>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6 """ retur...
python
def reduce_by(fn: Callable[[T1, T1], T1]) -> Callable[[ActualIterable[T1]], T1]: """ >>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6 """ retur...
['def', 'reduce_by', '(', 'fn', ':', 'Callable', '[', '[', 'T1', ',', 'T1', ']', ',', 'T1', ']', ')', '->', 'Callable', '[', '[', 'ActualIterable', '[', 'T1', ']', ']', ',', 'T1', ']', ':', 'return', 'lambda', 'collection', ':', 'functools', '.', 'reduce', '(', 'fn', ',', 'collection', ')']
>>> from Redy.Collections import Traversal, Flow >>> def mul(a: int, b: int): return a * b >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.reduce_by(mul)].unbox >>> assert x is 6
['>>>', 'from', 'Redy', '.', 'Collections', 'import', 'Traversal', 'Flow', '>>>', 'def', 'mul', '(', 'a', ':', 'int', 'b', ':', 'int', ')', ':', 'return', 'a', '*', 'b', '>>>', 'lst', ':', 'Iterable', '[', 'int', ']', '=', '[', '1', '2', '3', ']', '>>>', 'x', '=', 'Flow', '(', 'lst', ')', '[', 'Traversal', '.', 'reduce...
train
https://github.com/thautwarm/Redy/blob/8beee5c5f752edfd2754bb1e6b5f4acb016a7770/Redy/Collections/Traversal.py#L26-L34
9,756
SpamScope/mail-parser
mailparser/mailparser.py
MailParser.from_string
def from_string(cls, s): """ Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser """ log.debug("Parsing email from string") message = email.message_from_string(s) return cls(message)
python
def from_string(cls, s): """ Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser """ log.debug("Parsing email from string") message = email.message_from_string(s) return cls(message)
['def', 'from_string', '(', 'cls', ',', 's', ')', ':', 'log', '.', 'debug', '(', '"Parsing email from string"', ')', 'message', '=', 'email', '.', 'message_from_string', '(', 's', ')', 'return', 'cls', '(', 'message', ')']
Init a new object from a string. Args: s (string): raw email Returns: Instance of MailParser
['Init', 'a', 'new', 'object', 'from', 'a', 'string', '.']
train
https://github.com/SpamScope/mail-parser/blob/814b56d0b803feab9dea04f054b802ce138097e2/mailparser/mailparser.py#L207-L220
9,757
mosdef-hub/mbuild
mbuild/compound.py
Compound.boundingbox
def boundingbox(self): """Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound """ xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
python
def boundingbox(self): """Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound """ xyz = self.xyz return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0))
['def', 'boundingbox', '(', 'self', ')', ':', 'xyz', '=', 'self', '.', 'xyz', 'return', 'Box', '(', 'mins', '=', 'xyz', '.', 'min', '(', 'axis', '=', '0', ')', ',', 'maxs', '=', 'xyz', '.', 'max', '(', 'axis', '=', '0', ')', ')']
Compute the bounding box of the compound. Returns ------- mb.Box The bounding box for this Compound
['Compute', 'the', 'bounding', 'box', 'of', 'the', 'compound', '.']
train
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1078-L1088
9,758
Workiva/furious
furious/async.py
decode_async_options
def decode_async_options(options): """Decode Async options from JSON decoding.""" async_options = copy.deepcopy(options) # JSON don't like datetimes. eta = async_options.get('task_args', {}).get('eta') if eta: from datetime import datetime async_options['task_args']['eta'] = dateti...
python
def decode_async_options(options): """Decode Async options from JSON decoding.""" async_options = copy.deepcopy(options) # JSON don't like datetimes. eta = async_options.get('task_args', {}).get('eta') if eta: from datetime import datetime async_options['task_args']['eta'] = dateti...
['def', 'decode_async_options', '(', 'options', ')', ':', 'async_options', '=', 'copy', '.', 'deepcopy', '(', 'options', ')', "# JSON don't like datetimes.", 'eta', '=', 'async_options', '.', 'get', '(', "'task_args'", ',', '{', '}', ')', '.', 'get', '(', "'eta'", ')', 'if', 'eta', ':', 'from', 'datetime', 'import', 'd...
Decode Async options from JSON decoding.
['Decode', 'Async', 'options', 'from', 'JSON', 'decoding', '.']
train
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/async.py#L625-L648
9,759
bitesofcode/projexui
projexui/widgets/xnodewidget/xnodescene.py
XNodeScene.findNodeById
def findNodeById( self, objectId ): """ Looks up the node based on the unique node identifier. :param nodeId """ for item in self.items(): if ( isinstance(item, XNode) and item.objectId() == objectId): return item return None
python
def findNodeById( self, objectId ): """ Looks up the node based on the unique node identifier. :param nodeId """ for item in self.items(): if ( isinstance(item, XNode) and item.objectId() == objectId): return item return None
['def', 'findNodeById', '(', 'self', ',', 'objectId', ')', ':', 'for', 'item', 'in', 'self', '.', 'items', '(', ')', ':', 'if', '(', 'isinstance', '(', 'item', ',', 'XNode', ')', 'and', 'item', '.', 'objectId', '(', ')', '==', 'objectId', ')', ':', 'return', 'item', 'return', 'None']
Looks up the node based on the unique node identifier. :param nodeId
['Looks', 'up', 'the', 'node', 'based', 'on', 'the', 'unique', 'node', 'identifier', '.', ':', 'param', 'nodeId']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xnodewidget/xnodescene.py#L809-L818
9,760
googlesamples/assistant-sdk-python
google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py
ConversationStream.stop_recording
def stop_recording(self): """Stop recording from the audio source.""" self._stop_recording.set() with self._source_lock: self._source.stop() self._recording = False
python
def stop_recording(self): """Stop recording from the audio source.""" self._stop_recording.set() with self._source_lock: self._source.stop() self._recording = False
['def', 'stop_recording', '(', 'self', ')', ':', 'self', '.', '_stop_recording', '.', 'set', '(', ')', 'with', 'self', '.', '_source_lock', ':', 'self', '.', '_source', '.', 'stop', '(', ')', 'self', '.', '_recording', '=', 'False']
Stop recording from the audio source.
['Stop', 'recording', 'from', 'the', 'audio', 'source', '.']
train
https://github.com/googlesamples/assistant-sdk-python/blob/84995692f35be8e085de8dfa7032039a13ae3fab/google-assistant-sdk/googlesamples/assistant/grpc/audio_helpers.py#L281-L286
9,761
bitesofcode/projexui
projexui/widgets/xpopupwidget.py
XPopupWidget.keyPressEvent
def keyPressEvent( self, event ): """ Looks for the Esc key to close the popup. :param event | <QKeyEvent> """ if ( event.key() == Qt.Key_Escape ): self.reject() event.accept() return elif ( event.key()...
python
def keyPressEvent( self, event ): """ Looks for the Esc key to close the popup. :param event | <QKeyEvent> """ if ( event.key() == Qt.Key_Escape ): self.reject() event.accept() return elif ( event.key()...
['def', 'keyPressEvent', '(', 'self', ',', 'event', ')', ':', 'if', '(', 'event', '.', 'key', '(', ')', '==', 'Qt', '.', 'Key_Escape', ')', ':', 'self', '.', 'reject', '(', ')', 'event', '.', 'accept', '(', ')', 'return', 'elif', '(', 'event', '.', 'key', '(', ')', 'in', '(', 'Qt', '.', 'Key_Return', ',', 'Qt', '.', 'K...
Looks for the Esc key to close the popup. :param event | <QKeyEvent>
['Looks', 'for', 'the', 'Esc', 'key', 'to', 'close', 'the', 'popup', '.', ':', 'param', 'event', '|', '<QKeyEvent', '>']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L677-L694
9,762
piotr-rusin/spam-lists
spam_lists/host_collections.py
SortedHostCollection._get_match
def _get_match(self, host_object): """Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before inse...
python
def _get_match(self, host_object): """Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before inse...
['def', '_get_match', '(', 'self', ',', 'host_object', ')', ':', 'i', '=', 'self', '.', '_get_insertion_point', '(', 'host_object', ')', 'potential_match', '=', 'None', 'try', ':', 'potential_match', '=', 'self', '[', 'i', '-', '1', ']', 'except', 'IndexError', ':', 'pass', 'if', 'host_object', '.', 'is_match', '(', 'p...
Get an item matching the given host object. The item may be either a parent domain or identical value. Parent domains and existing identical values always precede insertion point for given value - therefore, we treat an item just before insertion point as potential match. :para...
['Get', 'an', 'item', 'matching', 'the', 'given', 'host', 'object', '.']
train
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L118-L138
9,763
aliyun/aliyun-log-python-sdk
aliyun/log/logclient.py
LogClient.get_begin_cursor
def get_begin_cursor(self, project_name, logstore_name, shard_id): """ Get begin cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string ...
python
def get_begin_cursor(self, project_name, logstore_name, shard_id): """ Get begin cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string ...
['def', 'get_begin_cursor', '(', 'self', ',', 'project_name', ',', 'logstore_name', ',', 'shard_id', ')', ':', 'return', 'self', '.', 'get_cursor', '(', 'project_name', ',', 'logstore_name', ',', 'shard_id', ',', '"begin"', ')']
Get begin cursor from log service for batch pull logs Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :type shard_id: int ...
['Get', 'begin', 'cursor', 'from', 'log', 'service', 'for', 'batch', 'pull', 'logs', 'Unsuccessful', 'opertaion', 'will', 'cause', 'an', 'LogException', '.', ':', 'type', 'project_name', ':', 'string', ':', 'param', 'project_name', ':', 'the', 'Project', 'name', ':', 'type', 'logstore_name', ':', 'string', ':', 'param'...
train
https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/logclient.py#L749-L766
9,764
jart/fabulous
fabulous/gotham.py
main
def main(): """I provide a command-line interface for this module """ print() print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print(lorem_gotham_title().center(50)) print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print() poem = lorem_gotham() for n in range(16...
python
def main(): """I provide a command-line interface for this module """ print() print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print(lorem_gotham_title().center(50)) print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print() poem = lorem_gotham() for n in range(16...
['def', 'main', '(', ')', ':', 'print', '(', ')', 'print', '(', '"-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-"', ')', 'print', '(', 'lorem_gotham_title', '(', ')', '.', 'center', '(', '50', ')', ')', 'print', '(', '"-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-"', ')', 'print', '(', ')', 'poem', '=', 'lorem...
I provide a command-line interface for this module
['I', 'provide', 'a', 'command', '-', 'line', 'interface', 'for', 'this', 'module']
train
https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/gotham.py#L108-L121
9,765
Gorialis/jishaku
jishaku/paginators.py
PaginatorInterface.wait_loop
async def wait_loop(self): """ Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`. """ start, back, forward, end, close = self.emojis def check(payload: discord.RawReactionActionEvent): """ Check...
python
async def wait_loop(self): """ Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`. """ start, back, forward, end, close = self.emojis def check(payload: discord.RawReactionActionEvent): """ Check...
['async', 'def', 'wait_loop', '(', 'self', ')', ':', 'start', ',', 'back', ',', 'forward', ',', 'end', ',', 'close', '=', 'self', '.', 'emojis', 'def', 'check', '(', 'payload', ':', 'discord', '.', 'RawReactionActionEvent', ')', ':', '"""\n Checks if this reaction is related to the paginator interface.\n ...
Waits on a loop for reactions to the message. This should not be called manually - it is handled by `send_to`.
['Waits', 'on', 'a', 'loop', 'for', 'reactions', 'to', 'the', 'message', '.', 'This', 'should', 'not', 'be', 'called', 'manually', '-', 'it', 'is', 'handled', 'by', 'send_to', '.']
train
https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/paginators.py#L197-L255
9,766
basler/pypylon
scripts/builddoxy2swig/doxy2swig/doxy2swig.py
Doxy2SWIG.handle_typical_memberdefs_no_overload
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: ...
python
def handle_typical_memberdefs_no_overload(self, signature, memberdef_nodes): """Produce standard documentation for memberdef_nodes.""" for n in memberdef_nodes: self.add_text(['\n', '%feature("docstring") ', signature, ' "', '\n']) if self.with_function_signature: ...
['def', 'handle_typical_memberdefs_no_overload', '(', 'self', ',', 'signature', ',', 'memberdef_nodes', ')', ':', 'for', 'n', 'in', 'memberdef_nodes', ':', 'self', '.', 'add_text', '(', '[', "'\\n'", ',', '\'%feature("docstring") \'', ',', 'signature', ',', '\' "\'', ',', "'\\n'", ']', ')', 'if', 'self', '.', 'with_fun...
Produce standard documentation for memberdef_nodes.
['Produce', 'standard', 'documentation', 'for', 'memberdef_nodes', '.']
train
https://github.com/basler/pypylon/blob/d3510fa419b1c2b17f3f0b80a5fbb720c7b84008/scripts/builddoxy2swig/doxy2swig/doxy2swig.py#L431-L438
9,767
bitprophet/botox
botox/aws.py
AWS.get_volumes_for_instance
def get_volumes_for_instance(self, arg, device=None): """ Return all EC2 Volume objects attached to ``arg`` instance name or ID. May specify ``device`` to limit to the (single) volume attached as that device. """ instance = self.get(arg) filters = {'attachment.in...
python
def get_volumes_for_instance(self, arg, device=None): """ Return all EC2 Volume objects attached to ``arg`` instance name or ID. May specify ``device`` to limit to the (single) volume attached as that device. """ instance = self.get(arg) filters = {'attachment.in...
['def', 'get_volumes_for_instance', '(', 'self', ',', 'arg', ',', 'device', '=', 'None', ')', ':', 'instance', '=', 'self', '.', 'get', '(', 'arg', ')', 'filters', '=', '{', "'attachment.instance-id'", ':', 'instance', '.', 'id', '}', 'if', 'device', 'is', 'not', 'None', ':', 'filters', '[', "'attachment.device'", ']',...
Return all EC2 Volume objects attached to ``arg`` instance name or ID. May specify ``device`` to limit to the (single) volume attached as that device.
['Return', 'all', 'EC2', 'Volume', 'objects', 'attached', 'to', 'arg', 'instance', 'name', 'or', 'ID', '.']
train
https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/aws.py#L340-L351
9,768
pgmpy/pgmpy
pgmpy/readwrite/XMLBIF.py
XMLBIFWriter.get_definition
def get_definition(self): """ Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d4...
python
def get_definition(self): """ Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d4...
['def', 'get_definition', '(', 'self', ')', ':', 'cpds', '=', 'self', '.', 'model', '.', 'get_cpds', '(', ')', 'cpds', '.', 'sort', '(', 'key', '=', 'lambda', 'x', ':', 'x', '.', 'variable', ')', 'definition_tag', '=', '{', '}', 'for', 'cpd', 'in', 'cpds', ':', 'definition_tag', '[', 'cpd', '.', 'variable', ']', '=', '...
Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d48977408>, 'family-out': <Element DEFI...
['Add', 'Definition', 'to', 'XMLBIF']
train
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/XMLBIF.py#L372-L399
9,769
architv/soccer-cli
soccer/writers.py
Stdout.scores
def scores(self, result, add_new_line=True): """Prints out the scores in a pretty format""" if result.goalsHomeTeam > result.goalsAwayTeam: homeColor, awayColor = (self.colors.WIN, self.colors.LOSE) elif result.goalsHomeTeam < result.goalsAwayTeam: homeColor, awayColor = ...
python
def scores(self, result, add_new_line=True): """Prints out the scores in a pretty format""" if result.goalsHomeTeam > result.goalsAwayTeam: homeColor, awayColor = (self.colors.WIN, self.colors.LOSE) elif result.goalsHomeTeam < result.goalsAwayTeam: homeColor, awayColor = ...
['def', 'scores', '(', 'self', ',', 'result', ',', 'add_new_line', '=', 'True', ')', ':', 'if', 'result', '.', 'goalsHomeTeam', '>', 'result', '.', 'goalsAwayTeam', ':', 'homeColor', ',', 'awayColor', '=', '(', 'self', '.', 'colors', '.', 'WIN', ',', 'self', '.', 'colors', '.', 'LOSE', ')', 'elif', 'result', '.', 'goal...
Prints out the scores in a pretty format
['Prints', 'out', 'the', 'scores', 'in', 'a', 'pretty', 'format']
train
https://github.com/architv/soccer-cli/blob/472e9f492f7633a8e9739e228a6c31de454da88b/soccer/writers.py#L149-L163
9,770
tjcsl/cslbot
cslbot/commands/weather.py
set_default
def set_default(nick, location, session, send, apikey): """Sets nick's default location to location.""" if valid_location(location, apikey): send("Setting default location") default = session.query(Weather_prefs).filter(Weather_prefs.nick == nick).first() if default is None: ...
python
def set_default(nick, location, session, send, apikey): """Sets nick's default location to location.""" if valid_location(location, apikey): send("Setting default location") default = session.query(Weather_prefs).filter(Weather_prefs.nick == nick).first() if default is None: ...
['def', 'set_default', '(', 'nick', ',', 'location', ',', 'session', ',', 'send', ',', 'apikey', ')', ':', 'if', 'valid_location', '(', 'location', ',', 'apikey', ')', ':', 'send', '(', '"Setting default location"', ')', 'default', '=', 'session', '.', 'query', '(', 'Weather_prefs', ')', '.', 'filter', '(', 'Weather_pr...
Sets nick's default location to location.
['Sets', 'nick', 's', 'default', 'location', 'to', 'location', '.']
train
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/weather.py#L73-L84
9,771
abarker/pdfCropMargins
src/pdfCropMargins/external_program_calls.py
get_external_subprocess_output
def get_external_subprocess_output(command_list, print_output=False, indent_string="", split_lines=True, ignore_called_process_errors=False, env=None): """Run the command and arguments in the command_list. Will search the system PATH. Returns the output as a list of lines. If print_out...
python
def get_external_subprocess_output(command_list, print_output=False, indent_string="", split_lines=True, ignore_called_process_errors=False, env=None): """Run the command and arguments in the command_list. Will search the system PATH. Returns the output as a list of lines. If print_out...
['def', 'get_external_subprocess_output', '(', 'command_list', ',', 'print_output', '=', 'False', ',', 'indent_string', '=', '""', ',', 'split_lines', '=', 'True', ',', 'ignore_called_process_errors', '=', 'False', ',', 'env', '=', 'None', ')', ':', '# Note ghostscript bounding box output writes to stderr! So we need ...
Run the command and arguments in the command_list. Will search the system PATH. Returns the output as a list of lines. If print_output is True the output is echoed to stdout, indented (or otherwise prefixed) by indent_string. Waits for command completion. Called process errors can be set to be igno...
['Run', 'the', 'command', 'and', 'arguments', 'in', 'the', 'command_list', '.', 'Will', 'search', 'the', 'system', 'PATH', '.', 'Returns', 'the', 'output', 'as', 'a', 'list', 'of', 'lines', '.', 'If', 'print_output', 'is', 'True', 'the', 'output', 'is', 'echoed', 'to', 'stdout', 'indented', '(', 'or', 'otherwise', 'pre...
train
https://github.com/abarker/pdfCropMargins/blob/55aca874613750ebf4ae69fd8851bdbb7696d6ac/src/pdfCropMargins/external_program_calls.py#L240-L277
9,772
pavoni/pyvera
pyvera/__init__.py
VeraThermostat.get_current_temperature
def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
python
def get_current_temperature(self, refresh=False): """Get current temperature""" if refresh: self.refresh() try: return float(self.get_value('temperature')) except (TypeError, ValueError): return None
['def', 'get_current_temperature', '(', 'self', ',', 'refresh', '=', 'False', ')', ':', 'if', 'refresh', ':', 'self', '.', 'refresh', '(', ')', 'try', ':', 'return', 'float', '(', 'self', '.', 'get_value', '(', "'temperature'", ')', ')', 'except', '(', 'TypeError', ',', 'ValueError', ')', ':', 'return', 'None']
Get current temperature
['Get', 'current', 'temperature']
train
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1076-L1083
9,773
spacetelescope/drizzlepac
drizzlepac/tweakutils.py
parse_skypos
def parse_skypos(ra, dec): """ Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn" """ ...
python
def parse_skypos(ra, dec): """ Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn" """ ...
['def', 'parse_skypos', '(', 'ra', ',', 'dec', ')', ':', 'rval', '=', 'make_val_float', '(', 'ra', ')', 'dval', '=', 'make_val_float', '(', 'dec', ')', 'if', 'rval', 'is', 'None', ':', 'rval', ',', 'dval', '=', 'radec_hmstodd', '(', 'ra', ',', 'dec', ')', 'return', 'rval', ',', 'dval']
Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn"
['Function', 'to', 'parse', 'RA', 'and', 'Dec', 'input', 'values', 'and', 'turn', 'them', 'into', 'decimal', 'degrees']
train
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/tweakutils.py#L173-L191
9,774
steffann/pylisp
pylisp/packet/lisp/control/map_reply_record.py
MapReplyRecord.from_bytes
def from_bytes(cls, bitstream): ''' Parse the given record and update properties accordingly ''' record = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): ...
python
def from_bytes(cls, bitstream): ''' Parse the given record and update properties accordingly ''' record = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): ...
['def', 'from_bytes', '(', 'cls', ',', 'bitstream', ')', ':', 'record', '=', 'cls', '(', ')', '# Convert to ConstBitStream (if not already provided)', 'if', 'not', 'isinstance', '(', 'bitstream', ',', 'ConstBitStream', ')', ':', 'if', 'isinstance', '(', 'bitstream', ',', 'Bits', ')', ':', 'bitstream', '=', 'ConstBitStr...
Parse the given record and update properties accordingly
['Parse', 'the', 'given', 'record', 'and', 'update', 'properties', 'accordingly']
train
https://github.com/steffann/pylisp/blob/907340f0c7ef2c4d4fe0c8e0a48df5be0d969407/pylisp/packet/lisp/control/map_reply_record.py#L142-L188
9,775
sethmlarson/virtualbox-python
virtualbox/library.py
IInternalSessionControl.on_network_adapter_change
def on_network_adapter_change(self, network_adapter, change_adapter): """Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInva...
python
def on_network_adapter_change(self, network_adapter, change_adapter): """Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInva...
['def', 'on_network_adapter_change', '(', 'self', ',', 'network_adapter', ',', 'change_adapter', ')', ':', 'if', 'not', 'isinstance', '(', 'network_adapter', ',', 'INetworkAdapter', ')', ':', 'raise', 'TypeError', '(', '"network_adapter can only be an instance of type INetworkAdapter"', ')', 'if', 'not', 'isinstance', ...
Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInvalidVmState` Session state prevents operation. raises...
['Triggered', 'when', 'settings', 'of', 'a', 'network', 'adapter', 'of', 'the', 'associated', 'virtual', 'machine', 'have', 'changed', '.']
train
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L28324-L28344
9,776
bitesofcode/projexui
projexui/windows/xdkwindow/xdkwindow.py
XdkWindow.closeContentsWidget
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
python
def closeContentsWidget( self ): """ Closes the current contents widget. """ widget = self.currentContentsWidget() if ( not widget ): return widget.close() widget.setParent(None) widget.deleteLater()
['def', 'closeContentsWidget', '(', 'self', ')', ':', 'widget', '=', 'self', '.', 'currentContentsWidget', '(', ')', 'if', '(', 'not', 'widget', ')', ':', 'return', 'widget', '.', 'close', '(', ')', 'widget', '.', 'setParent', '(', 'None', ')', 'widget', '.', 'deleteLater', '(', ')']
Closes the current contents widget.
['Closes', 'the', 'current', 'contents', 'widget', '.']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L246-L256
9,777
jsvine/spectra
spectra/grapefruit.py
Color.NewFromLab
def NewFromLab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0......
python
def NewFromLab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0......
['def', 'NewFromLab', '(', 'l', ',', 'a', ',', 'b', ',', 'alpha', '=', '1.0', ',', 'wref', '=', '_DEFAULT_WREF', ')', ':', 'return', 'Color', '(', 'Color', '.', 'XyzToRgb', '(', '*', 'Color', '.', 'LabToXyz', '(', 'l', ',', 'a', ',', 'b', ',', 'wref', ')', ')', ',', "'rgb'", ',', 'alpha', ',', 'wref', ')']
Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint refer...
['Create', 'a', 'new', 'instance', 'based', 'on', 'the', 'specifed', 'CIE', '-', 'LAB', 'values', '.']
train
https://github.com/jsvine/spectra/blob/2269a0ae9b5923154b15bd661fb81179608f7ec2/spectra/grapefruit.py#L1340-L1368
9,778
ska-sa/purr
Purr/Plugins/local_pychart/chart_data.py
write_csv
def write_csv(path, data): """This function writes comma-separated <data> to <path>. Parameter <path> is either a pathname or a file-like object that supports the |write()| method.""" fd = _try_open_file(path, 'w', 'The first argument must be a pathname or an object that support...
python
def write_csv(path, data): """This function writes comma-separated <data> to <path>. Parameter <path> is either a pathname or a file-like object that supports the |write()| method.""" fd = _try_open_file(path, 'w', 'The first argument must be a pathname or an object that support...
['def', 'write_csv', '(', 'path', ',', 'data', ')', ':', 'fd', '=', '_try_open_file', '(', 'path', ',', "'w'", ',', "'The first argument must be a pathname or an object that supports write() method'", ')', 'for', 'v', 'in', 'data', ':', 'fd', '.', 'write', '(', '","', '.', 'join', '(', '[', 'str', '(', 'x', ')', 'for',...
This function writes comma-separated <data> to <path>. Parameter <path> is either a pathname or a file-like object that supports the |write()| method.
['This', 'function', 'writes', 'comma', '-', 'separated', '<data', '>', 'to', '<path', '>', '.', 'Parameter', '<path', '>', 'is', 'either', 'a', 'pathname', 'or', 'a', 'file', '-', 'like', 'object', 'that', 'supports', 'the', '|write', '()', '|', 'method', '.']
train
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Plugins/local_pychart/chart_data.py#L258-L268
9,779
django-danceschool/django-danceschool
danceschool/core/models.py
Event.numRegisteredForRole
def numRegisteredForRole(self, role, includeTemporaryRegs=False): ''' Accepts a DanceRole object and returns the number of registrations of that role. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: ...
python
def numRegisteredForRole(self, role, includeTemporaryRegs=False): ''' Accepts a DanceRole object and returns the number of registrations of that role. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: ...
['def', 'numRegisteredForRole', '(', 'self', ',', 'role', ',', 'includeTemporaryRegs', '=', 'False', ')', ':', 'count', '=', 'self', '.', 'eventregistration_set', '.', 'filter', '(', 'cancelled', '=', 'False', ',', 'dropIn', '=', 'False', ',', 'role', '=', 'role', ')', '.', 'count', '(', ')', 'if', 'includeTemporaryReg...
Accepts a DanceRole object and returns the number of registrations of that role.
['Accepts', 'a', 'DanceRole', 'object', 'and', 'returns', 'the', 'number', 'of', 'registrations', 'of', 'that', 'role', '.']
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L967-L975
9,780
boriel/zxbasic
zxbparser.py
p_arr_assignment
def p_arr_assignment(p): """ statement : ARRAY_ID arg_list EQ expr | LET ARRAY_ID arg_list EQ expr """ i = 2 if p[1].upper() == 'LET' else 1 id_ = p[i] arg_list = p[i + 1] expr = p[i + 3] p[0] = None if arg_list is None or expr is None: return # There were err...
python
def p_arr_assignment(p): """ statement : ARRAY_ID arg_list EQ expr | LET ARRAY_ID arg_list EQ expr """ i = 2 if p[1].upper() == 'LET' else 1 id_ = p[i] arg_list = p[i + 1] expr = p[i + 3] p[0] = None if arg_list is None or expr is None: return # There were err...
['def', 'p_arr_assignment', '(', 'p', ')', ':', 'i', '=', '2', 'if', 'p', '[', '1', ']', '.', 'upper', '(', ')', '==', "'LET'", 'else', '1', 'id_', '=', 'p', '[', 'i', ']', 'arg_list', '=', 'p', '[', 'i', '+', '1', ']', 'expr', '=', 'p', '[', 'i', '+', '3', ']', 'p', '[', '0', ']', '=', 'None', 'if', 'arg_list', 'is', ...
statement : ARRAY_ID arg_list EQ expr | LET ARRAY_ID arg_list EQ expr
['statement', ':', 'ARRAY_ID', 'arg_list', 'EQ', 'expr', '|', 'LET', 'ARRAY_ID', 'arg_list', 'EQ', 'expr']
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbparser.py#L1069-L1101
9,781
dragnet-org/dragnet
dragnet/model_training.py
evaluate_extracted_tokens
def evaluate_extracted_tokens(gold_content, extr_content): """ Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-stand...
python
def evaluate_extracted_tokens(gold_content, extr_content): """ Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-stand...
['def', 'evaluate_extracted_tokens', '(', 'gold_content', ',', 'extr_content', ')', ':', 'if', 'isinstance', '(', 'gold_content', ',', 'string_', ')', ':', 'gold_content', '=', 'simple_tokenizer', '(', 'gold_content', ')', 'if', 'isinstance', '(', 'extr_content', ',', 'string_', ')', ':', 'extr_content', '=', 'simple_t...
Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-standard content, either as a string or as an already-tokenized ...
['Evaluate', 'the', 'similarity', 'between', 'gold', '-', 'standard', 'and', 'extracted', 'content', 'typically', 'for', 'a', 'single', 'HTML', 'document', 'as', 'another', 'way', 'of', 'evaluating', 'the', 'performance', 'of', 'an', 'extractor', 'model', '.']
train
https://github.com/dragnet-org/dragnet/blob/532c9d9f28e5b1b57f3cabc708218d3863a16322/dragnet/model_training.py#L51-L74
9,782
esheldon/fitsio
fitsio/hdu/base.py
HDUBase._get_repr_list
def _get_repr_list(self): """ Get some representation data common to all HDU types """ spacing = ' '*2 text = [''] text.append("%sfile: %s" % (spacing, self._filename)) text.append("%sextension: %d" % (spacing, self._info['hdunum']-1)) text.append( ...
python
def _get_repr_list(self): """ Get some representation data common to all HDU types """ spacing = ' '*2 text = [''] text.append("%sfile: %s" % (spacing, self._filename)) text.append("%sextension: %d" % (spacing, self._info['hdunum']-1)) text.append( ...
['def', '_get_repr_list', '(', 'self', ')', ':', 'spacing', '=', "' '", '*', '2', 'text', '=', '[', "''", ']', 'text', '.', 'append', '(', '"%sfile: %s"', '%', '(', 'spacing', ',', 'self', '.', '_filename', ')', ')', 'text', '.', 'append', '(', '"%sextension: %d"', '%', '(', 'spacing', ',', 'self', '.', '_info', '[', "...
Get some representation data common to all HDU types
['Get', 'some', 'representation', 'data', 'common', 'to', 'all', 'HDU', 'types']
train
https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/base.py#L333-L351
9,783
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py
brocade_interface_ext.get_ip_interface_input_request_type_get_request_interface_type
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface input = ET.SubElement(get_ip_interface, "input") ...
python
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface input = ET.SubElement(get_ip_interface, "input") ...
['def', 'get_ip_interface_input_request_type_get_request_interface_type', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'get_ip_interface', '=', 'ET', '.', 'Element', '(', '"get_ip_interface"', ')', 'config', '=', 'get_ip_interface', 'input', '=', 'ET', '.', ...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L398-L411
9,784
boriel/zxbasic
arch/zx48k/backend/__8bit.py
_band8
def _band8(ins): """ Pops top 2 operands out of the stack, and does 1st AND (bitwise) 2nd operand (top of the stack), pushes the result. 8 bit un/signed version """ op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) o...
python
def _band8(ins): """ Pops top 2 operands out of the stack, and does 1st AND (bitwise) 2nd operand (top of the stack), pushes the result. 8 bit un/signed version """ op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: op1, op2 = _int_ops(op1, op2) o...
['def', '_band8', '(', 'ins', ')', ':', 'op1', ',', 'op2', '=', 'tuple', '(', 'ins', '.', 'quad', '[', '2', ':', ']', ')', 'if', '_int_ops', '(', 'op1', ',', 'op2', ')', 'is', 'not', 'None', ':', 'op1', ',', 'op2', '=', '_int_ops', '(', 'op1', ',', 'op2', ')', 'output', '=', '_8bit_oper', '(', 'op1', ')', 'if', 'op2', ...
Pops top 2 operands out of the stack, and does 1st AND (bitwise) 2nd operand (top of the stack), pushes the result. 8 bit un/signed version
['Pops', 'top', '2', 'operands', 'out', 'of', 'the', 'stack', 'and', 'does', '1st', 'AND', '(', 'bitwise', ')', '2nd', 'operand', '(', 'top', 'of', 'the', 'stack', ')', 'pushes', 'the', 'result', '.']
train
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__8bit.py#L764-L791
9,785
craffel/mir_eval
mir_eval/io.py
load_time_series
def load_time_series(filename, delimiter=r'\s+'): r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotatio...
python
def load_time_series(filename, delimiter=r'\s+'): r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotatio...
['def', 'load_time_series', '(', 'filename', ',', 'delimiter', '=', "r'\\s+'", ')', ':', '# Use our universal function to load in the events', 'times', ',', 'values', '=', 'load_delimited', '(', 'filename', ',', '[', 'float', ',', 'float', ']', ',', 'delimiter', ')', 'times', '=', 'np', '.', 'array', '(', 'times', ')',...
r"""Import a time series from an annotation file. The file should consist of two columns of numeric values corresponding to the time and value of each sample of the time series. Parameters ---------- filename : str Path to the annotation file delimiter : str Separator regular e...
['r', 'Import', 'a', 'time', 'series', 'from', 'an', 'annotation', 'file', '.', 'The', 'file', 'should', 'consist', 'of', 'two', 'columns', 'of', 'numeric', 'values', 'corresponding', 'to', 'the', 'time', 'and', 'value', 'of', 'each', 'sample', 'of', 'the', 'time', 'series', '.']
train
https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/io.py#L245-L271
9,786
miguelgrinberg/python-engineio
engineio/asyncio_server.py
AsyncServer.start_background_task
def start_background_task(self, target, *args, **kwargs): """Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param targe...
python
def start_background_task(self, target, *args, **kwargs): """Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param targe...
['def', 'start_background_task', '(', 'self', ',', 'target', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'return', 'asyncio', '.', 'ensure_future', '(', 'target', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', ')']
Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param target: the target function to execute. :param args: arguments to ...
['Start', 'a', 'background', 'task', 'using', 'the', 'appropriate', 'async', 'model', '.']
train
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_server.py#L266-L279
9,787
corpusops/pdbclone
lib/pdb_clone/pdb.py
Pdb.precmd
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = ...
python
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = ...
['def', 'precmd', '(', 'self', ',', 'line', ')', ':', 'if', 'not', 'line', '.', 'strip', '(', ')', ':', 'return', 'line', 'args', '=', 'line', '.', 'split', '(', ')', 'while', 'args', '[', '0', ']', 'in', 'self', '.', 'aliases', ':', 'line', '=', 'self', '.', 'aliases', '[', 'args', '[', '0', ']', ']', 'ii', '=', '1', ...
Handle alias expansion and ';;' separator.
['Handle', 'alias', 'expansion', 'and', ';;', 'separator', '.']
train
https://github.com/corpusops/pdbclone/blob/f781537c243a4874b246d43dbdef8c4279f0094d/lib/pdb_clone/pdb.py#L683-L706
9,788
chrisspen/webarticle2text
webarticle2text/webarticle2text.py
tidyHTML
def tidyHTML(dirtyHTML): """ Runs an arbitrary HTML string through Tidy. """ try: from tidylib import tidy_document except ImportError as e: raise ImportError(("%s\nYou need to install pytidylib.\n" + "e.g. sudo pip install pytidylib") % e) options = { 'outpu...
python
def tidyHTML(dirtyHTML): """ Runs an arbitrary HTML string through Tidy. """ try: from tidylib import tidy_document except ImportError as e: raise ImportError(("%s\nYou need to install pytidylib.\n" + "e.g. sudo pip install pytidylib") % e) options = { 'outpu...
['def', 'tidyHTML', '(', 'dirtyHTML', ')', ':', 'try', ':', 'from', 'tidylib', 'import', 'tidy_document', 'except', 'ImportError', 'as', 'e', ':', 'raise', 'ImportError', '(', '(', '"%s\\nYou need to install pytidylib.\\n"', '+', '"e.g. sudo pip install pytidylib"', ')', '%', 'e', ')', 'options', '=', '{', "'output-xht...
Runs an arbitrary HTML string through Tidy.
['Runs', 'an', 'arbitrary', 'HTML', 'string', 'through', 'Tidy', '.']
train
https://github.com/chrisspen/webarticle2text/blob/3c88e948e31aedf1eccfea2106e5848d224771eb/webarticle2text/webarticle2text.py#L337-L355
9,789
ContinuumIO/menuinst
menuinst/win32.py
quoted
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
python
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
['def', 'quoted', '(', 's', ')', ':', '# strip any existing quotes', 's', '=', 's', '.', 'strip', '(', 'u\'"\'', ')', "# don't add quotes for minus or leading space", 'if', 's', '[', '0', ']', 'in', '(', "u'-'", ',', "u' '", ')', ':', 'return', 's', 'if', "u' '", 'in', 's', 'or', "u'/'", 'in', 's', ':', 'return', 'u\'"...
quotes a string if necessary.
['quotes', 'a', 'string', 'if', 'necessary', '.']
train
https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/win32.py#L106-L118
9,790
ralphje/imagemounter
imagemounter/filesystems.py
LvmFileSystemType.mount
def mount(self, volume): """Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it and fills :attr:`volumes` with the logical volumes. :raises NoLoopbackAvailableError: when no loopback was available :raises IncorrectFilesystemError: when ...
python
def mount(self, volume): """Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it and fills :attr:`volumes` with the logical volumes. :raises NoLoopbackAvailableError: when no loopback was available :raises IncorrectFilesystemError: when ...
['def', 'mount', '(', 'self', ',', 'volume', ')', ':', 'os', '.', 'environ', '[', "'LVM_SUPPRESS_FD_WARNINGS'", ']', '=', "'1'", '# find free loopback device', 'volume', '.', '_find_loopback', '(', ')', 'time', '.', 'sleep', '(', '0.2', ')', 'try', ':', '# Scan for new lvm volumes', 'result', '=', '_util', '.', 'check_...
Performs mount actions on a LVM. Scans for active volume groups from the loopback device, activates it and fills :attr:`volumes` with the logical volumes. :raises NoLoopbackAvailableError: when no loopback was available :raises IncorrectFilesystemError: when the volume is not a volume group
['Performs', 'mount', 'actions', 'on', 'a', 'LVM', '.', 'Scans', 'for', 'active', 'volume', 'groups', 'from', 'the', 'loopback', 'device', 'activates', 'it', 'and', 'fills', ':', 'attr', ':', 'volumes', 'with', 'the', 'logical', 'volumes', '.']
train
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/filesystems.py#L460-L494
9,791
10gen/mongo-orchestration
mongo_orchestration/replica_sets.py
ReplicaSet.repl_member_add
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
python
def repl_member_add(self, params): """create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False """ repl_config = self.config member_id = max([member['_id'] for member in repl_confi...
['def', 'repl_member_add', '(', 'self', ',', 'params', ')', ':', 'repl_config', '=', 'self', '.', 'config', 'member_id', '=', 'max', '(', '[', 'member', '[', "'_id'", ']', 'for', 'member', 'in', 'repl_config', '[', "'members'", ']', ']', ')', '+', '1', 'member_config', '=', 'self', '.', 'member_create', '(', 'params', ...
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
['create', 'new', 'mongod', 'instances', 'and', 'add', 'it', 'to', 'the', 'replica', 'set', '.', 'Args', ':', 'params', '-', 'mongod', 'params', 'return', 'True', 'if', 'operation', 'success', 'otherwise', 'False']
train
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L245-L258
9,792
zetaops/pyoko
pyoko/lib/utils.py
ub_to_str
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
python
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return st...
['def', 'ub_to_str', '(', 'string', ')', ':', 'if', 'not', 'isinstance', '(', 'string', ',', 'str', ')', ':', 'if', 'six', '.', 'PY2', ':', 'return', 'str', '(', 'string', ')', 'else', ':', 'return', 'string', '.', 'decode', '(', ')', 'return', 'string']
converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str)
['converts', 'py2', 'unicode', '/', 'py3', 'bytestring', 'into', 'str', 'Args', ':', 'string', '(', 'unicode', 'byte_string', ')', ':', 'string', 'to', 'be', 'converted', 'Returns', ':', '(', 'str', ')']
train
https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/lib/utils.py#L22-L36
9,793
awslabs/aws-sam-cli
samcli/local/lambda_service/lambda_error_responses.py
LambdaErrorResponses.unsupported_media_type
def unsupported_media_type(content_type): """ Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object...
python
def unsupported_media_type(content_type): """ Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object...
['def', 'unsupported_media_type', '(', 'content_type', ')', ':', 'exception_tuple', '=', 'LambdaErrorResponses', '.', 'UnsupportedMediaTypeException', 'return', 'BaseLocalService', '.', 'service_response', '(', 'LambdaErrorResponses', '.', '_construct_error_response_body', '(', 'LambdaErrorResponses', '.', 'USER_ERROR'...
Creates a Lambda Service UnsupportedMediaType Response Parameters ---------- content_type str Content Type of the request that was made Returns ------- Flask.Response A response object representing the UnsupportedMediaType Error
['Creates', 'a', 'Lambda', 'Service', 'UnsupportedMediaType', 'Response']
train
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambda_service/lambda_error_responses.py#L88-L109
9,794
DLR-RM/RAFCON
source/rafcon/core/states/container_state.py
ContainerState.change_state_id
def change_state_id(self, state_id=None): """ Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all data flows and transitions. :param state_id: The new state if of the state """ old_state_id = self.state_id ...
python
def change_state_id(self, state_id=None): """ Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all data flows and transitions. :param state_id: The new state if of the state """ old_state_id = self.state_id ...
['def', 'change_state_id', '(', 'self', ',', 'state_id', '=', 'None', ')', ':', 'old_state_id', '=', 'self', '.', 'state_id', 'super', '(', 'ContainerState', ',', 'self', ')', '.', 'change_state_id', '(', 'state_id', ')', '# Use private variables to change ids to prevent validity checks', '# change id in all transition...
Changes the id of the state to a new id. This functions replaces the old state_id with the new state_id in all data flows and transitions. :param state_id: The new state if of the state
['Changes', 'the', 'id', 'of', 'the', 'state', 'to', 'a', 'new', 'id', '.', 'This', 'functions', 'replaces', 'the', 'old', 'state_id', 'with', 'the', 'new', 'state_id', 'in', 'all', 'data', 'flows', 'and', 'transitions', '.']
train
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1624-L1646
9,795
bram85/topydo
topydo/lib/ChangeSet.py
ChangeSet._trim
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 ...
python
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 ...
['def', '_trim', '(', 'self', ')', ':', 'index', '=', 'self', '.', '_get_index', '(', ')', 'backup_limit', '=', 'config', '(', ')', '.', 'backup_count', '(', ')', '-', '1', 'for', 'changeset', 'in', 'index', '[', 'backup_limit', ':', ']', ':', 'self', '.', 'delete', '(', 'changeset', '[', '0', ']', ',', 'p_write', '=',...
Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards.
['Removes', 'oldest', 'backups', 'that', 'exceed', 'the', 'limit', 'configured', 'in', 'backup_count', 'option', '.']
train
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ChangeSet.py#L152-L164
9,796
SITools2/pySitools2_1.0
sitools2/core/pySitools2.py
SITools2Instance.__parseResponseServer
def __parseResponseServer(self): """Parses the response of the server. Exception --------- A Sitools2Exception is raised when the server does not send back a success.""" self.__logger.debug(Sitools2Abstract.getBaseUrl(self) + SITools2Instance.PROJECTS_URI) ...
python
def __parseResponseServer(self): """Parses the response of the server. Exception --------- A Sitools2Exception is raised when the server does not send back a success.""" self.__logger.debug(Sitools2Abstract.getBaseUrl(self) + SITools2Instance.PROJECTS_URI) ...
['def', '__parseResponseServer', '(', 'self', ')', ':', 'self', '.', '__logger', '.', 'debug', '(', 'Sitools2Abstract', '.', 'getBaseUrl', '(', 'self', ')', '+', 'SITools2Instance', '.', 'PROJECTS_URI', ')', 'result', '=', 'Util', '.', 'retrieveJsonResponseFromServer', '(', 'Sitools2Abstract', '.', 'getBaseUrl', '(', '...
Parses the response of the server. Exception --------- A Sitools2Exception is raised when the server does not send back a success.
['Parses', 'the', 'response', 'of', 'the', 'server', '.', 'Exception', '---------', 'A', 'Sitools2Exception', 'is', 'raised', 'when', 'the', 'server', 'does', 'not', 'send', 'back', 'a', 'success', '.']
train
https://github.com/SITools2/pySitools2_1.0/blob/acd13198162456ba401a0b923af989bb29feb3b6/sitools2/core/pySitools2.py#L96-L112
9,797
juju/python-libjuju
juju/client/_client1.py
ClientFacade.AddCharm
async def AddCharm(self, channel, url): ''' channel : str url : str Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddCharm', version=1, params=_...
python
async def AddCharm(self, channel, url): ''' channel : str url : str Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddCharm', version=1, params=_...
['async', 'def', 'AddCharm', '(', 'self', ',', 'channel', ',', 'url', ')', ':', '# map input types to rpc msg', '_params', '=', 'dict', '(', ')', 'msg', '=', 'dict', '(', 'type', '=', "'Client'", ',', 'request', '=', "'AddCharm'", ',', 'version', '=', '1', ',', 'params', '=', '_params', ')', '_params', '[', "'channel'"...
channel : str url : str Returns -> None
['channel', ':', 'str', 'url', ':', 'str', 'Returns', '-', '>', 'None']
train
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client1.py#L2957-L2972
9,798
cs50/lib50
lib50/_api.py
Slug._check_endings
def _check_endings(self): """Check begin/end of slug, raises Error if malformed.""" if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) ...
python
def _check_endings(self): """Check begin/end of slug, raises Error if malformed.""" if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) ...
['def', '_check_endings', '(', 'self', ')', ':', 'if', 'self', '.', 'slug', '.', 'startswith', '(', '"/"', ')', 'and', 'self', '.', 'slug', '.', 'endswith', '(', '"/"', ')', ':', 'raise', 'InvalidSlugError', '(', '_', '(', '"Invalid slug. Did you mean {}, without the leading and trailing slashes?"', '.', 'format', '(',...
Check begin/end of slug, raises Error if malformed.
['Check', 'begin', '/', 'end', 'of', 'slug', 'raises', 'Error', 'if', 'malformed', '.']
train
https://github.com/cs50/lib50/blob/941767f6c0a3b81af0cdea48c25c8d5a761086eb/lib50/_api.py#L420-L430
9,799
koszullab/metaTOR
metator/scripts/hicstuff.py
get_missing_bins
def get_missing_bins(original, trimmed): """Retrieve indices of a trimmed matrix with respect to the original matrix. Fairly fast but is only correct if diagonal values are different, which is always the case in practice. """ original_diag = np.diag(original) trimmed_diag = np.diag(trimmed) ...
python
def get_missing_bins(original, trimmed): """Retrieve indices of a trimmed matrix with respect to the original matrix. Fairly fast but is only correct if diagonal values are different, which is always the case in practice. """ original_diag = np.diag(original) trimmed_diag = np.diag(trimmed) ...
['def', 'get_missing_bins', '(', 'original', ',', 'trimmed', ')', ':', 'original_diag', '=', 'np', '.', 'diag', '(', 'original', ')', 'trimmed_diag', '=', 'np', '.', 'diag', '(', 'trimmed', ')', 'index', '=', '[', ']', 'm', '=', 'min', '(', 'original', '.', 'shape', ')', 'for', 'j', 'in', 'range', '(', 'min', '(', 'tri...
Retrieve indices of a trimmed matrix with respect to the original matrix. Fairly fast but is only correct if diagonal values are different, which is always the case in practice.
['Retrieve', 'indices', 'of', 'a', 'trimmed', 'matrix', 'with', 'respect', 'to', 'the', 'original', 'matrix', '.', 'Fairly', 'fast', 'but', 'is', 'only', 'correct', 'if', 'diagonal', 'values', 'are', 'different', 'which', 'is', 'always', 'the', 'case', 'in', 'practice', '.']
train
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L801-L816