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
2,000
yamcs/yamcs-python
yamcs-client/yamcs/archive/client.py
ArchiveClient.list_packets
def list_packets(self, name=None, start=None, stop=None, page_size=500, descending=False): """ Reads packet information between the specified start and stop time. Packets are sorted by generation time and sequence number. :param ~datetime.datetime start: Minimum generation time...
python
def list_packets(self, name=None, start=None, stop=None, page_size=500, descending=False): """ Reads packet information between the specified start and stop time. Packets are sorted by generation time and sequence number. :param ~datetime.datetime start: Minimum generation time...
['def', 'list_packets', '(', 'self', ',', 'name', '=', 'None', ',', 'start', '=', 'None', ',', 'stop', '=', 'None', ',', 'page_size', '=', '500', ',', 'descending', '=', 'False', ')', ':', 'params', '=', '{', "'order'", ':', "'desc'", 'if', 'descending', 'else', "'asc'", ',', '}', 'if', 'name', 'is', 'not', 'None', ':'...
Reads packet information between the specified start and stop time. Packets are sorted by generation time and sequence number. :param ~datetime.datetime start: Minimum generation time of the returned packets (inclusive) :param ~datetime.datetime...
['Reads', 'packet', 'information', 'between', 'the', 'specified', 'start', 'and', 'stop', 'time', '.']
train
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/archive/client.py#L222-L258
2,001
globocom/GloboNetworkAPI-client-python
networkapiclient/ApiV4Equipment.py
ApiV4Equipment.delete
def delete(self, ids): """ Method to delete equipments by their id's :param ids: Identifiers of equipments :return: None """ url = build_uri_with_ids('api/v4/equipment/%s/', ids) return super(ApiV4Equipment, self).delete(url)
python
def delete(self, ids): """ Method to delete equipments by their id's :param ids: Identifiers of equipments :return: None """ url = build_uri_with_ids('api/v4/equipment/%s/', ids) return super(ApiV4Equipment, self).delete(url)
['def', 'delete', '(', 'self', ',', 'ids', ')', ':', 'url', '=', 'build_uri_with_ids', '(', "'api/v4/equipment/%s/'", ',', 'ids', ')', 'return', 'super', '(', 'ApiV4Equipment', ',', 'self', ')', '.', 'delete', '(', 'url', ')']
Method to delete equipments by their id's :param ids: Identifiers of equipments :return: None
['Method', 'to', 'delete', 'equipments', 'by', 'their', 'id', 's']
train
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiV4Equipment.py#L65-L73
2,002
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py
brocade_firmware.logical_chassis_fwdl_status_output_overall_status
def logical_chassis_fwdl_status_output_overall_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status") config = logical_chassis_fwdl_status output = ET.SubElement(logical_chas...
python
def logical_chassis_fwdl_status_output_overall_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status") config = logical_chassis_fwdl_status output = ET.SubElement(logical_chas...
['def', 'logical_chassis_fwdl_status_output_overall_status', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'logical_chassis_fwdl_status', '=', 'ET', '.', 'Element', '(', '"logical_chassis_fwdl_status"', ')', 'config', '=', 'logical_chassis_fwdl_status', 'outp...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L840-L851
2,003
inasafe/inasafe
safe/gui/widgets/message_viewer.py
MessageViewer.generate_pdf
def generate_pdf(self): """Generate a PDF from the displayed content.""" printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path...
python
def generate_pdf(self): """Generate a PDF from the displayed content.""" printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path...
['def', 'generate_pdf', '(', 'self', ')', ':', 'printer', '=', 'QtGui', '.', 'QPrinter', '(', 'QtGui', '.', 'QPrinter', '.', 'HighResolution', ')', 'printer', '.', 'setPageSize', '(', 'QtGui', '.', 'QPrinter', '.', 'A4', ')', 'printer', '.', 'setColorMode', '(', 'QtGui', '.', 'QPrinter', '.', 'Color', ')', 'printer', '...
Generate a PDF from the displayed content.
['Generate', 'a', 'PDF', 'from', 'the', 'displayed', 'content', '.']
train
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/message_viewer.py#L378-L389
2,004
hydpy-dev/hydpy
hydpy/models/lland/lland_derived.py
KB.update
def update(self): """Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0) """ con = self.subpars.pars.contr...
python
def update(self): """Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0) """ con = self.subpars.pars.contr...
['def', 'update', '(', 'self', ')', ':', 'con', '=', 'self', '.', 'subpars', '.', 'pars', '.', 'control', 'self', '(', 'con', '.', 'eqb', '*', 'con', '.', 'tind', ')']
Update |KB| based on |EQB| and |TInd|. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb(10.0) >>> tind.value = 10.0 >>> derived.kb.update() >>> derived.kb kb(100.0)
['Update', '|KB|', 'based', 'on', '|EQB|', 'and', '|TInd|', '.']
train
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L112-L124
2,005
CivicSpleen/ckcache
ckcache/s3.py
S3Cache.list
def list(self, path=None, with_metadata=False, include_partitions=False): '''Get a list of all of bundle files in the cache. Does not return partition files''' import json sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix l = {} for e in self.bucket.list(...
python
def list(self, path=None, with_metadata=False, include_partitions=False): '''Get a list of all of bundle files in the cache. Does not return partition files''' import json sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix l = {} for e in self.bucket.list(...
['def', 'list', '(', 'self', ',', 'path', '=', 'None', ',', 'with_metadata', '=', 'False', ',', 'include_partitions', '=', 'False', ')', ':', 'import', 'json', 'sub_path', '=', 'self', '.', 'prefix', '+', "'/'", '+', 'path', '.', 'strip', '(', "'/'", ')', 'if', 'path', 'else', 'self', '.', 'prefix', 'l', '=', '{', '}',...
Get a list of all of bundle files in the cache. Does not return partition files
['Get', 'a', 'list', 'of', 'all', 'of', 'bundle', 'files', 'in', 'the', 'cache', '.', 'Does', 'not', 'return', 'partition', 'files']
train
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L440-L470
2,006
crocs-muni/roca
roca/detect.py
try_get_dn_string
def try_get_dn_string(subject, shorten=False): """ Returns DN as a string :param subject: :param shorten: :return: """ try: from cryptography.x509.oid import NameOID from cryptography.x509 import ObjectIdentifier oid_names = { getattr(NameOID, 'COMMON_NAME...
python
def try_get_dn_string(subject, shorten=False): """ Returns DN as a string :param subject: :param shorten: :return: """ try: from cryptography.x509.oid import NameOID from cryptography.x509 import ObjectIdentifier oid_names = { getattr(NameOID, 'COMMON_NAME...
['def', 'try_get_dn_string', '(', 'subject', ',', 'shorten', '=', 'False', ')', ':', 'try', ':', 'from', 'cryptography', '.', 'x509', '.', 'oid', 'import', 'NameOID', 'from', 'cryptography', '.', 'x509', 'import', 'ObjectIdentifier', 'oid_names', '=', '{', 'getattr', '(', 'NameOID', ',', "'COMMON_NAME'", ',', 'ObjectId...
Returns DN as a string :param subject: :param shorten: :return:
['Returns', 'DN', 'as', 'a', 'string', ':', 'param', 'subject', ':', ':', 'param', 'shorten', ':', ':', 'return', ':']
train
https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect.py#L237-L276
2,007
mwouts/jupytext
jupytext/cell_reader.py
LightScriptCellReader.find_region_end
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
python
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
['def', 'find_region_end', '(', 'self', ',', 'lines', ')', ':', 'if', 'self', '.', 'metadata', 'and', "'cell_type'", 'in', 'self', '.', 'metadata', ':', 'self', '.', 'cell_type', '=', 'self', '.', 'metadata', '.', 'pop', '(', "'cell_type'", ')', 'else', ':', 'self', '.', 'cell_type', '=', "'code'", 'parser', '=', 'Stri...
Find the end of the region started with start and end markers
['Find', 'the', 'end', 'of', 'the', 'region', 'started', 'with', 'start', 'and', 'end', 'markers']
train
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_reader.py#L509-L557
2,008
edx/pa11ycrawler
pa11ycrawler/pipelines/pa11y.py
ignore_rules_for_url
def ignore_rules_for_url(spider, url): """ Returns a list of ignore rules from the given spider, that are relevant to the given URL. """ ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {} return itertools.chain.from_iterable( rule_list for url_glob, rule_list ...
python
def ignore_rules_for_url(spider, url): """ Returns a list of ignore rules from the given spider, that are relevant to the given URL. """ ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {} return itertools.chain.from_iterable( rule_list for url_glob, rule_list ...
['def', 'ignore_rules_for_url', '(', 'spider', ',', 'url', ')', ':', 'ignore_rules', '=', 'getattr', '(', 'spider', ',', '"pa11y_ignore_rules"', ',', '{', '}', ')', 'or', '{', '}', 'return', 'itertools', '.', 'chain', '.', 'from_iterable', '(', 'rule_list', 'for', 'url_glob', ',', 'rule_list', 'in', 'ignore_rules', '.'...
Returns a list of ignore rules from the given spider, that are relevant to the given URL.
['Returns', 'a', 'list', 'of', 'ignore', 'rules', 'from', 'the', 'given', 'spider', 'that', 'are', 'relevant', 'to', 'the', 'given', 'URL', '.']
train
https://github.com/edx/pa11ycrawler/blob/fc672d4524463bc050ade4c7c97801c0d5bf8c9e/pa11ycrawler/pipelines/pa11y.py#L21-L32
2,009
a1ezzz/wasp-general
wasp_general/task/dependency.py
WTaskDependencyRegistryStorage.started_tasks
def started_tasks(self, task_registry_id=None, task_cls=None): """ Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will...
python
def started_tasks(self, task_registry_id=None, task_cls=None): """ Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will...
['def', 'started_tasks', '(', 'self', ',', 'task_registry_id', '=', 'None', ',', 'task_cls', '=', 'None', ')', ':', 'if', 'task_registry_id', 'is', 'not', 'None', ':', 'task', '=', 'None', 'for', 'registered_task', 'in', 'self', '.', '__started', ':', 'if', 'registered_task', '.', '__registry_tag__', '==', 'task_regist...
Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will be consists of this subclass only :return: None or WTask or tuple...
['Return', 'tasks', 'that', 'was', 'started', '.', 'Result', 'way', 'be', 'filtered', 'by', 'the', 'given', 'arguments', '.']
train
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L153-L178
2,010
xapple/plumbing
plumbing/common.py
sanitize_text
def sanitize_text(text): """Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace).""" # First replace characters that have specific effects with their repr # text = re.sub("(\s...
python
def sanitize_text(text): """Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace).""" # First replace characters that have specific effects with their repr # text = re.sub("(\s...
['def', 'sanitize_text', '(', 'text', ')', ':', '# First replace characters that have specific effects with their repr #', 'text', '=', 're', '.', 'sub', '(', '"(\\s)"', ',', 'lambda', 'm', ':', 'repr', '(', 'm', '.', 'group', '(', '0', ')', ')', '.', 'strip', '(', '"\'"', ')', ',', 'text', ')', '# Make it a unicode st...
Make a safe representation of a string. Note: the `\s` special character matches any whitespace character. This is equivalent to the set [\t\n\r\f\v] as well as ` ` (whitespace).
['Make', 'a', 'safe', 'representation', 'of', 'a', 'string', '.', 'Note', ':', 'the', '\\', 's', 'special', 'character', 'matches', 'any', 'whitespace', 'character', '.', 'This', 'is', 'equivalent', 'to', 'the', 'set', '[', '\\', 't', '\\', 'n', '\\', 'r', '\\', 'f', '\\', 'v', ']', 'as', 'well', 'as', '(', 'whitespace...
train
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L30-L41
2,011
benedictpaten/sonLib
tree.py
normaliseWV
def normaliseWV(wV, normFac=1.0): """ make char probs divisible by one """ f = sum(wV) / normFac return [ i/f for i in wV ]
python
def normaliseWV(wV, normFac=1.0): """ make char probs divisible by one """ f = sum(wV) / normFac return [ i/f for i in wV ]
['def', 'normaliseWV', '(', 'wV', ',', 'normFac', '=', '1.0', ')', ':', 'f', '=', 'sum', '(', 'wV', ')', '/', 'normFac', 'return', '[', 'i', '/', 'f', 'for', 'i', 'in', 'wV', ']']
make char probs divisible by one
['make', 'char', 'probs', 'divisible', 'by', 'one']
train
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L180-L185
2,012
erijo/tellcore-py
tellcore/telldus.py
DeviceFactory
def DeviceFactory(id, lib=None): """Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) re...
python
def DeviceFactory(id, lib=None): """Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance. """ lib = lib or Library() if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP: return DeviceGroup(id, lib=lib) re...
['def', 'DeviceFactory', '(', 'id', ',', 'lib', '=', 'None', ')', ':', 'lib', '=', 'lib', 'or', 'Library', '(', ')', 'if', 'lib', '.', 'tdGetDeviceType', '(', 'id', ')', '==', 'const', '.', 'TELLSTICK_TYPE_GROUP', ':', 'return', 'DeviceGroup', '(', 'id', ',', 'lib', '=', 'lib', ')', 'return', 'Device', '(', 'id', ',', ...
Create the correct device instance based on device type and return it. :return: a :class:`Device` or :class:`DeviceGroup` instance.
['Create', 'the', 'correct', 'device', 'instance', 'based', 'on', 'device', 'type', 'and', 'return', 'it', '.']
train
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L266-L274
2,013
vsoch/helpme
helpme/main/base/__init__.py
HelperBase.start
def start(self, positionals=None): '''start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user. '''...
python
def start(self, positionals=None): '''start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user. '''...
['def', 'start', '(', 'self', ',', 'positionals', '=', 'None', ')', ':', 'bot', '.', 'info', '(', "'[helpme|%s]'", '%', '(', 'self', '.', 'name', ')', ')', 'self', '.', 'speak', '(', ')', 'self', '.', '_start', '(', 'positionals', ')']
start the helper flow. We check helper system configurations to determine components that should be collected for the submission. This is where the client can also pass on any extra (positional) arguments in a list from the user.
['start', 'the', 'helper', 'flow', '.', 'We', 'check', 'helper', 'system', 'configurations', 'to', 'determine', 'components', 'that', 'should', 'be', 'collected', 'for', 'the', 'submission', '.', 'This', 'is', 'where', 'the', 'client', 'can', 'also', 'pass', 'on', 'any', 'extra', '(', 'positional', ')', 'arguments', 'i...
train
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/__init__.py#L105-L113
2,014
pmacosta/pcsv
pcsv/dsort.py
dsort
def dsort(fname, order, has_header=True, frow=0, ofname=None): r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the com...
python
def dsort(fname, order, has_header=True, frow=0, ofname=None): r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the com...
['def', 'dsort', '(', 'fname', ',', 'order', ',', 'has_header', '=', 'True', ',', 'frow', '=', '0', ',', 'ofname', '=', 'None', ')', ':', 'ofname', '=', 'fname', 'if', 'ofname', 'is', 'None', 'else', 'ofname', 'obj', '=', 'CsvFile', '(', 'fname', '=', 'fname', ',', 'has_header', '=', 'has_header', ',', 'frow', '=', 'fr...
r""" Sort file data. :param fname: Name of the comma-separated values file to sort :type fname: FileNameExists_ :param order: Sort order :type order: :ref:`CsvColFilter` :param has_header: Flag that indicates whether the comma-separated values file to sort has column ...
['r', 'Sort', 'file', 'data', '.']
train
https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/dsort.py#L37-L93
2,015
secdev/scapy
scapy/asn1/mib.py
_mib_register
def _mib_register(ident, value, the_mib, unresolved): """Internal function used to register an OID and its name in a MIBDict""" if ident in the_mib or ident in unresolved: return ident in the_mib resval = [] not_resolved = 0 for v in value: if _mib_re_integer.match(v): re...
python
def _mib_register(ident, value, the_mib, unresolved): """Internal function used to register an OID and its name in a MIBDict""" if ident in the_mib or ident in unresolved: return ident in the_mib resval = [] not_resolved = 0 for v in value: if _mib_re_integer.match(v): re...
['def', '_mib_register', '(', 'ident', ',', 'value', ',', 'the_mib', ',', 'unresolved', ')', ':', 'if', 'ident', 'in', 'the_mib', 'or', 'ident', 'in', 'unresolved', ':', 'return', 'ident', 'in', 'the_mib', 'resval', '=', '[', ']', 'not_resolved', '=', '0', 'for', 'v', 'in', 'value', ':', 'if', '_mib_re_integer', '.', '...
Internal function used to register an OID and its name in a MIBDict
['Internal', 'function', 'used', 'to', 'register', 'an', 'OID', 'and', 'its', 'name', 'in', 'a', 'MIBDict']
train
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/asn1/mib.py#L91-L128
2,016
OpenHydrology/floodestimation
floodestimation/analysis.py
GrowthCurveAnalysis.find_donor_catchments
def find_donor_catchments(self, include_subject_catchment='auto'): """ Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` ...
python
def find_donor_catchments(self, include_subject_catchment='auto'): """ Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` ...
['def', 'find_donor_catchments', '(', 'self', ',', 'include_subject_catchment', '=', "'auto'", ')', ':', '# Only if we have access to db with gauged catchment data', 'if', 'self', '.', 'gauged_cachments', ':', 'self', '.', 'donor_catchments', '=', 'self', '.', 'gauged_cachments', '.', 'most_similar_catchments', '(', 's...
Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` is set manually. The results are stored in :attr:`.donor_catchments`. The (lis...
['Find', 'list', 'of', 'suitable', 'donor', 'cachments', 'ranked', 'by', 'hydrological', 'similarity', 'distance', 'measure', '.', 'This', 'method', 'is', 'implicitly', 'called', 'when', 'calling', 'the', ':', 'meth', ':', '.', 'growth_curve', 'method', 'unless', 'the', 'attribute', ':', 'attr', ':', '.', 'donor_catchm...
train
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L897-L920
2,017
Duke-QCD/hic
hic/flow.py
Sampler.sample
def sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not...
python
def sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not...
['def', 'sample', '(', 'self', ',', 'multiplicity', ')', ':', 'if', 'self', '.', '_n', 'is', 'None', ':', 'return', 'self', '.', '_uniform_phi', '(', 'multiplicity', ')', '# Since the flow PDF does not have an analytic inverse CDF, I use a', '# simple accept-reject sampling algorithm. This is reasonably', '# efficient...
r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles.
['r', 'Randomly', 'sample', 'azimuthal', 'angles', '\\', 'phi', '.']
train
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L319-L354
2,018
Dallinger/Dallinger
dallinger/db.py
init_db
def init_db(drop_all=False, bind=engine): """Initialize the database, optionally dropping existing tables.""" try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = 'password authentication failed for ...
python
def init_db(drop_all=False, bind=engine): """Initialize the database, optionally dropping existing tables.""" try: if drop_all: Base.metadata.drop_all(bind=bind) Base.metadata.create_all(bind=bind) except OperationalError as err: msg = 'password authentication failed for ...
['def', 'init_db', '(', 'drop_all', '=', 'False', ',', 'bind', '=', 'engine', ')', ':', 'try', ':', 'if', 'drop_all', ':', 'Base', '.', 'metadata', '.', 'drop_all', '(', 'bind', '=', 'bind', ')', 'Base', '.', 'metadata', '.', 'create_all', '(', 'bind', '=', 'bind', ')', 'except', 'OperationalError', 'as', 'err', ':', '...
Initialize the database, optionally dropping existing tables.
['Initialize', 'the', 'database', 'optionally', 'dropping', 'existing', 'tables', '.']
train
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L104-L116
2,019
sdispater/eloquent
eloquent/migrations/migration_creator.py
MigrationCreator._populate_stub
def _populate_stub(self, name, stub, table): """ Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype:...
python
def _populate_stub(self, name, stub, table): """ Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype:...
['def', '_populate_stub', '(', 'self', ',', 'name', ',', 'stub', ',', 'table', ')', ':', 'stub', '=', 'stub', '.', 'replace', '(', "'DummyClass'", ',', 'self', '.', '_get_class_name', '(', 'name', ')', ')', 'if', 'table', 'is', 'not', 'None', ':', 'stub', '=', 'stub', '.', 'replace', '(', "'dummy_table'", ',', 'table',...
Populate the placeholders in the migration stub. :param name: The name of the migration :type name: str :param stub: The stub :type stub: str :param table: The table name :type table: str :rtype: str
['Populate', 'the', 'placeholders', 'in', 'the', 'migration', 'stub', '.']
train
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/migrations/migration_creator.py#L70-L90
2,020
nickmasster/xsmtplib
xsmtplib/xsmtplib.py
SMTP.connect_proxy
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0): """Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix w...
python
def connect_proxy(self, proxy_host='localhost', proxy_port=0, proxy_type=socks.HTTP, host='localhost', port=0): """Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix w...
['def', 'connect_proxy', '(', 'self', ',', 'proxy_host', '=', "'localhost'", ',', 'proxy_port', '=', '0', ',', 'proxy_type', '=', 'socks', '.', 'HTTP', ',', 'host', '=', "'localhost'", ',', 'port', '=', '0', ')', ':', 'if', 'proxy_type', 'not', 'in', 'socks', '.', 'DEFAULT_PORTS', '.', 'keys', '(', ')', ':', 'raise', '...
Connect to a host on a given port via proxy server If the hostname ends with a colon (`:') followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use. Note: This method is automatically invoked by __init__...
['Connect', 'to', 'a', 'host', 'on', 'a', 'given', 'port', 'via', 'proxy', 'server']
train
https://github.com/nickmasster/xsmtplib/blob/0207f5c72f2fec03f3ebdb3acb3a56401805f32f/xsmtplib/xsmtplib.py#L132-L183
2,021
ScienceLogic/amiuploader
amiimporter/AWSUtilities.py
AWSUtils.validate_bucket
def validate_bucket(self): """ Do a quick check to see if the s3 bucket is valid :return: """ s3_check_cmd = "aws s3 ls s3://{} --profile '{}' --region '{}'".format(self.bucket_name, self.aws_project, ...
python
def validate_bucket(self): """ Do a quick check to see if the s3 bucket is valid :return: """ s3_check_cmd = "aws s3 ls s3://{} --profile '{}' --region '{}'".format(self.bucket_name, self.aws_project, ...
['def', 'validate_bucket', '(', 'self', ')', ':', 's3_check_cmd', '=', '"aws s3 ls s3://{} --profile \'{}\' --region \'{}\'"', '.', 'format', '(', 'self', '.', 'bucket_name', ',', 'self', '.', 'aws_project', ',', 'self', '.', 'aws_regions', '[', '0', ']', ')', 'print', '"Checking for s3 bucket"', 'try', ':', 'subproces...
Do a quick check to see if the s3 bucket is valid :return:
['Do', 'a', 'quick', 'check', 'to', 'see', 'if', 'the', 's3', 'bucket', 'is', 'valid', ':', 'return', ':']
train
https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L83-L97
2,022
addisonlynch/iexfinance
iexfinance/__init__.py
get_available_symbols
def get_available_symbols(**kwargs): """ MOVED to iexfinance.refdata.get_symbols """ import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) respons...
python
def get_available_symbols(**kwargs): """ MOVED to iexfinance.refdata.get_symbols """ import warnings warnings.warn(WNG_MSG % ("get_available_symbols", "refdata.get_symbols")) _ALL_SYMBOLS_URL = "https://api.iextrading.com/1.0/ref-data/symbols" handler = _IEXBase(**kwargs) respons...
['def', 'get_available_symbols', '(', '*', '*', 'kwargs', ')', ':', 'import', 'warnings', 'warnings', '.', 'warn', '(', 'WNG_MSG', '%', '(', '"get_available_symbols"', ',', '"refdata.get_symbols"', ')', ')', '_ALL_SYMBOLS_URL', '=', '"https://api.iextrading.com/1.0/ref-data/symbols"', 'handler', '=', '_IEXBase', '(', '...
MOVED to iexfinance.refdata.get_symbols
['MOVED', 'to', 'iexfinance', '.', 'refdata', '.', 'get_symbols']
train
https://github.com/addisonlynch/iexfinance/blob/40f0bdcc51b329031d06178020fd774494250456/iexfinance/__init__.py#L73-L85
2,023
inveniosoftware/invenio-search
invenio_search/ext.py
_SearchState.flush_and_refresh
def flush_and_refresh(self, index): """Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests. """ self.client.indices.flush(wait_if_ongoing=True, index...
python
def flush_and_refresh(self, index): """Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests. """ self.client.indices.flush(wait_if_ongoing=True, index...
['def', 'flush_and_refresh', '(', 'self', ',', 'index', ')', ':', 'self', '.', 'client', '.', 'indices', '.', 'flush', '(', 'wait_if_ongoing', '=', 'True', ',', 'index', '=', 'index', ')', 'self', '.', 'client', '.', 'indices', '.', 'refresh', '(', 'index', '=', 'index', ')', 'self', '.', 'client', '.', 'cluster', '.',...
Flush and refresh one or more indices. .. warning:: Do not call this method unless you know what you are doing. This method is only intended to be called during tests.
['Flush', 'and', 'refresh', 'one', 'or', 'more', 'indices', '.']
train
https://github.com/inveniosoftware/invenio-search/blob/19c073d608d4c811f1c5aecb6622402d39715228/invenio_search/ext.py#L221-L233
2,024
seibert-media/Highton
highton/fields/field.py
Field.encode
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element...
python
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element...
['def', 'encode', '(', 'self', ')', ':', 'element', '=', 'ElementTree', '.', 'Element', '(', 'self', '.', 'name', ')', 'element', '=', 'self', '.', '_set_nil', '(', 'element', ',', 'lambda', 'value', ':', 'str', '(', 'value', ')', ')', 'return', 'element']
Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element
['Encodes', 'the', 'value', 'of', 'the', 'field', 'and', 'put', 'it', 'in', 'the', 'element', 'also', 'make', 'the', 'check', 'for', 'nil', '=', 'true', 'if', 'there', 'is', 'one']
train
https://github.com/seibert-media/Highton/blob/1519e4fb105f62882c2e7bc81065d994649558d8/highton/fields/field.py#L18-L28
2,025
etingof/pysnmp
pysnmp/smi/mibs/SNMPv2-SMI.py
MibTableColumn.destroyCommit
def destroyCommit(self, varBind, **context): """Destroy Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually remove requested Managed Object ...
python
def destroyCommit(self, varBind, **context): """Destroy Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually remove requested Managed Object ...
['def', 'destroyCommit', '(', 'self', ',', 'varBind', ',', '*', '*', 'context', ')', ':', 'name', ',', 'val', '=', 'varBind', '(', 'debug', '.', 'logger', '&', 'debug', '.', 'FLAG_INS', 'and', 'debug', '.', 'logger', '(', "'%s: destroyCommit(%s, %r)'", '%', '(', 'self', ',', 'name', ',', 'val', ')', ')', ')', 'instance...
Destroy Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually remove requested Managed Object Instance from the MIB tree. When multiple Managed Object...
['Destroy', 'Managed', 'Object', 'Instance', '.']
train
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L2267-L2327
2,026
475Cumulus/TBone
tbone/data/models.py
ModelSerializer.serialize
async def serialize(self, native=False): ''' Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False`` ...
python
async def serialize(self, native=False): ''' Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False`` ...
['async', 'def', 'serialize', '(', 'self', ',', 'native', '=', 'False', ')', ':', 'data', '=', '{', '}', '# iterate through all fields', 'for', 'field_name', ',', 'field', 'in', 'self', '.', '_fields', '.', 'items', '(', ')', ':', '# serialize field data', 'raw_data', '=', 'self', '.', '_data', '.', 'get', '(', 'field_...
Returns a serialized from of the model taking into account projection rules and ``@serialize`` decorated methods. :param native: Deternines if data is serialized to Python native types or primitive form. Defaults to ``False``
['Returns', 'a', 'serialized', 'from', 'of', 'the', 'model', 'taking', 'into', 'account', 'projection', 'rules', 'and']
train
https://github.com/475Cumulus/TBone/blob/5a6672d8bbac449a0ab9e99560609f671fe84d4d/tbone/data/models.py#L134-L157
2,027
saltstack/salt
salt/modules/vsphere.py
vsan_add_disks
def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None): ''' Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. p...
python
def vsan_add_disks(host, username, password, protocol=None, port=None, host_names=None): ''' Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. p...
['def', 'vsan_add_disks', '(', 'host', ',', 'username', ',', 'password', ',', 'protocol', '=', 'None', ',', 'port', '=', 'None', ',', 'host_names', '=', 'None', ')', ':', 'service_instance', '=', 'salt', '.', 'utils', '.', 'vmware', '.', 'get_service_instance', '(', 'host', '=', 'host', ',', 'username', '=', 'username'...
Add any VSAN-eligible disks to the VSAN System for the given host or list of host_names. host The location of the host. username The username used to login to the host, such as ``root``. password The password used to login to the host. protocol Optionally set to alter...
['Add', 'any', 'VSAN', '-', 'eligible', 'disks', 'to', 'the', 'VSAN', 'System', 'for', 'the', 'given', 'host', 'or', 'list', 'of', 'host_names', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L3367-L3469
2,028
materialsproject/pymatgen
pymatgen/io/abinit/nodes.py
Node.isinstance
def isinstance(self, class_or_string): """ Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive). ...
python
def isinstance(self, class_or_string): """ Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive). ...
['def', 'isinstance', '(', 'self', ',', 'class_or_string', ')', ':', 'if', 'class_or_string', 'is', 'None', ':', 'return', 'False', 'import', 'inspect', 'if', 'inspect', '.', 'isclass', '(', 'class_or_string', ')', ':', 'return', 'isinstance', '(', 'self', ',', 'class_or_string', ')', 'else', ':', 'return', 'self', '.'...
Check whether the node is a instance of `class_or_string`. Unlinke the standard isinstance builtin, the method accepts either a class or a string. In the later case, the string is compared with self.__class__.__name__ (case insensitive).
['Check', 'whether', 'the', 'node', 'is', 'a', 'instance', 'of', 'class_or_string', '.', 'Unlinke', 'the', 'standard', 'isinstance', 'builtin', 'the', 'method', 'accepts', 'either', 'a', 'class', 'or', 'a', 'string', '.', 'In', 'the', 'later', 'case', 'the', 'string', 'is', 'compared', 'with', 'self', '.', '__class__',...
train
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/nodes.py#L537-L549
2,029
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/common/sever_handler.py
UnixProcessHandler.launch_process
def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self....
python
def launch_process(self, command): # type: (Union[bytes,text_type])->None """* What you can do - It starts process and keep it. """ if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self....
['def', 'launch_process', '(', 'self', ',', 'command', ')', ':', '# type: (Union[bytes,text_type])->None', 'if', 'not', 'self', '.', 'option', 'is', 'None', ':', 'command_plus_option', '=', 'self', '.', 'command', '+', '" "', '+', 'self', '.', 'option', 'else', ':', 'command_plus_option', '=', 'self', '.', 'command', '...
* What you can do - It starts process and keep it.
['*', 'What', 'you', 'can', 'do', '-', 'It', 'starts', 'process', 'and', 'keep', 'it', '.']
train
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/common/sever_handler.py#L44-L67
2,030
splunk/splunk-sdk-python
splunklib/binding.py
ResponseReader.read
def read(self, size = None): """Reads a given number of characters from the response. :param size: The number of characters to read, or "None" to read the entire response. :type size: ``integer`` or "None" """ r = self._buffer self._buffer = b'' if s...
python
def read(self, size = None): """Reads a given number of characters from the response. :param size: The number of characters to read, or "None" to read the entire response. :type size: ``integer`` or "None" """ r = self._buffer self._buffer = b'' if s...
['def', 'read', '(', 'self', ',', 'size', '=', 'None', ')', ':', 'r', '=', 'self', '.', '_buffer', 'self', '.', '_buffer', '=', "b''", 'if', 'size', 'is', 'not', 'None', ':', 'size', '-=', 'len', '(', 'r', ')', 'r', '=', 'r', '+', 'self', '.', '_response', '.', 'read', '(', 'size', ')', 'return', 'r']
Reads a given number of characters from the response. :param size: The number of characters to read, or "None" to read the entire response. :type size: ``integer`` or "None"
['Reads', 'a', 'given', 'number', 'of', 'characters', 'from', 'the', 'response', '.']
train
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1303-L1316
2,031
woolfson-group/isambard
isambard/ampal/protein.py
Polypeptide.valid_backbone_bond_lengths
def valid_backbone_bond_lengths(self, atol=0.1): """True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of ...
python
def valid_backbone_bond_lengths(self, atol=0.1): """True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of ...
['def', 'valid_backbone_bond_lengths', '(', 'self', ',', 'atol', '=', '0.1', ')', ':', 'bond_lengths', '=', 'self', '.', 'backbone_bond_lengths', 'a1', '=', 'numpy', '.', 'allclose', '(', 'bond_lengths', '[', "'n_ca'", ']', ',', '[', 'ideal_backbone_bond_lengths', '[', "'n_ca'", ']', ']', '*', 'len', '(', 'self', ')', ...
True if all backbone bonds are within atol Angstroms of the expected distance. Notes ----- Ideal bond lengths taken from [1]. References ---------- .. [1] Schulz, G. E, and R. Heiner Schirmer. Principles Of Protein Structure. New York: Springer-Verlag, 1979. ...
['True', 'if', 'all', 'backbone', 'bonds', 'are', 'within', 'atol', 'Angstroms', 'of', 'the', 'expected', 'distance', '.']
train
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/protein.py#L891-L923
2,032
saltstack/salt
salt/utils/schedule.py
Schedule.run_job
def run_job(self, name): ''' Run a schedule job now ''' data = self._get_schedule().get(name, {}) if 'function' in data: func = data['function'] elif 'func' in data: func = data['func'] elif 'fun' in data: func = data['fun'] ...
python
def run_job(self, name): ''' Run a schedule job now ''' data = self._get_schedule().get(name, {}) if 'function' in data: func = data['function'] elif 'func' in data: func = data['func'] elif 'fun' in data: func = data['fun'] ...
['def', 'run_job', '(', 'self', ',', 'name', ')', ':', 'data', '=', 'self', '.', '_get_schedule', '(', ')', '.', 'get', '(', 'name', ',', '{', '}', ')', 'if', "'function'", 'in', 'data', ':', 'func', '=', 'data', '[', "'function'", ']', 'elif', "'func'", 'in', 'data', ':', 'func', '=', 'data', '[', "'func'", ']', 'elif...
Run a schedule job now
['Run', 'a', 'schedule', 'job', 'now']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schedule.py#L440-L470
2,033
numenta/htmresearch
projects/l2_pooling/continuous_location.py
runBasic
def runBasic(noiseLevel=None, profile=False): """ Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inferen...
python
def runBasic(noiseLevel=None, profile=False): """ Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inferen...
['def', 'runBasic', '(', 'noiseLevel', '=', 'None', ',', 'profile', '=', 'False', ')', ':', 'exp', '=', 'L4L2Experiment', '(', '"basic_continuous"', ',', 'numCorticalColumns', '=', '2', ')', 'objects', '=', 'createObjectMachine', '(', 'machineType', '=', '"continuous"', ',', 'numInputBits', '=', '21', ',', 'sensorInput...
Runs a basic experiment on continuous locations, learning a few locations on four basic objects, and inferring one of them. This experiment is mostly used for testing the pipeline, as the learned locations are too random and sparse to actually perform inference. Parameters: ---------------------------- @p...
['Runs', 'a', 'basic', 'experiment', 'on', 'continuous', 'locations', 'learning', 'a', 'few', 'locations', 'on', 'four', 'basic', 'objects', 'and', 'inferring', 'one', 'of', 'them', '.']
train
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/l2_pooling/continuous_location.py#L35-L107
2,034
agoragames/kairos
kairos/sql_backend.py
SqlGauge._insert_data
def _insert_data(self, name, value, timestamp, interval, config, **kwargs): '''Helper to insert data into sql.''' conn = self._client.connect() if not self._update_data(name, value, timestamp, interval, config, conn): try: kwargs = { 'name' : name, 'interval' : in...
python
def _insert_data(self, name, value, timestamp, interval, config, **kwargs): '''Helper to insert data into sql.''' conn = self._client.connect() if not self._update_data(name, value, timestamp, interval, config, conn): try: kwargs = { 'name' : name, 'interval' : in...
['def', '_insert_data', '(', 'self', ',', 'name', ',', 'value', ',', 'timestamp', ',', 'interval', ',', 'config', ',', '*', '*', 'kwargs', ')', ':', 'conn', '=', 'self', '.', '_client', '.', 'connect', '(', ')', 'if', 'not', 'self', '.', '_update_data', '(', 'name', ',', 'value', ',', 'timestamp', ',', 'interval', ',',...
Helper to insert data into sql.
['Helper', 'to', 'insert', 'data', 'into', 'sql', '.']
train
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/sql_backend.py#L508-L526
2,035
senaite/senaite.core
bika/lims/browser/widgets/referenceresultswidget.py
ReferenceResultsWidget.process_form
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, m...
python
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False): """Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, m...
['def', 'process_form', '(', 'self', ',', 'instance', ',', 'field', ',', 'form', ',', 'empty_marker', '=', 'None', ',', 'emptyReturnsMarker', '=', 'False', ')', ':', 'values', '=', '{', '}', '# Process settings from the reference definition first', 'ref_def', '=', 'form', '.', 'get', '(', '"ReferenceDefinition"', ')', ...
Return a list of dictionaries fit for ReferenceResultsField consumption. Only services which have float()able entries in result,min and max field will be included. If any of min, max, or result fields are blank, the row value is ignored here.
['Return', 'a', 'list', 'of', 'dictionaries', 'fit', 'for', 'ReferenceResultsField', 'consumption', '.', 'Only', 'services', 'which', 'have', 'float', '()', 'able', 'entries', 'in', 'result', 'min', 'and', 'max', 'field', 'will', 'be', 'included', '.', 'If', 'any', 'of', 'min', 'max', 'or', 'result', 'fields', 'are', '...
train
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/referenceresultswidget.py#L197-L239
2,036
Erotemic/utool
utool/util_path.py
touch
def touch(fpath, times=None, verbose=True): r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None ...
python
def touch(fpath, times=None, verbose=True): r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None ...
['def', 'touch', '(', 'fpath', ',', 'times', '=', 'None', ',', 'verbose', '=', 'True', ')', ':', 'try', ':', 'if', 'verbose', ':', 'print', '(', "'[util_path] touching %r'", '%', 'fpath', ')', 'with', 'open', '(', 'fpath', ',', "'a'", ')', ':', 'os', '.', 'utime', '(', 'fpath', ',', 'times', ')', 'except', 'Exception',...
r""" Creates file if it doesnt exist Args: fpath (str): file path times (None): verbose (bool): Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> fpath = '?' >>> times = None >>> verbose = True >>> result = ...
['r', 'Creates', 'file', 'if', 'it', 'doesnt', 'exist']
train
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_path.py#L672-L702
2,037
eyurtsev/fcsparser
fcsparser/api.py
FCSParser.get_channel_names
def get_channel_names(self): """Get list of channel names. Raises a warning if the names are not unique.""" names_s, names_n = self.channel_names_s, self.channel_names_n # Figure out which channel names to use if self._channel_naming == '$PnS': channel_names, channel_names_a...
python
def get_channel_names(self): """Get list of channel names. Raises a warning if the names are not unique.""" names_s, names_n = self.channel_names_s, self.channel_names_n # Figure out which channel names to use if self._channel_naming == '$PnS': channel_names, channel_names_a...
['def', 'get_channel_names', '(', 'self', ')', ':', 'names_s', ',', 'names_n', '=', 'self', '.', 'channel_names_s', ',', 'self', '.', 'channel_names_n', '# Figure out which channel names to use', 'if', 'self', '.', '_channel_naming', '==', "'$PnS'", ':', 'channel_names', ',', 'channel_names_alternate', '=', 'names_s', ...
Get list of channel names. Raises a warning if the names are not unique.
['Get', 'list', 'of', 'channel', 'names', '.', 'Raises', 'a', 'warning', 'if', 'the', 'names', 'are', 'not', 'unique', '.']
train
https://github.com/eyurtsev/fcsparser/blob/710e8e31d4b09ff6e73d47d86770be6ca2f4282c/fcsparser/api.py#L327-L353
2,038
thunder-project/thunder
thunder/series/series.py
Series.max
def max(self): """ Compute the max across records. """ return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True))
python
def max(self): """ Compute the max across records. """ return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True))
['def', 'max', '(', 'self', ')', ':', 'return', 'self', '.', '_constructor', '(', 'self', '.', 'values', '.', 'max', '(', 'axis', '=', 'self', '.', 'baseaxes', ',', 'keepdims', '=', 'True', ')', ')']
Compute the max across records.
['Compute', 'the', 'max', 'across', 'records', '.']
train
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/series.py#L239-L243
2,039
DavidLP/pilight
pilight/pilight.py
Client.run
def run(self): # Thread for receiving data from pilight """Receiver thread function called on Client.start().""" logging.debug('Pilight receiver thread started') if not self.callback: raise RuntimeError('No callback function set, cancel readout thread') def handle_messages(...
python
def run(self): # Thread for receiving data from pilight """Receiver thread function called on Client.start().""" logging.debug('Pilight receiver thread started') if not self.callback: raise RuntimeError('No callback function set, cancel readout thread') def handle_messages(...
['def', 'run', '(', 'self', ')', ':', '# Thread for receiving data from pilight', 'logging', '.', 'debug', '(', "'Pilight receiver thread started'", ')', 'if', 'not', 'self', '.', 'callback', ':', 'raise', 'RuntimeError', '(', "'No callback function set, cancel readout thread'", ')', 'def', 'handle_messages', '(', 'mes...
Receiver thread function called on Client.start().
['Receiver', 'thread', 'function', 'called', 'on', 'Client', '.', 'start', '()', '.']
train
https://github.com/DavidLP/pilight/blob/a319404034e761892a89c7205b6f1aff6ad8e205/pilight/pilight.py#L123-L154
2,040
Gandi/gandi.cli
gandi/cli/core/conf.py
GandiConfig.load_config
def load_config(cls): """ Load global and local configuration files and update if needed.""" config_file = os.path.expanduser(cls.home_config) global_conf = cls.load(config_file, 'global') cls.load(cls.local_config, 'local') # update global configuration if needed cls.upd...
python
def load_config(cls): """ Load global and local configuration files and update if needed.""" config_file = os.path.expanduser(cls.home_config) global_conf = cls.load(config_file, 'global') cls.load(cls.local_config, 'local') # update global configuration if needed cls.upd...
['def', 'load_config', '(', 'cls', ')', ':', 'config_file', '=', 'os', '.', 'path', '.', 'expanduser', '(', 'cls', '.', 'home_config', ')', 'global_conf', '=', 'cls', '.', 'load', '(', 'config_file', ',', "'global'", ')', 'cls', '.', 'load', '(', 'cls', '.', 'local_config', ',', "'local'", ')', '# update global configu...
Load global and local configuration files and update if needed.
['Load', 'global', 'and', 'local', 'configuration', 'files', 'and', 'update', 'if', 'needed', '.']
train
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/conf.py#L40-L46
2,041
hatemile/hatemile-for-python
setup.py
get_packages
def get_packages(): """ Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str) """ packages = find_packages(exclude=['tests']) packages.append('') packages.append('js') packages.append(LOCALES_DIRECTORY) for dir...
python
def get_packages(): """ Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str) """ packages = find_packages(exclude=['tests']) packages.append('') packages.append('js') packages.append(LOCALES_DIRECTORY) for dir...
['def', 'get_packages', '(', ')', ':', 'packages', '=', 'find_packages', '(', 'exclude', '=', '[', "'tests'", ']', ')', 'packages', '.', 'append', '(', "''", ')', 'packages', '.', 'append', '(', "'js'", ')', 'packages', '.', 'append', '(', 'LOCALES_DIRECTORY', ')', 'for', 'directory', 'in', 'os', '.', 'listdir', '(', '...
Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str)
['Returns', 'the', 'packages', 'used', 'for', 'HaTeMiLe', 'for', 'Python', '.']
train
https://github.com/hatemile/hatemile-for-python/blob/1e914f9aa09f6f8d78282af131311546ecba9fb8/setup.py#L42-L57
2,042
apache/incubator-mxnet
python/mxnet/autograd.py
get_symbol
def get_symbol(x): """Retrieve recorded computation history as `Symbol`. Parameters ---------- x : NDArray Array representing the head of computation graph. Returns ------- Symbol The retrieved Symbol. """ hdl = SymbolHandle() check_call(_LIB.MXAutogradGetSymbol...
python
def get_symbol(x): """Retrieve recorded computation history as `Symbol`. Parameters ---------- x : NDArray Array representing the head of computation graph. Returns ------- Symbol The retrieved Symbol. """ hdl = SymbolHandle() check_call(_LIB.MXAutogradGetSymbol...
['def', 'get_symbol', '(', 'x', ')', ':', 'hdl', '=', 'SymbolHandle', '(', ')', 'check_call', '(', '_LIB', '.', 'MXAutogradGetSymbol', '(', 'x', '.', 'handle', ',', 'ctypes', '.', 'byref', '(', 'hdl', ')', ')', ')', 'return', 'Symbol', '(', 'hdl', ')']
Retrieve recorded computation history as `Symbol`. Parameters ---------- x : NDArray Array representing the head of computation graph. Returns ------- Symbol The retrieved Symbol.
['Retrieve', 'recorded', 'computation', 'history', 'as', 'Symbol', '.']
train
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/autograd.py#L347-L362
2,043
KnuVerse/knuverse-sdk-python
knuverse/knufactor.py
Knufactor.verification_start
def verification_start( self, client, mode=None, verification_speed=None, row_doubling="off", phone_number=None, ): """ Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name ...
python
def verification_start( self, client, mode=None, verification_speed=None, row_doubling="off", phone_number=None, ): """ Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name ...
['def', 'verification_start', '(', 'self', ',', 'client', ',', 'mode', '=', 'None', ',', 'verification_speed', '=', 'None', ',', 'row_doubling', '=', '"off"', ',', 'phone_number', '=', 'None', ',', ')', ':', 'data', '=', '{', '"name"', ':', 'client', ',', '"user_agent"', ':', '"knuverse-sdk-python-v%s"', '%', 'self', '...
Start a verification. Uses POST to /verifications interface. :Args: * *client*: (str) Client's Name * *mode*: (str) Verification Mode. Allowed values: "audiopin", "audiopass" * *verification_speed*: (int) Allowed values: 0, 25, 50, 75, 100 * *row_doubling*: (str...
['Start', 'a', 'verification', '.', 'Uses', 'POST', 'to', '/', 'verifications', 'interface', '.']
train
https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L821-L860
2,044
luismsgomes/openfile
src/openfile.py
openfile
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False, makedirs=False, **kwargs): """Open filename and return a corresponding file object.""" if filename in ("-", None): return sys.stdin if "r" in mode else sys.stdout if expanduser: filename = os.path.expan...
python
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False, makedirs=False, **kwargs): """Open filename and return a corresponding file object.""" if filename in ("-", None): return sys.stdin if "r" in mode else sys.stdout if expanduser: filename = os.path.expan...
['def', 'openfile', '(', 'filename', ',', 'mode', '=', '"rt"', ',', '*', 'args', ',', 'expanduser', '=', 'False', ',', 'expandvars', '=', 'False', ',', 'makedirs', '=', 'False', ',', '*', '*', 'kwargs', ')', ':', 'if', 'filename', 'in', '(', '"-"', ',', 'None', ')', ':', 'return', 'sys', '.', 'stdin', 'if', '"r"', 'in'...
Open filename and return a corresponding file object.
['Open', 'filename', 'and', 'return', 'a', 'corresponding', 'file', 'object', '.']
train
https://github.com/luismsgomes/openfile/blob/08b3679967e5a7e026656db917d5ed92241d612a/src/openfile.py#L30-L57
2,045
JoseAntFer/pyny3d
pyny3d/geoms.py
root.plot
def plot(self, color='default', ret=False, ax=None): """ Generates a basic 3D visualization. :param color: Polygons color. :type color: matplotlib color, 'default' or 't' (transparent) :param ret: If True, returns the figure. It can be used to add more elem...
python
def plot(self, color='default', ret=False, ax=None): """ Generates a basic 3D visualization. :param color: Polygons color. :type color: matplotlib color, 'default' or 't' (transparent) :param ret: If True, returns the figure. It can be used to add more elem...
['def', 'plot', '(', 'self', ',', 'color', '=', "'default'", ',', 'ret', '=', 'False', ',', 'ax', '=', 'None', ')', ':', 'import', 'matplotlib', '.', 'pylab', 'as', 'plt', 'import', 'mpl_toolkits', '.', 'mplot3d', 'as', 'mplot3d', '# Bypass a plot\r', 'if', 'color', '==', 'False', ':', 'if', 'ax', 'is', 'None', ':', 'a...
Generates a basic 3D visualization. :param color: Polygons color. :type color: matplotlib color, 'default' or 't' (transparent) :param ret: If True, returns the figure. It can be used to add more elements to the plot or to modify it. :type ret: bool :param ...
['Generates', 'a', 'basic', '3D', 'visualization', '.', ':', 'param', 'color', ':', 'Polygons', 'color', '.', ':', 'type', 'color', ':', 'matplotlib', 'color', 'default', 'or', 't', '(', 'transparent', ')', ':', 'param', 'ret', ':', 'If', 'True', 'returns', 'the', 'figure', '.', 'It', 'can', 'be', 'used', 'to', 'add', ...
train
https://github.com/JoseAntFer/pyny3d/blob/fb81684935a24f7e50c975cb4383c81a63ab56df/pyny3d/geoms.py#L25-L85
2,046
watson-developer-cloud/python-sdk
ibm_watson/discovery_v1.py
RetrievalDetails._to_dict
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_...
['def', '_to_dict', '(', 'self', ')', ':', '_dict', '=', '{', '}', 'if', 'hasattr', '(', 'self', ',', "'document_retrieval_strategy'", ')', 'and', 'self', '.', 'document_retrieval_strategy', 'is', 'not', 'None', ':', '_dict', '[', "'document_retrieval_strategy'", ']', '=', 'self', '.', 'document_retrieval_strategy', 'r...
Return a json dictionary representing this model.
['Return', 'a', 'json', 'dictionary', 'representing', 'this', 'model', '.']
train
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L10160-L10167
2,047
mgoral/subconvert
src/subconvert/gui/tools/Synchronizer.py
Synchronizer._changeSubNos
def _changeSubNos(self, path, subNos, count, action, reverse=False): """Implementation of subs add/removal handling. Args: path: file path associated with model on which work is done subNos: list of added/removed subtitle numbers count: function which accepts current...
python
def _changeSubNos(self, path, subNos, count, action, reverse=False): """Implementation of subs add/removal handling. Args: path: file path associated with model on which work is done subNos: list of added/removed subtitle numbers count: function which accepts current...
['def', '_changeSubNos', '(', 'self', ',', 'path', ',', 'subNos', ',', 'count', ',', 'action', ',', 'reverse', '=', 'False', ')', ':', 'model', '=', 'self', '.', '_models', '.', 'get', '(', 'path', ')', 'if', 'model', 'is', 'None', ':', 'return', 'syncPoints', '=', '_syncPoints', '(', 'model', ')', 'syncSubNos', '=', '...
Implementation of subs add/removal handling. Args: path: file path associated with model on which work is done subNos: list of added/removed subtitle numbers count: function which accepts current sync point's subtitle number and subNos and returns anything...
['Implementation', 'of', 'subs', 'add', '/', 'removal', 'handling', '.']
train
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L255-L281
2,048
witchard/grole
grole.py
Request._readline
async def _readline(self, reader): """ Readline helper """ ret = await reader.readline() if len(ret) == 0 and reader.at_eof(): raise EOFError() return ret
python
async def _readline(self, reader): """ Readline helper """ ret = await reader.readline() if len(ret) == 0 and reader.at_eof(): raise EOFError() return ret
['async', 'def', '_readline', '(', 'self', ',', 'reader', ')', ':', 'ret', '=', 'await', 'reader', '.', 'readline', '(', ')', 'if', 'len', '(', 'ret', ')', '==', '0', 'and', 'reader', '.', 'at_eof', '(', ')', ':', 'raise', 'EOFError', '(', ')', 'return', 'ret']
Readline helper
['Readline', 'helper']
train
https://github.com/witchard/grole/blob/54c0bd13e4d4c74a2997ec4254527d937d6e0565/grole.py#L68-L75
2,049
snobear/ezmomi
ezmomi/ezmomi.py
EZMomi.status
def status(self): """Check power status""" vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", ...
python
def status(self): """Check power status""" vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", ...
['def', 'status', '(', 'self', ')', ':', 'vm', '=', 'self', '.', 'get_vm_failfast', '(', 'self', '.', 'config', '[', "'name'", ']', ')', 'extra', '=', 'self', '.', 'config', '[', "'extra'", ']', 'parserFriendly', '=', 'self', '.', 'config', '[', "'parserFriendly'", ']', 'status_to_print', '=', '[', ']', 'if', 'extra', ...
Check power status
['Check', 'power', 'status']
train
https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L522-L546
2,050
awslabs/sockeye
sockeye/encoder.py
EncoderSequence.encode
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. ...
python
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. ...
['def', 'encode', '(', 'self', ',', 'data', ':', 'mx', '.', 'sym', '.', 'Symbol', ',', 'data_length', ':', 'mx', '.', 'sym', '.', 'Symbol', ',', 'seq_len', ':', 'int', ')', '->', 'Tuple', '[', 'mx', '.', 'sym', '.', 'Symbol', ',', 'mx', '.', 'sym', '.', 'Symbol', ',', 'int', ']', ':', 'for', 'encoder', 'in', 'self', '....
Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. :param data_length: Vector with sequence lengths. :param seq_len: Maximum sequence length. :return: Encoded versions of input data (data, data_length, seq_len).
['Encodes', 'data', 'given', 'sequence', 'lengths', 'of', 'individual', 'examples', 'and', 'maximum', 'sequence', 'length', '.']
train
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L717-L731
2,051
basho/riak-python-client
riak/mapreduce.py
RiakMapReduce.add_key_filter
def add_key_filter(self, *args): """ Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce` """ if self._input_mode == 'query': raise ValueError('Key filters are not supported in a query.') ...
python
def add_key_filter(self, *args): """ Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce` """ if self._input_mode == 'query': raise ValueError('Key filters are not supported in a query.') ...
['def', 'add_key_filter', '(', 'self', ',', '*', 'args', ')', ':', 'if', 'self', '.', '_input_mode', '==', "'query'", ':', 'raise', 'ValueError', '(', "'Key filters are not supported in a query.'", ')', 'self', '.', '_key_filters', '.', 'append', '(', 'args', ')', 'return', 'self']
Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce`
['Add', 'a', 'single', 'key', 'filter', 'to', 'the', 'inputs', '.']
train
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/mapreduce.py#L160-L172
2,052
Neurosim-lab/netpyne
netpyne/support/recxelectrode.py
RecXElectrode.calcTransferResistance
def calcTransferResistance(self, gid, seg_coords): """Precompute mapping from segment to electrode locations""" sigma = 0.3 # mS/mm # Value used in NEURON extracellular recording example ("extracellular_stim_and_rec") # rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.0...
python
def calcTransferResistance(self, gid, seg_coords): """Precompute mapping from segment to electrode locations""" sigma = 0.3 # mS/mm # Value used in NEURON extracellular recording example ("extracellular_stim_and_rec") # rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.0...
['def', 'calcTransferResistance', '(', 'self', ',', 'gid', ',', 'seg_coords', ')', ':', 'sigma', '=', '0.3', '# mS/mm ', '# Value used in NEURON extracellular recording example ("extracellular_stim_and_rec")', '# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.028 S/cm = 0.0028 S/mm = 2.8 mS/mm ', '# rh...
Precompute mapping from segment to electrode locations
['Precompute', 'mapping', 'from', 'segment', 'to', 'electrode', 'locations']
train
https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/netpyne/support/recxelectrode.py#L67-L105
2,053
GNS3/gns3-server
gns3server/compute/vmware/vmware_vm.py
VMwareVM.adapters
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters """ # VMware VMs are limited to 10 adapters if adapters > 10: raise VMwareError("Number of adapters above the maximum supp...
python
def adapters(self, adapters): """ Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters """ # VMware VMs are limited to 10 adapters if adapters > 10: raise VMwareError("Number of adapters above the maximum supp...
['def', 'adapters', '(', 'self', ',', 'adapters', ')', ':', '# VMware VMs are limited to 10 adapters', 'if', 'adapters', '>', '10', ':', 'raise', 'VMwareError', '(', '"Number of adapters above the maximum supported of 10"', ')', 'self', '.', '_ethernet_adapters', '.', 'clear', '(', ')', 'for', 'adapter_number', 'in', '...
Sets the number of Ethernet adapters for this VMware VM instance. :param adapters: number of adapters
['Sets', 'the', 'number', 'of', 'Ethernet', 'adapters', 'for', 'this', 'VMware', 'VM', 'instance', '.']
train
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/vmware_vm.py#L655-L673
2,054
tkhyn/dirsync
dirsync/syncer.py
Syncer.do_work
def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creating directory %s' % self._dir2) try: os.makedirs(self._di...
python
def do_work(self): """ Do work """ self._starttime = time.time() if not os.path.isdir(self._dir2): if self._maketarget: if self._verbose: self.log('Creating directory %s' % self._dir2) try: os.makedirs(self._di...
['def', 'do_work', '(', 'self', ')', ':', 'self', '.', '_starttime', '=', 'time', '.', 'time', '(', ')', 'if', 'not', 'os', '.', 'path', '.', 'isdir', '(', 'self', '.', '_dir2', ')', ':', 'if', 'self', '.', '_maketarget', ':', 'if', 'self', '.', '_verbose', ':', 'self', '.', 'log', '(', "'Creating directory %s'", '%', ...
Do work
['Do', 'work']
train
https://github.com/tkhyn/dirsync/blob/a461a6c31a4cf521c1b6a8bcfcd8602e6288e8ce/dirsync/syncer.py#L183-L201
2,055
saltstack/salt
salt/states/net_napalm_yang.py
managed
def managed(name, data, **kwargs): ''' Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Us...
python
def managed(name, data, **kwargs): ''' Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Us...
['def', 'managed', '(', 'name', ',', 'data', ',', '*', '*', 'kwargs', ')', ':', 'models', '=', 'kwargs', '.', 'get', '(', "'models'", ',', 'None', ')', 'if', 'isinstance', '(', 'models', ',', 'tuple', ')', 'and', 'isinstance', '(', 'models', '[', '0', ']', ',', 'list', ')', ':', 'models', '=', 'models', '[', '0', ']', ...
Manage the device configuration given the input data structured according to the YANG models. data YANG structured data. models A list of models to be used when generating the config. profiles: ``None`` Use certain profiles to generate the config. If not specified, wi...
['Manage', 'the', 'device', 'configuration', 'given', 'the', 'input', 'data', 'structured', 'according', 'to', 'the', 'YANG', 'models', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/net_napalm_yang.py#L78-L202
2,056
Robin8Put/pmes
storage/rpc_methods.py
StorageTable.mailed_confirm
async def mailed_confirm(self, **params): """Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid """ if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = params.get("cid...
python
async def mailed_confirm(self, **params): """Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid """ if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = params.get("cid...
['async', 'def', 'mailed_confirm', '(', 'self', ',', '*', '*', 'params', ')', ':', 'if', 'not', 'params', ':', 'return', '{', '"error"', ':', '400', ',', '"reason"', ':', '"Missed required fields"', '}', '# Check if required fields exists', 'cid', '=', 'params', '.', 'get', '(', '"cid"', ')', 'buyer_address', '=', 'par...
Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid
['Sends', 'mail', 'to', 'user', 'after', 'offer', 'receiveing', 'Accepts', ':', '-', 'cid', '-', 'buyer', 'address', '-', 'price', '-', 'offer_type', '-', 'point', '-', 'coinid']
train
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/storage/rpc_methods.py#L461-L530
2,057
pytroll/satpy
satpy/multiscene.py
stack
def stack(datasets): """First dataset at the bottom.""" base = datasets[0].copy() for dataset in datasets[1:]: base = base.where(dataset.isnull(), dataset) return base
python
def stack(datasets): """First dataset at the bottom.""" base = datasets[0].copy() for dataset in datasets[1:]: base = base.where(dataset.isnull(), dataset) return base
['def', 'stack', '(', 'datasets', ')', ':', 'base', '=', 'datasets', '[', '0', ']', '.', 'copy', '(', ')', 'for', 'dataset', 'in', 'datasets', '[', '1', ':', ']', ':', 'base', '=', 'base', '.', 'where', '(', 'dataset', '.', 'isnull', '(', ')', ',', 'dataset', ')', 'return', 'base']
First dataset at the bottom.
['First', 'dataset', 'at', 'the', 'bottom', '.']
train
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/multiscene.py#L56-L61
2,058
has2k1/plydata
plydata/dataframe/helpers.py
_make_verb_helper
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
python
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
['def', '_make_verb_helper', '(', 'verb_func', ',', 'add_groups', '=', 'False', ')', ':', '@', 'wraps', '(', 'verb_func', ')', 'def', '_verb_func', '(', 'verb', ')', ':', 'verb', '.', 'expressions', ',', 'new_columns', '=', 'build_expressions', '(', 'verb', ')', 'if', 'add_groups', ':', 'verb', '.', 'groups', '=', 'new...
Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This is the function called after expressions created and adde...
['Create', 'function', 'that', 'prepares', 'verb', 'for', 'the', 'verb', 'function']
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/helpers.py#L156-L188
2,059
allenai/allennlp
allennlp/common/file_utils.py
split_s3_path
def split_s3_path(url: str) -> Tuple[str, str]: """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at begin...
python
def split_s3_path(url: str) -> Tuple[str, str]: """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at begin...
['def', 'split_s3_path', '(', 'url', ':', 'str', ')', '->', 'Tuple', '[', 'str', ',', 'str', ']', ':', 'parsed', '=', 'urlparse', '(', 'url', ')', 'if', 'not', 'parsed', '.', 'netloc', 'or', 'not', 'parsed', '.', 'path', ':', 'raise', 'ValueError', '(', '"bad s3 path {}"', '.', 'format', '(', 'url', ')', ')', 'bucket_n...
Split a full s3 path into the bucket name and path.
['Split', 'a', 'full', 's3', 'path', 'into', 'the', 'bucket', 'name', 'and', 'path', '.']
train
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/file_utils.py#L120-L130
2,060
tanghaibao/jcvi
jcvi/annotation/ahrd.py
merge
def merge(args): """ %prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained. """ p = OptionParser(merge.__doc__) opts, args = p...
python
def merge(args): """ %prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained. """ p = OptionParser(merge.__doc__) opts, args = p...
['def', 'merge', '(', 'args', ')', ':', 'p', '=', 'OptionParser', '(', 'merge', '.', '__doc__', ')', 'opts', ',', 'args', '=', 'p', '.', 'parse_args', '(', 'args', ')', 'if', 'len', '(', 'args', ')', '<', '1', ':', 'sys', '.', 'exit', '(', 'not', 'p', '.', 'print_help', '(', ')', ')', 'csvfiles', '=', 'args', 'cf', '='...
%prog merge output/*.csv > ahrd.csv Merge AHRD results, remove redundant headers, empty lines, etc. If there are multiple lines containing the same ID (first column). Then whatever comes the first will get retained.
['%prog', 'merge', 'output', '/', '*', '.', 'csv', '>', 'ahrd', '.', 'csv']
train
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/ahrd.py#L568-L609
2,061
saltstack/salt
salt/modules/win_dsc.py
get_config_status
def get_config_status(): ''' Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status ''' cmd = 'Get-Dsc...
python
def get_config_status(): ''' Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status ''' cmd = 'Get-Dsc...
['def', 'get_config_status', '(', ')', ':', 'cmd', '=', "'Get-DscConfigurationStatus | '", "'Select-Object -Property HostName, Status, MetaData, '", '\'@{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, \'', "'Type, Mode, RebootRequested, NumberofResources'", 'try', ':', 'return', '_pshell', '(', 'cmd'...
Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status
['Get', 'the', 'status', 'of', 'the', 'current', 'DSC', 'Configuration']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L589-L612
2,062
PmagPy/PmagPy
programs/demag_gui.py
Demag_GUI.update_warning_box
def update_warning_box(self): """ updates the warning box with whatever the warning_text variable contains for this specimen """ self.warning_box.Clear() if self.warning_text == "": self.warning_box.AppendText("No Problems") else: self.warn...
python
def update_warning_box(self): """ updates the warning box with whatever the warning_text variable contains for this specimen """ self.warning_box.Clear() if self.warning_text == "": self.warning_box.AppendText("No Problems") else: self.warn...
['def', 'update_warning_box', '(', 'self', ')', ':', 'self', '.', 'warning_box', '.', 'Clear', '(', ')', 'if', 'self', '.', 'warning_text', '==', '""', ':', 'self', '.', 'warning_box', '.', 'AppendText', '(', '"No Problems"', ')', 'else', ':', 'self', '.', 'warning_box', '.', 'AppendText', '(', 'self', '.', 'warning_te...
updates the warning box with whatever the warning_text variable contains for this specimen
['updates', 'the', 'warning', 'box', 'with', 'whatever', 'the', 'warning_text', 'variable', 'contains', 'for', 'this', 'specimen']
train
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L6155-L6164
2,063
gabstopper/smc-python
smc/vpn/route.py
RouteVPN.set_preshared_key
def set_preshared_key(self, new_key): """ Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None """ if self.data.get('preshared_key'): self.updat...
python
def set_preshared_key(self, new_key): """ Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None """ if self.data.get('preshared_key'): self.updat...
['def', 'set_preshared_key', '(', 'self', ',', 'new_key', ')', ':', 'if', 'self', '.', 'data', '.', 'get', '(', "'preshared_key'", ')', ':', 'self', '.', 'update', '(', 'preshared_key', '=', 'new_key', ')']
Set the preshared key for this VPN. A pre-shared key is only present when the tunnel type is 'VPN' or the encryption mode is 'transport'. :return: None
['Set', 'the', 'preshared', 'key', 'for', 'this', 'VPN', '.', 'A', 'pre', '-', 'shared', 'key', 'is', 'only', 'present', 'when', 'the', 'tunnel', 'type', 'is', 'VPN', 'or', 'the', 'encryption', 'mode', 'is', 'transport', '.', ':', 'return', ':', 'None']
train
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/route.py#L332-L341
2,064
robotools/fontParts
Lib/fontParts/base/groups.py
BaseGroups._get_side2KerningGroups
def _get_side2KerningGroups(self): """ Subclasses may override this method. """ found = {} for name, contents in self.items(): if name.startswith("public.kern2."): found[name] = contents return found
python
def _get_side2KerningGroups(self): """ Subclasses may override this method. """ found = {} for name, contents in self.items(): if name.startswith("public.kern2."): found[name] = contents return found
['def', '_get_side2KerningGroups', '(', 'self', ')', ':', 'found', '=', '{', '}', 'for', 'name', ',', 'contents', 'in', 'self', '.', 'items', '(', ')', ':', 'if', 'name', '.', 'startswith', '(', '"public.kern2."', ')', ':', 'found', '[', 'name', ']', '=', 'contents', 'return', 'found']
Subclasses may override this method.
['Subclasses', 'may', 'override', 'this', 'method', '.']
train
https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/groups.py#L149-L157
2,065
BeyondTheClouds/enoslib
enoslib/task.py
_make_env
def _make_env(resultdir=None): """Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function...
python
def _make_env(resultdir=None): """Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function...
['def', '_make_env', '(', 'resultdir', '=', 'None', ')', ':', 'env', '=', '{', '"config"', ':', '{', '}', ',', '# The config', '"resultdir"', ':', '""', ',', '# Path to the result directory', '"config_file"', ':', '""', ',', '# The initial config file', '"nodes"', ':', '{', '}', ',', '# Roles with nodes', '"phase"', ':...
Loads the env from `resultdir` if not `None` or makes a new one. An Enos environment handles all specific variables of an experiment. This function either generates a new environment or loads a previous one. If the value of `resultdir` is `None`, then this function makes a new environment and return it...
['Loads', 'the', 'env', 'from', 'resultdir', 'if', 'not', 'None', 'or', 'makes', 'a', 'new', 'one', '.']
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/task.py#L69-L110
2,066
vnmabus/dcor
dcor/_dcor.py
distance_stats_sqr
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
python
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
['def', 'distance_stats_sqr', '(', 'x', ',', 'y', ',', '*', '*', 'kwargs', ')', ':', 'if', '_can_use_fast_algorithm', '(', 'x', ',', 'y', ',', '*', '*', 'kwargs', ')', ':', 'return', '_distance_stats_sqr_fast', '(', 'x', ',', 'y', ')', 'else', ':', 'return', '_distance_sqr_stats_naive_generic', '(', 'x', ',', 'y', ',',...
distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- x: array_like First random vector. The co...
['distance_stats_sqr', '(', 'x', 'y', '*', 'exponent', '=', '1', ')']
train
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L537-L609
2,067
spyder-ide/spyder
spyder/plugins/projects/plugin.py
Projects.switch_to_plugin
def switch_to_plugin(self): """Switch to plugin.""" # Unmaxizime currently maximized plugin if (self.main.last_plugin is not None and self.main.last_plugin.ismaximized and self.main.last_plugin is not self): self.main.maximize_dockwidget() ...
python
def switch_to_plugin(self): """Switch to plugin.""" # Unmaxizime currently maximized plugin if (self.main.last_plugin is not None and self.main.last_plugin.ismaximized and self.main.last_plugin is not self): self.main.maximize_dockwidget() ...
['def', 'switch_to_plugin', '(', 'self', ')', ':', '# Unmaxizime currently maximized plugin\r', 'if', '(', 'self', '.', 'main', '.', 'last_plugin', 'is', 'not', 'None', 'and', 'self', '.', 'main', '.', 'last_plugin', '.', 'ismaximized', 'and', 'self', '.', 'main', '.', 'last_plugin', 'is', 'not', 'self', ')', ':', 'sel...
Switch to plugin.
['Switch', 'to', 'plugin', '.']
train
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/projects/plugin.py#L178-L190
2,068
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
_AddPropertiesForRepeatedField
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
python
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
['def', '_AddPropertiesForRepeatedField', '(', 'field', ',', 'cls', ')', ':', 'proto_field_name', '=', 'field', '.', 'name', 'property_name', '=', '_PropertyName', '(', 'proto_field_name', ')', 'def', 'getter', '(', 'self', ')', ':', 'field_value', '=', 'self', '.', '_fields', '.', 'get', '(', 'field', ')', 'if', 'fiel...
Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking i...
['Adds', 'a', 'public', 'property', 'for', 'a', 'repeated', 'protocol', 'message', 'field', '.', 'Clients', 'can', 'use', 'this', 'property', 'to', 'get', 'the', 'value', 'of', 'the', 'field', 'which', 'will', 'be', 'either', 'a', '_RepeatedScalarFieldContainer', 'or', '_RepeatedCompositeFieldContainer', '(', 'see', 'b...
train
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L586-L627
2,069
fvdsn/py-xml-escpos
xmlescpos/escpos.py
Escpos._print_image
def _print_image(self, line, size): """ Print formatted image """ i = 0 cont = 0 buffer = "" self._raw(S_RASTER_N) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0) self._raw(buffer.decode('hex')) buffer = "" while i < ...
python
def _print_image(self, line, size): """ Print formatted image """ i = 0 cont = 0 buffer = "" self._raw(S_RASTER_N) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0) self._raw(buffer.decode('hex')) buffer = "" while i < ...
['def', '_print_image', '(', 'self', ',', 'line', ',', 'size', ')', ':', 'i', '=', '0', 'cont', '=', '0', 'buffer', '=', '""', 'self', '.', '_raw', '(', 'S_RASTER_N', ')', 'buffer', '=', '"%02X%02X%02X%02X"', '%', '(', '(', '(', 'size', '[', '0', ']', '/', 'size', '[', '1', ']', ')', '/', '8', ')', ',', '0', ',', 'size...
Print formatted image
['Print', 'formatted', 'image']
train
https://github.com/fvdsn/py-xml-escpos/blob/7f77e039c960d5773fb919aed02ba392dccbc360/xmlescpos/escpos.py#L325-L345
2,070
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py
VIFHotPlugPluggingDriver.delete_hosting_device_resources
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port, **kwargs): """Deletes resources for a hosting device in a plugin specific way.""" if mgmt_port is not None: try: self._cleanup_hosting_port(context, mgmt_port['id...
python
def delete_hosting_device_resources(self, context, tenant_id, mgmt_port, **kwargs): """Deletes resources for a hosting device in a plugin specific way.""" if mgmt_port is not None: try: self._cleanup_hosting_port(context, mgmt_port['id...
['def', 'delete_hosting_device_resources', '(', 'self', ',', 'context', ',', 'tenant_id', ',', 'mgmt_port', ',', '*', '*', 'kwargs', ')', ':', 'if', 'mgmt_port', 'is', 'not', 'None', ':', 'try', ':', 'self', '.', '_cleanup_hosting_port', '(', 'context', ',', 'mgmt_port', '[', "'id'", ']', ')', 'except', 'n_exc', '.', '...
Deletes resources for a hosting device in a plugin specific way.
['Deletes', 'resources', 'for', 'a', 'hosting', 'device', 'in', 'a', 'plugin', 'specific', 'way', '.']
train
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L107-L119
2,071
brocade/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py
brocade_tunnels.overlay_gateway_site_extend_vlan_add
def overlay_gateway_site_extend_vlan_add(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") na...
python
def overlay_gateway_site_extend_vlan_add(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") na...
['def', 'overlay_gateway_site_extend_vlan_add', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'config', '=', 'ET', '.', 'Element', '(', '"config"', ')', 'overlay_gateway', '=', 'ET', '.', 'SubElement', '(', 'config', ',', '"overlay-gateway"', ',', 'xmlns', '=', '"urn:brocade.com:mgmt:brocade-tunnels"', ')', 'name_key...
Auto Generated Code
['Auto', 'Generated', 'Code']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L304-L320
2,072
log2timeline/dftimewolf
dftimewolf/lib/collectors/filesystem.py
FilesystemCollector.process
def process(self): """Checks whether the paths exists and updates the state accordingly.""" for path in self._paths: if os.path.exists(path): self.state.output.append((os.path.basename(path), path)) else: self.state.add_error( 'Path {0:s} does not exist'.format(str(path))...
python
def process(self): """Checks whether the paths exists and updates the state accordingly.""" for path in self._paths: if os.path.exists(path): self.state.output.append((os.path.basename(path), path)) else: self.state.add_error( 'Path {0:s} does not exist'.format(str(path))...
['def', 'process', '(', 'self', ')', ':', 'for', 'path', 'in', 'self', '.', '_paths', ':', 'if', 'os', '.', 'path', '.', 'exists', '(', 'path', ')', ':', 'self', '.', 'state', '.', 'output', '.', 'append', '(', '(', 'os', '.', 'path', '.', 'basename', '(', 'path', ')', ',', 'path', ')', ')', 'else', ':', 'self', '.', '...
Checks whether the paths exists and updates the state accordingly.
['Checks', 'whether', 'the', 'paths', 'exists', 'and', 'updates', 'the', 'state', 'accordingly', '.']
train
https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/collectors/filesystem.py#L37-L46
2,073
proteanhq/protean
src/protean/core/entity.py
Entity.exists
def exists(cls, excludes_, **filters): """ Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. ...
python
def exists(cls, excludes_, **filters): """ Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. ...
['def', 'exists', '(', 'cls', ',', 'excludes_', ',', '*', '*', 'filters', ')', ':', 'results', '=', 'cls', '.', 'query', '.', 'filter', '(', '*', '*', 'filters', ')', '.', 'exclude', '(', '*', '*', 'excludes_', ')', 'return', 'bool', '(', 'results', ')']
Return `True` if objects matching the provided filters and excludes exist if not return false. Calls the `filter` method by default, but can be overridden for better and quicker implementations that may be supported by a database. :param excludes_: entities without this combination...
['Return', 'True', 'if', 'objects', 'matching', 'the', 'provided', 'filters', 'and', 'excludes', 'exist', 'if', 'not', 'return', 'false', '.']
train
https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/entity.py#L429-L440
2,074
mcocdawc/chemcoord
src/chemcoord/configuration.py
write_configuration_file
def write_configuration_file(filepath=_give_default_file_path(), overwrite=False): """Create a configuration file. Writes the current state of settings into a configuration file. .. note:: Since a file is permamently written, this function is strictly speaking not side...
python
def write_configuration_file(filepath=_give_default_file_path(), overwrite=False): """Create a configuration file. Writes the current state of settings into a configuration file. .. note:: Since a file is permamently written, this function is strictly speaking not side...
['def', 'write_configuration_file', '(', 'filepath', '=', '_give_default_file_path', '(', ')', ',', 'overwrite', '=', 'False', ')', ':', 'config', '=', 'configparser', '.', 'ConfigParser', '(', ')', 'config', '.', 'read_dict', '(', 'settings', ')', 'if', 'os', '.', 'path', '.', 'isfile', '(', 'filepath', ')', 'and', 'n...
Create a configuration file. Writes the current state of settings into a configuration file. .. note:: Since a file is permamently written, this function is strictly speaking not sideeffect free. Args: filepath (str): Where to write the file. The default is under both UNIX and...
['Create', 'a', 'configuration', 'file', '.']
train
https://github.com/mcocdawc/chemcoord/blob/95561ce387c142227c38fb14a1d182179aef8f5f/src/chemcoord/configuration.py#L32-L59
2,075
pallets/werkzeug
src/werkzeug/http.py
is_byte_range_valid
def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: ...
python
def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: ...
['def', 'is_byte_range_valid', '(', 'start', ',', 'stop', ',', 'length', ')', ':', 'if', '(', 'start', 'is', 'None', ')', '!=', '(', 'stop', 'is', 'None', ')', ':', 'return', 'False', 'elif', 'start', 'is', 'None', ':', 'return', 'length', 'is', 'None', 'or', 'length', '>=', '0', 'elif', 'length', 'is', 'None', ':', 'r...
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7
['Checks', 'if', 'a', 'given', 'byte', 'content', 'range', 'is', 'valid', 'for', 'the', 'given', 'length', '.']
train
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L1222-L1235
2,076
Aloomaio/python-sdk
alooma_pysdk/alooma_pysdk.py
_Sender.__get_event
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and th...
python
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and th...
['def', '__get_event', '(', 'self', ',', 'block', '=', 'True', ',', 'timeout', '=', '1', ')', ':', 'while', 'True', ':', 'if', 'self', '.', '_exceeding_event', ':', '# An event was omitted from last batch', 'event', '=', 'self', '.', '_exceeding_event', 'self', '.', '_exceeding_event', '=', 'None', 'else', ':', '# No o...
Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned
['Retrieves', 'an', 'event', '.', 'If', 'self', '.', '_exceeding_event', 'is', 'not', 'None', 'it', 'll', 'be', 'returned', '.', 'Otherwise', 'an', 'event', 'is', 'dequeued', 'from', 'the', 'event', 'buffer', '.', 'If', 'The', 'event', 'which', 'was', 'retrieved', 'is', 'bigger', 'than', 'the', 'permitted', 'batch', 's...
train
https://github.com/Aloomaio/python-sdk/blob/e6e7322d0b23d90b1ff0320e9a9c431c82c0c277/alooma_pysdk/alooma_pysdk.py#L591-L614
2,077
MozillaSecurity/laniakea
laniakea/core/providers/ec2/manager.py
EC2Manager.retry_on_ec2_error
def retry_on_ec2_error(self, func, *args, **kwargs): """ Call the given method with the given arguments, retrying if the call failed due to an EC2ResponseError. This method will wait at most 30 seconds and perform up to 6 retries. If the method still fails, it will propagate the ...
python
def retry_on_ec2_error(self, func, *args, **kwargs): """ Call the given method with the given arguments, retrying if the call failed due to an EC2ResponseError. This method will wait at most 30 seconds and perform up to 6 retries. If the method still fails, it will propagate the ...
['def', 'retry_on_ec2_error', '(', 'self', ',', 'func', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'exception_retry_count', '=', '6', 'while', 'True', ':', 'try', ':', 'return', 'func', '(', '*', 'args', ',', '*', '*', 'kwargs', ')', 'except', '(', 'boto', '.', 'exception', '.', 'EC2ResponseError', ',', 'ssl'...
Call the given method with the given arguments, retrying if the call failed due to an EC2ResponseError. This method will wait at most 30 seconds and perform up to 6 retries. If the method still fails, it will propagate the error. :param func: Function to call :type func: functio...
['Call', 'the', 'given', 'method', 'with', 'the', 'given', 'arguments', 'retrying', 'if', 'the', 'call', 'failed', 'due', 'to', 'an', 'EC2ResponseError', '.', 'This', 'method', 'will', 'wait', 'at', 'most', '30', 'seconds', 'and', 'perform', 'up', 'to', '6', 'retries', '.', 'If', 'the', 'method', 'still', 'fails', 'it'...
train
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L36-L54
2,078
pip-services3-python/pip-services3-commons-python
pip_services3_commons/validate/PropertySchema.py
PropertySchema._perform_validation
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
python
def _perform_validation(self, path, value, results): """ Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new ...
['def', '_perform_validation', '(', 'self', ',', 'path', ',', 'value', ',', 'results', ')', ':', 'path', '=', 'self', '.', 'name', 'if', 'path', '==', 'None', 'or', 'len', '(', 'path', ')', '==', '0', 'else', 'path', '+', '"."', '+', 'self', '.', 'name', 'super', '(', 'PropertySchema', ',', 'self', ')', '.', '_perform_...
Validates a given value against the schema and configured validation rules. :param path: a dot notation path to the value. :param value: a value to be validated. :param results: a list with validation results to add new results.
['Validates', 'a', 'given', 'value', 'against', 'the', 'schema', 'and', 'configured', 'validation', 'rules', '.']
train
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/validate/PropertySchema.py#L40-L53
2,079
psd-tools/psd-tools
src/psd_tools/api/pil_io.py
get_color_mode
def get_color_mode(mode): """Convert PIL mode to ColorMode.""" name = mode.upper() name = name.rstrip('A') # Trim alpha. name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name) return getattr(ColorMode, name)
python
def get_color_mode(mode): """Convert PIL mode to ColorMode.""" name = mode.upper() name = name.rstrip('A') # Trim alpha. name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name) return getattr(ColorMode, name)
['def', 'get_color_mode', '(', 'mode', ')', ':', 'name', '=', 'mode', '.', 'upper', '(', ')', 'name', '=', 'name', '.', 'rstrip', '(', "'A'", ')', '# Trim alpha.', 'name', '=', '{', "'1'", ':', "'BITMAP'", ',', "'L'", ':', "'GRAYSCALE'", '}', '.', 'get', '(', 'name', ',', 'name', ')', 'return', 'getattr', '(', 'ColorMo...
Convert PIL mode to ColorMode.
['Convert', 'PIL', 'mode', 'to', 'ColorMode', '.']
train
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L14-L19
2,080
ska-sa/purr
Purr/Editors.py
_sanitizeFilename
def _sanitizeFilename(filename): """Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.""" global _sanitize_trans out = filename.translate(_sanitize_trans) # leading dot becomes "_" if out and out[0] == '.': ou...
python
def _sanitizeFilename(filename): """Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.""" global _sanitize_trans out = filename.translate(_sanitize_trans) # leading dot becomes "_" if out and out[0] == '.': ou...
['def', '_sanitizeFilename', '(', 'filename', ')', ':', 'global', '_sanitize_trans', 'out', '=', 'filename', '.', 'translate', '(', '_sanitize_trans', ')', '# leading dot becomes "_"', 'if', 'out', 'and', 'out', '[', '0', ']', '==', "'.'", ':', 'out', '=', 'out', '[', '1', ':', ']', 'return', 'out']
Sanitizes filename for use on Windows and other brain-dead systems, by replacing a number of illegal characters with underscores.
['Sanitizes', 'filename', 'for', 'use', 'on', 'Windows', 'and', 'other', 'brain', '-', 'dead', 'systems', 'by', 'replacing', 'a', 'number', 'of', 'illegal', 'characters', 'with', 'underscores', '.']
train
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Editors.py#L49-L57
2,081
iancmcc/ouimeaux
ouimeaux/device/__init__.py
Device.get_state
def get_state(self, force_update=False): """ Returns 0 if off and 1 if on. """ if force_update or self._state is None: return int(self.basicevent.GetBinaryState()['BinaryState']) return self._state
python
def get_state(self, force_update=False): """ Returns 0 if off and 1 if on. """ if force_update or self._state is None: return int(self.basicevent.GetBinaryState()['BinaryState']) return self._state
['def', 'get_state', '(', 'self', ',', 'force_update', '=', 'False', ')', ':', 'if', 'force_update', 'or', 'self', '.', '_state', 'is', 'None', ':', 'return', 'int', '(', 'self', '.', 'basicevent', '.', 'GetBinaryState', '(', ')', '[', "'BinaryState'", ']', ')', 'return', 'self', '.', '_state']
Returns 0 if off and 1 if on.
['Returns', '0', 'if', 'off', 'and', '1', 'if', 'on', '.']
train
https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/__init__.py#L36-L42
2,082
awslabs/serverless-application-model
samtranslator/intrinsics/resource_refs.py
SupportedResourceReferences.add
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" ...
python
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" ...
['def', 'add', '(', 'self', ',', 'logical_id', ',', 'property', ',', 'value', ')', ':', 'if', 'not', 'logical_id', 'or', 'not', 'property', ':', 'raise', 'ValueError', '(', '"LogicalId and property must be a non-empty string"', ')', 'if', 'not', 'value', 'or', 'not', 'isinstance', '(', 'value', ',', 'string_types', ')'...
Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaF...
['Add', 'the', 'information', 'that', 'resource', 'with', 'given', 'logical_id', 'supports', 'the', 'given', 'property', 'and', 'that', 'a', 'reference', 'to', 'logical_id', '.', 'property', 'resolves', 'to', 'given', 'value', '.']
train
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L17-L44
2,083
pytroll/trollimage
trollimage/image.py
Image._ycbcr2l
def _ycbcr2l(self, mode): """Convert from YCbCr to L. """ self._check_modes(("YCbCr", "YCbCrA")) self.channels = [self.channels[0]] + self.channels[3:] if self.fill_value is not None: self.fill_value = [self.fill_value[0]] + self.fill_value[3:] self.mode = mo...
python
def _ycbcr2l(self, mode): """Convert from YCbCr to L. """ self._check_modes(("YCbCr", "YCbCrA")) self.channels = [self.channels[0]] + self.channels[3:] if self.fill_value is not None: self.fill_value = [self.fill_value[0]] + self.fill_value[3:] self.mode = mo...
['def', '_ycbcr2l', '(', 'self', ',', 'mode', ')', ':', 'self', '.', '_check_modes', '(', '(', '"YCbCr"', ',', '"YCbCrA"', ')', ')', 'self', '.', 'channels', '=', '[', 'self', '.', 'channels', '[', '0', ']', ']', '+', 'self', '.', 'channels', '[', '3', ':', ']', 'if', 'self', '.', 'fill_value', 'is', 'not', 'None', ':'...
Convert from YCbCr to L.
['Convert', 'from', 'YCbCr', 'to', 'L', '.']
train
https://github.com/pytroll/trollimage/blob/d35a7665ad475ff230e457085523e21f2cd3f454/trollimage/image.py#L627-L635
2,084
wonambi-python/wonambi
wonambi/source/linear.py
calc_xyz2surf
def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None): """Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the location...
python
def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None): """Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the location...
['def', 'calc_xyz2surf', '(', 'surf', ',', 'xyz', ',', 'threshold', '=', '20', ',', 'exponent', '=', 'None', ',', 'std', '=', 'None', ')', ':', 'if', 'exponent', 'is', 'None', 'and', 'std', 'is', 'None', ':', 'exponent', '=', '1', 'if', 'exponent', 'is', 'not', 'None', ':', 'lg', '.', 'debug', '(', "'Vertex values base...
Calculate transformation matrix from xyz values to vertices. Parameters ---------- surf : instance of wonambi.attr.Surf the surface of only one hemisphere. xyz : numpy.ndarray nChan x 3 matrix, with the locations in x, y, z. std : float distance in mm of the Gaussian kernel ...
['Calculate', 'transformation', 'matrix', 'from', 'xyz', 'values', 'to', 'vertices', '.']
train
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L57-L136
2,085
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/npm/npm_client.py
NpmClient.update_package
def update_package(self, package_version_details, feed_id, package_name, package_version): """UpdatePackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_...
python
def update_package(self, package_version_details, feed_id, package_name, package_version): """UpdatePackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_...
['def', 'update_package', '(', 'self', ',', 'package_version_details', ',', 'feed_id', ',', 'package_name', ',', 'package_version', ')', ':', 'route_values', '=', '{', '}', 'if', 'feed_id', 'is', 'not', 'None', ':', 'route_values', '[', "'feedId'", ']', '=', 'self', '.', '_serialize', '.', 'url', '(', "'feed_id'", ',',...
UpdatePackage. [Preview API] :param :class:`<PackageVersionDetails> <azure.devops.v5_0.npm.models.PackageVersionDetails>` package_version_details: :param str feed_id: :param str package_name: :param str package_version: :rtype: :class:`<Package> <azure.devops.v5_0.npm.mod...
['UpdatePackage', '.', '[', 'Preview', 'API', ']', ':', 'param', ':', 'class', ':', '<PackageVersionDetails', '>', '<azure', '.', 'devops', '.', 'v5_0', '.', 'npm', '.', 'models', '.', 'PackageVersionDetails', '>', 'package_version_details', ':', ':', 'param', 'str', 'feed_id', ':', ':', 'param', 'str', 'package_name',...
train
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/npm/npm_client.py#L404-L426
2,086
dnephin/PyStaticConfiguration
staticconf/config.py
get_namespaces_from_names
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
python
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
['def', 'get_namespaces_from_names', '(', 'name', ',', 'all_names', ')', ':', 'names', '=', 'configuration_namespaces', '.', 'keys', '(', ')', 'if', 'all_names', 'else', '[', 'name', ']', 'for', 'name', 'in', 'names', ':', 'yield', 'get_namespace', '(', 'name', ')']
Return a generator which yields namespace objects.
['Return', 'a', 'generator', 'which', 'yields', 'namespace', 'objects', '.']
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L181-L185
2,087
amaas-fintech/amaas-core-sdk-python
amaascore/market_data/interface.py
MarketDataInterface.get_brokendate_fx_forward_rate
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date): """ This method takes calculates broken date forward FX rate based on the passed in parameters """ self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s ...
python
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date): """ This method takes calculates broken date forward FX rate based on the passed in parameters """ self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s ...
['def', 'get_brokendate_fx_forward_rate', '(', 'self', ',', 'asset_manager_id', ',', 'asset_id', ',', 'price_date', ',', 'value_date', ')', ':', 'self', '.', 'logger', '.', 'info', '(', "'Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s - Price Date: %s - Value Date: %s'", ',', 'asset_manager...
This method takes calculates broken date forward FX rate based on the passed in parameters
['This', 'method', 'takes', 'calculates', 'broken', 'date', 'forward', 'FX', 'rate', 'based', 'on', 'the', 'passed', 'in', 'parameters']
train
https://github.com/amaas-fintech/amaas-core-sdk-python/blob/347b71f8e776b2dde582b015e31b4802d91e8040/amaascore/market_data/interface.py#L225-L239
2,088
wright-group/WrightTools
WrightTools/artists/_helpers.py
add_sideplot
def add_sideplot( ax, along, pad=0., *, grid=True, zero_line=True, arrs_to_bin=None, normalize_bin=True, ymin=0, ymax=1.1, height=0.75, c="C0" ): """Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib...
python
def add_sideplot( ax, along, pad=0., *, grid=True, zero_line=True, arrs_to_bin=None, normalize_bin=True, ymin=0, ymax=1.1, height=0.75, c="C0" ): """Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib...
['def', 'add_sideplot', '(', 'ax', ',', 'along', ',', 'pad', '=', '0.', ',', '*', ',', 'grid', '=', 'True', ',', 'zero_line', '=', 'True', ',', 'arrs_to_bin', '=', 'None', ',', 'normalize_bin', '=', 'True', ',', 'ymin', '=', '0', ',', 'ymax', '=', '1.1', ',', 'height', '=', '0.75', ',', 'c', '=', '"C0"', ')', ':', '# d...
Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib AxesSubplot object The axis to add a sideplot along. along : {'x', 'y'} The dimension to add a sideplot along. pad : number (optional) Distance between axis and sideplo...
['Add', 'a', 'sideplot', 'to', 'an', 'axis', '.', 'Sideplots', 'share', 'their', 'corresponding', 'axis', '.']
train
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L78-L163
2,089
amaas-fintech/amaas-core-sdk-python
amaascore/market_data/fx_rate.py
FXRate.rate_timestamp
def rate_timestamp(self, rate_timestamp): """ Force the rate_timestamp to be a datetime :param rate_timestamp: :return: """ if rate_timestamp is not None: if isinstance(rate_timestamp, (str, type_check)): rate_timestamp = parse(rate_timestamp)....
python
def rate_timestamp(self, rate_timestamp): """ Force the rate_timestamp to be a datetime :param rate_timestamp: :return: """ if rate_timestamp is not None: if isinstance(rate_timestamp, (str, type_check)): rate_timestamp = parse(rate_timestamp)....
['def', 'rate_timestamp', '(', 'self', ',', 'rate_timestamp', ')', ':', 'if', 'rate_timestamp', 'is', 'not', 'None', ':', 'if', 'isinstance', '(', 'rate_timestamp', ',', '(', 'str', ',', 'type_check', ')', ')', ':', 'rate_timestamp', '=', 'parse', '(', 'rate_timestamp', ')', '.', 'replace', '(', 'tzinfo', '=', 'pytz', ...
Force the rate_timestamp to be a datetime :param rate_timestamp: :return:
['Force', 'the', 'rate_timestamp', 'to', 'be', 'a', 'datetime', ':', 'param', 'rate_timestamp', ':', ':', 'return', ':']
train
https://github.com/amaas-fintech/amaas-core-sdk-python/blob/347b71f8e776b2dde582b015e31b4802d91e8040/amaascore/market_data/fx_rate.py#L74-L87
2,090
kumar303/mohawk
mohawk/util.py
normalize_string
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
python
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
['def', 'normalize_string', '(', 'mac_type', ',', 'resource', ',', 'content_hash', ')', ':', 'normalized', '=', '[', "'hawk.'", '+', 'str', '(', 'HAWK_VER', ')', '+', "'.'", '+', 'mac_type', ',', 'normalize_header_attr', '(', 'resource', '.', 'timestamp', ')', ',', 'normalize_header_attr', '(', 'resource', '.', 'nonce'...
Serializes mac_type and resource into a HAWK string.
['Serializes', 'mac_type', 'and', 'resource', 'into', 'a', 'HAWK', 'string', '.']
train
https://github.com/kumar303/mohawk/blob/037be67ccf50ae704705e67add44e02737a65d21/mohawk/util.py#L109-L136
2,091
albu/albumentations
albumentations/augmentations/functional.py
preserve_channel_dim
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(resul...
python
def preserve_channel_dim(func): """Preserve dummy channel dim.""" @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2: result = np.expand_dims(resul...
['def', 'preserve_channel_dim', '(', 'func', ')', ':', '@', 'wraps', '(', 'func', ')', 'def', 'wrapped_function', '(', 'img', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', ':', 'shape', '=', 'img', '.', 'shape', 'result', '=', 'func', '(', 'img', ',', '*', 'args', ',', '*', '*', 'kwargs', ')', 'if', 'len', '(', 'shap...
Preserve dummy channel dim.
['Preserve', 'dummy', 'channel', 'dim', '.']
train
https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/functional.py#L47-L57
2,092
hyperledger/indy-plenum
plenum/common/txn_util.py
reqToTxn
def reqToTxn(req): """ Transform a client request such that it can be stored in the ledger. Also this is what will be returned to the client in the reply :param req: :return: """ if isinstance(req, str): req = json.loads(req) if isinstance(req, dict): kwargs = dict( ...
python
def reqToTxn(req): """ Transform a client request such that it can be stored in the ledger. Also this is what will be returned to the client in the reply :param req: :return: """ if isinstance(req, str): req = json.loads(req) if isinstance(req, dict): kwargs = dict( ...
['def', 'reqToTxn', '(', 'req', ')', ':', 'if', 'isinstance', '(', 'req', ',', 'str', ')', ':', 'req', '=', 'json', '.', 'loads', '(', 'req', ')', 'if', 'isinstance', '(', 'req', ',', 'dict', ')', ':', 'kwargs', '=', 'dict', '(', 'identifier', '=', 'req', '.', 'get', '(', 'f', '.', 'IDENTIFIER', '.', 'nm', ',', 'None',...
Transform a client request such that it can be stored in the ledger. Also this is what will be returned to the client in the reply :param req: :return:
['Transform', 'a', 'client', 'request', 'such', 'that', 'it', 'can', 'be', 'stored', 'in', 'the', 'ledger', '.', 'Also', 'this', 'is', 'what', 'will', 'be', 'returned', 'to', 'the', 'client', 'in', 'the', 'reply', ':', 'param', 'req', ':', ':', 'return', ':']
train
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/txn_util.py#L224-L253
2,093
spotify/gordon
gordon/plugins_loader.py
load_plugins
def load_plugins(config, plugin_kwargs): """ Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names ...
python
def load_plugins(config, plugin_kwargs): """ Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names ...
['def', 'load_plugins', '(', 'config', ',', 'plugin_kwargs', ')', ':', 'installed_plugins', '=', '_gather_installed_plugins', '(', ')', 'metrics_plugin', '=', '_get_metrics_plugin', '(', 'config', ',', 'installed_plugins', ')', 'if', 'metrics_plugin', ':', 'plugin_kwargs', '[', "'metrics'", ']', '=', 'metrics_plugin', ...
Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names of plugins, list of instantiated plugin objec...
['Discover', 'and', 'instantiate', 'plugins', '.']
train
https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/plugins_loader.py#L210-L237
2,094
totalgood/nlpia
src/nlpia/futil.py
find_filepath
def find_filepath( filename, basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')): """ Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_...
python
def find_filepath( filename, basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')): """ Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_...
['def', 'find_filepath', '(', 'filename', ',', 'basepaths', '=', '(', 'os', '.', 'path', '.', 'curdir', ',', 'DATA_PATH', ',', 'BIGDATA_PATH', ',', 'BASE_DIR', ',', "'~'", ',', "'~/Downloads'", ',', 'os', '.', 'path', '.', 'join', '(', "'/'", ',', "'tmp'", ')', ',', "'..'", ')', ')', ':', 'if', 'os', '.', 'path', '.', ...
Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_filepath(os.path.join(DATA_PATH, 'iq_test.csv')) True >>> p[-len('iq_test.csv'):] 'iq_test.csv' >>> find_filepath('exponentially-crazy-filename-2.7182818...
['Given', 'a', 'filename', 'or', 'path', 'see', 'if', 'it', 'exists', 'in', 'any', 'of', 'the', 'common', 'places', 'datafiles', 'might', 'be']
train
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/futil.py#L302-L321
2,095
hanguokai/youku
youku/youku_comments.py
YoukuComments.create_comment
def create_comment(self, access_token, video_id, content, reply_id=None, captcha_key=None, captcha_text=None): """doc: http://open.youku.com/docs/doc?id=41 """ url = 'https://openapi.youku.com/v2/comments/create.json' data = { 'client_id': self.client_i...
python
def create_comment(self, access_token, video_id, content, reply_id=None, captcha_key=None, captcha_text=None): """doc: http://open.youku.com/docs/doc?id=41 """ url = 'https://openapi.youku.com/v2/comments/create.json' data = { 'client_id': self.client_i...
['def', 'create_comment', '(', 'self', ',', 'access_token', ',', 'video_id', ',', 'content', ',', 'reply_id', '=', 'None', ',', 'captcha_key', '=', 'None', ',', 'captcha_text', '=', 'None', ')', ':', 'url', '=', "'https://openapi.youku.com/v2/comments/create.json'", 'data', '=', '{', "'client_id'", ':', 'self', '.', 'c...
doc: http://open.youku.com/docs/doc?id=41
['doc', ':', 'http', ':', '//', 'open', '.', 'youku', '.', 'com', '/', 'docs', '/', 'doc?id', '=', '41']
train
https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_comments.py#L129-L146
2,096
brocade/pynos
pynos/versions/ver_7/ver_7_0_0/interface.py
Interface.evpn_instance_mac_timer_max_count
def evpn_instance_mac_timer_max_count(self, **kwargs): """ Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled ...
python
def evpn_instance_mac_timer_max_count(self, **kwargs): """ Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled ...
['def', 'evpn_instance_mac_timer_max_count', '(', 'self', ',', '*', '*', 'kwargs', ')', ':', 'evpn_instance_name', '=', 'kwargs', '.', 'pop', '(', "'evpn_instance_name'", ',', "''", ')', 'max_count', '=', 'kwargs', '.', 'pop', '(', "'max_count'", ',', "'5'", ')', 'enable', '=', 'kwargs', '.', 'pop', '(', "'enable'", ',...
Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled or disabled.Default:``True``. get (bool) : Get config in...
['Add', 'Duplicate', 'MAC', 'max', 'count', 'under', 'evpn', 'instance', '.']
train
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_0_0/interface.py#L1174-L1244
2,097
gruns/icecream
icecream/icecream.py
extractArgumentsFromCallStr
def extractArgumentsFromCallStr(callStr): """ Parse the argument string via an AST instead of the overly simple callStr.split(','). The latter incorrectly splits any string parameters that contain commas therein, like ic(1, 'a,b', 2). """ def isTuple(ele): return classname(ele) == 'Tuple...
python
def extractArgumentsFromCallStr(callStr): """ Parse the argument string via an AST instead of the overly simple callStr.split(','). The latter incorrectly splits any string parameters that contain commas therein, like ic(1, 'a,b', 2). """ def isTuple(ele): return classname(ele) == 'Tuple...
['def', 'extractArgumentsFromCallStr', '(', 'callStr', ')', ':', 'def', 'isTuple', '(', 'ele', ')', ':', 'return', 'classname', '(', 'ele', ')', '==', "'Tuple'", 'paramsStr', '=', 'callStr', '.', 'split', '(', "'('", ',', '1', ')', '[', '-', '1', ']', '.', 'rsplit', '(', "')'", ',', '1', ')', '[', '0', ']', '.', 'strip...
Parse the argument string via an AST instead of the overly simple callStr.split(','). The latter incorrectly splits any string parameters that contain commas therein, like ic(1, 'a,b', 2).
['Parse', 'the', 'argument', 'string', 'via', 'an', 'AST', 'instead', 'of', 'the', 'overly', 'simple', 'callStr', '.', 'split', '(', ')', '.', 'The', 'latter', 'incorrectly', 'splits', 'any', 'string', 'parameters', 'that', 'contain', 'commas', 'therein', 'like', 'ic', '(', '1', 'a', 'b', '2', ')', '.']
train
https://github.com/gruns/icecream/blob/cb4f3d50ec747637721fe58b80f2cc2a2baedabf/icecream/icecream.py#L459-L494
2,098
minio/minio-py
minio/api.py
Minio.fget_object
def fget_object(self, bucket_name, object_name, file_path, request_headers=None, sse=None): """ Retrieves an object from a bucket and writes at file_path. Examples: minio.fget_object('foo', 'bar', 'localfile') :param bucket_name: Bucket to read object from. :param o...
python
def fget_object(self, bucket_name, object_name, file_path, request_headers=None, sse=None): """ Retrieves an object from a bucket and writes at file_path. Examples: minio.fget_object('foo', 'bar', 'localfile') :param bucket_name: Bucket to read object from. :param o...
['def', 'fget_object', '(', 'self', ',', 'bucket_name', ',', 'object_name', ',', 'file_path', ',', 'request_headers', '=', 'None', ',', 'sse', '=', 'None', ')', ':', 'is_valid_bucket_name', '(', 'bucket_name', ')', 'is_non_empty_string', '(', 'object_name', ')', 'stat', '=', 'self', '.', 'stat_object', '(', 'bucket_nam...
Retrieves an object from a bucket and writes at file_path. Examples: minio.fget_object('foo', 'bar', 'localfile') :param bucket_name: Bucket to read object from. :param object_name: Name of the object to read. :param file_path: Local file path to save the object. :p...
['Retrieves', 'an', 'object', 'from', 'a', 'bucket', 'and', 'writes', 'at', 'file_path', '.']
train
https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L573-L645
2,099
saltstack/salt
salt/modules/rh_ip.py
build_bond
def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse...
python
def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse...
['def', 'build_bond', '(', 'iface', ',', '*', '*', 'settings', ')', ':', 'rh_major', '=', '__grains__', '[', "'osrelease'", ']', '[', ':', '1', ']', 'opts', '=', '_parse_settings_bond', '(', 'settings', ',', 'iface', ')', 'try', ':', 'template', '=', 'JINJA', '.', 'get_template', '(', "'conf.jinja'", ')', 'except', 'ji...
Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb
['Create', 'a', 'bond', 'script', 'in', '/', 'etc', '/', 'modprobe', '.', 'd', 'with', 'the', 'passed', 'settings', 'and', 'load', 'the', 'bonding', 'kernel', 'module', '.']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L980-L1017