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
3,900
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/apis/default_api.py
DefaultApi.group_members_remove
def group_members_remove(self, device_group_id, body, **kwargs): # noqa: E501 """Remove a device from a group # noqa: E501 Remove one device from a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchrono...
python
def group_members_remove(self, device_group_id, body, **kwargs): # noqa: E501 """Remove a device from a group # noqa: E501 Remove one device from a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchrono...
['def', 'group_members_remove', '(', 'self', ',', 'device_group_id', ',', 'body', ',', '*', '*', 'kwargs', ')', ':', '# noqa: E501', 'kwargs', '[', "'_return_http_data_only'", ']', '=', 'True', 'if', 'kwargs', '.', 'get', '(', "'asynchronous'", ')', ':', 'return', 'self', '.', 'group_members_remove_with_http_info', '('...
Remove a device from a group # noqa: E501 Remove one device from a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.group_members_remove(device_group_id, body, asynchronous=...
['Remove', 'a', 'device', 'from', 'a', 'group', '#', 'noqa', ':', 'E501']
train
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/apis/default_api.py#L1830-L1851
3,901
rootpy/rootpy
rootpy/plotting/hist.py
_HistBase.fill_array
def fill_array(self, array, weights=None): """ Fill this histogram with a NumPy array """ try: try: from root_numpy import fill_hist as fill_func except ImportError: from root_numpy import fill_array as fill_func except Impo...
python
def fill_array(self, array, weights=None): """ Fill this histogram with a NumPy array """ try: try: from root_numpy import fill_hist as fill_func except ImportError: from root_numpy import fill_array as fill_func except Impo...
['def', 'fill_array', '(', 'self', ',', 'array', ',', 'weights', '=', 'None', ')', ':', 'try', ':', 'try', ':', 'from', 'root_numpy', 'import', 'fill_hist', 'as', 'fill_func', 'except', 'ImportError', ':', 'from', 'root_numpy', 'import', 'fill_array', 'as', 'fill_func', 'except', 'ImportError', ':', 'log', '.', 'critic...
Fill this histogram with a NumPy array
['Fill', 'this', 'histogram', 'with', 'a', 'NumPy', 'array']
train
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/hist.py#L1192-L1206
3,902
lowandrew/OLCTools
spadespipeline/sistr.py
Sistr.report
def report(self): """Creates sistr reports""" # Initialise strings to store report data header = '\t'.join(self.headers) + '\n' data = '' for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Each strain is a fresh row ...
python
def report(self): """Creates sistr reports""" # Initialise strings to store report data header = '\t'.join(self.headers) + '\n' data = '' for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Each strain is a fresh row ...
['def', 'report', '(', 'self', ')', ':', '# Initialise strings to store report data', 'header', '=', "'\\t'", '.', 'join', '(', 'self', '.', 'headers', ')', '+', "'\\n'", 'data', '=', "''", 'for', 'sample', 'in', 'self', '.', 'metadata', ':', 'if', 'sample', '.', 'general', '.', 'bestassemblyfile', '!=', "'NA'", ':', '...
Creates sistr reports
['Creates', 'sistr', 'reports']
train
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/sistr.py#L59-L95
3,903
saltstack/salt
salt/modules/namecheap_domains_dns.py
get_list
def get_list(sld, tld): ''' Gets a list of DNS servers associated with the requested domain. returns a dictionary of information about requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' namec...
python
def get_list(sld, tld): ''' Gets a list of DNS servers associated with the requested domain. returns a dictionary of information about requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' namec...
['def', 'get_list', '(', 'sld', ',', 'tld', ')', ':', 'opts', '=', 'salt', '.', 'utils', '.', 'namecheap', '.', 'get_opts', '(', "'namecheap.domains.dns.getlist'", ')', 'opts', '[', "'TLD'", ']', '=', 'tld', 'opts', '[', "'SLD'", ']', '=', 'sld', 'response_xml', '=', 'salt', '.', 'utils', '.', 'namecheap', '.', 'get_re...
Gets a list of DNS servers associated with the requested domain. returns a dictionary of information about requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains_dns.get_list sld tld
['Gets', 'a', 'list', 'of', 'DNS', 'servers', 'associated', 'with', 'the', 'requested', 'domain', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_domains_dns.py#L87-L115
3,904
Fortran-FOSS-Programmers/ford
ford/sourceform.py
FortranCodeUnit.prune
def prune(self): """ Remove anything which shouldn't be displayed. """ def to_include(obj): inc = obj.permission in self.display if self.settings['hide_undoc'].lower() == 'true' and not obj.doc: inc = False return inc if self.o...
python
def prune(self): """ Remove anything which shouldn't be displayed. """ def to_include(obj): inc = obj.permission in self.display if self.settings['hide_undoc'].lower() == 'true' and not obj.doc: inc = False return inc if self.o...
['def', 'prune', '(', 'self', ')', ':', 'def', 'to_include', '(', 'obj', ')', ':', 'inc', '=', 'obj', '.', 'permission', 'in', 'self', '.', 'display', 'if', 'self', '.', 'settings', '[', "'hide_undoc'", ']', '.', 'lower', '(', ')', '==', "'true'", 'and', 'not', 'obj', '.', 'doc', ':', 'inc', '=', 'False', 'return', 'in...
Remove anything which shouldn't be displayed.
['Remove', 'anything', 'which', 'shouldn', 't', 'be', 'displayed', '.']
train
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L998-L1034
3,905
objectrocket/python-client
objectrocket/instances/__init__.py
Instances._concrete_instance
def _concrete_instance(self, instance_doc): """Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance` """ ...
python
def _concrete_instance(self, instance_doc): """Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance` """ ...
['def', '_concrete_instance', '(', 'self', ',', 'instance_doc', ')', ':', 'if', 'not', 'isinstance', '(', 'instance_doc', ',', 'dict', ')', ':', 'return', 'None', '# Attempt to instantiate the appropriate class for the given instance document.', 'try', ':', 'service', '=', 'instance_doc', '[', "'service'", ']', 'cls', ...
Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance`
['Concretize', 'an', 'instance', 'document', '.']
train
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/instances/__init__.py#L99-L123
3,906
napalm-automation/napalm-logs
napalm_logs/device.py
NapalmLogsDeviceProc._emit
def _emit(self, **kwargs): ''' Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy. ''' oc_dict = {} for mapping, result_key in kwargs['mapping']['variables'].items(): result = kwargs[result_key]...
python
def _emit(self, **kwargs): ''' Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy. ''' oc_dict = {} for mapping, result_key in kwargs['mapping']['variables'].items(): result = kwargs[result_key]...
['def', '_emit', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'oc_dict', '=', '{', '}', 'for', 'mapping', ',', 'result_key', 'in', 'kwargs', '[', "'mapping'", ']', '[', "'variables'", ']', '.', 'items', '(', ')', ':', 'result', '=', 'kwargs', '[', 'result_key', ']', 'oc_dict', '=', 'napalm_logs', '.', 'utils', '.', ...
Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy.
['Emit', 'an', 'OpenConfig', 'object', 'given', 'a', 'certain', 'combination', 'of', 'fields', 'mappeed', 'in', 'the', 'config', 'to', 'the', 'corresponding', 'hierarchy', '.']
train
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L188-L200
3,907
razor-x/dichalcogenides
dichalcogenides/parameters/parameters.py
Parameters.parameter_list
def parameter_list(data): """Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict """ items = [] for item in data: param = Parameter(item[...
python
def parameter_list(data): """Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict """ items = [] for item in data: param = Parameter(item[...
['def', 'parameter_list', '(', 'data', ')', ':', 'items', '=', '[', ']', 'for', 'item', 'in', 'data', ':', 'param', '=', 'Parameter', '(', 'item', '[', "'name'", ']', ',', 'item', '[', "'value'", ']', ')', 'if', "'meta'", 'in', 'item', ':', 'param', '.', 'meta', '=', 'item', '[', "'meta'", ']', 'items', '.', 'append', ...
Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict
['Create', 'a', 'list', 'of', 'parameter', 'objects', 'from', 'a', 'dict', '.']
train
https://github.com/razor-x/dichalcogenides/blob/0fa1995a3a328b679c9926f73239d0ecdc6e5d3d/dichalcogenides/parameters/parameters.py#L163-L177
3,908
hobson/pug-dj
pug/dj/miner/views.py
stats
def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'): """ In addition to chart data in data['chart'], send statistics data to view in data['stats'] """ data = {} modified_chart_data = data['chart']['chartdata'] if 'y2' in data['chart']['chartdata']: matrix...
python
def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'): """ In addition to chart data in data['chart'], send statistics data to view in data['stats'] """ data = {} modified_chart_data = data['chart']['chartdata'] if 'y2' in data['chart']['chartdata']: matrix...
['def', 'stats', '(', 'request', ',', 'date_offset', '=', '0', ',', 'fields', '=', 'None', ',', 'title_prefix', '=', 'None', ',', 'model', '=', "'WikiItem'", ')', ':', 'data', '=', '{', '}', 'modified_chart_data', '=', 'data', '[', "'chart'", ']', '[', "'chartdata'", ']', 'if', "'y2'", 'in', 'data', '[', "'chart'", ']'...
In addition to chart data in data['chart'], send statistics data to view in data['stats']
['In', 'addition', 'to', 'chart', 'data', 'in', 'data', '[', 'chart', ']', 'send', 'statistics', 'data', 'to', 'view', 'in', 'data', '[', 'stats', ']']
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/views.py#L65-L95
3,909
paramiko/paramiko
paramiko/channel.py
Channel.set_environment_variable
def set_environment_variable(self, name, value): """ Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this...
python
def set_environment_variable(self, name, value): """ Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this...
['def', 'set_environment_variable', '(', 'self', ',', 'name', ',', 'value', ')', ':', 'm', '=', 'Message', '(', ')', 'm', '.', 'add_byte', '(', 'cMSG_CHANNEL_REQUEST', ')', 'm', '.', 'add_int', '(', 'self', '.', 'remote_chanid', ')', 'm', '.', 'add_string', '(', '"env"', ')', 'm', '.', 'add_boolean', '(', 'False', ')',...
Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your ...
['Set', 'the', 'value', 'of', 'an', 'environment', 'variable', '.']
train
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L338-L362
3,910
estnltk/estnltk
estnltk/np_chunker.py
NounPhraseChunker._getPhrase
def _getPhrase( self, i, sentence, NPlabels ): ''' Fetches the full length phrase from the position i based on the existing NP phrase annotations (from NPlabels); Returns list of sentence tokens in the phrase, and indices of the phrase; ''' ...
python
def _getPhrase( self, i, sentence, NPlabels ): ''' Fetches the full length phrase from the position i based on the existing NP phrase annotations (from NPlabels); Returns list of sentence tokens in the phrase, and indices of the phrase; ''' ...
['def', '_getPhrase', '(', 'self', ',', 'i', ',', 'sentence', ',', 'NPlabels', ')', ':', 'phrase', '=', '[', ']', 'indices', '=', '[', ']', 'if', '0', '<=', 'i', 'and', 'i', '<', 'len', '(', 'sentence', ')', 'and', 'NPlabels', '[', 'i', ']', '==', "'B'", ':', 'phrase', '=', '[', 'sentence', '[', 'i', ']', ']', 'indices...
Fetches the full length phrase from the position i based on the existing NP phrase annotations (from NPlabels); Returns list of sentence tokens in the phrase, and indices of the phrase;
['Fetches', 'the', 'full', 'length', 'phrase', 'from', 'the', 'position', 'i', 'based', 'on', 'the', 'existing', 'NP', 'phrase', 'annotations', '(', 'from', 'NPlabels', ')', ';', 'Returns', 'list', 'of', 'sentence', 'tokens', 'in', 'the', 'phrase', 'and', 'indices', 'of', 'the', 'phrase', ';']
train
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/np_chunker.py#L209-L229
3,911
resync/resync
resync/list_base_with_index.py
ListBaseWithIndex.as_xml_part
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0): """Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestam...
python
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0): """Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestam...
['def', 'as_xml_part', '(', 'self', ',', 'basename', '=', '"/tmp/sitemap.xml"', ',', 'part_number', '=', '0', ')', ':', 'if', '(', 'not', 'self', '.', 'requires_multifile', '(', ')', ')', ':', 'raise', 'ListBaseIndexError', '(', '"Request for component sitemap for list with only %d entries when max_sitemap_entries is s...
Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestamp should be used?
['Return', 'a', 'string', 'of', 'component', 'sitemap', 'number', 'part_number', '.']
train
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/list_base_with_index.py#L242-L270
3,912
mozilla/treeherder
treeherder/seta/common.py
job_priority_index
def job_priority_index(job_priorities): '''This structure helps with finding data from the job priorities table''' jp_index = {} # Creating this data structure which reduces how many times we iterate through the DB rows for jp in job_priorities: key = jp.unique_identifier() # This is gu...
python
def job_priority_index(job_priorities): '''This structure helps with finding data from the job priorities table''' jp_index = {} # Creating this data structure which reduces how many times we iterate through the DB rows for jp in job_priorities: key = jp.unique_identifier() # This is gu...
['def', 'job_priority_index', '(', 'job_priorities', ')', ':', 'jp_index', '=', '{', '}', '# Creating this data structure which reduces how many times we iterate through the DB rows', 'for', 'jp', 'in', 'job_priorities', ':', 'key', '=', 'jp', '.', 'unique_identifier', '(', ')', '# This is guaranteed by a unique compos...
This structure helps with finding data from the job priorities table
['This', 'structure', 'helps', 'with', 'finding', 'data', 'from', 'the', 'job', 'priorities', 'table']
train
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/seta/common.py#L10-L25
3,913
spyder-ide/spyder-kernels
spyder_kernels/console/kernel.py
SpyderKernel._pdb_frame
def _pdb_frame(self): """Return current Pdb frame if there is any""" if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
python
def _pdb_frame(self): """Return current Pdb frame if there is any""" if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
['def', '_pdb_frame', '(', 'self', ')', ':', 'if', 'self', '.', '_pdb_obj', 'is', 'not', 'None', 'and', 'self', '.', '_pdb_obj', '.', 'curframe', 'is', 'not', 'None', ':', 'return', 'self', '.', '_pdb_obj', '.', 'curframe']
Return current Pdb frame if there is any
['Return', 'current', 'Pdb', 'frame', 'if', 'there', 'is', 'any']
train
https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/console/kernel.py#L47-L50
3,914
openid/JWTConnect-Python-OidcService
src/oidcservice/oidc/pkce.py
add_code_challenge
def add_code_challenge(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :para...
python
def add_code_challenge(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :para...
['def', 'add_code_challenge', '(', 'request_args', ',', 'service', ',', '*', '*', 'kwargs', ')', ':', 'try', ':', 'cv_len', '=', 'service', '.', 'service_context', '.', 'config', '[', "'code_challenge'", ']', '[', "'length'", ']', 'except', 'KeyError', ':', 'cv_len', '=', '64', '# Use default', '# code_verifier: string...
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of ...
['PKCE', 'RFC', '7636', 'support', 'To', 'be', 'added', 'as', 'a', 'post_construct', 'method', 'to', 'an', ':', 'py', ':', 'class', ':', 'oidcservice', '.', 'oidc', '.', 'service', '.', 'Authorization', 'instance']
train
https://github.com/openid/JWTConnect-Python-OidcService/blob/759ab7adef30a7e3b9d75475e2971433b9613788/src/oidcservice/oidc/pkce.py#L9-L50
3,915
google/apitools
apitools/base/py/base_api.py
BaseApiClient.ProcessHttpRequest
def ProcessHttpRequest(self, http_request): """Hook for pre-processing of http requests.""" http_request.headers.update(self.additional_http_headers) if self.log_request: logging.info('Making http %s to %s', http_request.http_method, http_request.url) ...
python
def ProcessHttpRequest(self, http_request): """Hook for pre-processing of http requests.""" http_request.headers.update(self.additional_http_headers) if self.log_request: logging.info('Making http %s to %s', http_request.http_method, http_request.url) ...
['def', 'ProcessHttpRequest', '(', 'self', ',', 'http_request', ')', ':', 'http_request', '.', 'headers', '.', 'update', '(', 'self', '.', 'additional_http_headers', ')', 'if', 'self', '.', 'log_request', ':', 'logging', '.', 'info', '(', "'Making http %s to %s'", ',', 'http_request', '.', 'http_method', ',', 'http_req...
Hook for pre-processing of http requests.
['Hook', 'for', 'pre', '-', 'processing', 'of', 'http', 'requests', '.']
train
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L416-L430
3,916
pydata/xarray
xarray/convert.py
_iris_cell_methods_to_str
def _iris_cell_methods_to_str(cell_methods_obj): """ Converts a Iris cell methods into a string """ cell_methods = [] for cell_method in cell_methods_obj: names = ''.join(['{}: '.format(n) for n in cell_method.coord_names]) intervals = ' '.join(['interval: {}'.format(interval) ...
python
def _iris_cell_methods_to_str(cell_methods_obj): """ Converts a Iris cell methods into a string """ cell_methods = [] for cell_method in cell_methods_obj: names = ''.join(['{}: '.format(n) for n in cell_method.coord_names]) intervals = ' '.join(['interval: {}'.format(interval) ...
['def', '_iris_cell_methods_to_str', '(', 'cell_methods_obj', ')', ':', 'cell_methods', '=', '[', ']', 'for', 'cell_method', 'in', 'cell_methods_obj', ':', 'names', '=', "''", '.', 'join', '(', '[', "'{}: '", '.', 'format', '(', 'n', ')', 'for', 'n', 'in', 'cell_method', '.', 'coord_names', ']', ')', 'intervals', '=', ...
Converts a Iris cell methods into a string
['Converts', 'a', 'Iris', 'cell', 'methods', 'into', 'a', 'string']
train
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/convert.py#L194-L208
3,917
pypa/setuptools
setuptools/dist.py
Distribution.iter_distribution_names
def iter_distribution_names(self): """Yield all packages, modules, and extension names in distribution""" for pkg in self.packages or (): yield pkg for module in self.py_modules or (): yield module for ext in self.ext_modules or (): if isinstance(ex...
python
def iter_distribution_names(self): """Yield all packages, modules, and extension names in distribution""" for pkg in self.packages or (): yield pkg for module in self.py_modules or (): yield module for ext in self.ext_modules or (): if isinstance(ex...
['def', 'iter_distribution_names', '(', 'self', ')', ':', 'for', 'pkg', 'in', 'self', '.', 'packages', 'or', '(', ')', ':', 'yield', 'pkg', 'for', 'module', 'in', 'self', '.', 'py_modules', 'or', '(', ')', ':', 'yield', 'module', 'for', 'ext', 'in', 'self', '.', 'ext_modules', 'or', '(', ')', ':', 'if', 'isinstance', '...
Yield all packages, modules, and extension names in distribution
['Yield', 'all', 'packages', 'modules', 'and', 'extension', 'names', 'in', 'distribution']
train
https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/dist.py#L1069-L1085
3,918
linode/linode_api4-python
linode_api4/linode_client.py
LinodeClient.domain_create
def domain_create(self, domain, master=True, **kwargs): """ Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Lin...
python
def domain_create(self, domain, master=True, **kwargs): """ Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Lin...
['def', 'domain_create', '(', 'self', ',', 'domain', ',', 'master', '=', 'True', ',', '*', '*', 'kwargs', ')', ':', 'params', '=', '{', "'domain'", ':', 'domain', ',', "'type'", ':', "'master'", 'if', 'master', 'else', "'slave'", ',', '}', 'params', '.', 'update', '(', 'kwargs', ')', 'result', '=', 'self', '.', 'post',...
Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Linode's DNS manager. :type domain: str :param master: Whether ...
['Registers', 'a', 'new', 'Domain', 'on', 'the', 'acting', 'user', 's', 'account', '.', 'Make', 'sure', 'to', 'point', 'your', 'registrar', 'to', 'Linode', 's', 'nameservers', 'so', 'that', 'Linode', 's', 'DNS', 'manager', 'will', 'correctly', 'serve', 'your', 'domain', '.']
train
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L1028-L1054
3,919
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_prices
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
python
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
['def', 'get_prices', '(', 'self', ')', '->', 'List', '[', 'PriceModel', ']', ':', '# return self.security.prices.order_by(Price.date)', 'from', 'pricedb', '.', 'dal', 'import', 'Price', 'pricedb', '=', 'PriceDbApplication', '(', ')', 'repo', '=', 'pricedb', '.', 'get_price_repository', '(', ')', 'query', '=', '(', 're...
Returns all available prices for security
['Returns', 'all', 'available', 'prices', 'for', 'security']
train
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L236-L248
3,920
saltstack/salt
salt/modules/oracle.py
_parse_oratab
def _parse_oratab(sid): ''' Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions ''' if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'): ORATAB = '/etc/oratab' elif __grains__.get('kernel') in 'SunOS': ORATAB = '...
python
def _parse_oratab(sid): ''' Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions ''' if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'): ORATAB = '/etc/oratab' elif __grains__.get('kernel') in 'SunOS': ORATAB = '...
['def', '_parse_oratab', '(', 'sid', ')', ':', 'if', '__grains__', '.', 'get', '(', "'kernel'", ')', 'in', '(', "'Linux'", ',', "'AIX'", ',', "'FreeBSD'", ',', "'OpenBSD'", ',', "'NetBSD'", ')', ':', 'ORATAB', '=', "'/etc/oratab'", 'elif', '__grains__', '.', 'get', '(', "'kernel'", ')', 'in', "'SunOS'", ':', 'ORATAB', ...
Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions
['Return', 'ORACLE_HOME', 'for', 'a', 'given', 'SID', 'found', 'in', 'oratab']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L143-L166
3,921
robotools/fontMath
Lib/fontMath/mathGlyph.py
MathGlyph.drawPoints
def drawPoints(self, pointPen, filterRedundantPoints=False): """draw self using pointPen""" if filterRedundantPoints: pointPen = FilterRedundantPointPen(pointPen) for contour in self.contours: pointPen.beginPath(identifier=contour["identifier"]) for segmentTyp...
python
def drawPoints(self, pointPen, filterRedundantPoints=False): """draw self using pointPen""" if filterRedundantPoints: pointPen = FilterRedundantPointPen(pointPen) for contour in self.contours: pointPen.beginPath(identifier=contour["identifier"]) for segmentTyp...
['def', 'drawPoints', '(', 'self', ',', 'pointPen', ',', 'filterRedundantPoints', '=', 'False', ')', ':', 'if', 'filterRedundantPoints', ':', 'pointPen', '=', 'FilterRedundantPointPen', '(', 'pointPen', ')', 'for', 'contour', 'in', 'self', '.', 'contours', ':', 'pointPen', '.', 'beginPath', '(', 'identifier', '=', 'con...
draw self using pointPen
['draw', 'self', 'using', 'pointPen']
train
https://github.com/robotools/fontMath/blob/6abcb9d5a1ca19788fbde4418d7b5630c60990d8/Lib/fontMath/mathGlyph.py#L276-L286
3,922
dariusbakunas/rawdisk
rawdisk/util/rawstruct.py
RawStruct.get_field
def get_field(self, offset, length, format): """Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: ...
python
def get_field(self, offset, length, format): """Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: ...
['def', 'get_field', '(', 'self', ',', 'offset', ',', 'length', ',', 'format', ')', ':', 'return', 'struct', '.', 'unpack', '(', 'format', ',', 'self', '.', 'data', '[', 'offset', ':', 'offset', '+', 'length', ']', ')', '[', '0', ']']
Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: https://docs.python.org/2/library/struct.html#format-...
['Returns', 'unpacked', 'Python', 'struct', 'array', '.']
train
https://github.com/dariusbakunas/rawdisk/blob/1dc9d0b377fe5da3c406ccec4abc238c54167403/rawdisk/util/rawstruct.py#L92-L103
3,923
chrisspen/dtree
dtree.py
Tree.train
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
python
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
['def', 'train', '(', 'self', ',', 'record', ')', ':', 'assert', 'self', '.', 'data', '.', 'class_attribute_name', 'in', 'record', ',', '"The class attribute must be present in the record."', 'record', '=', 'record', '.', 'copy', '(', ')', 'self', '.', 'sample_count', '+=', '1', 'self', '.', 'tree', '.', 'train', '(', ...
Incrementally updates the tree with the given sample record.
['Incrementally', 'updates', 'the', 'tree', 'with', 'the', 'given', 'sample', 'record', '.']
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1415-L1423
3,924
disqus/overseer
overseer/templatetags/overseer_helpers.py
truncatechars
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: return...
python
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: return...
['def', 'truncatechars', '(', 'value', ',', 'arg', ')', ':', 'try', ':', 'length', '=', 'int', '(', 'arg', ')', 'except', 'ValueError', ':', '# Invalid literal for int().', 'return', 'value', '# Fail silently.', 'if', 'len', '(', 'value', ')', '>', 'length', ':', 'return', 'value', '[', ':', 'length', ']', '+', "'...'"...
Truncates a string after a certain number of chars. Argument: Number of chars to truncate after.
['Truncates', 'a', 'string', 'after', 'a', 'certain', 'number', 'of', 'chars', '.']
train
https://github.com/disqus/overseer/blob/b37573aba33b20aa86f89eb0c7e6f4d9905bedef/overseer/templatetags/overseer_helpers.py#L32-L44
3,925
campbellr/smashrun-client
smashrun/client.py
Smashrun.refresh_token
def refresh_token(self, **kwargs): """Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``. """ if 'client_secret' not in kwargs: kwargs.update(client_secret=se...
python
def refresh_token(self, **kwargs): """Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``. """ if 'client_secret' not in kwargs: kwargs.update(client_secret=se...
['def', 'refresh_token', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'if', "'client_secret'", 'not', 'in', 'kwargs', ':', 'kwargs', '.', 'update', '(', 'client_secret', '=', 'self', '.', 'client_secret', ')', 'if', "'client_id'", 'not', 'in', 'kwargs', ':', 'kwargs', '.', 'update', '(', 'client_id', '=', 'self', '....
Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``.
['Refresh', 'the', 'authentication', 'token', '.']
train
https://github.com/campbellr/smashrun-client/blob/2522cb4d0545cf482a49a9533f12aac94c5aecdc/smashrun/client.py#L53-L64
3,926
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle.install
def install(self, plugin): ''' Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. ''' if hasattr(plugin, 'setup'): plugin.setup(s...
python
def install(self, plugin): ''' Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. ''' if hasattr(plugin, 'setup'): plugin.setup(s...
['def', 'install', '(', 'self', ',', 'plugin', ')', ':', 'if', 'hasattr', '(', 'plugin', ',', "'setup'", ')', ':', 'plugin', '.', 'setup', '(', 'self', ')', 'if', 'not', 'callable', '(', 'plugin', ')', 'and', 'not', 'hasattr', '(', 'plugin', ',', "'apply'", ')', ':', 'raise', 'TypeError', '(', '"Plugins must be callabl...
Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API.
['Add', 'a', 'plugin', 'to', 'the', 'list', 'of', 'plugins', 'and', 'prepare', 'it', 'for', 'beeing', 'applied', 'to', 'all', 'routes', 'of', 'this', 'application', '.', 'A', 'plugin', 'may', 'be', 'a', 'simple', 'decorator', 'or', 'an', 'object', 'that', 'implements', 'the', ':', 'class', ':', 'Plugin', 'API', '.']
train
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L455-L465
3,927
Phelimb/ga4gh-mongo
ga4ghmongo/schema/models/variants.py
is_snp
def is_snp(reference_bases, alternate_bases): """ Return whether or not the variant is a SNP """ if len(reference_bases) > 1: return False for alt in alternate_bases: if alt is None: return False if alt not in ['A', 'C', 'G', 'T', 'N', '*']: return False r...
python
def is_snp(reference_bases, alternate_bases): """ Return whether or not the variant is a SNP """ if len(reference_bases) > 1: return False for alt in alternate_bases: if alt is None: return False if alt not in ['A', 'C', 'G', 'T', 'N', '*']: return False r...
['def', 'is_snp', '(', 'reference_bases', ',', 'alternate_bases', ')', ':', 'if', 'len', '(', 'reference_bases', ')', '>', '1', ':', 'return', 'False', 'for', 'alt', 'in', 'alternate_bases', ':', 'if', 'alt', 'is', 'None', ':', 'return', 'False', 'if', 'alt', 'not', 'in', '[', "'A'", ',', "'C'", ',', "'G'", ',', "'T'",...
Return whether or not the variant is a SNP
['Return', 'whether', 'or', 'not', 'the', 'variant', 'is', 'a', 'SNP']
train
https://github.com/Phelimb/ga4gh-mongo/blob/5f5a3e1922be0e0d13af1874fad6eed5418ee761/ga4ghmongo/schema/models/variants.py#L280-L289
3,928
saltstack/salt
salt/modules/mac_group.py
_list_gids
def _list_gids(): ''' Return a list of gids in use ''' output = __salt__['cmd.run']( ['dscacheutil', '-q', 'group'], output_loglevel='quiet', python_shell=False ) ret = set() for line in salt.utils.itertools.split(output, '\n'): if line.startswith('gid:'): ...
python
def _list_gids(): ''' Return a list of gids in use ''' output = __salt__['cmd.run']( ['dscacheutil', '-q', 'group'], output_loglevel='quiet', python_shell=False ) ret = set() for line in salt.utils.itertools.split(output, '\n'): if line.startswith('gid:'): ...
['def', '_list_gids', '(', ')', ':', 'output', '=', '__salt__', '[', "'cmd.run'", ']', '(', '[', "'dscacheutil'", ',', "'-q'", ',', "'group'", ']', ',', 'output_loglevel', '=', "'quiet'", ',', 'python_shell', '=', 'False', ')', 'ret', '=', 'set', '(', ')', 'for', 'line', 'in', 'salt', '.', 'utils', '.', 'itertools', '....
Return a list of gids in use
['Return', 'a', 'list', 'of', 'gids', 'in', 'use']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L75-L88
3,929
juju/charm-helpers
charmhelpers/coordinator.py
BaseCoordinator.granted
def granted(self, lock): '''Return True if a previously requested lock has been granted''' unit = hookenv.local_unit() ts = self.requests[unit].get(lock) if ts and self.grants.get(unit, {}).get(lock) == ts: return True return False
python
def granted(self, lock): '''Return True if a previously requested lock has been granted''' unit = hookenv.local_unit() ts = self.requests[unit].get(lock) if ts and self.grants.get(unit, {}).get(lock) == ts: return True return False
['def', 'granted', '(', 'self', ',', 'lock', ')', ':', 'unit', '=', 'hookenv', '.', 'local_unit', '(', ')', 'ts', '=', 'self', '.', 'requests', '[', 'unit', ']', '.', 'get', '(', 'lock', ')', 'if', 'ts', 'and', 'self', '.', 'grants', '.', 'get', '(', 'unit', ',', '{', '}', ')', '.', 'get', '(', 'lock', ')', '==', 'ts',...
Return True if a previously requested lock has been granted
['Return', 'True', 'if', 'a', 'previously', 'requested', 'lock', 'has', 'been', 'granted']
train
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L338-L344
3,930
SpikeInterface/spikeextractors
spikeextractors/tools.py
load_probe_file
def load_probe_file(recording, probe_file, channel_map=None, channel_groups=None): '''Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ...
python
def load_probe_file(recording, probe_file, channel_map=None, channel_groups=None): '''Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ...
['def', 'load_probe_file', '(', 'recording', ',', 'probe_file', ',', 'channel_map', '=', 'None', ',', 'channel_groups', '=', 'None', ')', ':', 'probe_file', '=', 'Path', '(', 'probe_file', ')', 'if', 'probe_file', '.', 'suffix', '==', "'.prb'", ':', 'probe_dict', '=', 'read_python', '(', 'probe_file', ')', 'if', "'chan...
Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ---------- recording: RecordingExtractor The recording extractor to channel...
['Loads', 'channel', 'information', 'into', 'recording', 'extractor', '.', 'If', 'a', '.', 'prb', 'file', 'is', 'given', 'then', 'location', 'and', 'group', 'information', 'for', 'each', 'channel', 'is', 'stored', '.', 'If', 'a', '.', 'csv', 'file', 'is', 'given', 'then', 'it', 'will', 'only', 'store', 'location']
train
https://github.com/SpikeInterface/spikeextractors/blob/cbe3b8778a215f0bbd743af8b306856a87e438e1/spikeextractors/tools.py#L35-L136
3,931
twoolie/NBT
nbt/region.py
RegionFile.get_nbt
def get_nbt(self, x, z): """ Return a NBTFile of the specified chunk. Raise InconceivedChunk if the chunk is not included in the file. """ # TODO: cache results? data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError. data = BytesIO(data) ...
python
def get_nbt(self, x, z): """ Return a NBTFile of the specified chunk. Raise InconceivedChunk if the chunk is not included in the file. """ # TODO: cache results? data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError. data = BytesIO(data) ...
['def', 'get_nbt', '(', 'self', ',', 'x', ',', 'z', ')', ':', '# TODO: cache results?', 'data', '=', 'self', '.', 'get_blockdata', '(', 'x', ',', 'z', ')', '# This may raise a RegionFileFormatError.', 'data', '=', 'BytesIO', '(', 'data', ')', 'err', '=', 'None', 'try', ':', 'nbt', '=', 'NBTFile', '(', 'buffer', '=', 'd...
Return a NBTFile of the specified chunk. Raise InconceivedChunk if the chunk is not included in the file.
['Return', 'a', 'NBTFile', 'of', 'the', 'specified', 'chunk', '.', 'Raise', 'InconceivedChunk', 'if', 'the', 'chunk', 'is', 'not', 'included', 'in', 'the', 'file', '.']
train
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L585-L606
3,932
heroku-python/django-postgrespool
django_postgrespool/base.py
DatabaseWrapper._dispose
def _dispose(self): """Dispose of the pool for this instance, closing all connections.""" self.close() # _DBProxy.dispose doesn't actually call dispose on the pool conn_params = self.get_connection_params() key = db_pool._serialize(**conn_params) try: pool = d...
python
def _dispose(self): """Dispose of the pool for this instance, closing all connections.""" self.close() # _DBProxy.dispose doesn't actually call dispose on the pool conn_params = self.get_connection_params() key = db_pool._serialize(**conn_params) try: pool = d...
['def', '_dispose', '(', 'self', ')', ':', 'self', '.', 'close', '(', ')', "# _DBProxy.dispose doesn't actually call dispose on the pool", 'conn_params', '=', 'self', '.', 'get_connection_params', '(', ')', 'key', '=', 'db_pool', '.', '_serialize', '(', '*', '*', 'conn_params', ')', 'try', ':', 'pool', '=', 'db_pool', ...
Dispose of the pool for this instance, closing all connections.
['Dispose', 'of', 'the', 'pool', 'for', 'this', 'instance', 'closing', 'all', 'connections', '.']
train
https://github.com/heroku-python/django-postgrespool/blob/ce83a4d49c19eded86d86d5fcfa8daaeea5ef662/django_postgrespool/base.py#L91-L103
3,933
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop.plotJacobi
def plotJacobi(self,*args,**kwargs): """ NAME: plotE PURPOSE: plot Jacobi(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ ...
python
def plotJacobi(self,*args,**kwargs): """ NAME: plotE PURPOSE: plot Jacobi(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ ...
['def', 'plotJacobi', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'if', 'kwargs', '.', 'pop', '(', "'normed'", ',', 'False', ')', ':', 'kwargs', '[', "'d2'", ']', '=', "'Jacobinorm'", 'else', ':', 'kwargs', '[', "'d2'", ']', '=', "'Jacobi'", 'return', 'self', '.', 'plot', '(', '*', 'args', ',', '*...
NAME: plotE PURPOSE: plot Jacobi(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS)
['NAME', ':', 'plotE', 'PURPOSE', ':', 'plot', 'Jacobi', '(', '.', ')', 'along', 'the', 'orbit', 'INPUT', ':', 'bovy_plot', '.', 'bovy_plot', 'inputs', 'OUTPUT', ':', 'figure', 'to', 'output', 'device', 'HISTORY', ':', '2014', '-', '06', '-', '16', '-', 'Written', '-', 'Bovy', '(', 'IAS', ')']
train
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L1848-L1865
3,934
ivanprjcts/sdklib
sdklib/html/base.py
HTML5libMixin.find_element_by_xpath
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ """ ...
python
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ """ ...
['def', 'find_element_by_xpath', '(', 'self', ',', 'xpath', ')', ':', 'from', 'sdklib', '.', 'html', '.', 'elem', 'import', 'Elem5lib', 'return', 'Elem5lib', '(', 'self', '.', 'html_obj', '.', 'find', '(', 'self', '.', '_convert_xpath', '(', 'xpath', ')', ')', ')']
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_
['Finds', 'an', 'element', 'by', 'xpath', '.']
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/html/base.py#L121-L132
3,935
HttpRunner/HttpRunner
httprunner/utils.py
dump_json_file
def dump_json_file(json_data, pwd_dir_path, dump_file_name): """ dump json data to file """ class PythonObjectEncoder(json.JSONEncoder): def default(self, obj): try: return super().default(self, obj) except TypeError: return str(obj) logs_...
python
def dump_json_file(json_data, pwd_dir_path, dump_file_name): """ dump json data to file """ class PythonObjectEncoder(json.JSONEncoder): def default(self, obj): try: return super().default(self, obj) except TypeError: return str(obj) logs_...
['def', 'dump_json_file', '(', 'json_data', ',', 'pwd_dir_path', ',', 'dump_file_name', ')', ':', 'class', 'PythonObjectEncoder', '(', 'json', '.', 'JSONEncoder', ')', ':', 'def', 'default', '(', 'self', ',', 'obj', ')', ':', 'try', ':', 'return', 'super', '(', ')', '.', 'default', '(', 'self', ',', 'obj', ')', 'except...
dump json data to file
['dump', 'json', 'data', 'to', 'file']
train
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/utils.py#L527-L570
3,936
CalebBell/fpi
fpi/drag.py
Flemmer_Banks
def Flemmer_Banks(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds n...
python
def Flemmer_Banks(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds n...
['def', 'Flemmer_Banks', '(', 'Re', ')', ':', 'E', '=', '0.383', '*', 'Re', '**', '0.356', '-', '0.207', '*', 'Re', '**', '0.396', '-', '0.143', '/', '(', '1', '+', '(', 'log10', '(', 'Re', ')', ')', '**', '2', ')', 'Cd', '=', '24.', '/', 'Re', '*', '10', '**', 'E', 'return', 'Cd']
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds number of the sphere, [-] ...
['r', 'Calculates', 'drag', 'coefficient', 'of', 'a', 'smooth', 'sphere', 'using', 'the', 'method', 'in', '[', '1', ']', '_', 'as', 'described', 'in', '[', '2', ']', '_', '.']
train
https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/drag.py#L383-L424
3,937
hishnash/djangochannelsrestframework
djangochannelsrestframework/consumers.py
DjangoViewAsConsumer.handle_action
async def handle_action(self, action: str, request_id: str, **kwargs): """ run the action. """ try: await self.check_permissions(action, **kwargs) if action not in self.actions: raise MethodNotAllowed(method=action) content, status = ...
python
async def handle_action(self, action: str, request_id: str, **kwargs): """ run the action. """ try: await self.check_permissions(action, **kwargs) if action not in self.actions: raise MethodNotAllowed(method=action) content, status = ...
['async', 'def', 'handle_action', '(', 'self', ',', 'action', ':', 'str', ',', 'request_id', ':', 'str', ',', '*', '*', 'kwargs', ')', ':', 'try', ':', 'await', 'self', '.', 'check_permissions', '(', 'action', ',', '*', '*', 'kwargs', ')', 'if', 'action', 'not', 'in', 'self', '.', 'actions', ':', 'raise', 'MethodNotAll...
run the action.
['run', 'the', 'action', '.']
train
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L222-L249
3,938
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py
brocade_aaa.service_password_encryption
def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade-aaa") password_encryption = ET.SubElement(service, "password-encryption") callback = k...
python
def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade-aaa") password_encryption = ET.SubElement(service, "password-encryption") callback = k...
['def', 'service_password_encryption', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'service', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"service"', ',', 'xmlns', '=', '"urn:brocade.com:mgmt:brocade-aaa"', ')', 'password_encryption', '=', '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_aaa.py#L161-L169
3,939
bulkan/robotframework-requests
src/RequestsLibrary/RequestsKeywords.py
RequestsKeywords.update_session
def update_session(self, alias, headers=None, cookies=None): """Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session """ session = self._cache.switch(alias) ses...
python
def update_session(self, alias, headers=None, cookies=None): """Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session """ session = self._cache.switch(alias) ses...
['def', 'update_session', '(', 'self', ',', 'alias', ',', 'headers', '=', 'None', ',', 'cookies', '=', 'None', ')', ':', 'session', '=', 'self', '.', '_cache', '.', 'switch', '(', 'alias', ')', 'session', '.', 'headers', '=', 'merge_setting', '(', 'headers', ',', 'session', '.', 'headers', ')', 'session', '.', 'cookies...
Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session
['Update', 'Session', 'Headers', ':', 'update', 'a', 'HTTP', 'Session', 'Headers']
train
https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L449-L458
3,940
lrq3000/pyFileFixity
pyFileFixity/lib/brownanrs/polynomial.py
Polynomial.derive
def derive(self): '''Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))''' #res = [0] * (len(self)-1) # pre-allocate the list, it will be one item shorter because the constant coefficient (x^0) will be removed #for i in _range(2, len(self)+1): # start at 2 to skip the first...
python
def derive(self): '''Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))''' #res = [0] * (len(self)-1) # pre-allocate the list, it will be one item shorter because the constant coefficient (x^0) will be removed #for i in _range(2, len(self)+1): # start at 2 to skip the first...
['def', 'derive', '(', 'self', ')', ':', '#res = [0] * (len(self)-1) # pre-allocate the list, it will be one item shorter because the constant coefficient (x^0) will be removed', "#for i in _range(2, len(self)+1): # start at 2 to skip the first coeff which is useless since it's a constant (x^0) so we +1, and because we...
Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))
['Compute', 'the', 'formal', 'derivative', 'of', 'the', 'polynomial', ':', 'sum', '(', 'i', '*', 'coeff', '[', 'i', ']', 'x^', '(', 'i', '-', '1', '))']
train
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/brownanrs/polynomial.py#L358-L369
3,941
minhhoit/yacms
yacms/generic/fields.py
KeywordsField.contribute_to_class
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
python
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
['def', 'contribute_to_class', '(', 'self', ',', 'cls', ',', 'name', ')', ':', 'super', '(', 'KeywordsField', ',', 'self', ')', '.', 'contribute_to_class', '(', 'cls', ',', 'name', ')', 'string_field_name', '=', 'list', '(', 'self', '.', 'fields', '.', 'keys', '(', ')', ')', '[', '0', ']', '%', 'self', '.', 'related_fi...
Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``.
['Swap', 'out', 'any', 'reference', 'to', 'KeywordsField', 'with', 'the', 'KEYWORDS_FIELD_string', 'field', 'in', 'search_fields', '.']
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L206-L226
3,942
HEPData/hepdata-converter
hepdata_converter/parsers/oldhepdata_parser.py
OldHEPData._parse_header
def _parse_header(self, data): """Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list """ return_list = [] headers = data.split(':') for header in headers: he...
python
def _parse_header(self, data): """Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list """ return_list = [] headers = data.split(':') for header in headers: he...
['def', '_parse_header', '(', 'self', ',', 'data', ')', ':', 'return_list', '=', '[', ']', 'headers', '=', 'data', '.', 'split', '(', "':'", ')', 'for', 'header', 'in', 'headers', ':', 'header', '=', 're', '.', 'split', '(', "' IN '", ',', 'header', ',', 'flags', '=', 're', '.', 'I', ')', '# ignore case', 'xheader', '=...
Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list
['Parse', 'header', '(', 'xheader', 'or', 'yheader', ')']
train
https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L552-L571
3,943
6809/MC6809
MC6809/components/mc6809_base.py
CPUBase.burst_run
def burst_run(self): """ Run CPU as fast as Python can... """ # https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... get_and_call_next_op = self.get_and_call_next_op for __ in range(self.outer_burst_op_count): for __ in range(self.inner_burst_op_count): ...
python
def burst_run(self): """ Run CPU as fast as Python can... """ # https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... get_and_call_next_op = self.get_and_call_next_op for __ in range(self.outer_burst_op_count): for __ in range(self.inner_burst_op_count): ...
['def', 'burst_run', '(', 'self', ')', ':', '# https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...', 'get_and_call_next_op', '=', 'self', '.', 'get_and_call_next_op', 'for', '__', 'in', 'range', '(', 'self', '.', 'outer_burst_op_count', ')', ':', 'for', '__', 'in', 'range', '(', 'self', '.', 'inne...
Run CPU as fast as Python can...
['Run', 'CPU', 'as', 'fast', 'as', 'Python', 'can', '...']
train
https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_base.py#L285-L294
3,944
nickjj/ansigenome
ansigenome/export.py
Export.graph_dot
def graph_dot(self): """ Export a graph of the data in dot format. """ default_graphviz_template = """ digraph role_dependencies { size="%size" dpi=%dpi ratio="fill" landscape=false rankdir="BT"; node [shape = "box", style = ...
python
def graph_dot(self): """ Export a graph of the data in dot format. """ default_graphviz_template = """ digraph role_dependencies { size="%size" dpi=%dpi ratio="fill" landscape=false rankdir="BT"; node [shape = "box", style = ...
['def', 'graph_dot', '(', 'self', ')', ':', 'default_graphviz_template', '=', '"""\ndigraph role_dependencies {\n size="%size"\n dpi=%dpi\n ratio="fill"\n landscape=false\n rankdir="BT";\n\n node [shape = "box",\n style = "rounded,filled",\n fillcolor ...
Export a graph of the data in dot format.
['Export', 'a', 'graph', 'of', 'the', 'data', 'in', 'dot', 'format', '.']
train
https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L82-L161
3,945
KrzyHonk/bpmn-python
bpmn_python/graph/classes/events/catch_event_type.py
CatchEvent.set_parallel_multiple
def set_parallel_multiple(self, value): """ Setter for 'parallel_multiple' field. :param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value. """ if value is None or not isinstance(value, bool): raise TypeError("Paralle...
python
def set_parallel_multiple(self, value): """ Setter for 'parallel_multiple' field. :param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value. """ if value is None or not isinstance(value, bool): raise TypeError("Paralle...
['def', 'set_parallel_multiple', '(', 'self', ',', 'value', ')', ':', 'if', 'value', 'is', 'None', 'or', 'not', 'isinstance', '(', 'value', ',', 'bool', ')', ':', 'raise', 'TypeError', '(', '"ParallelMultiple must be set to a bool"', ')', 'else', ':', 'self', '.', '__parallel_multiple', '=', 'value']
Setter for 'parallel_multiple' field. :param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
['Setter', 'for', 'parallel_multiple', 'field', '.', ':', 'param', 'value', '-', 'a', 'new', 'value', 'of', 'parallel_multiple', 'field', '.', 'Must', 'be', 'a', 'boolean', 'type', '.', 'Does', 'not', 'accept', 'None', 'value', '.']
train
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/graph/classes/events/catch_event_type.py#L32-L40
3,946
numenta/htmresearch
htmresearch/frameworks/sp_paper/sp_metrics.py
binaryEntropyVectorized
def binaryEntropyVectorized(x): """ Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy """ entropy = - x*np.log2(x) - (1-x)*np.log2(1-x) entropy[x*(1 - x) == 0] = 0 return entropy
python
def binaryEntropyVectorized(x): """ Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy """ entropy = - x*np.log2(x) - (1-x)*np.log2(1-x) entropy[x*(1 - x) == 0] = 0 return entropy
['def', 'binaryEntropyVectorized', '(', 'x', ')', ':', 'entropy', '=', '-', 'x', '*', 'np', '.', 'log2', '(', 'x', ')', '-', '(', '1', '-', 'x', ')', '*', 'np', '.', 'log2', '(', '1', '-', 'x', ')', 'entropy', '[', 'x', '*', '(', '1', '-', 'x', ')', '==', '0', ']', '=', '0', 'return', 'entropy']
Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy
['Calculate', 'entropy', 'for', 'a', 'list', 'of', 'binary', 'random', 'variables', ':', 'param', 'x', ':', '(', 'numpy', 'array', ')', 'the', 'probability', 'of', 'the', 'variable', 'to', 'be', '1', '.', ':', 'return', ':', 'entropy', ':', '(', 'numpy', 'array', ')', 'entropy']
train
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/sp_paper/sp_metrics.py#L725-L733
3,947
chukysoria/pyspotify-connect
spotifyconnect/__init__.py
_setup_logging
def _setup_logging(): """Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal function. """ import logging logger = logging.getLogger('spotify-connect') handler = logging.NullHandler() logger.addHandler(h...
python
def _setup_logging(): """Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal function. """ import logging logger = logging.getLogger('spotify-connect') handler = logging.NullHandler() logger.addHandler(h...
['def', '_setup_logging', '(', ')', ':', 'import', 'logging', 'logger', '=', 'logging', '.', 'getLogger', '(', "'spotify-connect'", ')', 'handler', '=', 'logging', '.', 'NullHandler', '(', ')', 'logger', '.', 'addHandler', '(', 'handler', ')']
Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal function.
['Setup', 'logging', 'to', 'log', 'to', 'nowhere', 'by', 'default', '.']
train
https://github.com/chukysoria/pyspotify-connect/blob/bd157fa4fb2b51b3641f198a35384678c1a4fa11/spotifyconnect/__init__.py#L19-L31
3,948
sibirrer/lenstronomy
lenstronomy/Util/prob_density.py
SkewGaussian.pdf_new
def pdf_new(self, x, mu, sigma, skw): """ function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return: """ if skw > 1 or skw < -1: print("skewness %s out of range" % skw) ...
python
def pdf_new(self, x, mu, sigma, skw): """ function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return: """ if skw > 1 or skw < -1: print("skewness %s out of range" % skw) ...
['def', 'pdf_new', '(', 'self', ',', 'x', ',', 'mu', ',', 'sigma', ',', 'skw', ')', ':', 'if', 'skw', '>', '1', 'or', 'skw', '<', '-', '1', ':', 'print', '(', '"skewness %s out of range"', '%', 'skw', ')', 'skw', '=', '1.', 'e', ',', 'w', ',', 'a', '=', 'self', '.', 'map_mu_sigma_skw', '(', 'mu', ',', 'sigma', ',', 'sk...
function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return:
['function', 'with', 'different', 'parameterisation', ':', 'param', 'x', ':', ':', 'param', 'mu', ':', 'mean', ':', 'param', 'sigma', ':', 'sigma', ':', 'param', 'skw', ':', 'skewness', ':', 'return', ':']
train
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/prob_density.py#L25-L39
3,949
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py
brocade_ras_ext.show_support_save_status_output_show_support_save_status_message
def show_support_save_status_output_show_support_save_status_message(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_support_save_status = ET.Element("show_support_save_status") config = show_support_save_status output = ET.SubElement(show_s...
python
def show_support_save_status_output_show_support_save_status_message(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_support_save_status = ET.Element("show_support_save_status") config = show_support_save_status output = ET.SubElement(show_s...
['def', 'show_support_save_status_output_show_support_save_status_message', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'show_support_save_status', '=', 'ET', '.', 'Element', '(', '"show_support_save_status"', ')', 'config', '=', 'show_support_save_status',...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ras_ext.py#L255-L267
3,950
Faylixe/pygame_vkeyboard
pygame_vkeyboard/vkeyboard.py
VKeyboardLayout.set_uppercase
def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value ...
python
def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value ...
['def', 'set_uppercase', '(', 'self', ',', 'uppercase', ')', ':', 'for', 'row', 'in', 'self', '.', 'rows', ':', 'for', 'key', 'in', 'row', '.', 'keys', ':', 'if', 'type', '(', 'key', ')', '==', 'VKey', ':', 'if', 'uppercase', ':', 'key', '.', 'value', '=', 'key', '.', 'value', '.', 'upper', '(', ')', 'else', ':', 'key'...
Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise.
['Sets', 'layout', 'uppercase', 'state', '.']
train
https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L500-L511
3,951
wmayner/pyphi
pyphi/actual.py
Transition.potential_purviews
def potential_purviews(self, direction, mechanism, purviews=False): """Return all purviews that could belong to the |MIC|/|MIE|. Filters out trivially-reducible purviews. Args: direction (str): Either |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism of interes...
python
def potential_purviews(self, direction, mechanism, purviews=False): """Return all purviews that could belong to the |MIC|/|MIE|. Filters out trivially-reducible purviews. Args: direction (str): Either |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism of interes...
['def', 'potential_purviews', '(', 'self', ',', 'direction', ',', 'mechanism', ',', 'purviews', '=', 'False', ')', ':', 'system', '=', 'self', '.', 'system', '[', 'direction', ']', 'return', '[', 'purview', 'for', 'purview', 'in', 'system', '.', 'potential_purviews', '(', 'direction', ',', 'mechanism', ',', 'purviews',...
Return all purviews that could belong to the |MIC|/|MIE|. Filters out trivially-reducible purviews. Args: direction (str): Either |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism of interest. Keyword Args: purviews (tuple[int]): Optional subset of...
['Return', 'all', 'purviews', 'that', 'could', 'belong', 'to', 'the', '|MIC|', '/', '|MIE|', '.']
train
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L366-L383
3,952
smarie/python-valid8
valid8/entry_points.py
get_none_policy_text
def get_none_policy_text(none_policy, # type: int verbose=False # type: bool ): """ Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: """ if none_policy is N...
python
def get_none_policy_text(none_policy, # type: int verbose=False # type: bool ): """ Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: """ if none_policy is N...
['def', 'get_none_policy_text', '(', 'none_policy', ',', '# type: int', 'verbose', '=', 'False', '# type: bool', ')', ':', 'if', 'none_policy', 'is', 'NonePolicy', '.', 'SKIP', ':', 'return', '"accept None without performing validation"', 'if', 'verbose', 'else', "'SKIP'", 'elif', 'none_policy', 'is', 'NonePolicy', '.'...
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return:
['Returns', 'a', 'user', '-', 'friendly', 'description', 'of', 'a', 'NonePolicy', 'taking', 'into', 'account', 'NoneArgPolicy']
train
https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/entry_points.py#L53-L76
3,953
quantumlib/Cirq
cirq/circuits/circuit.py
Circuit.findall_operations_between
def findall_operations_between(self, start_frontier: Dict[ops.Qid, int], end_frontier: Dict[ops.Qid, int], omit_crossing_operations: bool = False ) -> List[Tuple[int, ops.Operation...
python
def findall_operations_between(self, start_frontier: Dict[ops.Qid, int], end_frontier: Dict[ops.Qid, int], omit_crossing_operations: bool = False ) -> List[Tuple[int, ops.Operation...
['def', 'findall_operations_between', '(', 'self', ',', 'start_frontier', ':', 'Dict', '[', 'ops', '.', 'Qid', ',', 'int', ']', ',', 'end_frontier', ':', 'Dict', '[', 'ops', '.', 'Qid', ',', 'int', ']', ',', 'omit_crossing_operations', ':', 'bool', '=', 'False', ')', '->', 'List', '[', 'Tuple', '[', 'int', ',', 'ops', ...
Finds operations between the two given frontiers. If a qubit is in `start_frontier` but not `end_frontier`, its end index defaults to the end of the circuit. If a qubit is in `end_frontier` but not `start_frontier`, its start index defaults to the start of the circuit. Operations on qub...
['Finds', 'operations', 'between', 'the', 'two', 'given', 'frontiers', '.']
train
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/circuits/circuit.py#L623-L671
3,954
csaez/wishlib
wishlib/qt/helpers.py
wrapinstance
def wrapinstance(ptr, base=None): """convert a pointer to a Qt class instance (PySide/PyQt compatible)""" if ptr is None: return None ptr = long(ptr) # Ensure type from wishlib.qt import active, QtCore, QtGui if active == "PySide": import shiboken if base is None: ...
python
def wrapinstance(ptr, base=None): """convert a pointer to a Qt class instance (PySide/PyQt compatible)""" if ptr is None: return None ptr = long(ptr) # Ensure type from wishlib.qt import active, QtCore, QtGui if active == "PySide": import shiboken if base is None: ...
['def', 'wrapinstance', '(', 'ptr', ',', 'base', '=', 'None', ')', ':', 'if', 'ptr', 'is', 'None', ':', 'return', 'None', 'ptr', '=', 'long', '(', 'ptr', ')', '# Ensure type', 'from', 'wishlib', '.', 'qt', 'import', 'active', ',', 'QtCore', ',', 'QtGui', 'if', 'active', '==', '"PySide"', ':', 'import', 'shiboken', 'if'...
convert a pointer to a Qt class instance (PySide/PyQt compatible)
['convert', 'a', 'pointer', 'to', 'a', 'Qt', 'class', 'instance', '(', 'PySide', '/', 'PyQt', 'compatible', ')']
train
https://github.com/csaez/wishlib/blob/c212fa7875006a332a4cefbf69885ced9647bc2f/wishlib/qt/helpers.py#L98-L121
3,955
tensorflow/tensor2tensor
tensor2tensor/layers/modalities.py
image_top
def image_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg # TODO(lukaszkaiser): is this a universal enough way to get channels? num_channels = model_hparams.problem.num_channels with tf.variable_scope("rgb_softmax"): body_output_shape = ...
python
def image_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg # TODO(lukaszkaiser): is this a universal enough way to get channels? num_channels = model_hparams.problem.num_channels with tf.variable_scope("rgb_softmax"): body_output_shape = ...
['def', 'image_top', '(', 'body_output', ',', 'targets', ',', 'model_hparams', ',', 'vocab_size', ')', ':', 'del', 'targets', '# unused arg', '# TODO(lukaszkaiser): is this a universal enough way to get channels?', 'num_channels', '=', 'model_hparams', '.', 'problem', '.', 'num_channels', 'with', 'tf', '.', 'variable_s...
Top transformation for images.
['Top', 'transformation', 'for', 'images', '.']
train
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L955-L972
3,956
twisted/mantissa
xmantissa/people.py
PhoneNumberContactType.createContactItem
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} ...
python
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} ...
['def', 'createContactItem', '(', 'self', ',', 'person', ',', 'label', ',', 'number', ')', ':', 'if', 'number', ':', 'return', 'PhoneNumber', '(', 'store', '=', 'person', '.', 'store', ',', 'person', '=', 'person', ',', 'label', '=', 'label', ',', 'number', '=', 'number', ')']
Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the n...
['Create', 'a', 'L', '{', 'PhoneNumber', '}', 'item', 'for', 'C', '{', 'number', '}', 'associated', 'with', 'C', '{', 'person', '}', '.']
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2016-L2034
3,957
oceanprotocol/squid-py
squid_py/agreements/register_service_agreement.py
execute_pending_service_agreements
def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn): """ Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, ...
python
def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn): """ Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, ...
['def', 'execute_pending_service_agreements', '(', 'storage_path', ',', 'account', ',', 'actor_type', ',', 'did_resolver_fn', ')', ':', 'keeper', '=', 'Keeper', '.', 'get_instance', '(', ')', '# service_agreement_id, did, service_definition_id, price, files, start_time, status', 'for', '(', 'agreement_id', ',', 'did', ...
Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, str :param account: :param actor_type: :param did_resolver_fn: :return:
['Iterates', 'over', 'pending', 'service', 'agreements', 'recorded', 'in', 'the', 'local', 'storage', 'fetches', 'their', 'service', 'definitions', 'and', 'subscribes', 'to', 'service', 'agreement', 'events', '.']
train
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L174-L215
3,958
sarugaku/requirementslib
tasks/__init__.py
clean
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f"python setup.py clean") dist = ROOT.joinpath("dist") build = ROOT.joinpath("build") print(f"[clean] Removing {dist} and {build}") if dist.exists(): shutil.rmtree(str(dist)) if build.exists(): shuti...
python
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f"python setup.py clean") dist = ROOT.joinpath("dist") build = ROOT.joinpath("build") print(f"[clean] Removing {dist} and {build}") if dist.exists(): shutil.rmtree(str(dist)) if build.exists(): shuti...
['def', 'clean', '(', 'ctx', ')', ':', 'ctx', '.', 'run', '(', 'f"python setup.py clean"', ')', 'dist', '=', 'ROOT', '.', 'joinpath', '(', '"dist"', ')', 'build', '=', 'ROOT', '.', 'joinpath', '(', '"build"', ')', 'print', '(', 'f"[clean] Removing {dist} and {build}"', ')', 'if', 'dist', '.', 'exists', '(', ')', ':', '...
Clean previously built package artifacts.
['Clean', 'previously', 'built', 'package', 'artifacts', '.']
train
https://github.com/sarugaku/requirementslib/blob/de78a01e8abc1fc47155516a96008d97035e8063/tasks/__init__.py#L56-L66
3,959
SiLab-Bonn/basil
basil/HL/GPAC.py
GPAC.set_current
def set_current(self, channel, value, unit='A'): '''Setting current of current source ''' dac_offset = self._ch_cal[channel]['DAC']['offset'] dac_gain = self._ch_cal[channel]['DAC']['gain'] if unit == 'raw': value = value elif unit == 'A': value = ...
python
def set_current(self, channel, value, unit='A'): '''Setting current of current source ''' dac_offset = self._ch_cal[channel]['DAC']['offset'] dac_gain = self._ch_cal[channel]['DAC']['gain'] if unit == 'raw': value = value elif unit == 'A': value = ...
['def', 'set_current', '(', 'self', ',', 'channel', ',', 'value', ',', 'unit', '=', "'A'", ')', ':', 'dac_offset', '=', 'self', '.', '_ch_cal', '[', 'channel', ']', '[', "'DAC'", ']', '[', "'offset'", ']', 'dac_gain', '=', 'self', '.', '_ch_cal', '[', 'channel', ']', '[', "'DAC'", ']', '[', "'gain'", ']', 'if', 'unit',...
Setting current of current source
['Setting', 'current', 'of', 'current', 'source']
train
https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/HL/GPAC.py#L858-L874
3,960
CamDavidsonPilon/lifelines
lifelines/generate_datasets.py
right_censor_lifetimes
def right_censor_lifetimes(lifetimes, max_, min_=0): """ Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right ...
python
def right_censor_lifetimes(lifetimes, max_, min_=0): """ Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right ...
['def', 'right_censor_lifetimes', '(', 'lifetimes', ',', 'max_', ',', 'min_', '=', '0', ')', ':', 'n', '=', 'lifetimes', '.', 'shape', '[', '0', ']', 'u', '=', 'min_', '+', '(', 'max_', '-', 'min_', ')', '*', 'random', '.', 'rand', '(', 'n', ')', 'observations', '=', 'np', '.', 'minimum', '(', 'u', ',', 'lifetimes', ')...
Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right censoring, and D_i (observed death or did not) I think...
['Right', 'censor', 'the', 'deaths', 'uniformly', 'lifetimes', ':', '(', 'n', ')', 'array', 'of', 'positive', 'random', 'variables', 'max_', ':', 'the', 'max', 'time', 'a', 'censorship', 'can', 'occur', 'min_', ':', 'the', 'min', 'time', 'a', 'censorship', 'can', 'occur']
train
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/generate_datasets.py#L130-L146
3,961
gccxml/pygccxml
pygccxml/declarations/type_traits.py
is_array
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
python
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
['def', 'is_array', '(', 'type_', ')', ':', 'nake_type', '=', 'remove_alias', '(', 'type_', ')', 'nake_type', '=', 'remove_reference', '(', 'nake_type', ')', 'nake_type', '=', 'remove_cv', '(', 'nake_type', ')', 'return', 'isinstance', '(', 'nake_type', ',', 'cpptypes', '.', 'array_t', ')']
returns True, if type represents C++ array type, False otherwise
['returns', 'True', 'if', 'type', 'represents', 'C', '++', 'array', 'type', 'False', 'otherwise']
train
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L280-L285
3,962
matrix-org/matrix-python-sdk
matrix_client/client.py
MatrixClient.stop_listener_thread
def stop_listener_thread(self): """ Stop listener thread running in the background """ if self.sync_thread: self.should_listen = False self.sync_thread.join() self.sync_thread = None
python
def stop_listener_thread(self): """ Stop listener thread running in the background """ if self.sync_thread: self.should_listen = False self.sync_thread.join() self.sync_thread = None
['def', 'stop_listener_thread', '(', 'self', ')', ':', 'if', 'self', '.', 'sync_thread', ':', 'self', '.', 'should_listen', '=', 'False', 'self', '.', 'sync_thread', '.', 'join', '(', ')', 'self', '.', 'sync_thread', '=', 'None']
Stop listener thread running in the background
['Stop', 'listener', 'thread', 'running', 'in', 'the', 'background']
train
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/client.py#L533-L539
3,963
ecell/ecell4
ecell4/util/viz.py
plot_world_with_plotly
def plot_world_with_plotly(world, species_list=None, max_count=1000): """ Plot a World on IPython Notebook """ if isinstance(world, str): from .simulation import load_world world = load_world(world) if species_list is None: species_list = [sp.serial() for sp in world.list_sp...
python
def plot_world_with_plotly(world, species_list=None, max_count=1000): """ Plot a World on IPython Notebook """ if isinstance(world, str): from .simulation import load_world world = load_world(world) if species_list is None: species_list = [sp.serial() for sp in world.list_sp...
['def', 'plot_world_with_plotly', '(', 'world', ',', 'species_list', '=', 'None', ',', 'max_count', '=', '1000', ')', ':', 'if', 'isinstance', '(', 'world', ',', 'str', ')', ':', 'from', '.', 'simulation', 'import', 'load_world', 'world', '=', 'load_world', '(', 'world', ')', 'if', 'species_list', 'is', 'None', ':', 's...
Plot a World on IPython Notebook
['Plot', 'a', 'World', 'on', 'IPython', 'Notebook']
train
https://github.com/ecell/ecell4/blob/a4a1229661c39b2059adbbacae9090e5ba664e01/ecell4/util/viz.py#L2136-L2182
3,964
saltstack/salt
salt/modules/boto_kms.py
get_key_policy
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profil...
python
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profil...
['def', 'get_key_policy', '(', 'key_id', ',', 'policy_name', ',', 'region', '=', 'None', ',', 'key', '=', 'None', ',', 'keyid', '=', 'None', ',', 'profile', '=', 'None', ')', ':', 'conn', '=', '_get_conn', '(', 'region', '=', 'region', ',', 'key', '=', 'key', ',', 'keyid', '=', 'keyid', ',', 'profile', '=', 'profile', ...
Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
['Get', 'the', 'policy', 'for', 'the', 'specified', 'key', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kms.py#L415-L435
3,965
liip/taxi
taxi/timesheet/parser.py
TimesheetParser.duration_to_text
def duration_to_text(self, duration): """ Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a num...
python
def duration_to_text(self, duration): """ Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a num...
['def', 'duration_to_text', '(', 'self', ',', 'duration', ')', ':', 'if', 'isinstance', '(', 'duration', ',', 'tuple', ')', ':', 'start', '=', '(', 'duration', '[', '0', ']', '.', 'strftime', '(', 'self', '.', 'ENTRY_DURATION_FORMAT', ')', 'if', 'duration', '[', '0', ']', 'is', 'not', 'None', 'else', "''", ')', 'end', ...
Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a number.
['Return', 'the', 'textual', 'representation', 'of', 'the', 'given', 'duration', '.', 'The', 'duration', 'can', 'either', 'be', 'a', 'tuple', 'of', ':', 'class', ':', 'datetime', '.', 'time', 'objects', 'or', 'a', 'simple', 'number', '.', 'The', 'returned', 'text', 'will', 'be', 'either', 'a', 'hhmm', '-', 'hhmm', 'str...
train
https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/parser.py#L101-L120
3,966
sporteasy/python-poeditor
poeditor/client.py
POEditorAPI._run
def _run(self, url_path, headers=None, **kwargs): """ Requests API """ url = self._construct_url(url_path) payload = kwargs payload.update({'api_token': self.api_token}) return self._make_request(url, payload, headers)
python
def _run(self, url_path, headers=None, **kwargs): """ Requests API """ url = self._construct_url(url_path) payload = kwargs payload.update({'api_token': self.api_token}) return self._make_request(url, payload, headers)
['def', '_run', '(', 'self', ',', 'url_path', ',', 'headers', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'url', '=', 'self', '.', '_construct_url', '(', 'url_path', ')', 'payload', '=', 'kwargs', 'payload', '.', 'update', '(', '{', "'api_token'", ':', 'self', '.', 'api_token', '}', ')', 'return', 'self', '.', '_ma...
Requests API
['Requests', 'API']
train
https://github.com/sporteasy/python-poeditor/blob/e9c0a8ab08816903122f730b73ffaab46601076c/poeditor/client.py#L129-L138
3,967
lightning-viz/lightning-python
lightning/main.py
Lightning.disable_ipython
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = F...
python
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = F...
['def', 'disable_ipython', '(', 'self', ')', ':', 'from', 'IPython', '.', 'core', '.', 'getipython', 'import', 'get_ipython', 'self', '.', 'ipython_enabled', '=', 'False', 'ip', '=', 'get_ipython', '(', ')', 'formatter', '=', 'ip', '.', 'display_formatter', '.', 'formatters', '[', "'text/html'", ']', 'formatter', '.', ...
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
['Disable', 'plotting', 'in', 'the', 'iPython', 'notebook', '.']
train
https://github.com/lightning-viz/lightning-python/blob/68563e1da82d162d204069d7586f7c695b8bd4a6/lightning/main.py#L85-L98
3,968
PolicyStat/jobtastic
jobtastic/task.py
JobtasticTask._get_cache
def _get_cache(self): """ Return the cache to use for thundering herd protection, etc. """ if not self._cache: self._cache = get_cache(self.app) return self._cache
python
def _get_cache(self): """ Return the cache to use for thundering herd protection, etc. """ if not self._cache: self._cache = get_cache(self.app) return self._cache
['def', '_get_cache', '(', 'self', ')', ':', 'if', 'not', 'self', '.', '_cache', ':', 'self', '.', '_cache', '=', 'get_cache', '(', 'self', '.', 'app', ')', 'return', 'self', '.', '_cache']
Return the cache to use for thundering herd protection, etc.
['Return', 'the', 'cache', 'to', 'use', 'for', 'thundering', 'herd', 'protection', 'etc', '.']
train
https://github.com/PolicyStat/jobtastic/blob/19cd3137ebf46877cee1ee5155d318bb6261ee1c/jobtastic/task.py#L405-L411
3,969
UDST/urbansim
urbansim/models/dcm.py
MNLDiscreteChoiceModelGroup.probabilities
def probabilities(self, choosers, alternatives): """ Returns alternative probabilties for each chooser segment as a dictionary keyed by segment name. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households...
python
def probabilities(self, choosers, alternatives): """ Returns alternative probabilties for each chooser segment as a dictionary keyed by segment name. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households...
['def', 'probabilities', '(', 'self', ',', 'choosers', ',', 'alternatives', ')', ':', 'logger', '.', 'debug', '(', "'start: calculate probabilities in LCM group {}'", '.', 'format', '(', 'self', '.', 'name', ')', ')', 'probs', '=', '{', '}', 'for', 'name', ',', 'df', 'in', 'self', '.', '_iter_groups', '(', 'choosers', ...
Returns alternative probabilties for each chooser segment as a dictionary keyed by segment name. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. Must have a column matching the .segmentation_col attri...
['Returns', 'alternative', 'probabilties', 'for', 'each', 'chooser', 'segment', 'as', 'a', 'dictionary', 'keyed', 'by', 'segment', 'name', '.']
train
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/dcm.py#L1089-L1117
3,970
ClericPy/torequests
torequests/crawlers.py
CleanRequest.reset_new_request
def reset_new_request(self): """Remove the non-sense args from the self.ignore, return self.new_request""" raw_url = self.new_request['url'] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) new_url = self._join_url( parsed_url, [i for i in qsl if i not...
python
def reset_new_request(self): """Remove the non-sense args from the self.ignore, return self.new_request""" raw_url = self.new_request['url'] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) new_url = self._join_url( parsed_url, [i for i in qsl if i not...
['def', 'reset_new_request', '(', 'self', ')', ':', 'raw_url', '=', 'self', '.', 'new_request', '[', "'url'", ']', 'parsed_url', '=', 'urlparse', '(', 'raw_url', ')', 'qsl', '=', 'parse_qsl', '(', 'parsed_url', '.', 'query', ')', 'new_url', '=', 'self', '.', '_join_url', '(', 'parsed_url', ',', '[', 'i', 'for', 'i', 'i...
Remove the non-sense args from the self.ignore, return self.new_request
['Remove', 'the', 'non', '-', 'sense', 'args', 'from', 'the', 'self', '.', 'ignore', 'return', 'self', '.', 'new_request']
train
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/crawlers.py#L282-L323
3,971
codelv/enaml-native
src/enamlnative/android/android_picker.py
AndroidPicker.create_widget
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Picker(self.get_context(), None, d.style or '@attr/numberPickerStyle')
python
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Picker(self.get_context(), None, d.style or '@attr/numberPickerStyle')
['def', 'create_widget', '(', 'self', ')', ':', 'd', '=', 'self', '.', 'declaration', 'self', '.', 'widget', '=', 'Picker', '(', 'self', '.', 'get_context', '(', ')', ',', 'None', ',', 'd', '.', 'style', 'or', "'@attr/numberPickerStyle'", ')']
Create the underlying widget.
['Create', 'the', 'underlying', 'widget', '.']
train
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_picker.py#L45-L51
3,972
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewpanel.py
XViewPanel.setLocked
def setLocked(self, state, force=False): """ Sets the locked state for this panel to the inputed state. :param state | <bool> """ if not force and state == self._locked: return self._locked = state tabbar = self.tabBar() ...
python
def setLocked(self, state, force=False): """ Sets the locked state for this panel to the inputed state. :param state | <bool> """ if not force and state == self._locked: return self._locked = state tabbar = self.tabBar() ...
['def', 'setLocked', '(', 'self', ',', 'state', ',', 'force', '=', 'False', ')', ':', 'if', 'not', 'force', 'and', 'state', '==', 'self', '.', '_locked', ':', 'return', 'self', '.', '_locked', '=', 'state', 'tabbar', '=', 'self', '.', 'tabBar', '(', ')', 'tabbar', '.', 'setLocked', '(', 'state', ')', 'if', 'self', '.',...
Sets the locked state for this panel to the inputed state. :param state | <bool>
['Sets', 'the', 'locked', 'state', 'for', 'this', 'panel', 'to', 'the', 'inputed', 'state', '.', ':', 'param', 'state', '|', '<bool', '>']
train
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanel.py#L1470-L1492
3,973
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
Credentials._to_dict
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'source_type') and self.source_type is not None: ...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'source_type') and self.source_type is not None: ...
['def', '_to_dict', '(', 'self', ')', ':', '_dict', '=', '{', '}', 'if', 'hasattr', '(', 'self', ',', "'credential_id'", ')', 'and', 'self', '.', 'credential_id', 'is', 'not', 'None', ':', '_dict', '[', "'credential_id'", ']', '=', 'self', '.', 'credential_id', 'if', 'hasattr', '(', 'self', ',', "'source_type'", ')', '...
Return a json dictionary representing this model.
['Return', 'a', 'json', 'dictionary', 'representing', 'this', 'model', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4549-L4560
3,974
mattbierner/blotre-py
blotre.py
Blotre._add_auth_headers
def _add_auth_headers(self, base): """Attach the acces_token to a request.""" if 'access_token' in self.creds: return _extend(base, { 'authorization': 'Bearer ' + self.creds['access_token'] }) return base
python
def _add_auth_headers(self, base): """Attach the acces_token to a request.""" if 'access_token' in self.creds: return _extend(base, { 'authorization': 'Bearer ' + self.creds['access_token'] }) return base
['def', '_add_auth_headers', '(', 'self', ',', 'base', ')', ':', 'if', "'access_token'", 'in', 'self', '.', 'creds', ':', 'return', '_extend', '(', 'base', ',', '{', "'authorization'", ':', "'Bearer '", '+', 'self', '.', 'creds', '[', "'access_token'", ']', '}', ')', 'return', 'base']
Attach the acces_token to a request.
['Attach', 'the', 'acces_token', 'to', 'a', 'request', '.']
train
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L200-L206
3,975
PMBio/limix-backup
limix/deprecated/archive/varianceDecompositionOld.py
VarianceDecomposition.estimateHeritabilities
def estimateHeritabilities(self, K, verbose=False): """ estimate variance components and fixed effects from a single trait model having only two terms """ # Fit single trait model varg = SP.zeros(self.P) varn = SP.zeros(self.P) fixed = SP.zeros(...
python
def estimateHeritabilities(self, K, verbose=False): """ estimate variance components and fixed effects from a single trait model having only two terms """ # Fit single trait model varg = SP.zeros(self.P) varn = SP.zeros(self.P) fixed = SP.zeros(...
['def', 'estimateHeritabilities', '(', 'self', ',', 'K', ',', 'verbose', '=', 'False', ')', ':', '# Fit single trait model', 'varg', '=', 'SP', '.', 'zeros', '(', 'self', '.', 'P', ')', 'varn', '=', 'SP', '.', 'zeros', '(', 'self', '.', 'P', ')', 'fixed', '=', 'SP', '.', 'zeros', '(', '(', '1', ',', 'self', '.', 'P', '...
estimate variance components and fixed effects from a single trait model having only two terms
['estimate', 'variance', 'components', 'and', 'fixed', 'effects', 'from', 'a', 'single', 'trait', 'model', 'having', 'only', 'two', 'terms']
train
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L768-L802
3,976
kbr/fritzconnection
fritzconnection/fritzconnection.py
FritzConnection.get_action_arguments
def get_action_arguments(self, service_name, action_name): """ Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type. """ return self.services[service_name].actio...
python
def get_action_arguments(self, service_name, action_name): """ Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type. """ return self.services[service_name].actio...
['def', 'get_action_arguments', '(', 'self', ',', 'service_name', ',', 'action_name', ')', ':', 'return', 'self', '.', 'services', '[', 'service_name', ']', '.', 'actions', '[', 'action_name', ']', '.', 'info']
Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type.
['Returns', 'a', 'list', 'of', 'tuples', 'with', 'all', 'known', 'arguments', 'for', 'the', 'given', 'service', '-', 'and', 'action', '-', 'name', 'combination', '.', 'The', 'tuples', 'contain', 'the', 'argument', '-', 'name', 'direction', 'and', 'data_type', '.']
train
https://github.com/kbr/fritzconnection/blob/b183f759ef19dd1652371e912d36cfe34f6639ac/fritzconnection/fritzconnection.py#L351-L357
3,977
jbarlow83/OCRmyPDF
src/ocrmypdf/pdfinfo/__init__.py
_normalize_stack
def _normalize_stack(graphobjs): """Convert runs of qQ's in the stack into single graphobjs""" for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q for char in operator: # Split into individual ...
python
def _normalize_stack(graphobjs): """Convert runs of qQ's in the stack into single graphobjs""" for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q for char in operator: # Split into individual ...
['def', '_normalize_stack', '(', 'graphobjs', ')', ':', 'for', 'operands', ',', 'operator', 'in', 'graphobjs', ':', 'operator', '=', 'str', '(', 'operator', ')', 'if', 're', '.', 'match', '(', "r'Q*q+$'", ',', 'operator', ')', ':', '# Zero or more Q, one or more q', 'for', 'char', 'in', 'operator', ':', '# Split into i...
Convert runs of qQ's in the stack into single graphobjs
['Convert', 'runs', 'of', 'qQ', 's', 'in', 'the', 'stack', 'into', 'single', 'graphobjs']
train
https://github.com/jbarlow83/OCRmyPDF/blob/79c84eefa353632a3d7ccddbd398c6678c1c1777/src/ocrmypdf/pdfinfo/__init__.py#L109-L117
3,978
pkgw/pwkit
pwkit/ellipses.py
sigmascale
def sigmascale (nsigma): """Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in Na...
python
def sigmascale (nsigma): """Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in Na...
['def', 'sigmascale', '(', 'nsigma', ')', ':', 'from', 'scipy', '.', 'special', 'import', 'erfc', 'return', 'np', '.', 'sqrt', '(', '-', '2', '*', 'np', '.', 'log', '(', 'erfc', '(', 'nsigma', '/', 'np', '.', 'sqrt', '(', '2', ')', ')', ')', ')']
Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in NaN.
['Say', 'we', 'take', 'a', 'Gaussian', 'bivariate', 'and', 'convert', 'the', 'parameters', 'of', 'the', 'distribution', 'to', 'an', 'ellipse', '(', 'major', 'minor', 'PA', ')', '.', 'By', 'what', 'factor', 'should', 'we', 'scale', 'those', 'axes', 'to', 'make', 'the', 'area', 'of', 'the', 'ellipse', 'correspond', 'to',...
train
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/ellipses.py#L44-L54
3,979
pandas-dev/pandas
pandas/core/strings.py
str_replace
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a charact...
python
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a charact...
['def', 'str_replace', '(', 'arr', ',', 'pat', ',', 'repl', ',', 'n', '=', '-', '1', ',', 'case', '=', 'None', ',', 'flags', '=', '0', ',', 'regex', '=', 'True', ')', ':', '# Check whether repl is valid (GH 13438, GH 15055)', 'if', 'not', '(', 'is_string_like', '(', 'repl', ')', 'or', 'callable', '(', 'repl', ')', ')',...
r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a character sequence or regular expression. .. versionadded:: 0.20.0 ...
['r', 'Replace', 'occurrences', 'of', 'pattern', '/', 'regex', 'in', 'the', 'Series', '/', 'Index', 'with', 'some', 'other', 'string', '.', 'Equivalent', 'to', ':', 'meth', ':', 'str', '.', 'replace', 'or', ':', 'func', ':', 're', '.', 'sub', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/strings.py#L423-L578
3,980
log2timeline/plaso
plaso/engine/profilers.py
SampleFileProfiler.Start
def Start(self): """Starts the profiler.""" filename = '{0:s}-{1:s}.csv.gz'.format( self._FILENAME_PREFIX, self._identifier) if self._path: filename = os.path.join(self._path, filename) self._sample_file = gzip.open(filename, 'wb') self._WritesString(self._FILE_HEADER) self._star...
python
def Start(self): """Starts the profiler.""" filename = '{0:s}-{1:s}.csv.gz'.format( self._FILENAME_PREFIX, self._identifier) if self._path: filename = os.path.join(self._path, filename) self._sample_file = gzip.open(filename, 'wb') self._WritesString(self._FILE_HEADER) self._star...
['def', 'Start', '(', 'self', ')', ':', 'filename', '=', "'{0:s}-{1:s}.csv.gz'", '.', 'format', '(', 'self', '.', '_FILENAME_PREFIX', ',', 'self', '.', '_identifier', ')', 'if', 'self', '.', '_path', ':', 'filename', '=', 'os', '.', 'path', '.', 'join', '(', 'self', '.', '_path', ',', 'filename', ')', 'self', '.', '_sa...
Starts the profiler.
['Starts', 'the', 'profiler', '.']
train
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/profilers.py#L89-L99
3,981
pyhys/minimalmodbus
dummy_serial.py
Serial.write
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Pytho...
python
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Pytho...
['def', 'write', '(', 'self', ',', 'inputdata', ')', ':', 'if', 'VERBOSE', ':', '_print_out', '(', "'\\nDummy_serial: Writing to port. Given:'", '+', 'repr', '(', 'inputdata', ')', '+', "'\\n'", ')', 'if', 'sys', '.', 'version_info', '[', '0', ']', '>', '2', ':', 'if', 'not', 'type', '(', 'inputdata', ')', '==', 'bytes...
Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
['Write', 'to', 'a', 'port', 'on', 'dummy_serial', '.']
train
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/dummy_serial.py#L141-L169
3,982
wonambi-python/wonambi
wonambi/trans/analyze.py
export_event_params
def export_event_params(filename, params, count=None, density=None): """Write event analysis data to CSV.""" heading_row_1 = ['Segment index', 'Start time', 'End time', 'Stitches', 'Stage', 'Cycle', ...
python
def export_event_params(filename, params, count=None, density=None): """Write event analysis data to CSV.""" heading_row_1 = ['Segment index', 'Start time', 'End time', 'Stitches', 'Stage', 'Cycle', ...
['def', 'export_event_params', '(', 'filename', ',', 'params', ',', 'count', '=', 'None', ',', 'density', '=', 'None', ')', ':', 'heading_row_1', '=', '[', "'Segment index'", ',', "'Start time'", ',', "'End time'", ',', "'Stitches'", ',', "'Stage'", ',', "'Cycle'", ',', "'Event type'", ',', "'Channel'", ']', 'spacer', ...
Write event analysis data to CSV.
['Write', 'event', 'analysis', 'data', 'to', 'CSV', '.']
train
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/analyze.py#L169-L292
3,983
happyleavesaoc/python-voobly
voobly/__init__.py
_make_request
def _make_request(session, url, argument=None, params=None, raw=False): """Make a request to API endpoint.""" if not params: params = {} params['key'] = session.auth.key try: if argument: request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument) ...
python
def _make_request(session, url, argument=None, params=None, raw=False): """Make a request to API endpoint.""" if not params: params = {} params['key'] = session.auth.key try: if argument: request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument) ...
['def', '_make_request', '(', 'session', ',', 'url', ',', 'argument', '=', 'None', ',', 'params', '=', 'None', ',', 'raw', '=', 'False', ')', ':', 'if', 'not', 'params', ':', 'params', '=', '{', '}', 'params', '[', "'key'", ']', '=', 'session', '.', 'auth', '.', 'key', 'try', ':', 'if', 'argument', ':', 'request_url', ...
Make a request to API endpoint.
['Make', 'a', 'request', 'to', 'API', 'endpoint', '.']
train
https://github.com/happyleavesaoc/python-voobly/blob/83b4ab7d630a00459c2a64e55e3ac85c7be38194/voobly/__init__.py#L112-L136
3,984
readbeyond/aeneas
aeneas/plotter.py
PlotTimeScale.draw_png
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type i...
python
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type i...
['def', 'draw_png', '(', 'self', ',', 'image', ',', 'h_zoom', ',', 'v_zoom', ',', 'current_y', ')', ':', '# PIL object', 'draw', '=', 'ImageDraw', '.', 'Draw', '(', 'image', ')', 'mws', '=', 'self', '.', 'rconf', '.', 'mws', 'pixels_per_second', '=', 'int', '(', 'h_zoom', '/', 'mws', ')', 'current_y_px', '=', 'current_...
Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image`
['Draw', 'this', 'time', 'scale', 'to', 'PNG', '.']
train
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L305-L341
3,985
django-cumulus/django-cumulus
cumulus/management/commands/syncfiles.py
Command.set_options
def set_options(self, options): """ Sets instance variables based on an options dict """ # COMMAND LINE OPTIONS self.wipe = options.get("wipe") self.test_run = options.get("test_run") self.quiet = options.get("test_run") self.container_name = options.get("...
python
def set_options(self, options): """ Sets instance variables based on an options dict """ # COMMAND LINE OPTIONS self.wipe = options.get("wipe") self.test_run = options.get("test_run") self.quiet = options.get("test_run") self.container_name = options.get("...
['def', 'set_options', '(', 'self', ',', 'options', ')', ':', '# COMMAND LINE OPTIONS', 'self', '.', 'wipe', '=', 'options', '.', 'get', '(', '"wipe"', ')', 'self', '.', 'test_run', '=', 'options', '.', 'get', '(', '"test_run"', ')', 'self', '.', 'quiet', '=', 'options', '.', 'get', '(', '"test_run"', ')', 'self', '.',...
Sets instance variables based on an options dict
['Sets', 'instance', 'variables', 'based', 'on', 'an', 'options', 'dict']
train
https://github.com/django-cumulus/django-cumulus/blob/64feb07b857af28f226be4899e875c29405e261d/cumulus/management/commands/syncfiles.py#L45-L97
3,986
tanghaibao/jcvi
jcvi/assembly/hic.py
density
def density(args): """ %prog density test.clm Estimate link density of contigs. """ p = OptionParser(density.__doc__) p.add_option("--save", default=False, action="store_true", help="Write log densitites of contigs to file") p.set_cpus() opts, args = p.parse_args(args) ...
python
def density(args): """ %prog density test.clm Estimate link density of contigs. """ p = OptionParser(density.__doc__) p.add_option("--save", default=False, action="store_true", help="Write log densitites of contigs to file") p.set_cpus() opts, args = p.parse_args(args) ...
['def', 'density', '(', 'args', ')', ':', 'p', '=', 'OptionParser', '(', 'density', '.', '__doc__', ')', 'p', '.', 'add_option', '(', '"--save"', ',', 'default', '=', 'False', ',', 'action', '=', '"store_true"', ',', 'help', '=', '"Write log densitites of contigs to file"', ')', 'p', '.', 'set_cpus', '(', ')', 'opts', ...
%prog density test.clm Estimate link density of contigs.
['%prog', 'density', 'test', '.', 'clm']
train
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L952-L985
3,987
watson-developer-cloud/python-sdk
ibm_watson/assistant_v1.py
Context._from_dict
def _from_dict(cls, _dict): """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() if 'conversation_id' in _dict: args['conversation_id'] = _dict.get('conversation_id') del xtra['conversation_id'] if 'system' in _dict: ...
python
def _from_dict(cls, _dict): """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() if 'conversation_id' in _dict: args['conversation_id'] = _dict.get('conversation_id') del xtra['conversation_id'] if 'system' in _dict: ...
['def', '_from_dict', '(', 'cls', ',', '_dict', ')', ':', 'args', '=', '{', '}', 'xtra', '=', '_dict', '.', 'copy', '(', ')', 'if', "'conversation_id'", 'in', '_dict', ':', 'args', '[', "'conversation_id'", ']', '=', '_dict', '.', 'get', '(', "'conversation_id'", ')', 'del', 'xtra', '[', "'conversation_id'", ']', 'if',...
Initialize a Context object from a json dictionary.
['Initialize', 'a', 'Context', 'object', 'from', 'a', 'json', 'dictionary', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L2944-L2959
3,988
Microsoft/knack
knack/arguments.py
ArgumentRegistry.register_cli_argument
def register_cli_argument(self, scope, dest, argtype, **kwargs): """ Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for ...
python
def register_cli_argument(self, scope, dest, argtype, **kwargs): """ Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for ...
['def', 'register_cli_argument', '(', 'self', ',', 'scope', ',', 'dest', ',', 'argtype', ',', '*', '*', 'kwargs', ')', ':', 'argument', '=', 'CLIArgumentType', '(', 'overrides', '=', 'argtype', ',', '*', '*', 'kwargs', ')', 'self', '.', 'arguments', '[', 'scope', ']', '[', 'dest', ']', '=', 'argument']
Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for :type dest: str :param argtype: The argument type for this com...
['Add', 'an', 'argument', 'to', 'the', 'argument', 'registry']
train
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L93-L105
3,989
tgalal/yowsup
yowsup/axolotl/manager.py
AxolotlManager.set_prekeys_as_sent
def set_prekeys_as_sent(self, prekeyIds): """ :param prekeyIds: :type prekeyIds: list :return: :rtype: """ logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds)) self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekey...
python
def set_prekeys_as_sent(self, prekeyIds): """ :param prekeyIds: :type prekeyIds: list :return: :rtype: """ logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds)) self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekey...
['def', 'set_prekeys_as_sent', '(', 'self', ',', 'prekeyIds', ')', ':', 'logger', '.', 'debug', '(', '"set_prekeys_as_sent(prekeyIds=[%d prekeyIds])"', '%', 'len', '(', 'prekeyIds', ')', ')', 'self', '.', '_store', '.', 'preKeyStore', '.', 'setAsSent', '(', '[', 'prekey', '.', 'getId', '(', ')', 'for', 'prekey', 'in', ...
:param prekeyIds: :type prekeyIds: list :return: :rtype:
[':', 'param', 'prekeyIds', ':', ':', 'type', 'prekeyIds', ':', 'list', ':', 'return', ':', ':', 'rtype', ':']
train
https://github.com/tgalal/yowsup/blob/b0739461ba962bf221fc76047d9d60d8ce61bc3e/yowsup/axolotl/manager.py#L86-L94
3,990
pandas-dev/pandas
pandas/core/arrays/timedeltas.py
TimedeltaArray._add_datetime_arraylike
def _add_datetime_arraylike(self, other): """ Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 from pandas.core.arrays import DatetimeArray ...
python
def _add_datetime_arraylike(self, other): """ Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 from pandas.core.arrays import DatetimeArray ...
['def', '_add_datetime_arraylike', '(', 'self', ',', 'other', ')', ':', 'if', 'isinstance', '(', 'other', ',', 'np', '.', 'ndarray', ')', ':', '# At this point we have already checked that dtype is datetime64', 'from', 'pandas', '.', 'core', '.', 'arrays', 'import', 'DatetimeArray', 'other', '=', 'DatetimeArray', '(', ...
Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.
['Add', 'DatetimeArray', '/', 'Index', 'or', 'ndarray', '[', 'datetime64', ']', 'to', 'TimedeltaArray', '.']
train
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/timedeltas.py#L392-L402
3,991
phaethon/kamene
kamene/packet.py
Packet.command
def command(self): """Returns a string representing the command you have to type to obtain the same packet""" f = [] for fn,fv in self.fields.items(): fld = self.get_field(fn) if isinstance(fv, Packet): fv = fv.command() elif fld.islist and fld...
python
def command(self): """Returns a string representing the command you have to type to obtain the same packet""" f = [] for fn,fv in self.fields.items(): fld = self.get_field(fn) if isinstance(fv, Packet): fv = fv.command() elif fld.islist and fld...
['def', 'command', '(', 'self', ')', ':', 'f', '=', '[', ']', 'for', 'fn', ',', 'fv', 'in', 'self', '.', 'fields', '.', 'items', '(', ')', ':', 'fld', '=', 'self', '.', 'get_field', '(', 'fn', ')', 'if', 'isinstance', '(', 'fv', ',', 'Packet', ')', ':', 'fv', '=', 'fv', '.', 'command', '(', ')', 'elif', 'fld', '.', 'is...
Returns a string representing the command you have to type to obtain the same packet
['Returns', 'a', 'string', 'representing', 'the', 'command', 'you', 'have', 'to', 'type', 'to', 'obtain', 'the', 'same', 'packet']
train
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L1049-L1066
3,992
numenta/htmresearch
htmresearch/frameworks/layers/sequence_object_machine.py
SequenceObjectMachine._generateFeatures
def _generateFeatures(self): """ Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column. """ size = self.sensorInputSize bits = self.numInputBits self.features = []...
python
def _generateFeatures(self): """ Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column. """ size = self.sensorInputSize bits = self.numInputBits self.features = []...
['def', '_generateFeatures', '(', 'self', ')', ':', 'size', '=', 'self', '.', 'sensorInputSize', 'bits', '=', 'self', '.', 'numInputBits', 'self', '.', 'features', '=', '[', ']', 'for', '_', 'in', 'xrange', '(', 'self', '.', 'numColumns', ')', ':', 'self', '.', 'features', '.', 'append', '(', '[', 'self', '.', '_genera...
Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column.
['Generates', 'a', 'pool', 'of', 'features', 'to', 'be', 'used', 'for', 'the', 'experiments', '.']
train
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/sequence_object_machine.py#L268-L282
3,993
jtwhite79/pyemu
pyemu/mat/mat_handler.py
get_maxsing
def get_maxsing(self,eigthresh=1.0e-5): """ Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns -----...
python
def get_maxsing(self,eigthresh=1.0e-5): """ Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns -----...
['def', 'get_maxsing', '(', 'self', ',', 'eigthresh', '=', '1.0e-5', ')', ':', '#sthresh =np.abs((self.s.x / self.s.x[0]) - eigthresh)', 'sthresh', '=', 'self', '.', 's', '.', 'x', '.', 'flatten', '(', ')', '/', 'self', '.', 's', '.', 'x', '[', '0', ']', 'ising', '=', '0', 'for', 'i', ',', 'st', 'in', 'enumerate', '(',...
Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns ------- int : int number of singular ...
['Get', 'the', 'number', 'of', 'singular', 'components', 'with', 'a', 'singular', 'value', 'ratio', 'greater', 'than', 'or', 'equal', 'to', 'eigthresh']
train
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/mat/mat_handler.py#L973-L998
3,994
creare-com/pydem
pydem/dem_processing.py
TileEdge.get
def get(self, key, side): """ Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return """ return getattr(self...
python
def get(self, key, side): """ Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return """ return getattr(self...
['def', 'get', '(', 'self', ',', 'key', ',', 'side', ')', ':', 'return', 'getattr', '(', 'self', ',', 'side', ')', '.', 'ravel', '(', ')', '[', 'self', '.', 'keys', '[', 'key', ']', ']']
Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return
['Returns', 'an', 'edge', 'given', 'a', 'particular', 'key', 'Parmeters', '----------', 'key', ':', 'tuple', '(', 'te', 'be', 'le', 're', ')', 'tuple', 'that', 'identifies', 'a', 'tile', 'side', ':', 'str', 'top', 'bottom', 'left', 'or', 'right', 'which', 'edge', 'to', 'return']
train
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L234-L244
3,995
cbrand/vpnchooser
src/vpnchooser/resources/vpn.py
VpnListResource.post
def post(self) -> Vpn: """ Creates the vpn with the given data. """ vpn = Vpn() session.add(vpn) self.update(vpn) session.flush() session.commit() return vpn, 201, { 'Location': url_for('vpn', vpn_id=vpn.id) }
python
def post(self) -> Vpn: """ Creates the vpn with the given data. """ vpn = Vpn() session.add(vpn) self.update(vpn) session.flush() session.commit() return vpn, 201, { 'Location': url_for('vpn', vpn_id=vpn.id) }
['def', 'post', '(', 'self', ')', '->', 'Vpn', ':', 'vpn', '=', 'Vpn', '(', ')', 'session', '.', 'add', '(', 'vpn', ')', 'self', '.', 'update', '(', 'vpn', ')', 'session', '.', 'flush', '(', ')', 'session', '.', 'commit', '(', ')', 'return', 'vpn', ',', '201', ',', '{', "'Location'", ':', 'url_for', '(', "'vpn'", ',', ...
Creates the vpn with the given data.
['Creates', 'the', 'vpn', 'with', 'the', 'given', 'data', '.']
train
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/resources/vpn.py#L121-L132
3,996
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py
brocade_notification_stream.RIBVRFRouteLimitExceeded_originator_switch_info_switchVcsId
def RIBVRFRouteLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") origin...
python
def RIBVRFRouteLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") origin...
['def', 'RIBVRFRouteLimitExceeded_originator_switch_info_switchVcsId', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'RIBVRFRouteLimitExceeded', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"RIBVRFRouteLimitExceeded"', ',', 'xmlns', '=', '"http://brocad...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py#L492-L502
3,997
astropy/photutils
photutils/aperture/ellipse.py
EllipticalMaskMixin.to_mask
def to_mask(self, method='exact', subpixels=5): """ Return a list of `~photutils.ApertureMask` objects, one for each aperture position. Parameters ---------- method : {'exact', 'center', 'subpixel'}, optional The method used to determine the overlap of the ap...
python
def to_mask(self, method='exact', subpixels=5): """ Return a list of `~photutils.ApertureMask` objects, one for each aperture position. Parameters ---------- method : {'exact', 'center', 'subpixel'}, optional The method used to determine the overlap of the ap...
['def', 'to_mask', '(', 'self', ',', 'method', '=', "'exact'", ',', 'subpixels', '=', '5', ')', ':', 'use_exact', ',', 'subpixels', '=', 'self', '.', '_translate_mask_mode', '(', 'method', ',', 'subpixels', ')', 'if', 'hasattr', '(', 'self', ',', "'a'", ')', ':', 'a', '=', 'self', '.', 'a', 'b', '=', 'self', '.', 'b', ...
Return a list of `~photutils.ApertureMask` objects, one for each aperture position. Parameters ---------- method : {'exact', 'center', 'subpixel'}, optional The method used to determine the overlap of the aperture on the pixel grid. Not all options are available...
['Return', 'a', 'list', 'of', '~photutils', '.', 'ApertureMask', 'objects', 'one', 'for', 'each', 'aperture', 'position', '.']
train
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/aperture/ellipse.py#L26-L98
3,998
ninuxorg/nodeshot
nodeshot/community/participation/models/base.py
UpdateCountsMixin.delete
def delete(self, *args, **kwargs): """ custom delete method to update counts """ super(UpdateCountsMixin, self).delete(*args, **kwargs) self.update_count()
python
def delete(self, *args, **kwargs): """ custom delete method to update counts """ super(UpdateCountsMixin, self).delete(*args, **kwargs) self.update_count()
['def', 'delete', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'super', '(', 'UpdateCountsMixin', ',', 'self', ')', '.', 'delete', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', 'self', '.', 'update_count', '(', ')']
custom delete method to update counts
['custom', 'delete', 'method', 'to', 'update', 'counts']
train
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/participation/models/base.py#L29-L32
3,999
seleniumbase/SeleniumBase
seleniumbase/fixtures/email_manager.py
EmailManager.replace_entities
def replace_entities(self, html): """ Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced """ def fixup(text): """replace the htmlentities in some text""" ...
python
def replace_entities(self, html): """ Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced """ def fixup(text): """replace the htmlentities in some text""" ...
['def', 'replace_entities', '(', 'self', ',', 'html', ')', ':', 'def', 'fixup', '(', 'text', ')', ':', '"""replace the htmlentities in some text"""', 'text', '=', 'text', '.', 'group', '(', '0', ')', 'if', 'text', '[', ':', '2', ']', '==', '"&#"', ':', '# character reference', 'try', ':', 'if', 'text', '[', ':', '3', '...
Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced
['Replace', 'htmlentities', 'with', 'unicode', 'characters']
train
https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/email_manager.py#L454-L481