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
7,700
Galarzaa90/tibia.py
tibiapy/world.py
World._parse_world_info
def _parse_world_info(self, world_info_table): """ Parses the World Information table from Tibia.com and adds the found values to the object. Parameters ---------- world_info_table: :class:`list`[:class:`bs4.Tag`] """ world_info = {} for row in world_info...
python
def _parse_world_info(self, world_info_table): """ Parses the World Information table from Tibia.com and adds the found values to the object. Parameters ---------- world_info_table: :class:`list`[:class:`bs4.Tag`] """ world_info = {} for row in world_info...
['def', '_parse_world_info', '(', 'self', ',', 'world_info_table', ')', ':', 'world_info', '=', '{', '}', 'for', 'row', 'in', 'world_info_table', ':', 'cols_raw', '=', 'row', '.', 'find_all', '(', "'td'", ')', 'cols', '=', '[', 'ele', '.', 'text', '.', 'strip', '(', ')', 'for', 'ele', 'in', 'cols_raw', ']', 'field', ',...
Parses the World Information table from Tibia.com and adds the found values to the object. Parameters ---------- world_info_table: :class:`list`[:class:`bs4.Tag`]
['Parses', 'the', 'World', 'Information', 'table', 'from', 'Tibia', '.', 'com', 'and', 'adds', 'the', 'found', 'values', 'to', 'the', 'object', '.']
train
https://github.com/Galarzaa90/tibia.py/blob/02ba1a8f1e18177ef5c7dcd44affc8d761d59e12/tibiapy/world.py#L306-L352
7,701
PMEAL/OpenPNM
openpnm/materials/VoronoiFibers.py
DelaunayGeometry._rotate_and_chop
def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]): r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating con...
python
def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]): r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating con...
['def', '_rotate_and_chop', '(', 'self', ',', 'verts', ',', 'normal', ',', 'axis', '=', '[', '0', ',', '0', ',', '1', ']', ')', ':', 'xaxis', '=', '[', '1', ',', '0', ',', '0', ']', 'yaxis', '=', '[', '0', ',', '1', ',', '0', ']', 'zaxis', '=', '[', '0', ',', '0', ',', '1', ']', 'angle', '=', 'tr', '.', 'angle_between_...
r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating convex hull in order to arrange them in hull order for calcula...
['r', 'Method', 'to', 'rotate', 'a', 'set', 'of', 'vertices', '(', 'or', 'coords', ')', 'to', 'align', 'with', 'an', 'axis', 'points', 'must', 'be', 'coplanar', 'and', 'normal', 'must', 'be', 'given', 'Chops', 'axis', 'coord', 'to', 'give', 'vertices', 'back', 'in', '2D', 'Used', 'to', 'prepare', 'verts', 'for', 'print...
train
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/materials/VoronoiFibers.py#L955-L995
7,702
hbldh/pybankid
bankid/certutils.py
split_certificate
def split_certificate(certificate_path, destination_folder, password=None): """Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This method splits a potentially password-protected `PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate (format ``.p12`` or ``.pfx``) into on...
python
def split_certificate(certificate_path, destination_folder, password=None): """Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This method splits a potentially password-protected `PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate (format ``.p12`` or ``.pfx``) into on...
['def', 'split_certificate', '(', 'certificate_path', ',', 'destination_folder', ',', 'password', '=', 'None', ')', ':', 'try', ':', '# Attempt Linux and Darwin call first.', 'p', '=', 'subprocess', '.', 'Popen', '(', '[', '"openssl"', ',', '"version"', ']', ',', 'stdout', '=', 'subprocess', '.', 'PIPE', ',', 'stderr',...
Splits a PKCS12 certificate into Base64-encoded DER certificate and key. This method splits a potentially password-protected `PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate (format ``.p12`` or ``.pfx``) into one certificate and one key part, both in `pem <https://en.wikipedia.org/wiki/X.5...
['Splits', 'a', 'PKCS12', 'certificate', 'into', 'Base64', '-', 'encoded', 'DER', 'certificate', 'and', 'key', '.']
train
https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/certutils.py#L62-L152
7,703
Shapeways/coyote_framework
coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py
WebElementWrapper.click
def click(self, force_click=False): """ Clicks the element @type force_click: bool @param force_click: force a click on the element using javascript, skipping webdriver @rtype: WebElementWrapper @return: Returns itself """ js_exec...
python
def click(self, force_click=False): """ Clicks the element @type force_click: bool @param force_click: force a click on the element using javascript, skipping webdriver @rtype: WebElementWrapper @return: Returns itself """ js_exec...
['def', 'click', '(', 'self', ',', 'force_click', '=', 'False', ')', ':', 'js_executor', '=', 'self', '.', 'driver_wrapper', '.', 'js_executor', 'def', 'click_element', '(', ')', ':', '"""\n Wrapper to call click\n """', 'return', 'self', '.', 'element', '.', 'click', '(', ')', 'def', 'force_click...
Clicks the element @type force_click: bool @param force_click: force a click on the element using javascript, skipping webdriver @rtype: WebElementWrapper @return: Returns itself
['Clicks', 'the', 'element']
train
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/webdriver/webdriverwrapper/WebElementWrapper.py#L127-L157
7,704
YosaiProject/yosai
yosai/core/serialize/marshalling.py
default_unmarshaller
def default_unmarshaller(instance, state): """ Restore the state of an object. If the ``__setstate__()`` method exists on the instance, it is called with the state object as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``. :param instance: an uninitialized instance ...
python
def default_unmarshaller(instance, state): """ Restore the state of an object. If the ``__setstate__()`` method exists on the instance, it is called with the state object as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``. :param instance: an uninitialized instance ...
['def', 'default_unmarshaller', '(', 'instance', ',', 'state', ')', ':', 'if', 'hasattr', '(', 'instance', ',', "'__setstate__'", ')', ':', 'instance', '.', '__setstate__', '(', 'state', ')', 'else', ':', 'try', ':', 'instance', '.', '__dict__', '.', 'update', '(', 'state', ')', 'except', 'AttributeError', ':', 'raise'...
Restore the state of an object. If the ``__setstate__()`` method exists on the instance, it is called with the state object as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``. :param instance: an uninitialized instance :param state: the state object, as returned by :fun...
['Restore', 'the', 'state', 'of', 'an', 'object', '.']
train
https://github.com/YosaiProject/yosai/blob/7f96aa6b837ceae9bf3d7387cd7e35f5ab032575/yosai/core/serialize/marshalling.py#L26-L44
7,705
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py
GroupSizer
def GroupSizer(field_number, is_repeated, is_packed): """Returns a sizer for a group field.""" tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() ...
python
def GroupSizer(field_number, is_repeated, is_packed): """Returns a sizer for a group field.""" tag_size = _TagSize(field_number) * 2 assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: result += element.ByteSize() ...
['def', 'GroupSizer', '(', 'field_number', ',', 'is_repeated', ',', 'is_packed', ')', ':', 'tag_size', '=', '_TagSize', '(', 'field_number', ')', '*', '2', 'assert', 'not', 'is_packed', 'if', 'is_repeated', ':', 'def', 'RepeatedFieldSize', '(', 'value', ')', ':', 'result', '=', 'tag_size', '*', 'len', '(', 'value', ')'...
Returns a sizer for a group field.
['Returns', 'a', 'sizer', 'for', 'a', 'group', 'field', '.']
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L274-L289
7,706
ternaris/marv
marv/cli.py
marvcli_undiscard
def marvcli_undiscard(datasets): """Undiscard DATASETS previously discarded.""" create_app() setids = parse_setids(datasets, discarded=True) dataset = Dataset.__table__ stmt = dataset.update()\ .where(dataset.c.setid.in_(setids))\ .values(discarded=False) db....
python
def marvcli_undiscard(datasets): """Undiscard DATASETS previously discarded.""" create_app() setids = parse_setids(datasets, discarded=True) dataset = Dataset.__table__ stmt = dataset.update()\ .where(dataset.c.setid.in_(setids))\ .values(discarded=False) db....
['def', 'marvcli_undiscard', '(', 'datasets', ')', ':', 'create_app', '(', ')', 'setids', '=', 'parse_setids', '(', 'datasets', ',', 'discarded', '=', 'True', ')', 'dataset', '=', 'Dataset', '.', '__table__', 'stmt', '=', 'dataset', '.', 'update', '(', ')', '.', 'where', '(', 'dataset', '.', 'c', '.', 'setid', '.', 'in...
Undiscard DATASETS previously discarded.
['Undiscard', 'DATASETS', 'previously', 'discarded', '.']
train
https://github.com/ternaris/marv/blob/c221354d912ff869bbdb4f714a86a70be30d823e/marv/cli.py#L234-L244
7,707
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
gap_to_sorl
def gap_to_sorl(time_gap): """ P1D to +1DAY :param time_gap: :return: solr's format duration. """ quantity, unit = parse_ISO8601(time_gap) if unit[0] == "WEEKS": return "+{0}DAYS".format(quantity * 7) else: return "+{0}{1}".format(quantity, unit[0])
python
def gap_to_sorl(time_gap): """ P1D to +1DAY :param time_gap: :return: solr's format duration. """ quantity, unit = parse_ISO8601(time_gap) if unit[0] == "WEEKS": return "+{0}DAYS".format(quantity * 7) else: return "+{0}{1}".format(quantity, unit[0])
['def', 'gap_to_sorl', '(', 'time_gap', ')', ':', 'quantity', ',', 'unit', '=', 'parse_ISO8601', '(', 'time_gap', ')', 'if', 'unit', '[', '0', ']', '==', '"WEEKS"', ':', 'return', '"+{0}DAYS"', '.', 'format', '(', 'quantity', '*', '7', ')', 'else', ':', 'return', '"+{0}{1}"', '.', 'format', '(', 'quantity', ',', 'unit'...
P1D to +1DAY :param time_gap: :return: solr's format duration.
['P1D', 'to', '+', '1DAY', ':', 'param', 'time_gap', ':', ':', 'return', ':', 'solr', 's', 'format', 'duration', '.']
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L185-L195
7,708
DataONEorg/d1_python
lib_common/src/d1_common/type_conversions.py
str_to_etree
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the ...
python
def str_to_etree(xml_str, encoding='utf-8'): """Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the ...
['def', 'str_to_etree', '(', 'xml_str', ',', 'encoding', '=', "'utf-8'", ')', ':', 'parser', '=', 'xml', '.', 'etree', '.', 'ElementTree', '.', 'XMLParser', '(', 'encoding', '=', 'encoding', ')', 'return', 'xml', '.', 'etree', '.', 'ElementTree', '.', 'fromstring', '(', 'xml_str', ',', 'parser', '=', 'parser', ')']
Deserialize API XML doc to an ElementTree. Args: xml_str: bytes DataONE API XML doc encoding: str Decoder to use when converting the XML doc ``bytes`` to a Unicode str. Returns: ElementTree: Matching the API version of the XML doc.
['Deserialize', 'API', 'XML', 'doc', 'to', 'an', 'ElementTree', '.']
train
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/type_conversions.py#L506-L521
7,709
klahnakoski/pyLibrary
mo_math/vendor/strangman/stats.py
zs
def zs(inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist, item)) return zscores
python
def zs(inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist, item)) return zscores
['def', 'zs', '(', 'inlist', ')', ':', 'zscores', '=', '[', ']', 'for', 'item', 'in', 'inlist', ':', 'zscores', '.', 'append', '(', 'z', '(', 'inlist', ',', 'item', ')', ')', 'return', 'zscores']
Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist)
['Returns', 'a', 'list', 'of', 'z', '-', 'scores', 'one', 'for', 'each', 'score', 'in', 'the', 'passed', 'list', '.']
train
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L690-L699
7,710
kubernetes-client/python
kubernetes/client/apis/batch_v2alpha1_api.py
BatchV2alpha1Api.list_namespaced_cron_job
def list_namespaced_cron_job(self, namespace, **kwargs): """ list or watch objects of kind CronJob This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_cron_job(namespace, async_...
python
def list_namespaced_cron_job(self, namespace, **kwargs): """ list or watch objects of kind CronJob This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_cron_job(namespace, async_...
['def', 'list_namespaced_cron_job', '(', 'self', ',', 'namespace', ',', '*', '*', 'kwargs', ')', ':', 'kwargs', '[', "'_return_http_data_only'", ']', '=', 'True', 'if', 'kwargs', '.', 'get', '(', "'async_req'", ')', ':', 'return', 'self', '.', 'list_namespaced_cron_job_with_http_info', '(', 'namespace', ',', '*', '*', ...
list or watch objects of kind CronJob This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_cron_job(namespace, async_req=True) >>> result = thread.get() :param async_req bool ...
['list', 'or', 'watch', 'objects', 'of', 'kind', 'CronJob', 'This', 'method', 'makes', 'a', 'synchronous', 'HTTP', 'request', 'by', 'default', '.', 'To', 'make', 'an', 'asynchronous', 'HTTP', 'request', 'please', 'pass', 'async_req', '=', 'True', '>>>', 'thread', '=', 'api', '.', 'list_namespaced_cron_job', '(', 'names...
train
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/batch_v2alpha1_api.py#L617-L644
7,711
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_integration_response
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto...
python
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto...
['def', 'describe_api_integration_response', '(', 'restApiId', ',', 'resourcePath', ',', 'httpMethod', ',', 'statusCode', ',', 'region', '=', 'None', ',', 'key', '=', 'None', ',', 'keyid', '=', 'None', ',', 'profile', '=', 'None', ')', ':', 'try', ':', 'resource', '=', 'describe_api_resource', '(', 'restApiId', ',', 'r...
Get an integration response for a given method in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode
['Get', 'an', 'integration', 'response', 'for', 'a', 'given', 'method', 'in', 'a', 'given', 'API']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1225-L1247
7,712
hazelcast/hazelcast-python-client
hazelcast/proxy/transactional_list.py
TransactionalList.add
def add(self, item): """ Transactional implementation of :func:`List.add(item) <hazelcast.proxy.list.List.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if the item is added successfully, ``false`` otherwise. """ check_not_none(item, "it...
python
def add(self, item): """ Transactional implementation of :func:`List.add(item) <hazelcast.proxy.list.List.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if the item is added successfully, ``false`` otherwise. """ check_not_none(item, "it...
['def', 'add', '(', 'self', ',', 'item', ')', ':', 'check_not_none', '(', 'item', ',', '"item can\'t be none"', ')', 'return', 'self', '.', '_encode_invoke', '(', 'transactional_list_add_codec', ',', 'item', '=', 'self', '.', '_to_data', '(', 'item', ')', ')']
Transactional implementation of :func:`List.add(item) <hazelcast.proxy.list.List.add>` :param item: (object), the new item to be added. :return: (bool), ``true`` if the item is added successfully, ``false`` otherwise.
['Transactional', 'implementation', 'of', ':', 'func', ':', 'List', '.', 'add', '(', 'item', ')', '<hazelcast', '.', 'proxy', '.', 'list', '.', 'List', '.', 'add', '>']
train
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_list.py#L11-L19
7,713
thomasvandoren/bugzscout-py
bugzscout/ext/cli.py
_from_args
def _from_args(args): """Factory method to create a new instance from command line args. :param args: instance of :class:`argparse.Namespace` """ return bugzscout.BugzScout(args.url, args.user, args.project, args.area)
python
def _from_args(args): """Factory method to create a new instance from command line args. :param args: instance of :class:`argparse.Namespace` """ return bugzscout.BugzScout(args.url, args.user, args.project, args.area)
['def', '_from_args', '(', 'args', ')', ':', 'return', 'bugzscout', '.', 'BugzScout', '(', 'args', '.', 'url', ',', 'args', '.', 'user', ',', 'args', '.', 'project', ',', 'args', '.', 'area', ')']
Factory method to create a new instance from command line args. :param args: instance of :class:`argparse.Namespace`
['Factory', 'method', 'to', 'create', 'a', 'new', 'instance', 'from', 'command', 'line', 'args', '.']
train
https://github.com/thomasvandoren/bugzscout-py/blob/514528e958a97e0e7b36870037c5c69661511824/bugzscout/ext/cli.py#L42-L47
7,714
bovee/Aston
aston/trace/math_traces.py
movingaverage
def movingaverage(arr, window): """ Calculates the moving average ("rolling mean") of an array of a certain window size. """ m = np.ones(int(window)) / int(window) return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')
python
def movingaverage(arr, window): """ Calculates the moving average ("rolling mean") of an array of a certain window size. """ m = np.ones(int(window)) / int(window) return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect')
['def', 'movingaverage', '(', 'arr', ',', 'window', ')', ':', 'm', '=', 'np', '.', 'ones', '(', 'int', '(', 'window', ')', ')', '/', 'int', '(', 'window', ')', 'return', 'scipy', '.', 'ndimage', '.', 'convolve1d', '(', 'arr', ',', 'm', ',', 'axis', '=', '0', ',', 'mode', '=', "'reflect'", ')']
Calculates the moving average ("rolling mean") of an array of a certain window size.
['Calculates', 'the', 'moving', 'average', '(', 'rolling', 'mean', ')', 'of', 'an', 'array', 'of', 'a', 'certain', 'window', 'size', '.']
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_traces.py#L73-L79
7,715
casacore/python-casacore
casacore/measures/__init__.py
measures.riseset
def riseset(self, crd, ev="5deg"): """This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as a quantity or string ...
python
def riseset(self, crd, ev="5deg"): """This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as a quantity or string ...
['def', 'riseset', '(', 'self', ',', 'crd', ',', 'ev', '=', '"5deg"', ')', ':', 'a', '=', 'self', '.', 'rise', '(', 'crd', ',', 'ev', ')', 'if', 'isinstance', '(', 'a', '[', "'rise'", ']', ',', 'str', ')', ':', 'return', '{', '"rise"', ':', '{', '"last"', ':', 'a', '[', '0', ']', ',', '"utc"', ':', 'a', '[', '0', ']', ...
This will give the rise/set times of a source. It needs the position in the frame, and a time. If the latter is not set, the current time will be used. :param crd: a direction measure :param ev: the elevation limit as a quantity or string :returns: The returned value is a `dict`...
['This', 'will', 'give', 'the', 'rise', '/', 'set', 'times', 'of', 'a', 'source', '.', 'It', 'needs', 'the', 'position', 'in', 'the', 'frame', 'and', 'a', 'time', '.', 'If', 'the', 'latter', 'is', 'not', 'set', 'the', 'current', 'time', 'will', 'be', 'used', '.']
train
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/measures/__init__.py#L807-L850
7,716
tanghaibao/jcvi
jcvi/apps/ks.py
prepare
def prepare(args): """ %prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta Pick sequences from cdsfile to form pairs, ready to be calculated. The pairsfile can be generated from formats.blast.cscore(). The first two columns contain the pair. """ from jcvi.formats.fasta import Fast...
python
def prepare(args): """ %prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta Pick sequences from cdsfile to form pairs, ready to be calculated. The pairsfile can be generated from formats.blast.cscore(). The first two columns contain the pair. """ from jcvi.formats.fasta import Fast...
['def', 'prepare', '(', 'args', ')', ':', 'from', 'jcvi', '.', 'formats', '.', 'fasta', 'import', 'Fasta', 'p', '=', 'OptionParser', '(', 'prepare', '.', '__doc__', ')', 'p', '.', 'set_outfile', '(', ')', 'opts', ',', 'args', '=', 'p', '.', 'parse_args', '(', 'args', ')', 'outfile', '=', 'opts', '.', 'outfile', 'if', '...
%prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta Pick sequences from cdsfile to form pairs, ready to be calculated. The pairsfile can be generated from formats.blast.cscore(). The first two columns contain the pair.
['%prog', 'prepare', 'pairsfile', 'cdsfile', '[', 'pepfile', ']', '-', 'o', 'paired', '.', 'cds', '.', 'fasta']
train
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/ks.py#L412-L467
7,717
openego/ding0
ding0/core/network/__init__.py
GridDing0.find_path
def find_path(self, node_source, node_target, type='nodes'): """Determines shortest path Determines the shortest path from `node_source` to `node_target` in _graph using networkx' shortest path algorithm. Args ---- node_source: GridDing0 source node,...
python
def find_path(self, node_source, node_target, type='nodes'): """Determines shortest path Determines the shortest path from `node_source` to `node_target` in _graph using networkx' shortest path algorithm. Args ---- node_source: GridDing0 source node,...
['def', 'find_path', '(', 'self', ',', 'node_source', ',', 'node_target', ',', 'type', '=', "'nodes'", ')', ':', 'if', '(', 'node_source', 'in', 'self', '.', '_graph', '.', 'nodes', '(', ')', ')', 'and', '(', 'node_target', 'in', 'self', '.', '_graph', '.', 'nodes', '(', ')', ')', ':', 'path', '=', 'nx', '.', 'shortest...
Determines shortest path Determines the shortest path from `node_source` to `node_target` in _graph using networkx' shortest path algorithm. Args ---- node_source: GridDing0 source node, member of _graph node_target: GridDing0 target node...
['Determines', 'shortest', 'path']
train
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/network/__init__.py#L319-L359
7,718
bslatkin/dpxdt
dpxdt/server/auth.py
manage_admins
def manage_admins(): """Page for viewing and managing build admins.""" build = g.build # Do not show cached data db.session.add(build) db.session.refresh(build) add_form = forms.AddAdminForm() if add_form.validate_on_submit(): invitation_user_id = '%s:%s' % ( models.Us...
python
def manage_admins(): """Page for viewing and managing build admins.""" build = g.build # Do not show cached data db.session.add(build) db.session.refresh(build) add_form = forms.AddAdminForm() if add_form.validate_on_submit(): invitation_user_id = '%s:%s' % ( models.Us...
['def', 'manage_admins', '(', ')', ':', 'build', '=', 'g', '.', 'build', '# Do not show cached data', 'db', '.', 'session', '.', 'add', '(', 'build', ')', 'db', '.', 'session', '.', 'refresh', '(', 'build', ')', 'add_form', '=', 'forms', '.', 'AddAdminForm', '(', ')', 'if', 'add_form', '.', 'validate_on_submit', '(', '...
Page for viewing and managing build admins.
['Page', 'for', 'viewing', 'and', 'managing', 'build', 'admins', '.']
train
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L469-L518
7,719
zebpalmer/WeatherAlerts
weatheralerts/geo.py
SameCodes._load_same_codes
def _load_same_codes(self, refresh=False): """Loads the Same Codes into this object""" if refresh is True: self._get_same_codes() else: self._cached_same_codes()
python
def _load_same_codes(self, refresh=False): """Loads the Same Codes into this object""" if refresh is True: self._get_same_codes() else: self._cached_same_codes()
['def', '_load_same_codes', '(', 'self', ',', 'refresh', '=', 'False', ')', ':', 'if', 'refresh', 'is', 'True', ':', 'self', '.', '_get_same_codes', '(', ')', 'else', ':', 'self', '.', '_cached_same_codes', '(', ')']
Loads the Same Codes into this object
['Loads', 'the', 'Same', 'Codes', 'into', 'this', 'object']
train
https://github.com/zebpalmer/WeatherAlerts/blob/b99513571571fa0d65b90be883bb3bc000994027/weatheralerts/geo.py#L106-L111
7,720
vtkiorg/vtki
vtki/renderer.py
Renderer.remove_actor
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Renderer. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can b...
python
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Renderer. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can b...
['def', 'remove_actor', '(', 'self', ',', 'actor', ',', 'reset_camera', '=', 'False', ')', ':', 'name', '=', 'None', 'if', 'isinstance', '(', 'actor', ',', 'str', ')', ':', 'name', '=', 'actor', 'keys', '=', 'list', '(', 'self', '.', '_actors', '.', 'keys', '(', ')', ')', 'names', '=', '[', ']', 'for', 'k', 'in', 'keys...
Removes an actor from the Renderer. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool ...
['Removes', 'an', 'actor', 'from', 'the', 'Renderer', '.']
train
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L544-L603
7,721
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py
has_neigh
def has_neigh(tag_name, params=None, content=None, left=True): """ This function generates functions, which matches all tags with neighbours defined by parameters. Args: tag_name (str): Tag has to have neighbour with this tagname. params (dict): Tag has to have neighbour with this param...
python
def has_neigh(tag_name, params=None, content=None, left=True): """ This function generates functions, which matches all tags with neighbours defined by parameters. Args: tag_name (str): Tag has to have neighbour with this tagname. params (dict): Tag has to have neighbour with this param...
['def', 'has_neigh', '(', 'tag_name', ',', 'params', '=', 'None', ',', 'content', '=', 'None', ',', 'left', '=', 'True', ')', ':', 'def', 'has_neigh_closure', '(', 'element', ')', ':', 'if', 'not', 'element', '.', 'parent', 'or', 'not', '(', 'element', '.', 'isTag', '(', ')', 'and', 'not', 'element', '.', 'isEndTag', '...
This function generates functions, which matches all tags with neighbours defined by parameters. Args: tag_name (str): Tag has to have neighbour with this tagname. params (dict): Tag has to have neighbour with this parameters. params (str): Tag has to have neighbour with this content. ...
['This', 'function', 'generates', 'functions', 'which', 'matches', 'all', 'tags', 'with', 'neighbours', 'defined', 'by', 'parameters', '.']
train
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L115-L158
7,722
jxtech/wechatpy
wechatpy/pay/api/withhold.py
WeChatWithhold.query_order
def query_order(self, transaction_id=None, out_trade_no=None): """ 查询订单 api :param transaction_id: 二选一 微信订单号 微信的订单号,优先使用 :param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。 :return: 返回的结果信息 """ if not transaction_id and not out_trade_no: ...
python
def query_order(self, transaction_id=None, out_trade_no=None): """ 查询订单 api :param transaction_id: 二选一 微信订单号 微信的订单号,优先使用 :param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。 :return: 返回的结果信息 """ if not transaction_id and not out_trade_no: ...
['def', 'query_order', '(', 'self', ',', 'transaction_id', '=', 'None', ',', 'out_trade_no', '=', 'None', ')', ':', 'if', 'not', 'transaction_id', 'and', 'not', 'out_trade_no', ':', 'raise', 'ValueError', '(', '"transaction_id and out_trade_no must be a choice."', ')', 'data', '=', '{', '"appid"', ':', 'self', '.', 'ap...
查询订单 api :param transaction_id: 二选一 微信订单号 微信的订单号,优先使用 :param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。 :return: 返回的结果信息
['查询订单', 'api']
train
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/pay/api/withhold.py#L158-L174
7,723
aiogram/aiogram
aiogram/utils/executor.py
Executor.set_webhook
def set_webhook(self, webhook_path: Optional[str] = None, request_handler: Any = WebhookRequestHandler, route_name: str = DEFAULT_ROUTE_NAME, web_app: Optional[Application] = None): """ Set webhook for bot :param webhook_path: Optional[str] (default: None) :param req...
python
def set_webhook(self, webhook_path: Optional[str] = None, request_handler: Any = WebhookRequestHandler, route_name: str = DEFAULT_ROUTE_NAME, web_app: Optional[Application] = None): """ Set webhook for bot :param webhook_path: Optional[str] (default: None) :param req...
['def', 'set_webhook', '(', 'self', ',', 'webhook_path', ':', 'Optional', '[', 'str', ']', '=', 'None', ',', 'request_handler', ':', 'Any', '=', 'WebhookRequestHandler', ',', 'route_name', ':', 'str', '=', 'DEFAULT_ROUTE_NAME', ',', 'web_app', ':', 'Optional', '[', 'Application', ']', '=', 'None', ')', ':', 'self', '.'...
Set webhook for bot :param webhook_path: Optional[str] (default: None) :param request_handler: Any (default: WebhookRequestHandler) :param route_name: str Name of webhook handler route (default: 'webhook_handler') :param web_app: Optional[Application] (default: None) :return:
['Set', 'webhook', 'for', 'bot']
train
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/utils/executor.py#L263-L275
7,724
xflr6/gsheets
gsheets/models.py
SpreadSheet.findall
def findall(self, title=None): """Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty) """ if title is None: ...
python
def findall(self, title=None): """Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty) """ if title is None: ...
['def', 'findall', '(', 'self', ',', 'title', '=', 'None', ')', ':', 'if', 'title', 'is', 'None', ':', 'return', 'list', '(', 'self', '.', '_sheets', ')', 'if', 'title', 'not', 'in', 'self', '.', '_titles', ':', 'return', '[', ']', 'return', 'list', '(', 'self', '.', '_titles', '[', 'title', ']', ')']
Return a list of worksheets with the given title. Args: title(str): title/name of the worksheets to return, or ``None`` for all Returns: list: list of contained worksheet instances (possibly empty)
['Return', 'a', 'list', 'of', 'worksheets', 'with', 'the', 'given', 'title', '.']
train
https://github.com/xflr6/gsheets/blob/ca4f1273044704e529c1138e3f942836fc496e1b/gsheets/models.py#L122-L134
7,725
lwcook/horsetail-matching
horsetailmatching/surrogates.py
PolySurrogate.predict
def predict(self, u): '''Predicts the output value at u from the fitted polynomial expansion. Therefore the method train() must be called first. :param numpy.ndarray u: input value at which to predict the output. :return: q_approx - the predicted value of the output at u :rtyp...
python
def predict(self, u): '''Predicts the output value at u from the fitted polynomial expansion. Therefore the method train() must be called first. :param numpy.ndarray u: input value at which to predict the output. :return: q_approx - the predicted value of the output at u :rtyp...
['def', 'predict', '(', 'self', ',', 'u', ')', ':', 'y', ',', 'ysub', '=', '0', ',', 'np', '.', 'zeros', '(', 'self', '.', 'N_poly', ')', 'for', 'ip', 'in', 'range', '(', 'self', '.', 'N_poly', ')', ':', 'inds', '=', 'tuple', '(', 'self', '.', 'index_polys', '[', 'ip', ']', ')', 'ysub', '[', 'ip', ']', '=', 'self', '.'...
Predicts the output value at u from the fitted polynomial expansion. Therefore the method train() must be called first. :param numpy.ndarray u: input value at which to predict the output. :return: q_approx - the predicted value of the output at u :rtype: float *Sample Usage*:...
['Predicts', 'the', 'output', 'value', 'at', 'u', 'from', 'the', 'fitted', 'polynomial', 'expansion', '.', 'Therefore', 'the', 'method', 'train', '()', 'must', 'be', 'called', 'first', '.']
train
https://github.com/lwcook/horsetail-matching/blob/f3d5f8d01249debbca978f412ce4eae017458119/horsetailmatching/surrogates.py#L72-L98
7,726
DomainTools/python_api
domaintools/api.py
delimited
def delimited(items, character='|'): """Returns a character delimited version of the provided list as a Python string""" return '|'.join(items) if type(items) in (list, tuple, set) else items
python
def delimited(items, character='|'): """Returns a character delimited version of the provided list as a Python string""" return '|'.join(items) if type(items) in (list, tuple, set) else items
['def', 'delimited', '(', 'items', ',', 'character', '=', "'|'", ')', ':', 'return', "'|'", '.', 'join', '(', 'items', ')', 'if', 'type', '(', 'items', ')', 'in', '(', 'list', ',', 'tuple', ',', 'set', ')', 'else', 'items']
Returns a character delimited version of the provided list as a Python string
['Returns', 'a', 'character', 'delimited', 'version', 'of', 'the', 'provided', 'list', 'as', 'a', 'Python', 'string']
train
https://github.com/DomainTools/python_api/blob/17be85fd4913fbe14d7660a4f4829242f1663e60/domaintools/api.py#L10-L12
7,727
jmurty/xml4h
xml4h/nodes.py
Node.write
def write(self, writer=None, encoding='utf-8', indent=0, newline='', omit_declaration=False, node_depth=0, quote_char='"'): """ Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or st...
python
def write(self, writer=None, encoding='utf-8', indent=0, newline='', omit_declaration=False, node_depth=0, quote_char='"'): """ Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or st...
['def', 'write', '(', 'self', ',', 'writer', '=', 'None', ',', 'encoding', '=', "'utf-8'", ',', 'indent', '=', '0', ',', 'newline', '=', "''", ',', 'omit_declaration', '=', 'False', ',', 'node_depth', '=', '0', ',', 'quote_char', '=', '\'"\'', ')', ':', 'xml4h', '.', 'write_node', '(', 'self', ',', 'writer', '=', 'writ...
Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param s...
['Serialize', 'this', 'node', 'and', 'its', 'descendants', 'to', 'text', 'writing', 'the', 'output', 'to', 'a', 'given', '*', 'writer', '*', 'or', 'to', 'stdout', '.']
train
https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/nodes.py#L450-L492
7,728
log2timeline/dfvfs
dfvfs/lib/cpio.py
CPIOArchiveFile.Open
def Open(self, file_object): """Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported. """ file_object.seek(0, os.SEEK_SET) signature_...
python
def Open(self, file_object): """Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported. """ file_object.seek(0, os.SEEK_SET) signature_...
['def', 'Open', '(', 'self', ',', 'file_object', ')', ':', 'file_object', '.', 'seek', '(', '0', ',', 'os', '.', 'SEEK_SET', ')', 'signature_data', '=', 'file_object', '.', 'read', '(', '6', ')', 'self', '.', 'file_format', '=', 'None', 'if', 'len', '(', 'signature_data', ')', '>', '2', ':', 'if', 'signature_data', '['...
Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported.
['Opens', 'the', 'CPIO', 'archive', 'file', '.']
train
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/cpio.py#L293-L325
7,729
noahbenson/neuropythy
neuropythy/io/core.py
forget_exporter
def forget_exporter(name): ''' forget_exporter(name) yields True if an exporter of type name was successfully forgotten from the neuropythy exporters list and false otherwise. This function must be called before an exporter can be replaced. ''' global exporters name = name.lower() if...
python
def forget_exporter(name): ''' forget_exporter(name) yields True if an exporter of type name was successfully forgotten from the neuropythy exporters list and false otherwise. This function must be called before an exporter can be replaced. ''' global exporters name = name.lower() if...
['def', 'forget_exporter', '(', 'name', ')', ':', 'global', 'exporters', 'name', '=', 'name', '.', 'lower', '(', ')', 'if', 'name', 'in', 'exporters', ':', 'exporters', '=', 'exporters', '.', 'discard', '(', 'name', ')', 'delattr', '(', 'save', ',', 'name', ')', 'return', 'True', 'else', ':', 'return', 'False']
forget_exporter(name) yields True if an exporter of type name was successfully forgotten from the neuropythy exporters list and false otherwise. This function must be called before an exporter can be replaced.
['forget_exporter', '(', 'name', ')', 'yields', 'True', 'if', 'an', 'exporter', 'of', 'type', 'name', 'was', 'successfully', 'forgotten', 'from', 'the', 'neuropythy', 'exporters', 'list', 'and', 'false', 'otherwise', '.', 'This', 'function', 'must', 'be', 'called', 'before', 'an', 'exporter', 'can', 'be', 'replaced', '...
train
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/io/core.py#L229-L242
7,730
openstates/billy
billy/web/public/views/legislators.py
legislator_inactive
def legislator_inactive(request, abbr, legislator): ''' Context: - vote_preview_row_template - old_roles - abbr - metadata - legislator - sources - sponsored_bills - legislator_votes - has_votes - nav_active Templates: ...
python
def legislator_inactive(request, abbr, legislator): ''' Context: - vote_preview_row_template - old_roles - abbr - metadata - legislator - sources - sponsored_bills - legislator_votes - has_votes - nav_active Templates: ...
['def', 'legislator_inactive', '(', 'request', ',', 'abbr', ',', 'legislator', ')', ':', 'sponsored_bills', '=', 'legislator', '.', 'sponsored_bills', '(', 'limit', '=', '6', ',', 'sort', '=', '[', '(', "'action_dates.first'", ',', 'pymongo', '.', 'DESCENDING', ')', ']', ')', 'legislator_votes', '=', 'list', '(', 'legi...
Context: - vote_preview_row_template - old_roles - abbr - metadata - legislator - sources - sponsored_bills - legislator_votes - has_votes - nav_active Templates: - billy/web/public/legislator.html - billy/web/public/vo...
['Context', ':', '-', 'vote_preview_row_template', '-', 'old_roles', '-', 'abbr', '-', 'metadata', '-', 'legislator', '-', 'sources', '-', 'sponsored_bills', '-', 'legislator_votes', '-', 'has_votes', '-', 'nav_active']
train
https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/legislators.py#L176-L211
7,731
google/dotty
efilter/transforms/solve.py
solve_let
def solve_let(expr, vars): """Solves a let-form by calling RHS with nested scope.""" lhs_value = solve(expr.lhs, vars).value if not isinstance(lhs_value, structured.IStructured): raise errors.EfilterTypeError( root=expr.lhs, query=expr.original, message="The LHS of 'let' must...
python
def solve_let(expr, vars): """Solves a let-form by calling RHS with nested scope.""" lhs_value = solve(expr.lhs, vars).value if not isinstance(lhs_value, structured.IStructured): raise errors.EfilterTypeError( root=expr.lhs, query=expr.original, message="The LHS of 'let' must...
['def', 'solve_let', '(', 'expr', ',', 'vars', ')', ':', 'lhs_value', '=', 'solve', '(', 'expr', '.', 'lhs', ',', 'vars', ')', '.', 'value', 'if', 'not', 'isinstance', '(', 'lhs_value', ',', 'structured', '.', 'IStructured', ')', ':', 'raise', 'errors', '.', 'EfilterTypeError', '(', 'root', '=', 'expr', '.', 'lhs', ','...
Solves a let-form by calling RHS with nested scope.
['Solves', 'a', 'let', '-', 'form', 'by', 'calling', 'RHS', 'with', 'nested', 'scope', '.']
train
https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/transforms/solve.py#L450-L459
7,732
gwastro/pycbc
pycbc/results/legacy_grb.py
initialize_page
def initialize_page(title, style, script, header=None): """ A function that returns a markup.py page object with the required html header. """ page = markup.page(mode="strict_html") page._escape = False page.init(title=title, css=style, script=script, header=header) return page
python
def initialize_page(title, style, script, header=None): """ A function that returns a markup.py page object with the required html header. """ page = markup.page(mode="strict_html") page._escape = False page.init(title=title, css=style, script=script, header=header) return page
['def', 'initialize_page', '(', 'title', ',', 'style', ',', 'script', ',', 'header', '=', 'None', ')', ':', 'page', '=', 'markup', '.', 'page', '(', 'mode', '=', '"strict_html"', ')', 'page', '.', '_escape', '=', 'False', 'page', '.', 'init', '(', 'title', '=', 'title', ',', 'css', '=', 'style', ',', 'script', '=', 'sc...
A function that returns a markup.py page object with the required html header.
['A', 'function', 'that', 'returns', 'a', 'markup', '.', 'py', 'page', 'object', 'with', 'the', 'required', 'html', 'header', '.']
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/results/legacy_grb.py#L31-L41
7,733
ionelmc/python-cogen
cogen/core/queue.py
Queue.task_done
def task_done(self, **kws): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently...
python
def task_done(self, **kws): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently...
['def', 'task_done', '(', 'self', ',', '*', '*', 'kws', ')', ':', 'unfinished', '=', 'self', '.', 'unfinished_tasks', '-', '1', 'op', '=', 'None', 'if', 'unfinished', '<=', '0', ':', 'if', 'unfinished', '<', '0', ':', 'raise', 'ValueError', '(', "'task_done() called too many times'", ')', 'op', '=', 'QDone', '(', 'self...
Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items...
['Indicate', 'that', 'a', 'formerly', 'enqueued', 'task', 'is', 'complete', '.', 'Used', 'by', 'Queue', 'consumer', 'threads', '.', 'For', 'each', 'get', '()', 'used', 'to', 'fetch', 'a', 'task', 'a', 'subsequent', 'call', 'to', 'task_done', '()', 'tells', 'the', 'queue', 'that', 'the', 'processing', 'on', 'the', 'task...
train
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/queue.py#L194-L215
7,734
antocuni/pdb
pdb.py
Pdb.do_display
def do_display(self, arg): """ display expression Add expression to the display list; expressions in this list are evaluated at each step, and printed every time its value changes. WARNING: since the expressions is evaluated multiple time, pay attention not to p...
python
def do_display(self, arg): """ display expression Add expression to the display list; expressions in this list are evaluated at each step, and printed every time its value changes. WARNING: since the expressions is evaluated multiple time, pay attention not to p...
['def', 'do_display', '(', 'self', ',', 'arg', ')', ':', 'try', ':', 'value', '=', 'self', '.', '_getval_or_undefined', '(', 'arg', ')', 'except', ':', 'return', 'self', '.', '_get_display_list', '(', ')', '[', 'arg', ']', '=', 'value']
display expression Add expression to the display list; expressions in this list are evaluated at each step, and printed every time its value changes. WARNING: since the expressions is evaluated multiple time, pay attention not to put expressions with side-effects in the ...
['display', 'expression']
train
https://github.com/antocuni/pdb/blob/a88be00d31f1ff38e26711a1d99589d830524c9e/pdb.py#L834-L850
7,735
cloud-custodian/cloud-custodian
tools/c7n_gcp/c7n_gcp/mu.py
LogSubscriber.remove
def remove(self, func): """Remove any provisioned log sink if auto created""" if not self.data['name'].startswith(self.prefix): return parent = self.get_parent(self.get_log()) _, sink_path, _ = self.get_sink() client = self.session.client( 'logging', 'v2',...
python
def remove(self, func): """Remove any provisioned log sink if auto created""" if not self.data['name'].startswith(self.prefix): return parent = self.get_parent(self.get_log()) _, sink_path, _ = self.get_sink() client = self.session.client( 'logging', 'v2',...
['def', 'remove', '(', 'self', ',', 'func', ')', ':', 'if', 'not', 'self', '.', 'data', '[', "'name'", ']', '.', 'startswith', '(', 'self', '.', 'prefix', ')', ':', 'return', 'parent', '=', 'self', '.', 'get_parent', '(', 'self', '.', 'get_log', '(', ')', ')', '_', ',', 'sink_path', ',', '_', '=', 'self', '.', 'get_sin...
Remove any provisioned log sink if auto created
['Remove', 'any', 'provisioned', 'log', 'sink', 'if', 'auto', 'created']
train
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/mu.py#L686-L699
7,736
honzamach/pynspect
pynspect/traversers.py
BaseFilteringTreeTraverser.evaluate_binop_comparison
def evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """ if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if...
python
def evaluate_binop_comparison(self, operation, left, right, **kwargs): """ Evaluate given comparison binary operation with given operands. """ if not operation in self.binops_comparison: raise ValueError("Invalid comparison binary operation '{}'".format(operation)) if...
['def', 'evaluate_binop_comparison', '(', 'self', ',', 'operation', ',', 'left', ',', 'right', ',', '*', '*', 'kwargs', ')', ':', 'if', 'not', 'operation', 'in', 'self', '.', 'binops_comparison', ':', 'raise', 'ValueError', '(', '"Invalid comparison binary operation \'{}\'"', '.', 'format', '(', 'operation', ')', ')', ...
Evaluate given comparison binary operation with given operands.
['Evaluate', 'given', 'comparison', 'binary', 'operation', 'with', 'given', 'operands', '.']
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L651-L684
7,737
cyrus-/cypy
cypy/cg.py
CG.append_once
def append_once(cls, code, **kwargs): """One-off code generation using append. If keyword args are provided, initialized using :meth:`with_id_processor`. """ if kwargs: g = cls.with_id_processor() g._append_context(kwargs) else: ...
python
def append_once(cls, code, **kwargs): """One-off code generation using append. If keyword args are provided, initialized using :meth:`with_id_processor`. """ if kwargs: g = cls.with_id_processor() g._append_context(kwargs) else: ...
['def', 'append_once', '(', 'cls', ',', 'code', ',', '*', '*', 'kwargs', ')', ':', 'if', 'kwargs', ':', 'g', '=', 'cls', '.', 'with_id_processor', '(', ')', 'g', '.', '_append_context', '(', 'kwargs', ')', 'else', ':', 'g', '=', 'cls', '(', ')', 'g', '.', 'append', '(', 'code', ')', 'return', 'g', '.', 'code']
One-off code generation using append. If keyword args are provided, initialized using :meth:`with_id_processor`.
['One', '-', 'off', 'code', 'generation', 'using', 'append', '.', 'If', 'keyword', 'args', 'are', 'provided', 'initialized', 'using', ':', 'meth', ':', 'with_id_processor', '.']
train
https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/cg.py#L89-L101
7,738
GNS3/gns3-server
gns3server/controller/__init__.py
Controller.get_loaded_project
def get_loaded_project(self, project_id): """ Returns a project or raise a 404 error. If project is not finished to load wait for it """ project = self.get_project(project_id) yield from project.wait_loaded() return project
python
def get_loaded_project(self, project_id): """ Returns a project or raise a 404 error. If project is not finished to load wait for it """ project = self.get_project(project_id) yield from project.wait_loaded() return project
['def', 'get_loaded_project', '(', 'self', ',', 'project_id', ')', ':', 'project', '=', 'self', '.', 'get_project', '(', 'project_id', ')', 'yield', 'from', 'project', '.', 'wait_loaded', '(', ')', 'return', 'project']
Returns a project or raise a 404 error. If project is not finished to load wait for it
['Returns', 'a', 'project', 'or', 'raise', 'a', '404', 'error', '.']
train
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/__init__.py#L543-L551
7,739
dhermes/bezier
src/bezier/_surface_intersection.py
_geometric_intersect
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.Intersec...
python
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify): r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.Intersec...
['def', '_geometric_intersect', '(', 'nodes1', ',', 'degree1', ',', 'nodes2', ',', 'degree2', ',', 'verify', ')', ':', 'all_intersections', '=', '_geometric_intersection', '.', 'all_intersections', 'return', 'generic_intersect', '(', 'nodes1', ',', 'degree1', ',', 'nodes2', ',', 'degree2', ',', 'verify', ',', 'all_inte...
r"""Find all intersections among edges of two surfaces. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Uses :func:`generic_intersect` with the :attr:`~.IntersectionStrategy.GEOMETRIC` intersection strategy. Args: nodes1...
['r', 'Find', 'all', 'intersections', 'among', 'edges', 'of', 'two', 'surfaces', '.']
train
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L813-L848
7,740
nikcub/floyd
floyd/util/unicode.py
to_utf8
def to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """ if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
python
def to_utf8(value): """Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string. """ if isinstance(value, unicode): return value.encode('utf-8') assert isinstance(value, str) return value
['def', 'to_utf8', '(', 'value', ')', ':', 'if', 'isinstance', '(', 'value', ',', 'unicode', ')', ':', 'return', 'value', '.', 'encode', '(', "'utf-8'", ')', 'assert', 'isinstance', '(', 'value', ',', 'str', ')', 'return', 'value']
Returns a string encoded using UTF-8. This function comes from `Tornado`_. :param value: A unicode or string to be encoded. :returns: The encoded string.
['Returns', 'a', 'string', 'encoded', 'using', 'UTF', '-', '8', '.']
train
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/unicode.py#L42-L56
7,741
tjvr/skip
skip/__init__.py
Interpreter.push_script
def push_script(self, scriptable, script, callback=None): """Run the script and add it to the list of threads.""" if script in self.threads: self.threads[script].finish() thread = Thread(self.run_script(scriptable, script), scriptable, callback) ...
python
def push_script(self, scriptable, script, callback=None): """Run the script and add it to the list of threads.""" if script in self.threads: self.threads[script].finish() thread = Thread(self.run_script(scriptable, script), scriptable, callback) ...
['def', 'push_script', '(', 'self', ',', 'scriptable', ',', 'script', ',', 'callback', '=', 'None', ')', ':', 'if', 'script', 'in', 'self', '.', 'threads', ':', 'self', '.', 'threads', '[', 'script', ']', '.', 'finish', '(', ')', 'thread', '=', 'Thread', '(', 'self', '.', 'run_script', '(', 'scriptable', ',', 'script',...
Run the script and add it to the list of threads.
['Run', 'the', 'script', 'and', 'add', 'it', 'to', 'the', 'list', 'of', 'threads', '.']
train
https://github.com/tjvr/skip/blob/ac84f7198079732bf22c3b8cbc0dc1a073b1d539/skip/__init__.py#L134-L141
7,742
splunk/splunk-sdk-python
examples/job.py
Program.run
def run(self, argv): """Dispatch the given command.""" command = argv[0] handlers = { 'cancel': self.cancel, 'create': self.create, 'events': self.events, 'finalize': self.finalize, 'list': self.list, 'pause': self.pause, ...
python
def run(self, argv): """Dispatch the given command.""" command = argv[0] handlers = { 'cancel': self.cancel, 'create': self.create, 'events': self.events, 'finalize': self.finalize, 'list': self.list, 'pause': self.pause, ...
['def', 'run', '(', 'self', ',', 'argv', ')', ':', 'command', '=', 'argv', '[', '0', ']', 'handlers', '=', '{', "'cancel'", ':', 'self', '.', 'cancel', ',', "'create'", ':', 'self', '.', 'create', ',', "'events'", ':', 'self', '.', 'events', ',', "'finalize'", ':', 'self', '.', 'finalize', ',', "'list'", ':', 'self', '...
Dispatch the given command.
['Dispatch', 'the', 'given', 'command', '.']
train
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L209-L231
7,743
FutunnOpen/futuquant
futuquant/common/pbjson.py
dict2pb
def dict2pb(cls, adict, strict=False): """ Takes a class representing the ProtoBuf Message and fills it with data from the dict. """ obj = cls() for field in obj.DESCRIPTOR.fields: if not field.label == field.LABEL_REQUIRED: continue if not field.has_default_value: ...
python
def dict2pb(cls, adict, strict=False): """ Takes a class representing the ProtoBuf Message and fills it with data from the dict. """ obj = cls() for field in obj.DESCRIPTOR.fields: if not field.label == field.LABEL_REQUIRED: continue if not field.has_default_value: ...
['def', 'dict2pb', '(', 'cls', ',', 'adict', ',', 'strict', '=', 'False', ')', ':', 'obj', '=', 'cls', '(', ')', 'for', 'field', 'in', 'obj', '.', 'DESCRIPTOR', '.', 'fields', ':', 'if', 'not', 'field', '.', 'label', '==', 'field', '.', 'LABEL_REQUIRED', ':', 'continue', 'if', 'not', 'field', '.', 'has_default_value', ...
Takes a class representing the ProtoBuf Message and fills it with data from the dict.
['Takes', 'a', 'class', 'representing', 'the', 'ProtoBuf', 'Message', 'and', 'fills', 'it', 'with', 'data', 'from', 'the', 'dict', '.']
train
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/pbjson.py#L40-L81
7,744
kylejusticemagnuson/pyti
pyti/directional_indicators.py
calculate_up_moves
def calculate_up_moves(high_data): """ Up Move. Formula: UPMOVE = Ht - Ht-1 """ up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))] return [np.nan] + up_moves
python
def calculate_up_moves(high_data): """ Up Move. Formula: UPMOVE = Ht - Ht-1 """ up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))] return [np.nan] + up_moves
['def', 'calculate_up_moves', '(', 'high_data', ')', ':', 'up_moves', '=', '[', 'high_data', '[', 'idx', ']', '-', 'high_data', '[', 'idx', '-', '1', ']', 'for', 'idx', 'in', 'range', '(', '1', ',', 'len', '(', 'high_data', ')', ')', ']', 'return', '[', 'np', '.', 'nan', ']', '+', 'up_moves']
Up Move. Formula: UPMOVE = Ht - Ht-1
['Up', 'Move', '.']
train
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L13-L21
7,745
ihgazni2/edict
edict/edict.py
dict2tlist
def dict2tlist(this_dict,**kwargs): ''' #sequence will be losted d = {'a':'b','c':'d'} dict2tlist(d) ''' if('check' in kwargs): check = kwargs['check'] else: check = 1 if(check): if(isinstance(this_dict,dict)): pass else: ...
python
def dict2tlist(this_dict,**kwargs): ''' #sequence will be losted d = {'a':'b','c':'d'} dict2tlist(d) ''' if('check' in kwargs): check = kwargs['check'] else: check = 1 if(check): if(isinstance(this_dict,dict)): pass else: ...
['def', 'dict2tlist', '(', 'this_dict', ',', '*', '*', 'kwargs', ')', ':', 'if', '(', "'check'", 'in', 'kwargs', ')', ':', 'check', '=', 'kwargs', '[', "'check'", ']', 'else', ':', 'check', '=', '1', 'if', '(', 'check', ')', ':', 'if', '(', 'isinstance', '(', 'this_dict', ',', 'dict', ')', ')', ':', 'pass', 'else', ':'...
#sequence will be losted d = {'a':'b','c':'d'} dict2tlist(d)
['#sequence', 'will', 'be', 'losted', 'd', '=', '{', 'a', ':', 'b', 'c', ':', 'd', '}', 'dict2tlist', '(', 'd', ')']
train
https://github.com/ihgazni2/edict/blob/44a08ccc10b196aa3854619b4c51ddb246778a34/edict/edict.py#L744-L774
7,746
ThreatConnect-Inc/tcex
tcex/tcex_resources.py
Resource.associations
def associations(self, association_resource): """Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. ...
python
def associations(self, association_resource): """Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. ...
['def', 'associations', '(', 'self', ',', 'association_resource', ')', ':', 'resource', '=', 'self', '.', 'copy', '(', ')', 'resource', '.', '_request_entity', '=', 'association_resource', '.', 'api_entity', 'resource', '.', '_request_uri', '=', "'{}/{}'", '.', 'format', '(', 'resource', '.', '_request_uri', ',', 'asso...
Retrieve Association for this resource of the type in association_resource. This method will return all *resources* (group, indicators, task, victims, etc) for this resource that are associated with the provided association resource_type. **Example Endpoints URI's** +--------+--------...
['Retrieve', 'Association', 'for', 'this', 'resource', 'of', 'the', 'type', 'in', 'association_resource', '.']
train
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L397-L431
7,747
ReFirmLabs/binwalk
src/binwalk/core/module.py
Module.result
def result(self, r=None, **kwargs): ''' Validates a result, stores it in self.results and prints it. Accepts the same kwargs as the binwalk.core.module.Result class. @r - An existing instance of binwalk.core.module.Result. Returns an instance of binwalk.core.module.Result. ...
python
def result(self, r=None, **kwargs): ''' Validates a result, stores it in self.results and prints it. Accepts the same kwargs as the binwalk.core.module.Result class. @r - An existing instance of binwalk.core.module.Result. Returns an instance of binwalk.core.module.Result. ...
['def', 'result', '(', 'self', ',', 'r', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'r', 'is', 'None', ':', 'r', '=', 'Result', '(', '*', '*', 'kwargs', ')', '# Add the name of the current module to the result', 'r', '.', 'module', '=', 'self', '.', '__class__', '.', '__name__', '# Any module that is reporti...
Validates a result, stores it in self.results and prints it. Accepts the same kwargs as the binwalk.core.module.Result class. @r - An existing instance of binwalk.core.module.Result. Returns an instance of binwalk.core.module.Result.
['Validates', 'a', 'result', 'stores', 'it', 'in', 'self', '.', 'results', 'and', 'prints', 'it', '.', 'Accepts', 'the', 'same', 'kwargs', 'as', 'the', 'binwalk', '.', 'core', '.', 'module', '.', 'Result', 'class', '.']
train
https://github.com/ReFirmLabs/binwalk/blob/a0c5315fd2bae167e5c3d8469ce95d5defc743c2/src/binwalk/core/module.py#L458-L503
7,748
eandersson/amqpstorm
amqpstorm/basic.py
Basic._consume_add_and_get_tag
def _consume_add_and_get_tag(self, consume_rpc_result): """Add the tag to the channel and return it. :param dict consume_rpc_result: :rtype: str """ consumer_tag = consume_rpc_result['consumer_tag'] self._channel.add_consumer_tag(consumer_tag) return consumer_ta...
python
def _consume_add_and_get_tag(self, consume_rpc_result): """Add the tag to the channel and return it. :param dict consume_rpc_result: :rtype: str """ consumer_tag = consume_rpc_result['consumer_tag'] self._channel.add_consumer_tag(consumer_tag) return consumer_ta...
['def', '_consume_add_and_get_tag', '(', 'self', ',', 'consume_rpc_result', ')', ':', 'consumer_tag', '=', 'consume_rpc_result', '[', "'consumer_tag'", ']', 'self', '.', '_channel', '.', 'add_consumer_tag', '(', 'consumer_tag', ')', 'return', 'consumer_tag']
Add the tag to the channel and return it. :param dict consume_rpc_result: :rtype: str
['Add', 'the', 'tag', 'to', 'the', 'channel', 'and', 'return', 'it', '.']
train
https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/basic.py#L268-L277
7,749
wummel/linkchecker
linkcheck/bookmarks/opera.py
find_bookmark_file
def find_bookmark_file (): """Return the bookmark file of the Opera profile. Returns absolute filename if found, or empty string if no bookmark file could be found. """ try: dirname = get_profile_dir() if os.path.isdir(dirname): for name in OperaBookmarkFiles: ...
python
def find_bookmark_file (): """Return the bookmark file of the Opera profile. Returns absolute filename if found, or empty string if no bookmark file could be found. """ try: dirname = get_profile_dir() if os.path.isdir(dirname): for name in OperaBookmarkFiles: ...
['def', 'find_bookmark_file', '(', ')', ':', 'try', ':', 'dirname', '=', 'get_profile_dir', '(', ')', 'if', 'os', '.', 'path', '.', 'isdir', '(', 'dirname', ')', ':', 'for', 'name', 'in', 'OperaBookmarkFiles', ':', 'fname', '=', 'os', '.', 'path', '.', 'join', '(', 'dirname', ',', 'name', ')', 'if', 'os', '.', 'path', ...
Return the bookmark file of the Opera profile. Returns absolute filename if found, or empty string if no bookmark file could be found.
['Return', 'the', 'bookmark', 'file', 'of', 'the', 'Opera', 'profile', '.', 'Returns', 'absolute', 'filename', 'if', 'found', 'or', 'empty', 'string', 'if', 'no', 'bookmark', 'file', 'could', 'be', 'found', '.']
train
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/bookmarks/opera.py#L40-L54
7,750
dmlc/gluon-nlp
scripts/sentiment_analysis/finetune_lm.py
train
def train(): """Training process""" start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num = 0 epoch_wc = 0...
python
def train(): """Training process""" start_pipeline_time = time.time() # Training/Testing best_valid_acc = 0 stop_early = 0 for epoch in range(args.epochs): # Epoch training stats start_epoch_time = time.time() epoch_L = 0.0 epoch_sent_num = 0 epoch_wc = 0...
['def', 'train', '(', ')', ':', 'start_pipeline_time', '=', 'time', '.', 'time', '(', ')', '# Training/Testing', 'best_valid_acc', '=', '0', 'stop_early', '=', '0', 'for', 'epoch', 'in', 'range', '(', 'args', '.', 'epochs', ')', ':', '# Epoch training stats', 'start_epoch_time', '=', 'time', '.', 'time', '(', ')', 'epo...
Training process
['Training', 'process']
train
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/sentiment_analysis/finetune_lm.py#L263-L340
7,751
ionelmc/python-fields
src/fields/__init__.py
class_sealer
def class_sealer(fields, defaults, base=__base__, make_init_func=make_init_func, initializer=True, comparable=True, printable=True, convertible=False, pass_kwargs=False): """ This sealer makes a normal container class. It's mutable and supports arguments with default values. ...
python
def class_sealer(fields, defaults, base=__base__, make_init_func=make_init_func, initializer=True, comparable=True, printable=True, convertible=False, pass_kwargs=False): """ This sealer makes a normal container class. It's mutable and supports arguments with default values. ...
['def', 'class_sealer', '(', 'fields', ',', 'defaults', ',', 'base', '=', '__base__', ',', 'make_init_func', '=', 'make_init_func', ',', 'initializer', '=', 'True', ',', 'comparable', '=', 'True', ',', 'printable', '=', 'True', ',', 'convertible', '=', 'False', ',', 'pass_kwargs', '=', 'False', ')', ':', 'baseclass_nam...
This sealer makes a normal container class. It's mutable and supports arguments with default values.
['This', 'sealer', 'makes', 'a', 'normal', 'container', 'class', '.', 'It', 's', 'mutable', 'and', 'supports', 'arguments', 'with', 'default', 'values', '.']
train
https://github.com/ionelmc/python-fields/blob/91e13560173abcc42cc1a95cbe2956b307126416/src/fields/__init__.py#L120-L201
7,752
openstack/networking-cisco
networking_cisco/ml2_drivers/nexus/nexus_restapi_client.py
CiscoNexusRestapiClient.send_request
def send_request(self, method, action, body=None, headers=None, ipaddr=None): """Perform the HTTP request. The response is in either JSON format or plain text. A GET method will invoke a JSON response while a PUT/POST/DELETE returns message from the the server in pla...
python
def send_request(self, method, action, body=None, headers=None, ipaddr=None): """Perform the HTTP request. The response is in either JSON format or plain text. A GET method will invoke a JSON response while a PUT/POST/DELETE returns message from the the server in pla...
['def', 'send_request', '(', 'self', ',', 'method', ',', 'action', ',', 'body', '=', 'None', ',', 'headers', '=', 'None', ',', 'ipaddr', '=', 'None', ')', ':', 'action', '=', "''", '.', 'join', '(', '[', 'self', '.', 'scheme', ',', "'://%s/'", ',', 'action', ']', ')', 'if', 'netaddr', '.', 'valid_ipv6', '(', 'ipaddr', ...
Perform the HTTP request. The response is in either JSON format or plain text. A GET method will invoke a JSON response while a PUT/POST/DELETE returns message from the the server in plain text format. Exception is raised when server replies with an INTERNAL SERVER ERROR status ...
['Perform', 'the', 'HTTP', 'request', '.']
train
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_client.py#L107-L229
7,753
django-crispy-forms/django-crispy-forms
crispy_forms/templatetags/crispy_forms_utils.py
specialspaceless
def specialspaceless(parser, token): """ Removes whitespace between HTML tags, and introduces a whitespace after buttons an inputs, necessary for Bootstrap to place them correctly in the layout. """ nodelist = parser.parse(('endspecialspaceless',)) parser.delete_first_token() return Spe...
python
def specialspaceless(parser, token): """ Removes whitespace between HTML tags, and introduces a whitespace after buttons an inputs, necessary for Bootstrap to place them correctly in the layout. """ nodelist = parser.parse(('endspecialspaceless',)) parser.delete_first_token() return Spe...
['def', 'specialspaceless', '(', 'parser', ',', 'token', ')', ':', 'nodelist', '=', 'parser', '.', 'parse', '(', '(', "'endspecialspaceless'", ',', ')', ')', 'parser', '.', 'delete_first_token', '(', ')', 'return', 'SpecialSpacelessNode', '(', 'nodelist', ')']
Removes whitespace between HTML tags, and introduces a whitespace after buttons an inputs, necessary for Bootstrap to place them correctly in the layout.
['Removes', 'whitespace', 'between', 'HTML', 'tags', 'and', 'introduces', 'a', 'whitespace', 'after', 'buttons', 'an', 'inputs', 'necessary', 'for', 'Bootstrap', 'to', 'place', 'them', 'correctly', 'in', 'the', 'layout', '.']
train
https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_utils.py#L38-L47
7,754
mryellow/maze_explorer
mazeexp/engine/world.py
WorldLayer.get_state
def get_state(self): """ Create state from sensors and battery """ # Include battery level in state battery = self.player.stats['battery']/100 # Create observation from sensor proximities # TODO: Have state persist, then update columns by `sensed_type` # ...
python
def get_state(self): """ Create state from sensors and battery """ # Include battery level in state battery = self.player.stats['battery']/100 # Create observation from sensor proximities # TODO: Have state persist, then update columns by `sensed_type` # ...
['def', 'get_state', '(', 'self', ')', ':', '# Include battery level in state', 'battery', '=', 'self', '.', 'player', '.', 'stats', '[', "'battery'", ']', '/', '100', '# Create observation from sensor proximities', '# TODO: Have state persist, then update columns by `sensed_type`', '# Multi-channel; detecting `items`'...
Create state from sensors and battery
['Create', 'state', 'from', 'sensors', 'and', 'battery']
train
https://github.com/mryellow/maze_explorer/blob/ab8a25ccd05105d2fe57e0213d690cfc07e45827/mazeexp/engine/world.py#L402-L434
7,755
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.get_cash_balance
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
python
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
['def', 'get_cash_balance', '(', 'self', ')', ':', 'cash', '=', 'False', 'try', ':', 'response', '=', 'self', '.', 'session', '.', 'get', '(', "'/browse/cashBalanceAj.action'", ')', 'json_response', '=', 'response', '.', 'json', '(', ')', 'if', 'self', '.', 'session', '.', 'json_success', '(', 'json_response', ')', ':'...
Returns the account cash balance available for investing Returns ------- float The cash balance in your account.
['Returns', 'the', 'account', 'cash', 'balance', 'available', 'for', 'investing']
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L154-L186
7,756
pyrogram/pyrogram
pyrogram/client/types/messages_and_media/message.py
Message.reply_video
def reply_video( self, video: str, quote: bool = None, caption: str = "", parse_mode: str = "", duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, supports_streaming: bool = True, disable_notification: bool = Non...
python
def reply_video( self, video: str, quote: bool = None, caption: str = "", parse_mode: str = "", duration: int = 0, width: int = 0, height: int = 0, thumb: str = None, supports_streaming: bool = True, disable_notification: bool = Non...
['def', 'reply_video', '(', 'self', ',', 'video', ':', 'str', ',', 'quote', ':', 'bool', '=', 'None', ',', 'caption', ':', 'str', '=', '""', ',', 'parse_mode', ':', 'str', '=', '""', ',', 'duration', ':', 'int', '=', '0', ',', 'width', ':', 'int', '=', '0', ',', 'height', ':', 'int', '=', '0', ',', 'thumb', ':', 'str',...
Bound method *reply_video* of :obj:`Message <pyrogram.Message>`. Use as a shortcut for: .. code-block:: python client.send_video( chat_id=message.chat.id, video=video ) Example: .. code-block:: python messag...
['Bound', 'method', '*', 'reply_video', '*', 'of', ':', 'obj', ':', 'Message', '<pyrogram', '.', 'Message', '>', '.']
train
https://github.com/pyrogram/pyrogram/blob/e7258a341ba905cfa86264c22040654db732ec1c/pyrogram/client/types/messages_and_media/message.py#L1997-L2135
7,757
delph-in/pydelphin
delphin/mrs/query.py
select_hcons
def select_hcons(xmrs, hi=None, relation=None, lo=None): """ Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* ...
python
def select_hcons(xmrs, hi=None, relation=None, lo=None): """ Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* ...
['def', 'select_hcons', '(', 'xmrs', ',', 'hi', '=', 'None', ',', 'relation', '=', 'None', ',', 'lo', '=', 'None', ')', ':', 'hcmatch', '=', 'lambda', 'hc', ':', '(', '(', 'hi', 'is', 'None', 'or', 'hc', '.', 'hi', '==', 'hi', ')', 'and', '(', 'relation', 'is', 'None', 'or', 'hc', '.', 'relation', '==', 'relation', ')'...
Return the list of matching HCONS for *xmrs*. :class:`~delphin.mrs.components.HandleConstraint` objects for *xmrs* match if their `hi` matches *hi*, `relation` matches *relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo* filters are ignored if they are `None`. Args: xmrs (:cla...
['Return', 'the', 'list', 'of', 'matching', 'HCONS', 'for', '*', 'xmrs', '*', '.']
train
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/query.py#L158-L180
7,758
riga/scinum
scinum.py
acosh
def acosh(x): """ acosh(x) Hyperbolic arc cos function. """ _math = infer_math(x) if _math is math: return _math.acosh(x) else: return _math.arccosh(x)
python
def acosh(x): """ acosh(x) Hyperbolic arc cos function. """ _math = infer_math(x) if _math is math: return _math.acosh(x) else: return _math.arccosh(x)
['def', 'acosh', '(', 'x', ')', ':', '_math', '=', 'infer_math', '(', 'x', ')', 'if', '_math', 'is', 'math', ':', 'return', '_math', '.', 'acosh', '(', 'x', ')', 'else', ':', 'return', '_math', '.', 'arccosh', '(', 'x', ')']
acosh(x) Hyperbolic arc cos function.
['acosh', '(', 'x', ')', 'Hyperbolic', 'arc', 'cos', 'function', '.']
train
https://github.com/riga/scinum/blob/55eb6d8aa77beacee5a07443392954b8a0aad8cb/scinum.py#L1256-L1264
7,759
cloud-custodian/cloud-custodian
c7n/mu.py
PythonPackageArchive.get_reader
def get_reader(self): """Return a read-only :py:class:`~zipfile.ZipFile`.""" assert self._closed, "Archive not closed" buf = io.BytesIO(self.get_bytes()) return zipfile.ZipFile(buf, mode='r')
python
def get_reader(self): """Return a read-only :py:class:`~zipfile.ZipFile`.""" assert self._closed, "Archive not closed" buf = io.BytesIO(self.get_bytes()) return zipfile.ZipFile(buf, mode='r')
['def', 'get_reader', '(', 'self', ')', ':', 'assert', 'self', '.', '_closed', ',', '"Archive not closed"', 'buf', '=', 'io', '.', 'BytesIO', '(', 'self', '.', 'get_bytes', '(', ')', ')', 'return', 'zipfile', '.', 'ZipFile', '(', 'buf', ',', 'mode', '=', "'r'", ')']
Return a read-only :py:class:`~zipfile.ZipFile`.
['Return', 'a', 'read', '-', 'only', ':', 'py', ':', 'class', ':', '~zipfile', '.', 'ZipFile', '.']
train
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/mu.py#L235-L239
7,760
crunchyroll/ef-open
efopen/ef_resolve_config.py
merge_files
def merge_files(context): """ Given a context containing path to template, env, and service: merge config into template and output the result to stdout Args: context: a populated context object """ resolver = EFTemplateResolver( profile=context.profile, region=context.region, env=conte...
python
def merge_files(context): """ Given a context containing path to template, env, and service: merge config into template and output the result to stdout Args: context: a populated context object """ resolver = EFTemplateResolver( profile=context.profile, region=context.region, env=conte...
['def', 'merge_files', '(', 'context', ')', ':', 'resolver', '=', 'EFTemplateResolver', '(', 'profile', '=', 'context', '.', 'profile', ',', 'region', '=', 'context', '.', 'region', ',', 'env', '=', 'context', '.', 'env', ',', 'service', '=', 'context', '.', 'service', ')', 'try', ':', 'with', 'open', '(', 'context', '...
Given a context containing path to template, env, and service: merge config into template and output the result to stdout Args: context: a populated context object
['Given', 'a', 'context', 'containing', 'path', 'to', 'template', 'env', 'and', 'service', ':', 'merge', 'config', 'into', 'template', 'and', 'output', 'the', 'result', 'to', 'stdout', 'Args', ':', 'context', ':', 'a', 'populated', 'context', 'object']
train
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_resolve_config.py#L92-L175
7,761
SCIP-Interfaces/PySCIPOpt
examples/unfinished/mctransp_tuplelist.py
mctransp
def mctransp(I,J,K,c,d,M): """mctransp -- model for solving the Multi-commodity Transportation Problem Parameters: - I: set of customers - J: set of facilities - K: set of commodities - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k - d[i][k]: demand for ...
python
def mctransp(I,J,K,c,d,M): """mctransp -- model for solving the Multi-commodity Transportation Problem Parameters: - I: set of customers - J: set of facilities - K: set of commodities - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k - d[i][k]: demand for ...
['def', 'mctransp', '(', 'I', ',', 'J', ',', 'K', ',', 'c', ',', 'd', ',', 'M', ')', ':', 'model', '=', 'Model', '(', '"multi-commodity transportation"', ')', '# Create variables', 'x', '=', '{', '}', 'for', '(', 'i', ',', 'j', ',', 'k', ')', 'in', 'c', ':', 'x', '[', 'i', ',', 'j', ',', 'k', ']', '=', 'model', '.', 'a...
mctransp -- model for solving the Multi-commodity Transportation Problem Parameters: - I: set of customers - J: set of facilities - K: set of commodities - c[i,j,k]: unit transportation cost on arc (i,j) for commodity k - d[i][k]: demand for commodity k at node i - M[...
['mctransp', '--', 'model', 'for', 'solving', 'the', 'Multi', '-', 'commodity', 'Transportation', 'Problem', 'Parameters', ':', '-', 'I', ':', 'set', 'of', 'customers', '-', 'J', ':', 'set', 'of', 'facilities', '-', 'K', ':', 'set', 'of', 'commodities', '-', 'c', '[', 'i', 'j', 'k', ']', ':', 'unit', 'transportation', ...
train
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/unfinished/mctransp_tuplelist.py#L15-L47
7,762
obriencj/python-javatools
javatools/opcodes.py
_unpack_lookupswitch
def _unpack_lookupswitch(bc, offset): """ function for unpacking the lookupswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, npairs), offset = _unpack(_struct_ii, bc, offset) switches = list() for _index in range(npairs): pair, offset ...
python
def _unpack_lookupswitch(bc, offset): """ function for unpacking the lookupswitch op arguments """ jump = (offset % 4) if jump: offset += (4 - jump) (default, npairs), offset = _unpack(_struct_ii, bc, offset) switches = list() for _index in range(npairs): pair, offset ...
['def', '_unpack_lookupswitch', '(', 'bc', ',', 'offset', ')', ':', 'jump', '=', '(', 'offset', '%', '4', ')', 'if', 'jump', ':', 'offset', '+=', '(', '4', '-', 'jump', ')', '(', 'default', ',', 'npairs', ')', ',', 'offset', '=', '_unpack', '(', '_struct_ii', ',', 'bc', ',', 'offset', ')', 'switches', '=', 'list', '(',...
function for unpacking the lookupswitch op arguments
['function', 'for', 'unpacking', 'the', 'lookupswitch', 'op', 'arguments']
train
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L171-L187
7,763
spyder-ide/spyder
spyder/widgets/fileswitcher.py
FileSwitcher.goto_line
def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) try: self.plugin.go_to_line(line_number) except AttributeError: pass
python
def goto_line(self, line_number): """Go to specified line number in current active editor.""" if line_number: line_number = int(line_number) try: self.plugin.go_to_line(line_number) except AttributeError: pass
['def', 'goto_line', '(', 'self', ',', 'line_number', ')', ':', 'if', 'line_number', ':', 'line_number', '=', 'int', '(', 'line_number', ')', 'try', ':', 'self', '.', 'plugin', '.', 'go_to_line', '(', 'line_number', ')', 'except', 'AttributeError', ':', 'pass']
Go to specified line number in current active editor.
['Go', 'to', 'specified', 'line', 'number', 'in', 'current', 'active', 'editor', '.']
train
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/fileswitcher.py#L590-L597
7,764
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioSegmentation.py
computePreRec
def computePreRec(cm, class_names): ''' This function computes the precision, recall and f1 measures, given a confusion matrix ''' n_classes = cm.shape[0] if len(class_names) != n_classes: print("Error in computePreRec! Confusion matrix and class_names " "list must be of th...
python
def computePreRec(cm, class_names): ''' This function computes the precision, recall and f1 measures, given a confusion matrix ''' n_classes = cm.shape[0] if len(class_names) != n_classes: print("Error in computePreRec! Confusion matrix and class_names " "list must be of th...
['def', 'computePreRec', '(', 'cm', ',', 'class_names', ')', ':', 'n_classes', '=', 'cm', '.', 'shape', '[', '0', ']', 'if', 'len', '(', 'class_names', ')', '!=', 'n_classes', ':', 'print', '(', '"Error in computePreRec! Confusion matrix and class_names "', '"list must be of the same size!"', ')', 'return', 'precision'...
This function computes the precision, recall and f1 measures, given a confusion matrix
['This', 'function', 'computes', 'the', 'precision', 'recall', 'and', 'f1', 'measures', 'given', 'a', 'confusion', 'matrix']
train
https://github.com/tyiannak/pyAudioAnalysis/blob/e3da991e7247492deba50648a4c7c0f41e684af4/pyAudioAnalysis/audioSegmentation.py#L124-L141
7,765
phdata/sdc-api-tool
sdctool/commands.py
import_pipeline
def import_pipeline(conf, args): """Import a pipeline from json.""" with open(args.pipeline_json) as pipeline_json: dst = conf.config['instances'][args.dst_instance] dst_url = api.build_pipeline_url(build_instance_url(dst)) dst_auth = tuple([conf.creds['instances'][args.dst_instance]['us...
python
def import_pipeline(conf, args): """Import a pipeline from json.""" with open(args.pipeline_json) as pipeline_json: dst = conf.config['instances'][args.dst_instance] dst_url = api.build_pipeline_url(build_instance_url(dst)) dst_auth = tuple([conf.creds['instances'][args.dst_instance]['us...
['def', 'import_pipeline', '(', 'conf', ',', 'args', ')', ':', 'with', 'open', '(', 'args', '.', 'pipeline_json', ')', 'as', 'pipeline_json', ':', 'dst', '=', 'conf', '.', 'config', '[', "'instances'", ']', '[', 'args', '.', 'dst_instance', ']', 'dst_url', '=', 'api', '.', 'build_pipeline_url', '(', 'build_instance_url...
Import a pipeline from json.
['Import', 'a', 'pipeline', 'from', 'json', '.']
train
https://github.com/phdata/sdc-api-tool/blob/8c86cfa89773ad411226264293d5b574194045de/sdctool/commands.py#L20-L29
7,766
inveniosoftware-attic/invenio-utils
invenio_utils/datastructures.py
SmartDict.__setitem
def __setitem(self, chunk, key, keys, value, extend=False): """Helper function to fill up the dictionary.""" def setitem(chunk): if keys: return self.__setitem(chunk, keys[0], keys[1:], value, extend) else: return value if key in ['.', ']'...
python
def __setitem(self, chunk, key, keys, value, extend=False): """Helper function to fill up the dictionary.""" def setitem(chunk): if keys: return self.__setitem(chunk, keys[0], keys[1:], value, extend) else: return value if key in ['.', ']'...
['def', '__setitem', '(', 'self', ',', 'chunk', ',', 'key', ',', 'keys', ',', 'value', ',', 'extend', '=', 'False', ')', ':', 'def', 'setitem', '(', 'chunk', ')', ':', 'if', 'keys', ':', 'return', 'self', '.', '__setitem', '(', 'chunk', ',', 'keys', '[', '0', ']', ',', 'keys', '[', '1', ':', ']', ',', 'value', ',', 'ex...
Helper function to fill up the dictionary.
['Helper', 'function', 'to', 'fill', 'up', 'the', 'dictionary', '.']
train
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/datastructures.py#L323-L373
7,767
AltSchool/dynamic-rest
dynamic_rest/processors.py
register_post_processor
def register_post_processor(func): """ Register a post processor function to be run as the final step in serialization. The data passed in will already have gone through the sideloading processor. Usage: @register_post_processor def my_post_processor(data): # do stuff wi...
python
def register_post_processor(func): """ Register a post processor function to be run as the final step in serialization. The data passed in will already have gone through the sideloading processor. Usage: @register_post_processor def my_post_processor(data): # do stuff wi...
['def', 'register_post_processor', '(', 'func', ')', ':', 'global', 'POST_PROCESSORS', 'key', '=', 'func', '.', '__name__', 'POST_PROCESSORS', '[', 'key', ']', '=', 'func', 'return', 'func']
Register a post processor function to be run as the final step in serialization. The data passed in will already have gone through the sideloading processor. Usage: @register_post_processor def my_post_processor(data): # do stuff with `data` return data
['Register', 'a', 'post', 'processor', 'function', 'to', 'be', 'run', 'as', 'the', 'final', 'step', 'in', 'serialization', '.', 'The', 'data', 'passed', 'in', 'will', 'already', 'have', 'gone', 'through', 'the', 'sideloading', 'processor', '.']
train
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/processors.py#L15-L32
7,768
learningequality/ricecooker
ricecooker/utils/zip.py
write_file_to_zip_with_neutral_metadata
def write_file_to_zip_with_neutral_metadata(zfile, filename, content): """ Write the string `content` to `filename` in the open ZipFile `zfile`. Args: zfile (ZipFile): open ZipFile to write the content into filename (str): the file path within the zip file to write into content (str)...
python
def write_file_to_zip_with_neutral_metadata(zfile, filename, content): """ Write the string `content` to `filename` in the open ZipFile `zfile`. Args: zfile (ZipFile): open ZipFile to write the content into filename (str): the file path within the zip file to write into content (str)...
['def', 'write_file_to_zip_with_neutral_metadata', '(', 'zfile', ',', 'filename', ',', 'content', ')', ':', 'info', '=', 'zipfile', '.', 'ZipInfo', '(', 'filename', ',', 'date_time', '=', '(', '2015', ',', '10', ',', '21', ',', '7', ',', '28', ',', '0', ')', ')', 'info', '.', 'compress_type', '=', 'zipfile', '.', 'ZIP_...
Write the string `content` to `filename` in the open ZipFile `zfile`. Args: zfile (ZipFile): open ZipFile to write the content into filename (str): the file path within the zip file to write into content (str): the content to write into the zip Returns: None
['Write', 'the', 'string', 'content', 'to', 'filename', 'in', 'the', 'open', 'ZipFile', 'zfile', '.', 'Args', ':', 'zfile', '(', 'ZipFile', ')', ':', 'open', 'ZipFile', 'to', 'write', 'the', 'content', 'into', 'filename', '(', 'str', ')', ':', 'the', 'file', 'path', 'within', 'the', 'zip', 'file', 'to', 'write', 'into'...
train
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/utils/zip.py#L42-L55
7,769
Kronuz/pyScss
scss/extension/compass/sprites.py
sprite_map_name
def sprite_map_name(map): """ Returns the name of a sprite map The name is derived from the folder than contains the sprites. """ map = map.render() sprite_maps = _get_cache('sprite_maps') sprite_map = sprite_maps.get(map) if not sprite_map: log.error("No sprite map found: %s", m...
python
def sprite_map_name(map): """ Returns the name of a sprite map The name is derived from the folder than contains the sprites. """ map = map.render() sprite_maps = _get_cache('sprite_maps') sprite_map = sprite_maps.get(map) if not sprite_map: log.error("No sprite map found: %s", m...
['def', 'sprite_map_name', '(', 'map', ')', ':', 'map', '=', 'map', '.', 'render', '(', ')', 'sprite_maps', '=', '_get_cache', '(', "'sprite_maps'", ')', 'sprite_map', '=', 'sprite_maps', '.', 'get', '(', 'map', ')', 'if', 'not', 'sprite_map', ':', 'log', '.', 'error', '(', '"No sprite map found: %s"', ',', 'map', ',',...
Returns the name of a sprite map The name is derived from the folder than contains the sprites.
['Returns', 'the', 'name', 'of', 'a', 'sprite', 'map', 'The', 'name', 'is', 'derived', 'from', 'the', 'folder', 'than', 'contains', 'the', 'sprites', '.']
train
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/sprites.py#L428-L440
7,770
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_union
def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L...
python
def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L...
['def', 'afw_union', '(', 'afw_1', ':', 'dict', ',', 'afw_2', ':', 'dict', ')', '->', 'dict', ':', '# make sure new root state is unique', 'initial_state', '=', "'root'", 'i', '=', '0', 'while', 'initial_state', 'in', 'afw_1', '[', "'states'", ']', 'or', 'initial_state', 'in', 'afw_2', '[', "'states'", ']', ':', 'initi...
Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∪ = (Σ, S_1 ∪ S_2 ∪ {root}, ρ_...
['Returns', 'a', 'AFW', 'that', 'reads', 'the', 'union', 'of', 'the', 'languages', 'read', 'by', 'input', 'AFWs', '.']
train
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L368-L432
7,771
sorgerlab/indra
indra/tools/reading/submit_reading_pipeline.py
Submitter.submit_reading
def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job, num_tries=1, stagger=0): """Submit a batch of reading jobs Parameters ---------- input_fname : str The name of the file containing the ids to be read. start_ix : int ...
python
def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job, num_tries=1, stagger=0): """Submit a batch of reading jobs Parameters ---------- input_fname : str The name of the file containing the ids to be read. start_ix : int ...
['def', 'submit_reading', '(', 'self', ',', 'input_fname', ',', 'start_ix', ',', 'end_ix', ',', 'ids_per_job', ',', 'num_tries', '=', '1', ',', 'stagger', '=', '0', ')', ':', '# stash this for later.', 'self', '.', 'ids_per_job', '=', 'ids_per_job', '# Upload the pmid_list to Amazon S3', 'id_list_key', '=', "'reading_r...
Submit a batch of reading jobs Parameters ---------- input_fname : str The name of the file containing the ids to be read. start_ix : int The line index of the first item in the list to read. end_ix : int The line index of the last item in the...
['Submit', 'a', 'batch', 'of', 'reading', 'jobs']
train
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/submit_reading_pipeline.py#L397-L466
7,772
emilydolson/avida-spatial-tools
avidaspatial/utils.py
initialize_grid
def initialize_grid(world_size, inner): """ Creates an empty grid (2d list) with the dimensions specified in world_size. Each element is initialized to the inner argument. """ data = [] for i in range(world_size[1]): data.append([]) for j in range(world_size[0]): dat...
python
def initialize_grid(world_size, inner): """ Creates an empty grid (2d list) with the dimensions specified in world_size. Each element is initialized to the inner argument. """ data = [] for i in range(world_size[1]): data.append([]) for j in range(world_size[0]): dat...
['def', 'initialize_grid', '(', 'world_size', ',', 'inner', ')', ':', 'data', '=', '[', ']', 'for', 'i', 'in', 'range', '(', 'world_size', '[', '1', ']', ')', ':', 'data', '.', 'append', '(', '[', ']', ')', 'for', 'j', 'in', 'range', '(', 'world_size', '[', '0', ']', ')', ':', 'data', '[', 'i', ']', '.', 'append', '(',...
Creates an empty grid (2d list) with the dimensions specified in world_size. Each element is initialized to the inner argument.
['Creates', 'an', 'empty', 'grid', '(', '2d', 'list', ')', 'with', 'the', 'dimensions', 'specified', 'in', 'world_size', '.', 'Each', 'element', 'is', 'initialized', 'to', 'the', 'inner', 'argument', '.']
train
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L382-L393
7,773
spacetelescope/drizzlepac
drizzlepac/imageObject.py
baseImageObject.updateData
def updateData(self,exten,data): """ Write out updated data and header to the original input file for this object. """ _extnum=self._interpretExten(exten) fimg = fileutil.openImage(self._filename, mode='update', memmap=False) fimg[_extnum].data = data fimg[_ex...
python
def updateData(self,exten,data): """ Write out updated data and header to the original input file for this object. """ _extnum=self._interpretExten(exten) fimg = fileutil.openImage(self._filename, mode='update', memmap=False) fimg[_extnum].data = data fimg[_ex...
['def', 'updateData', '(', 'self', ',', 'exten', ',', 'data', ')', ':', '_extnum', '=', 'self', '.', '_interpretExten', '(', 'exten', ')', 'fimg', '=', 'fileutil', '.', 'openImage', '(', 'self', '.', '_filename', ',', 'mode', '=', "'update'", ',', 'memmap', '=', 'False', ')', 'fimg', '[', '_extnum', ']', '.', 'data', '...
Write out updated data and header to the original input file for this object.
['Write', 'out', 'updated', 'data', 'and', 'header', 'to', 'the', 'original', 'input', 'file', 'for', 'this', 'object', '.']
train
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L212-L220
7,774
tjcsl/cslbot
cslbot/commands/guarded.py
cmd
def cmd(send, _, args): """Shows the currently guarded nicks. Syntax: {command} """ guarded = args['handler'].guarded if not guarded: send("Nobody is guarded.") else: send(", ".join(guarded))
python
def cmd(send, _, args): """Shows the currently guarded nicks. Syntax: {command} """ guarded = args['handler'].guarded if not guarded: send("Nobody is guarded.") else: send(", ".join(guarded))
['def', 'cmd', '(', 'send', ',', '_', ',', 'args', ')', ':', 'guarded', '=', 'args', '[', "'handler'", ']', '.', 'guarded', 'if', 'not', 'guarded', ':', 'send', '(', '"Nobody is guarded."', ')', 'else', ':', 'send', '(', '", "', '.', 'join', '(', 'guarded', ')', ')']
Shows the currently guarded nicks. Syntax: {command}
['Shows', 'the', 'currently', 'guarded', 'nicks', '.']
train
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/guarded.py#L22-L32
7,775
fhamborg/news-please
newsplease/__main__.py
NewsPleaseLauncher.get_expanded_path
def get_expanded_path(self, path): """ expands a path that starts with an ~ to an absolute path :param path: :return: """ if path.startswith('~'): return os.path.expanduser('~') + path[1:] else: return path
python
def get_expanded_path(self, path): """ expands a path that starts with an ~ to an absolute path :param path: :return: """ if path.startswith('~'): return os.path.expanduser('~') + path[1:] else: return path
['def', 'get_expanded_path', '(', 'self', ',', 'path', ')', ':', 'if', 'path', '.', 'startswith', '(', "'~'", ')', ':', 'return', 'os', '.', 'path', '.', 'expanduser', '(', "'~'", ')', '+', 'path', '[', '1', ':', ']', 'else', ':', 'return', 'path']
expands a path that starts with an ~ to an absolute path :param path: :return:
['expands', 'a', 'path', 'that', 'starts', 'with', 'an', '~', 'to', 'an', 'absolute', 'path', ':', 'param', 'path', ':', ':', 'return', ':']
train
https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/__main__.py#L317-L326
7,776
Dallinger/Dallinger
dallinger/experiment_server/gunicorn.py
StandaloneServer.load
def load(self): """Return our application to be run.""" app = util.import_app("dallinger.experiment_server.sockets:app") if self.options.get("mode") == "debug": app.debug = True return app
python
def load(self): """Return our application to be run.""" app = util.import_app("dallinger.experiment_server.sockets:app") if self.options.get("mode") == "debug": app.debug = True return app
['def', 'load', '(', 'self', ')', ':', 'app', '=', 'util', '.', 'import_app', '(', '"dallinger.experiment_server.sockets:app"', ')', 'if', 'self', '.', 'options', '.', 'get', '(', '"mode"', ')', '==', '"debug"', ':', 'app', '.', 'debug', '=', 'True', 'return', 'app']
Return our application to be run.
['Return', 'our', 'application', 'to', 'be', 'run', '.']
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/gunicorn.py#L52-L57
7,777
opentracing/opentracing-python
opentracing/scope_managers/tornado.py
TornadoScopeManager.activate
def activate(self, span, finish_on_close): """ Make a :class:`~opentracing.Span` instance active. :param span: the :class:`~opentracing.Span` that should become active. :param finish_on_close: whether *span* should automatically be finished when :meth:`Scope.close()` is call...
python
def activate(self, span, finish_on_close): """ Make a :class:`~opentracing.Span` instance active. :param span: the :class:`~opentracing.Span` that should become active. :param finish_on_close: whether *span* should automatically be finished when :meth:`Scope.close()` is call...
['def', 'activate', '(', 'self', ',', 'span', ',', 'finish_on_close', ')', ':', 'context', '=', 'self', '.', '_get_context', '(', ')', 'if', 'context', 'is', 'None', ':', 'return', 'super', '(', 'TornadoScopeManager', ',', 'self', ')', '.', 'activate', '(', 'span', ',', 'finish_on_close', ')', 'scope', '=', '_TornadoSc...
Make a :class:`~opentracing.Span` instance active. :param span: the :class:`~opentracing.Span` that should become active. :param finish_on_close: whether *span* should automatically be finished when :meth:`Scope.close()` is called. If no :func:`tracer_stack_context()` is detected, ...
['Make', 'a', ':', 'class', ':', '~opentracing', '.', 'Span', 'instance', 'active', '.']
train
https://github.com/opentracing/opentracing-python/blob/5ceb76d67b01c1c3316cfed02371d7922830e317/opentracing/scope_managers/tornado.py#L87-L114
7,778
jwodder/javaproperties
javaproperties/reading.py
parse
def parse(fp): """ Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a generator of ``(key, value, original_lines)`` triples for every entry in ``fp`` (including duplicate keys) in order of occurrence. The th...
python
def parse(fp): """ Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a generator of ``(key, value, original_lines)`` triples for every entry in ``fp`` (including duplicate keys) in order of occurrence. The th...
['def', 'parse', '(', 'fp', ')', ':', 'def', 'lineiter', '(', ')', ':', 'while', 'True', ':', 'ln', '=', 'fp', '.', 'readline', '(', ')', 'if', 'isinstance', '(', 'ln', ',', 'binary_type', ')', ':', 'ln', '=', 'ln', '.', 'decode', '(', "'iso-8859-1'", ')', 'if', 'ln', '==', "''", ':', 'return', 'for', 'l', 'in', 'ascii...
Parse the contents of the `~io.IOBase.readline`-supporting file-like object ``fp`` as a simple line-oriented ``.properties`` file and return a generator of ``(key, value, original_lines)`` triples for every entry in ``fp`` (including duplicate keys) in order of occurrence. The third element of each tri...
['Parse', 'the', 'contents', 'of', 'the', '~io', '.', 'IOBase', '.', 'readline', '-', 'supporting', 'file', '-', 'like', 'object', 'fp', 'as', 'a', 'simple', 'line', '-', 'oriented', '.', 'properties', 'file', 'and', 'return', 'a', 'generator', 'of', '(', 'key', 'value', 'original_lines', ')', 'triples', 'for', 'every'...
train
https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/reading.py#L68-L123
7,779
jobovy/galpy
galpy/df/streamdf.py
streamdf._parse_call_args
def _parse_call_args(self,*args,**kwargs): """Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)""" interp= kwargs.get('interp',self._useInterp) if len(args) == 5: raise IOError("Must specify...
python
def _parse_call_args(self,*args,**kwargs): """Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)""" interp= kwargs.get('interp',self._useInterp) if len(args) == 5: raise IOError("Must specify...
['def', '_parse_call_args', '(', 'self', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'interp', '=', 'kwargs', '.', 'get', '(', "'interp'", ',', 'self', '.', '_useInterp', ')', 'if', 'len', '(', 'args', ')', '==', '5', ':', 'raise', 'IOError', '(', '"Must specify phi for streamdf"', ')', 'elif', 'len', '(', 'ar...
Helper function to parse the arguments to the __call__ and related functions, return [6,nobj] array of frequencies (:3) and angles (3:)
['Helper', 'function', 'to', 'parse', 'the', 'arguments', 'to', 'the', '__call__', 'and', 'related', 'functions', 'return', '[', '6', 'nobj', ']', 'array', 'of', 'frequencies', '(', ':', '3', ')', 'and', 'angles', '(', '3', ':', ')']
train
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L2606-L2639
7,780
pantsbuild/pants
src/python/pants/goal/run_tracker.py
RunTracker.post_stats
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None): """POST stats to the given url. :return: True if upload was successful, False otherwise. """ def error(msg): # Report aleady closed, so just print error. print('WARNING: Failed to upload stats to {}. due to {}'.format(sta...
python
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None): """POST stats to the given url. :return: True if upload was successful, False otherwise. """ def error(msg): # Report aleady closed, so just print error. print('WARNING: Failed to upload stats to {}. due to {}'.format(sta...
['def', 'post_stats', '(', 'cls', ',', 'stats_url', ',', 'stats', ',', 'timeout', '=', '2', ',', 'auth_provider', '=', 'None', ')', ':', 'def', 'error', '(', 'msg', ')', ':', '# Report aleady closed, so just print error.', 'print', '(', "'WARNING: Failed to upload stats to {}. due to {}'", '.', 'format', '(', 'stats_ur...
POST stats to the given url. :return: True if upload was successful, False otherwise.
['POST', 'stats', 'to', 'the', 'given', 'url', '.']
train
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/run_tracker.py#L355-L397
7,781
ibis-project/ibis
ibis/pandas/execution/generic.py
wrap_case_result
def wrap_case_result(raw, expr): """Wrap a CASE statement result in a Series and handle returning scalars. Parameters ---------- raw : ndarray[T] The raw results of executing the ``CASE`` expression expr : ValueExpr The expression from the which `raw` was computed Returns -...
python
def wrap_case_result(raw, expr): """Wrap a CASE statement result in a Series and handle returning scalars. Parameters ---------- raw : ndarray[T] The raw results of executing the ``CASE`` expression expr : ValueExpr The expression from the which `raw` was computed Returns -...
['def', 'wrap_case_result', '(', 'raw', ',', 'expr', ')', ':', 'raw_1d', '=', 'np', '.', 'atleast_1d', '(', 'raw', ')', 'if', 'np', '.', 'any', '(', 'pd', '.', 'isnull', '(', 'raw_1d', ')', ')', ':', 'result', '=', 'pd', '.', 'Series', '(', 'raw_1d', ')', 'else', ':', 'result', '=', 'pd', '.', 'Series', '(', 'raw_1d', ...
Wrap a CASE statement result in a Series and handle returning scalars. Parameters ---------- raw : ndarray[T] The raw results of executing the ``CASE`` expression expr : ValueExpr The expression from the which `raw` was computed Returns ------- Union[scalar, Series]
['Wrap', 'a', 'CASE', 'statement', 'result', 'in', 'a', 'Series', 'and', 'handle', 'returning', 'scalars', '.']
train
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/pandas/execution/generic.py#L930-L953
7,782
cloud-custodian/cloud-custodian
c7n/policy.py
Policy.get_variables
def get_variables(self, variables=None): """Get runtime variables for policy interpolation. Runtime variables are merged with the passed in variables if any. """ # Global policy variable expansion, we have to carry forward on # various filter/action local vocabularies. W...
python
def get_variables(self, variables=None): """Get runtime variables for policy interpolation. Runtime variables are merged with the passed in variables if any. """ # Global policy variable expansion, we have to carry forward on # various filter/action local vocabularies. W...
['def', 'get_variables', '(', 'self', ',', 'variables', '=', 'None', ')', ':', '# Global policy variable expansion, we have to carry forward on', '# various filter/action local vocabularies. Where possible defer', '# by using a format string.', '#', '# See https://github.com/capitalone/cloud-custodian/issues/2330', 'if...
Get runtime variables for policy interpolation. Runtime variables are merged with the passed in variables if any.
['Get', 'runtime', 'variables', 'for', 'policy', 'interpolation', '.']
train
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/policy.py#L836-L880
7,783
inasafe/inasafe
safe/datastore/folder.py
Folder._add_vector_layer
def _add_vector_layer(self, vector_layer, layer_name, save_style=False): """Add a vector layer to the folder. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :par...
python
def _add_vector_layer(self, vector_layer, layer_name, save_style=False): """Add a vector layer to the folder. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :par...
['def', '_add_vector_layer', '(', 'self', ',', 'vector_layer', ',', 'layer_name', ',', 'save_style', '=', 'False', ')', ':', 'if', 'not', 'self', '.', 'is_writable', '(', ')', ':', 'return', 'False', ',', "'The destination is not writable.'", 'output', '=', 'QFileInfo', '(', 'self', '.', 'uri', '.', 'filePath', '(', 'l...
Add a vector layer to the folder. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_st...
['Add', 'a', 'vector', 'layer', 'to', 'the', 'folder', '.']
train
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/datastore/folder.py#L182-L226
7,784
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py
keep_only_positive_boxes
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
python
def keep_only_positive_boxes(boxes): """ Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList) """ assert isinstance(boxes, (list, tuple)) assert isinstance(boxes[0], BoxList) assert boxes[0].has_...
['def', 'keep_only_positive_boxes', '(', 'boxes', ')', ':', 'assert', 'isinstance', '(', 'boxes', ',', '(', 'list', ',', 'tuple', ')', ')', 'assert', 'isinstance', '(', 'boxes', '[', '0', ']', ',', 'BoxList', ')', 'assert', 'boxes', '[', '0', ']', '.', 'has_field', '(', '"labels"', ')', 'positive_boxes', '=', '[', ']',...
Given a set of BoxList containing the `labels` field, return a set of BoxList for which `labels > 0`. Arguments: boxes (list of BoxList)
['Given', 'a', 'set', 'of', 'BoxList', 'containing', 'the', 'labels', 'field', 'return', 'a', 'set', 'of', 'BoxList', 'for', 'which', 'labels', '>', '0', '.']
train
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py#L13-L33
7,785
bdauvergne/python-oath
oath/_hotp.py
hotp
def hotp(key,counter,format='dec6',hash=hashlib.sha1): ''' Compute a HOTP value as prescribed by RFC4226 :param key: the HOTP secret key given as an hexadecimal string :param counter: the OTP generation counter :param format: the output format, can be: ...
python
def hotp(key,counter,format='dec6',hash=hashlib.sha1): ''' Compute a HOTP value as prescribed by RFC4226 :param key: the HOTP secret key given as an hexadecimal string :param counter: the OTP generation counter :param format: the output format, can be: ...
['def', 'hotp', '(', 'key', ',', 'counter', ',', 'format', '=', "'dec6'", ',', 'hash', '=', 'hashlib', '.', 'sha1', ')', ':', 'bin_hotp', '=', '__hotp', '(', 'key', ',', 'counter', ',', 'hash', ')', 'if', 'format', '==', "'dec4'", ':', 'return', 'dec', '(', 'bin_hotp', ',', '4', ')', 'elif', 'format', '==', "'dec6'", '...
Compute a HOTP value as prescribed by RFC4226 :param key: the HOTP secret key given as an hexadecimal string :param counter: the OTP generation counter :param format: the output format, can be: - hex, for a variable length hexadecimal format, ...
['Compute', 'a', 'HOTP', 'value', 'as', 'prescribed', 'by', 'RFC4226']
train
https://github.com/bdauvergne/python-oath/blob/c37cd63880b39032b9ba69cd1516e6fb06923e46/oath/_hotp.py#L43-L91
7,786
housecanary/hc-api-python
housecanary/apiclient.py
PropertyComponentWrapper.rental_report
def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json". ""...
python
def rental_report(self, address, zipcode, format_type="json"): """Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json". ""...
['def', 'rental_report', '(', 'self', ',', 'address', ',', 'zipcode', ',', 'format_type', '=', '"json"', ')', ':', '# only json is supported by rental report.', 'query_params', '=', '{', '"format"', ':', 'format_type', ',', '"address"', ':', 'address', ',', '"zipcode"', ':', 'zipcode', '}', 'return', 'self', '.', '_api...
Call the rental_report component Rental Report only supports a single address. Args: - address - zipcode Kwargs: - format_type - "json", "xlsx" or "all". Default is "json".
['Call', 'the', 'rental_report', 'component']
train
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/apiclient.py#L435-L455
7,787
kensho-technologies/graphql-compiler
graphql_compiler/query_formatting/gremlin_formatting.py
_safe_gremlin_string
def _safe_gremlin_string(value): """Sanitize and represent a string argument in Gremlin.""" if not isinstance(value, six.string_types): if isinstance(value, bytes): # should only happen in py3 value = value.decode('utf-8') else: raise GraphQLInvalidArgumentError(u'Attemp...
python
def _safe_gremlin_string(value): """Sanitize and represent a string argument in Gremlin.""" if not isinstance(value, six.string_types): if isinstance(value, bytes): # should only happen in py3 value = value.decode('utf-8') else: raise GraphQLInvalidArgumentError(u'Attemp...
['def', '_safe_gremlin_string', '(', 'value', ')', ':', 'if', 'not', 'isinstance', '(', 'value', ',', 'six', '.', 'string_types', ')', ':', 'if', 'isinstance', '(', 'value', ',', 'bytes', ')', ':', '# should only happen in py3', 'value', '=', 'value', '.', 'decode', '(', "'utf-8'", ')', 'else', ':', 'raise', 'GraphQLIn...
Sanitize and represent a string argument in Gremlin.
['Sanitize', 'and', 'represent', 'a', 'string', 'argument', 'in', 'Gremlin', '.']
train
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/query_formatting/gremlin_formatting.py#L18-L48
7,788
getpelican/pelican-plugins
filetime_from_git/actions.py
filetime_from_git
def filetime_from_git(content, git_content): ''' Update modification and creation times from git ''' if not content.settings['GIT_FILETIME_FROM_GIT']: # Disabled for everything return if not string_to_bool(content.metadata.get('gittime', 'yes')): # Disable for this content ...
python
def filetime_from_git(content, git_content): ''' Update modification and creation times from git ''' if not content.settings['GIT_FILETIME_FROM_GIT']: # Disabled for everything return if not string_to_bool(content.metadata.get('gittime', 'yes')): # Disable for this content ...
['def', 'filetime_from_git', '(', 'content', ',', 'git_content', ')', ':', 'if', 'not', 'content', '.', 'settings', '[', "'GIT_FILETIME_FROM_GIT'", ']', ':', '# Disabled for everything', 'return', 'if', 'not', 'string_to_bool', '(', 'content', '.', 'metadata', '.', 'get', '(', "'gittime'", ',', "'yes'", ')', ')', ':', ...
Update modification and creation times from git
['Update', 'modification', 'and', 'creation', 'times', 'from', 'git']
train
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/filetime_from_git/actions.py#L18-L66
7,789
mikedh/trimesh
trimesh/util.py
sigfig_round
def sigfig_round(values, sigfig=1): """ Round a single value to a specified number of significant figures. Parameters ---------- values: float, value to be rounded sigfig: int, number of significant figures to reduce to Returns ---------- rounded: values, but rounded to the specif...
python
def sigfig_round(values, sigfig=1): """ Round a single value to a specified number of significant figures. Parameters ---------- values: float, value to be rounded sigfig: int, number of significant figures to reduce to Returns ---------- rounded: values, but rounded to the specif...
['def', 'sigfig_round', '(', 'values', ',', 'sigfig', '=', '1', ')', ':', 'as_int', ',', 'multiplier', '=', 'sigfig_int', '(', 'values', ',', 'sigfig', ')', 'rounded', '=', 'as_int', '*', '(', '10', '**', 'multiplier', ')', 'return', 'rounded']
Round a single value to a specified number of significant figures. Parameters ---------- values: float, value to be rounded sigfig: int, number of significant figures to reduce to Returns ---------- rounded: values, but rounded to the specified number of significant figures Examples...
['Round', 'a', 'single', 'value', 'to', 'a', 'specified', 'number', 'of', 'significant', 'figures', '.']
train
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/util.py#L1555-L1584
7,790
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py
convert_softmax
def convert_softmax(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output...
python
def convert_softmax(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output...
['def', 'convert_softmax', '(', 'builder', ',', 'layer', ',', 'input_names', ',', 'output_names', ',', 'keras_layer', ')', ':', 'input_name', ',', 'output_name', '=', '(', 'input_names', '[', '0', ']', ',', 'output_names', '[', '0', ']', ')', 'builder', '.', 'add_softmax', '(', 'name', '=', 'layer', ',', 'input_name', ...
Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
['Convert', 'a', 'softmax', 'layer', 'from', 'keras', 'to', 'coreml', '.']
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers.py#L902-L916
7,791
viniciuschiele/flask-io
flask_io/tracing.py
Tracer.__default_emit_trace
def __default_emit_trace(self, data): """ Writes the given tracing data to Python Logging. :param data: The tracing data to be written. """ message = format_trace_data(data) self.io.logger.info(message)
python
def __default_emit_trace(self, data): """ Writes the given tracing data to Python Logging. :param data: The tracing data to be written. """ message = format_trace_data(data) self.io.logger.info(message)
['def', '__default_emit_trace', '(', 'self', ',', 'data', ')', ':', 'message', '=', 'format_trace_data', '(', 'data', ')', 'self', '.', 'io', '.', 'logger', '.', 'info', '(', 'message', ')']
Writes the given tracing data to Python Logging. :param data: The tracing data to be written.
['Writes', 'the', 'given', 'tracing', 'data', 'to', 'Python', 'Logging', '.']
train
https://github.com/viniciuschiele/flask-io/blob/4e559419b3d8e6859f83fa16557b00542d5f3aa7/flask_io/tracing.py#L99-L106
7,792
tamasgal/km3pipe
km3pipe/io/root.py
interpol_hist2d
def interpol_hist2d(h2d, oversamp_factor=10): """Sample the interpolator of a root 2d hist. Root's hist2d has a weird internal interpolation routine, also using neighbouring bins. """ from rootpy import ROOTError xlim = h2d.bins(axis=0) ylim = h2d.bins(axis=1) xn = h2d.nbins(0) yn ...
python
def interpol_hist2d(h2d, oversamp_factor=10): """Sample the interpolator of a root 2d hist. Root's hist2d has a weird internal interpolation routine, also using neighbouring bins. """ from rootpy import ROOTError xlim = h2d.bins(axis=0) ylim = h2d.bins(axis=1) xn = h2d.nbins(0) yn ...
['def', 'interpol_hist2d', '(', 'h2d', ',', 'oversamp_factor', '=', '10', ')', ':', 'from', 'rootpy', 'import', 'ROOTError', 'xlim', '=', 'h2d', '.', 'bins', '(', 'axis', '=', '0', ')', 'ylim', '=', 'h2d', '.', 'bins', '(', 'axis', '=', '1', ')', 'xn', '=', 'h2d', '.', 'nbins', '(', '0', ')', 'yn', '=', 'h2d', '.', 'nb...
Sample the interpolator of a root 2d hist. Root's hist2d has a weird internal interpolation routine, also using neighbouring bins.
['Sample', 'the', 'interpolator', 'of', 'a', 'root', '2d', 'hist', '.']
train
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/root.py#L70-L91
7,793
senaite/senaite.core
bika/lims/browser/worksheet/views/results.py
ManageResultsView.get_wide_interims
def get_wide_interims(self): """Returns a dictionary with the analyses services from the current worksheet which have at least one interim with 'Wide' attribute set to true and that have not been yet submitted The structure of the returned dictionary is the following: <Analysis_...
python
def get_wide_interims(self): """Returns a dictionary with the analyses services from the current worksheet which have at least one interim with 'Wide' attribute set to true and that have not been yet submitted The structure of the returned dictionary is the following: <Analysis_...
['def', 'get_wide_interims', '(', 'self', ')', ':', 'outdict', '=', '{', '}', 'allowed_states', '=', '[', "'assigned'", ',', "'unassigned'", ']', 'for', 'analysis', 'in', 'self', '.', 'context', '.', 'getAnalyses', '(', ')', ':', '# TODO Workflow - Analysis Use a query instead of this', 'if', 'api', '.', 'get_workflow_...
Returns a dictionary with the analyses services from the current worksheet which have at least one interim with 'Wide' attribute set to true and that have not been yet submitted The structure of the returned dictionary is the following: <Analysis_keyword>: { 'analysis': <Ana...
['Returns', 'a', 'dictionary', 'with', 'the', 'analyses', 'services', 'from', 'the', 'current', 'worksheet', 'which', 'have', 'at', 'least', 'one', 'interim', 'with', 'Wide', 'attribute', 'set', 'to', 'true', 'and', 'that', 'have', 'not', 'been', 'yet', 'submitted']
train
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/worksheet/views/results.py#L139-L190
7,794
python-cmd2/cmd2
cmd2/cmd2.py
Cmd.register_cmdfinalization_hook
def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: """Register a hook to be called after a command is completed, whether it completes successfully or not.""" self._v...
python
def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData], plugin.CommandFinalizationData]) -> None: """Register a hook to be called after a command is completed, whether it completes successfully or not.""" self._v...
['def', 'register_cmdfinalization_hook', '(', 'self', ',', 'func', ':', 'Callable', '[', '[', 'plugin', '.', 'CommandFinalizationData', ']', ',', 'plugin', '.', 'CommandFinalizationData', ']', ')', '->', 'None', ':', 'self', '.', '_validate_cmdfinalization_callable', '(', 'func', ')', 'self', '.', '_cmdfinalization_hoo...
Register a hook to be called after a command is completed, whether it completes successfully or not.
['Register', 'a', 'hook', 'to', 'be', 'called', 'after', 'a', 'command', 'is', 'completed', 'whether', 'it', 'completes', 'successfully', 'or', 'not', '.']
train
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/cmd2.py#L4050-L4054
7,795
brentp/skidmarks
skidmarks.py
auto_correlation
def auto_correlation(sequence): """ test for the autocorrelation of a sequence between t and t - 1 as the 'auto_correlation' it is less likely that the sequence is generated randomly. :param sequence: any iterable with at most 2 values that can be turned into a float via np.floa...
python
def auto_correlation(sequence): """ test for the autocorrelation of a sequence between t and t - 1 as the 'auto_correlation' it is less likely that the sequence is generated randomly. :param sequence: any iterable with at most 2 values that can be turned into a float via np.floa...
['def', 'auto_correlation', '(', 'sequence', ')', ':', 'if', 'isinstance', '(', 'sequence', ',', 'basestring', ')', ':', 'sequence', '=', 'map', '(', 'int', ',', 'sequence', ')', 'seq', '=', 'np', '.', 'array', '(', 'list', '(', 'sequence', ')', ',', 'dtype', '=', 'np', '.', 'float', ')', 'dseq', '=', 'np', '.', 'colum...
test for the autocorrelation of a sequence between t and t - 1 as the 'auto_correlation' it is less likely that the sequence is generated randomly. :param sequence: any iterable with at most 2 values that can be turned into a float via np.float . e.g. '1001001' ...
['test', 'for', 'the', 'autocorrelation', 'of', 'a', 'sequence', 'between', 't', 'and', 't', '-', '1', 'as', 'the', 'auto_correlation', 'it', 'is', 'less', 'likely', 'that', 'the', 'sequence', 'is', 'generated', 'randomly', '.', ':', 'param', 'sequence', ':', 'any', 'iterable', 'with', 'at', 'most', '2', 'values', 'tha...
train
https://github.com/brentp/skidmarks/blob/f63b9f1b822cb47991215b655155b5041e86ea39/skidmarks.py#L102-L129
7,796
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py
TransformSystem.dpi
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi
python
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi
['def', 'dpi', '(', 'self', ')', ':', 'if', 'self', '.', '_dpi', 'is', 'None', ':', 'if', 'self', '.', '_canvas', 'is', 'None', ':', 'return', 'None', 'else', ':', 'return', 'self', '.', 'canvas', '.', 'dpi', 'else', ':', 'return', 'self', '.', '_dpi']
Physical resolution of the document coordinate system (dots per inch).
['Physical', 'resolution', 'of', 'the', 'document', 'coordinate', 'system', '(', 'dots', 'per', 'inch', ')', '.']
train
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py#L241-L251
7,797
materialsproject/pymatgen
pymatgen/analysis/path_finder.py
StaticPotential.rescale_field
def rescale_field(self, new_dim): """ Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of th...
python
def rescale_field(self, new_dim): """ Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of th...
['def', 'rescale_field', '(', 'self', ',', 'new_dim', ')', ':', 'v_dim', '=', 'self', '.', '__v', '.', 'shape', 'padded_v', '=', 'np', '.', 'lib', '.', 'pad', '(', 'self', '.', '__v', ',', '(', '(', '0', ',', '1', ')', ',', '(', '0', ',', '1', ')', ',', '(', '0', ',', '1', ')', ')', ',', 'mode', '=', "'wrap'", ')', 'og...
Changes the discretization of the potential field by linear interpolation. This is necessary if the potential field obtained from DFT is strangely skewed, or is too fine or coarse. Obeys periodic boundary conditions at the edges of the cell. Alternatively useful for mixing potentials tha...
['Changes', 'the', 'discretization', 'of', 'the', 'potential', 'field', 'by', 'linear', 'interpolation', '.', 'This', 'is', 'necessary', 'if', 'the', 'potential', 'field', 'obtained', 'from', 'DFT', 'is', 'strangely', 'skewed', 'or', 'is', 'too', 'fine', 'or', 'coarse', '.', 'Obeys', 'periodic', 'boundary', 'conditions...
train
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/path_finder.py#L285-L310
7,798
nion-software/nionswift
nion/swift/Facade.py
ViewTask.close
def close(self) -> None: """Close the task. .. versionadded:: 1.0 This method must be called when the task is no longer needed. """ self.__data_channel_buffer.stop() self.__data_channel_buffer.close() self.__data_channel_buffer = None if not self.__was_p...
python
def close(self) -> None: """Close the task. .. versionadded:: 1.0 This method must be called when the task is no longer needed. """ self.__data_channel_buffer.stop() self.__data_channel_buffer.close() self.__data_channel_buffer = None if not self.__was_p...
['def', 'close', '(', 'self', ')', '->', 'None', ':', 'self', '.', '__data_channel_buffer', '.', 'stop', '(', ')', 'self', '.', '__data_channel_buffer', '.', 'close', '(', ')', 'self', '.', '__data_channel_buffer', '=', 'None', 'if', 'not', 'self', '.', '__was_playing', ':', 'self', '.', '__hardware_source', '.', 'stop...
Close the task. .. versionadded:: 1.0 This method must be called when the task is no longer needed.
['Close', 'the', 'task', '.']
train
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/Facade.py#L1613-L1624
7,799
romanorac/discomll
discomll/ensemble/core/k_medoids.py
fit
def fit(sim_mat, D_len, cidx): """ Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: ...
python
def fit(sim_mat, D_len, cidx): """ Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: ...
['def', 'fit', '(', 'sim_mat', ',', 'D_len', ',', 'cidx', ')', ':', 'min_energy', '=', 'np', '.', 'inf', 'for', 'j', 'in', 'range', '(', '3', ')', ':', '# select indices in each sample that maximizes its dimension', 'inds', '=', '[', 'np', '.', 'argmin', '(', '[', 'sim_mat', '[', 'idy', ']', '.', 'get', '(', 'idx', ','...
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters. D: numpy array - Symmetric distance matrix k: int - number of clusters
['Algorithm', 'maximizes', 'energy', 'between', 'clusters', 'which', 'is', 'distinction', 'in', 'this', 'algorithm', '.', 'Distance', 'matrix', 'contains', 'mostly', '0', 'which', 'are', 'overlooked', 'due', 'to', 'search', 'of', 'maximal', 'distances', '.', 'Algorithm', 'does', 'not', 'try', 'to', 'retain', 'k', 'clus...
train
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/k_medoids.py#L8-L41