repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
openpermissions/chub
chub/api.py
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L61-L69
def _sub_resource(self, path): """ get or create sub resource """ if path not in self.resource_map: self.resource_map[path] = Resource( path, self.fetch, self.resource_map, default_headers=self.default_headers) return self.resource_map[...
[ "def", "_sub_resource", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "resource_map", ":", "self", ".", "resource_map", "[", "path", "]", "=", "Resource", "(", "path", ",", "self", ".", "fetch", ",", "self", ".", "resour...
get or create sub resource
[ "get", "or", "create", "sub", "resource" ]
python
train
basho/riak-python-client
riak/codecs/pbuf.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/codecs/pbuf.py#L847-L895
def decode_timeseries_row(self, tsrow, tscols=None, convert_timestamp=False): """ Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode...
[ "def", "decode_timeseries_row", "(", "self", ",", "tsrow", ",", "tscols", "=", "None", ",", "convert_timestamp", "=", "False", ")", ":", "row", "=", "[", "]", "for", "i", ",", "cell", "in", "enumerate", "(", "tsrow", ".", "cells", ")", ":", "col", "=...
Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode. :type tscols: list :rtype list
[ "Decodes", "a", "TsRow", "into", "a", "list" ]
python
train
yohell/python-tui
tui/__init__.py
https://github.com/yohell/python-tui/blob/de2e678e2f00e5940de52c000214dbcb8812a222/tui/__init__.py#L1513-L1533
def strsettings(self, indent=0, maxindent=25, width=0): """Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is short...
[ "def", "strsettings", "(", "self", ",", "indent", "=", "0", ",", "maxindent", "=", "25", ",", "width", "=", "0", ")", ":", "out", "=", "[", "]", "makelabel", "=", "lambda", "name", ":", "' '", "*", "indent", "+", "name", "+", "': '", "settingsinden...
Return user friendly help on positional arguments. indent is the number of spaces preceeding the text on each line. The indent of the documentation is dependent on the length of the longest label that is shorter than maxindent. A label longer than maxindent will be p...
[ "Return", "user", "friendly", "help", "on", "positional", "arguments", "." ]
python
valid
saltstack/salt
salt/states/pagerduty_service.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_service.py#L87-L98
def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure a pagerduty service does not exist. Name can be the service name or pagerduty service id. ''' r = __salt__['pagerduty_util.resource_absent']('services', ['name', 'id...
[ "def", "absent", "(", "profile", "=", "'pagerduty'", ",", "subdomain", "=", "None", ",", "api_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "r", "=", "__salt__", "[", "'pagerduty_util.resource_absent'", "]", "(", "'services'", ",", "[", "'name'", ...
Ensure a pagerduty service does not exist. Name can be the service name or pagerduty service id.
[ "Ensure", "a", "pagerduty", "service", "does", "not", "exist", ".", "Name", "can", "be", "the", "service", "name", "or", "pagerduty", "service", "id", "." ]
python
train
twilio/twilio-python
twilio/rest/notify/v1/service/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/notify/v1/service/__init__.py#L38-L87
def create(self, friendly_name=values.unset, apn_credential_sid=values.unset, gcm_credential_sid=values.unset, messaging_service_sid=values.unset, facebook_messenger_page_id=values.unset, default_apn_notification_protocol_version=values.unset, default_gcm_noti...
[ "def", "create", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "apn_credential_sid", "=", "values", ".", "unset", ",", "gcm_credential_sid", "=", "values", ".", "unset", ",", "messaging_service_sid", "=", "values", ".", "unset", ",", "...
Create a new ServiceInstance :param unicode friendly_name: A string to describe the resource :param unicode apn_credential_sid: The SID of the Credential to use for APN Bindings :param unicode gcm_credential_sid: The SID of the Credential to use for GCM Bindings :param unicode messaging...
[ "Create", "a", "new", "ServiceInstance" ]
python
train
Josef-Friedrich/tmep
tmep/doc.py
https://github.com/Josef-Friedrich/tmep/blob/326de14f5b9498696a1f06a8be3d39e33e376102/tmep/doc.py#L33-L52
def extract_value(self, string, key, inline_code=True): """Extract strings from the docstrings .. code-block:: text * synopsis: ``%shorten{text, max_size}`` * example: ``%shorten{$title, 32}`` * description: Shorten “text” on word boundarys. """ reg...
[ "def", "extract_value", "(", "self", ",", "string", ",", "key", ",", "inline_code", "=", "True", ")", ":", "regex", "=", "r'\\* '", "+", "key", "+", "': '", "if", "inline_code", ":", "regex", "=", "regex", "+", "'``(.*)``'", "else", ":", "regex", "=", ...
Extract strings from the docstrings .. code-block:: text * synopsis: ``%shorten{text, max_size}`` * example: ``%shorten{$title, 32}`` * description: Shorten “text” on word boundarys.
[ "Extract", "strings", "from", "the", "docstrings" ]
python
train
jstitch/MambuPy
MambuPy/mambuutil.py
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/mambuutil.py#L548-L562
def getproductsurl(idproduct, *args, **kwargs): """Request loan Products URL. If idproduct is set, you'll get a response adequate for a MambuProduct object. If not set, you'll get a response adequate for a MambuProducts object. See mambuproduct module and pydoc for further information. No current ...
[ "def", "getproductsurl", "(", "idproduct", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "productidparam", "=", "\"\"", "if", "idproduct", "==", "\"\"", "else", "\"/\"", "+", "idproduct", "url", "=", "getmambuurl", "(", "*", "args", ",", "*", "*...
Request loan Products URL. If idproduct is set, you'll get a response adequate for a MambuProduct object. If not set, you'll get a response adequate for a MambuProducts object. See mambuproduct module and pydoc for further information. No current implemented filter parameters. See Mambu official ...
[ "Request", "loan", "Products", "URL", "." ]
python
train
pandas-dev/pandas
pandas/core/groupby/base.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/base.py#L33-L67
def _gotitem(self, key, ndim, subset=None): """ Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on ...
[ "def", "_gotitem", "(", "self", ",", "key", ",", "ndim", ",", "subset", "=", "None", ")", ":", "# create a new object to prevent aliasing", "if", "subset", "is", "None", ":", "subset", "=", "self", ".", "obj", "# we need to make a shallow copy of ourselves", "# wi...
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on
[ "Sub", "-", "classes", "to", "define", ".", "Return", "a", "sliced", "object", "." ]
python
train
ajyoon/blur
blur/markov/graph.py
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/markov/graph.py#L152-L206
def feather_links(self, factor=0.01, include_self=False): """ Feather the links of connected nodes. Go through every node in the network and make it inherit the links of the other nodes it is connected to. Because the link weight sum for any given node can be very different with...
[ "def", "feather_links", "(", "self", ",", "factor", "=", "0.01", ",", "include_self", "=", "False", ")", ":", "def", "feather_node", "(", "node", ")", ":", "node_weight_sum", "=", "sum", "(", "l", ".", "weight", "for", "l", "in", "node", ".", "link_lis...
Feather the links of connected nodes. Go through every node in the network and make it inherit the links of the other nodes it is connected to. Because the link weight sum for any given node can be very different within a graph, the weights of inherited links are made proportional to th...
[ "Feather", "the", "links", "of", "connected", "nodes", "." ]
python
train
pmichali/whodunit
whodunit/__init__.py
https://github.com/pmichali/whodunit/blob/eed9107533766d716469e35fbb647a39dfa07035/whodunit/__init__.py#L306-L319
def sort(self): """Sort by commit size, per author.""" # First sort commits by author email users = [] # Group commits by author email, so they can be merged for _, group in itertools.groupby(sorted(self.commits), operator.attrgetter('aut...
[ "def", "sort", "(", "self", ")", ":", "# First sort commits by author email", "users", "=", "[", "]", "# Group commits by author email, so they can be merged", "for", "_", ",", "group", "in", "itertools", ".", "groupby", "(", "sorted", "(", "self", ".", "commits", ...
Sort by commit size, per author.
[ "Sort", "by", "commit", "size", "per", "author", "." ]
python
train
hollenstein/maspy
maspy/sil.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/sil.py#L271-L327
def expectedLabelPosition(peptide, labelStateInfo, sequence=None, modPositions=None): """Returns a modification description of a certain label state of a peptide. :param peptide: Peptide sequence used to calculat the expected label state modifications :param labelStateInfo...
[ "def", "expectedLabelPosition", "(", "peptide", ",", "labelStateInfo", ",", "sequence", "=", "None", ",", "modPositions", "=", "None", ")", ":", "if", "modPositions", "is", "None", ":", "modPositions", "=", "maspy", ".", "peptidemethods", ".", "returnModPosition...
Returns a modification description of a certain label state of a peptide. :param peptide: Peptide sequence used to calculat the expected label state modifications :param labelStateInfo: An entry of :attr:`LabelDescriptor.labels` that describes a label state :param sequence: unmodified amino...
[ "Returns", "a", "modification", "description", "of", "a", "certain", "label", "state", "of", "a", "peptide", "." ]
python
train
ask/carrot
carrot/messaging.py
https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/messaging.py#L712-L772
def send(self, message_data, routing_key=None, delivery_mode=None, mandatory=False, immediate=False, priority=0, content_type=None, content_encoding=None, serializer=None, exchange=None): """Send a message. :param message_data: The message data to send. Can be a list, ...
[ "def", "send", "(", "self", ",", "message_data", ",", "routing_key", "=", "None", ",", "delivery_mode", "=", "None", ",", "mandatory", "=", "False", ",", "immediate", "=", "False", ",", "priority", "=", "0", ",", "content_type", "=", "None", ",", "conten...
Send a message. :param message_data: The message data to send. Can be a list, dictionary or a string. :keyword routing_key: A custom routing key for the message. If not set, the default routing key set in the :attr:`routing_key` attribute is used. :keyword ...
[ "Send", "a", "message", "." ]
python
train
apple/turicreate
deps/src/boost_1_68_0/libs/predef/tools/ci/common.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/common.py#L683-L709
def install_toolset(self, toolset): ''' Installs specific toolset on CI system. ''' info = toolset_info[toolset] if sys.platform.startswith('linux'): os.chdir(self.work_dir) if 'ppa' in info: for ppa in info['ppa']: util...
[ "def", "install_toolset", "(", "self", ",", "toolset", ")", ":", "info", "=", "toolset_info", "[", "toolset", "]", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "os", ".", "chdir", "(", "self", ".", "work_dir", ")", "if", ...
Installs specific toolset on CI system.
[ "Installs", "specific", "toolset", "on", "CI", "system", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/distributions/poisson_lognormal.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/poisson_lognormal.py#L45-L85
def quadrature_scheme_lognormal_gauss_hermite( loc, scale, quadrature_size, validate_args=False, name=None): # pylint: disable=unused-argument """Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadratur...
[ "def", "quadrature_scheme_lognormal_gauss_hermite", "(", "loc", ",", "scale", ",", "quadrature_size", ",", "validate_args", "=", "False", ",", "name", "=", "None", ")", ":", "# pylint: disable=unused-argument", "with", "tf", ".", "name_scope", "(", "name", "or", "...
Use Gauss-Hermite quadrature to form quadrature on positive-reals. Note: for a given `quadrature_size`, this method is generally less accurate than `quadrature_scheme_lognormal_quantiles`. Args: loc: `float`-like (batch of) scalar `Tensor`; the location parameter of the LogNormal prior. scale: `fl...
[ "Use", "Gauss", "-", "Hermite", "quadrature", "to", "form", "quadrature", "on", "positive", "-", "reals", "." ]
python
test
cbrand/vpnchooser
src/vpnchooser/helpers/parser.py
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/helpers/parser.py#L9-L44
def id_from_url(url, param_name: str) -> int: """ Parses an object and tries to extract a url. Tries to parse if a resource_url has been given it as a url. :raise ValueError: If no id could be extracted. """ if url is None: raise ValueError('url is none') elif isinstance(url, int...
[ "def", "id_from_url", "(", "url", ",", "param_name", ":", "str", ")", "->", "int", ":", "if", "url", "is", "None", ":", "raise", "ValueError", "(", "'url is none'", ")", "elif", "isinstance", "(", "url", ",", "int", ")", ":", "# Seems to already be the url...
Parses an object and tries to extract a url. Tries to parse if a resource_url has been given it as a url. :raise ValueError: If no id could be extracted.
[ "Parses", "an", "object", "and", "tries", "to", "extract", "a", "url", ".", "Tries", "to", "parse", "if", "a", "resource_url", "has", "been", "given", "it", "as", "a", "url", ".", ":", "raise", "ValueError", ":", "If", "no", "id", "could", "be", "ext...
python
train
GoogleCloudPlatform/python-repo-tools
gcp_devrel/tools/requirements.py
https://github.com/GoogleCloudPlatform/python-repo-tools/blob/87422ba91814529848a2b8bf8be4294283a3e041/gcp_devrel/tools/requirements.py#L85-L112
def update_req(req): """Updates a given req object with the latest version.""" if not req.name: return req, None info = get_package_info(req.name) if info['info'].get('_pypi_hidden'): print('{} is hidden on PyPI and will not be updated.'.format(req)) return req, None if _...
[ "def", "update_req", "(", "req", ")", ":", "if", "not", "req", ".", "name", ":", "return", "req", ",", "None", "info", "=", "get_package_info", "(", "req", ".", "name", ")", "if", "info", "[", "'info'", "]", ".", "get", "(", "'_pypi_hidden'", ")", ...
Updates a given req object with the latest version.
[ "Updates", "a", "given", "req", "object", "with", "the", "latest", "version", "." ]
python
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/search.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/search.py#L571-L650
def match(self, word): """ Return True if the given Word is part of the constraint: - the word (or lemma) occurs in Constraint.words, OR - the word (or lemma) occurs in Constraint.taxa taxonomy tree, AND - the word and/or chunk tags match those defined in the constraint. ...
[ "def", "match", "(", "self", ",", "word", ")", ":", "# If the constraint has a custom function it must return True.", "if", "self", ".", "custom", "is", "not", "None", "and", "self", ".", "custom", "(", "word", ")", "is", "False", ":", "return", "False", "# If...
Return True if the given Word is part of the constraint: - the word (or lemma) occurs in Constraint.words, OR - the word (or lemma) occurs in Constraint.taxa taxonomy tree, AND - the word and/or chunk tags match those defined in the constraint. Individual terms in Constra...
[ "Return", "True", "if", "the", "given", "Word", "is", "part", "of", "the", "constraint", ":", "-", "the", "word", "(", "or", "lemma", ")", "occurs", "in", "Constraint", ".", "words", "OR", "-", "the", "word", "(", "or", "lemma", ")", "occurs", "in", ...
python
train
ThreatConnect-Inc/tcex
tcex/tcex_ti/mappings/group/group_types/document.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/document.py#L55-L67
def file_name(self, file_name): """ Updates the file_name. Args: file_name: """ if not self.can_update(): self._tcex.handle_error(910, [self.type]) self._data['fileName'] = file_name request = {'fileName': file_name} return self.t...
[ "def", "file_name", "(", "self", ",", "file_name", ")", ":", "if", "not", "self", ".", "can_update", "(", ")", ":", "self", ".", "_tcex", ".", "handle_error", "(", "910", ",", "[", "self", ".", "type", "]", ")", "self", ".", "_data", "[", "'fileNam...
Updates the file_name. Args: file_name:
[ "Updates", "the", "file_name", "." ]
python
train
saltstack/salt
salt/modules/inspectlib/fsdb.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/fsdb.py#L104-L113
def flush(self, table): ''' Flush table. :param table: :return: ''' table_path = os.path.join(self.db_path, table) if os.path.exists(table_path): os.unlink(table_path)
[ "def", "flush", "(", "self", ",", "table", ")", ":", "table_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "db_path", ",", "table", ")", "if", "os", ".", "path", ".", "exists", "(", "table_path", ")", ":", "os", ".", "unlink", "(",...
Flush table. :param table: :return:
[ "Flush", "table", "." ]
python
train
zarr-developers/zarr
zarr/core.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L2244-L2302
def astype(self, dtype): """Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same ...
[ "def", "astype", "(", "self", ",", "dtype", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "filters", "=", "[", "]", "if", "self", ".", "_filters", ":", "filters", ".", "extend", "(", "self", ".", "_filters", ")", "filters", ".", ...
Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same underlying chunk data. Modifying any...
[ "Returns", "a", "view", "that", "does", "on", "the", "fly", "type", "conversion", "of", "the", "underlying", "data", "." ]
python
train
stephantul/somber
somber/plsom.py
https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/plsom.py#L139-L147
def _update_params(self, constants): """Update the params.""" constants = np.max(np.min(constants, 1)) self.params['r']['value'] = max([self.params['r']['value'], constants]) epsilon = constants / self.params['r']['value'] influence = self...
[ "def", "_update_params", "(", "self", ",", "constants", ")", ":", "constants", "=", "np", ".", "max", "(", "np", ".", "min", "(", "constants", ",", "1", ")", ")", "self", ".", "params", "[", "'r'", "]", "[", "'value'", "]", "=", "max", "(", "[", ...
Update the params.
[ "Update", "the", "params", "." ]
python
train
pybel/pybel-tools
src/pybel_tools/mutation/bound.py
https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/mutation/bound.py#L29-L38
def build_delete_node_by_hash(manager: Manager) -> Callable[[BELGraph, str], None]: """Make a delete function that's bound to the manager.""" @in_place_transformation def delete_node_by_hash(graph: BELGraph, node_hash: str) -> None: """Remove a node by identifier.""" node = manager.get_dsl_...
[ "def", "build_delete_node_by_hash", "(", "manager", ":", "Manager", ")", "->", "Callable", "[", "[", "BELGraph", ",", "str", "]", ",", "None", "]", ":", "@", "in_place_transformation", "def", "delete_node_by_hash", "(", "graph", ":", "BELGraph", ",", "node_has...
Make a delete function that's bound to the manager.
[ "Make", "a", "delete", "function", "that", "s", "bound", "to", "the", "manager", "." ]
python
valid
ellisonbg/vizarray
vizarray/__init__.py
https://github.com/ellisonbg/vizarray/blob/3221a232ecf54e8348094aacfc5719b40d89a451/vizarray/__init__.py#L129-L137
def disable_notebook(): """Disable automatic visualization of NumPy arrays in the IPython Notebook.""" try: from IPython.core.getipython import get_ipython except ImportError: raise ImportError('This feature requires IPython 1.0+') ip = get_ipython() f = ip.display_formatter.formatte...
[ "def", "disable_notebook", "(", ")", ":", "try", ":", "from", "IPython", ".", "core", ".", "getipython", "import", "get_ipython", "except", "ImportError", ":", "raise", "ImportError", "(", "'This feature requires IPython 1.0+'", ")", "ip", "=", "get_ipython", "(",...
Disable automatic visualization of NumPy arrays in the IPython Notebook.
[ "Disable", "automatic", "visualization", "of", "NumPy", "arrays", "in", "the", "IPython", "Notebook", "." ]
python
train
mogproject/mog-commons-python
src/mog_commons/command.py
https://github.com/mogproject/mog-commons-python/blob/951cf0fa9a56248b4d45be720be25f1d4b7e1bff/src/mog_commons/command.py#L41-L49
def __convert_env(env, encoding): """Environment variables should be bytes not unicode on Windows.""" d = dict(os.environ, **(oget(env, {}))) # workaround for Windows+Python3 environment if not SHOULD_NOT_ENCODE_ARGS: return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items()) ...
[ "def", "__convert_env", "(", "env", ",", "encoding", ")", ":", "d", "=", "dict", "(", "os", ".", "environ", ",", "*", "*", "(", "oget", "(", "env", ",", "{", "}", ")", ")", ")", "# workaround for Windows+Python3 environment", "if", "not", "SHOULD_NOT_ENC...
Environment variables should be bytes not unicode on Windows.
[ "Environment", "variables", "should", "be", "bytes", "not", "unicode", "on", "Windows", "." ]
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/rst/dplp.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/rst/dplp.py#L93-L114
def dplptree2dgparentedtree(self): """Convert the tree from DPLP's format into a conventional binary tree, which can be easily converted into output formats like RS3. """ def transform(dplp_tree): """Transform a DPLP parse tree into a more conventional parse tree.""" ...
[ "def", "dplptree2dgparentedtree", "(", "self", ")", ":", "def", "transform", "(", "dplp_tree", ")", ":", "\"\"\"Transform a DPLP parse tree into a more conventional parse tree.\"\"\"", "if", "isinstance", "(", "dplp_tree", ",", "basestring", ")", "or", "not", "hasattr", ...
Convert the tree from DPLP's format into a conventional binary tree, which can be easily converted into output formats like RS3.
[ "Convert", "the", "tree", "from", "DPLP", "s", "format", "into", "a", "conventional", "binary", "tree", "which", "can", "be", "easily", "converted", "into", "output", "formats", "like", "RS3", "." ]
python
train
dossier/dossier.label
dossier/label/label.py
https://github.com/dossier/dossier.label/blob/d445e56b02ffd91ad46b0872cfbff62b9afef7ec/dossier/label/label.py#L852-L884
def everything(self, include_deleted=False, content_id=None, subtopic_id=None, prefix=None): '''Returns a generator of all labels in the store. If `include_deleted` is :const:`True`, labels that have been overwritten with more recent labels are also included. If `con...
[ "def", "everything", "(", "self", ",", "include_deleted", "=", "False", ",", "content_id", "=", "None", ",", "subtopic_id", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "content_id", "is", "not", "None", ":", "ranges", "=", "[", "(", "(", ...
Returns a generator of all labels in the store. If `include_deleted` is :const:`True`, labels that have been overwritten with more recent labels are also included. If `content_id` is not :const:`None`, only labels for that content ID are retrieved; and then if `subtopic_id` is not ...
[ "Returns", "a", "generator", "of", "all", "labels", "in", "the", "store", "." ]
python
train
foremast/foremast
src/foremast/utils/generate_s3_tags.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/generate_s3_tags.py#L4-L20
def generated_tag_data(tags): """Convert :obj:`dict` to S3 Tag list. Args: tags (dict): Dictonary of tag key and tag value passed. Returns: list: List of dictionaries. """ generated_tags = [] for key, value in tags.items(): generated_tags.append({ 'Key': ke...
[ "def", "generated_tag_data", "(", "tags", ")", ":", "generated_tags", "=", "[", "]", "for", "key", ",", "value", "in", "tags", ".", "items", "(", ")", ":", "generated_tags", ".", "append", "(", "{", "'Key'", ":", "key", ",", "'Value'", ":", "value", ...
Convert :obj:`dict` to S3 Tag list. Args: tags (dict): Dictonary of tag key and tag value passed. Returns: list: List of dictionaries.
[ "Convert", ":", "obj", ":", "dict", "to", "S3", "Tag", "list", "." ]
python
train
andycasey/sick
sick/models/create.py
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/create.py#L49-L161
def create(output_prefix, grid_flux_filename, wavelength_filenames, clobber=False, grid_flux_filename_format="csv", **kwargs): """ Create a new *sick* model from files describing the parameter names, fluxes, and wavelengths. """ if not clobber: # Check to make sure the output files won'...
[ "def", "create", "(", "output_prefix", ",", "grid_flux_filename", ",", "wavelength_filenames", ",", "clobber", "=", "False", ",", "grid_flux_filename_format", "=", "\"csv\"", ",", "*", "*", "kwargs", ")", ":", "if", "not", "clobber", ":", "# Check to make sure the...
Create a new *sick* model from files describing the parameter names, fluxes, and wavelengths.
[ "Create", "a", "new", "*", "sick", "*", "model", "from", "files", "describing", "the", "parameter", "names", "fluxes", "and", "wavelengths", "." ]
python
train
Parquery/icontract
icontract/_recompute.py
https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_recompute.py#L275-L285
def visit_IfExp(self, node: ast.IfExp) -> Any: """Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.""" test = self.visit(node=node.test) if test: result = self.visit(node=node.body) else: result = self.visit(node=node.orelse) ...
[ "def", "visit_IfExp", "(", "self", ",", "node", ":", "ast", ".", "IfExp", ")", "->", "Any", ":", "test", "=", "self", ".", "visit", "(", "node", "=", "node", ".", "test", ")", "if", "test", ":", "result", "=", "self", ".", "visit", "(", "node", ...
Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.
[ "Visit", "the", "test", "and", "depending", "on", "its", "outcome", "the", "body", "or", "orelse", "." ]
python
train
robotpy/pyfrc
lib/pyfrc/physics/visionsim.py
https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/physics/visionsim.py#L190-L236
def compute(self, now, x, y, angle): """ Call this when vision processing should be enabled :param now: The value passed to ``update_sim`` :param x: Returned from physics_controller.get_position :param y: Returned from physics_controller.get_pos...
[ "def", "compute", "(", "self", ",", "now", ",", "x", ",", "y", ",", "angle", ")", ":", "# Normalize angle to [-180,180]", "output", "=", "[", "]", "angle", "=", "(", "(", "angle", "+", "math", ".", "pi", ")", "%", "(", "math", ".", "pi", "*", "2"...
Call this when vision processing should be enabled :param now: The value passed to ``update_sim`` :param x: Returned from physics_controller.get_position :param y: Returned from physics_controller.get_position :param angle: Returned from physics_control...
[ "Call", "this", "when", "vision", "processing", "should", "be", "enabled", ":", "param", "now", ":", "The", "value", "passed", "to", "update_sim", ":", "param", "x", ":", "Returned", "from", "physics_controller", ".", "get_position", ":", "param", "y", ":", ...
python
train
caffeinehit/django-oauth2-provider
provider/views.py
https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L469-L492
def access_token_response(self, access_token): """ Returns a successful response after creating the access token as defined in :rfc:`5.1`. """ response_data = { 'access_token': access_token.token, 'token_type': constants.TOKEN_TYPE, 'expires_i...
[ "def", "access_token_response", "(", "self", ",", "access_token", ")", ":", "response_data", "=", "{", "'access_token'", ":", "access_token", ".", "token", ",", "'token_type'", ":", "constants", ".", "TOKEN_TYPE", ",", "'expires_in'", ":", "access_token", ".", "...
Returns a successful response after creating the access token as defined in :rfc:`5.1`.
[ "Returns", "a", "successful", "response", "after", "creating", "the", "access", "token", "as", "defined", "in", ":", "rfc", ":", "5", ".", "1", "." ]
python
train
JoelBender/bacpypes
py25/bacpypes/debugging.py
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/debugging.py#L91-L212
def debug_contents(self, indent=1, file=sys.stdout, _ids=None): """Debug the contents of an object.""" if _debug: _log.debug("debug_contents indent=%r file=%r _ids=%r", indent, file, _ids) klasses = list(self.__class__.__mro__) klasses.reverse() if _debug: _log.debug(" - klas...
[ "def", "debug_contents", "(", "self", ",", "indent", "=", "1", ",", "file", "=", "sys", ".", "stdout", ",", "_ids", "=", "None", ")", ":", "if", "_debug", ":", "_log", ".", "debug", "(", "\"debug_contents indent=%r file=%r _ids=%r\"", ",", "indent", ",", ...
Debug the contents of an object.
[ "Debug", "the", "contents", "of", "an", "object", "." ]
python
train
jobovy/galpy
galpy/util/bovy_coords.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L372-L415
def sphergal_to_rectgal(l,b,d,vr,pmll,pmbb,degree=False): """ NAME: sphergal_to_rectgal PURPOSE: transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs) INPUT: l - Galactic longitude (rad) b - Gala...
[ "def", "sphergal_to_rectgal", "(", "l", ",", "b", ",", "d", ",", "vr", ",", "pmll", ",", "pmbb", ",", "degree", "=", "False", ")", ":", "XYZ", "=", "lbd_to_XYZ", "(", "l", ",", "b", ",", "d", ",", "degree", "=", "degree", ")", "vxvyvz", "=", "v...
NAME: sphergal_to_rectgal PURPOSE: transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs) INPUT: l - Galactic longitude (rad) b - Galactic lattitude (rad) d - distance (kpc) vr - line-of-s...
[ "NAME", ":" ]
python
train
ianmiell/shutit
emailer.py
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L88-L125
def __set_config(self, cfg_section): """Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__ """ defaults = [ 'shutit.core.alerting.emailer.mailto', None, 'shutit.core.alerting.emailer.mailfrom', 'angry@shutit.tk', 'shutit.core.alerting.emailer.s...
[ "def", "__set_config", "(", "self", ",", "cfg_section", ")", ":", "defaults", "=", "[", "'shutit.core.alerting.emailer.mailto'", ",", "None", ",", "'shutit.core.alerting.emailer.mailfrom'", ",", "'angry@shutit.tk'", ",", "'shutit.core.alerting.emailer.smtp_server'", ",", "'...
Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__
[ "Set", "a", "local", "config", "array", "up", "according", "to", "defaults", "and", "main", "shutit", "configuration" ]
python
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L198-L222
def load_conditions(self, filename=None): """Read the initial conditions from a file and assign them to the respective |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object. If no filename or dirname is passed, the ones defined by the |ConditionMa...
[ "def", "load_conditions", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "self", ".", "hasconditions", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "_conditiondefaultfilename", "namespace", "=", "locals", "(", ")", "for", "s...
Read the initial conditions from a file and assign them to the respective |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used.
[ "Read", "the", "initial", "conditions", "from", "a", "file", "and", "assign", "them", "to", "the", "respective", "|StateSequence|", "and", "/", "or", "|LogSequence|", "objects", "handled", "by", "the", "actual", "|Sequences|", "object", "." ]
python
train
deepmind/sonnet
sonnet/python/modules/base_info.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/base_info.py#L119-L142
def _from_proto_sparse_tensor(sparse_tensor_proto, process_leafs): """Deserializes a `tf.SparseTensor` from `sparse_tensor_proto`. Args: sparse_tensor_proto: A proto representing a `tf.SparseTensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. Returns: A...
[ "def", "_from_proto_sparse_tensor", "(", "sparse_tensor_proto", ",", "process_leafs", ")", ":", "if", "not", "sparse_tensor_proto", ".", "HasField", "(", "\"named_tuple\"", ")", ":", "raise", "base_errors", ".", "ModuleInfoError", "(", "\"Error while deserializing a Spars...
Deserializes a `tf.SparseTensor` from `sparse_tensor_proto`. Args: sparse_tensor_proto: A proto representing a `tf.SparseTensor`. process_leafs: A function to be applied to the leaf valued of the nested structure. Returns: An instance of `tf.SparseTensor`.
[ "Deserializes", "a", "tf", ".", "SparseTensor", "from", "sparse_tensor_proto", "." ]
python
train
RJT1990/pyflux
pyflux/tsm.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/tsm.py#L187-L221
def _laplace_fit(self,obj_type): """ Performs a Laplace approximation to the posterior Parameters ---------- obj_type : method Whether a likelihood or a posterior Returns ---------- None (plots posterior) """ # Get Mode and Inverse H...
[ "def", "_laplace_fit", "(", "self", ",", "obj_type", ")", ":", "# Get Mode and Inverse Hessian information", "y", "=", "self", ".", "fit", "(", "method", "=", "'PML'", ",", "printer", "=", "False", ")", "if", "y", ".", "ihessian", "is", "None", ":", "raise...
Performs a Laplace approximation to the posterior Parameters ---------- obj_type : method Whether a likelihood or a posterior Returns ---------- None (plots posterior)
[ "Performs", "a", "Laplace", "approximation", "to", "the", "posterior" ]
python
train
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/executor.py
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L206-L214
def update_from(self, mapping): """ Updates the set of parameters from a mapping for keys that already exist """ for key, value in mapping.items(): if key in self: if isinstance(value, Parameter): value = value.value self[ke...
[ "def", "update_from", "(", "self", ",", "mapping", ")", ":", "for", "key", ",", "value", "in", "mapping", ".", "items", "(", ")", ":", "if", "key", "in", "self", ":", "if", "isinstance", "(", "value", ",", "Parameter", ")", ":", "value", "=", "valu...
Updates the set of parameters from a mapping for keys that already exist
[ "Updates", "the", "set", "of", "parameters", "from", "a", "mapping", "for", "keys", "that", "already", "exist" ]
python
train
trailofbits/manticore
manticore/ethereum/solidity.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/solidity.py#L196-L205
def get_func_argument_types(self, hsh: bytes): """Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned. """ if not i...
[ "def", "get_func_argument_types", "(", "self", ",", "hsh", ":", "bytes", ")", ":", "if", "not", "isinstance", "(", "hsh", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "raise", "TypeError", "(", "'The selector argument must be a concrete byte array'", ")",...
Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned.
[ "Returns", "the", "tuple", "type", "signature", "for", "the", "arguments", "of", "the", "function", "associated", "with", "the", "selector", "hsh", "." ]
python
valid
larsyencken/csvdiff
csvdiff/patch.py
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L326-L337
def _is_significant(change, significance): """ Return True if a change is genuinely significant given our tolerance. """ try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
[ "def", "_is_significant", "(", "change", ",", "significance", ")", ":", "try", ":", "a", "=", "float", "(", "change", "[", "'from'", "]", ")", "b", "=", "float", "(", "change", "[", "'to'", "]", ")", "except", "ValueError", ":", "return", "True", "re...
Return True if a change is genuinely significant given our tolerance.
[ "Return", "True", "if", "a", "change", "is", "genuinely", "significant", "given", "our", "tolerance", "." ]
python
train
muatik/naive-bayes-classifier
naiveBayesClassifier/trainer.py
https://github.com/muatik/naive-bayes-classifier/blob/cdc1d8681ef6674e946cff38e87ce3b00c732fbb/naiveBayesClassifier/trainer.py#L11-L21
def train(self, text, className): """ enhances trained data using the given text and class """ self.data.increaseClass(className) tokens = self.tokenizer.tokenize(text) for token in tokens: token = self.tokenizer.remove_stop_words(token) token = s...
[ "def", "train", "(", "self", ",", "text", ",", "className", ")", ":", "self", ".", "data", ".", "increaseClass", "(", "className", ")", "tokens", "=", "self", ".", "tokenizer", ".", "tokenize", "(", "text", ")", "for", "token", "in", "tokens", ":", "...
enhances trained data using the given text and class
[ "enhances", "trained", "data", "using", "the", "given", "text", "and", "class" ]
python
train
TkTech/Jawa
jawa/util/utf.py
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/utf.py#L12-L52
def decode_modified_utf8(s: bytes) -> str: """ Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string. """ s = bytearray(s) buff = [] buffer_...
[ "def", "decode_modified_utf8", "(", "s", ":", "bytes", ")", "->", "str", ":", "s", "=", "bytearray", "(", "s", ")", "buff", "=", "[", "]", "buffer_append", "=", "buff", ".", "append", "ix", "=", "0", "while", "ix", "<", "len", "(", "s", ")", ":",...
Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string.
[ "Decodes", "a", "bytestring", "containing", "modified", "UTF", "-", "8", "as", "defined", "in", "section", "4", ".", "4", ".", "7", "of", "the", "JVM", "specification", "." ]
python
train
google/apitools
apitools/base/py/transfer.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/transfer.py#L286-L297
def __SetTotal(self, info): """Sets the total size based off info if possible otherwise 0.""" if 'content-range' in info: _, _, total = info['content-range'].rpartition('/') if total != '*': self.__total_size = int(total) # Note "total_size is None" means ...
[ "def", "__SetTotal", "(", "self", ",", "info", ")", ":", "if", "'content-range'", "in", "info", ":", "_", ",", "_", ",", "total", "=", "info", "[", "'content-range'", "]", ".", "rpartition", "(", "'/'", ")", "if", "total", "!=", "'*'", ":", "self", ...
Sets the total size based off info if possible otherwise 0.
[ "Sets", "the", "total", "size", "based", "off", "info", "if", "possible", "otherwise", "0", "." ]
python
train
astropy/photutils
photutils/psf/sandbox.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/sandbox.py#L365-L383
def to_rectified(self, x, y): """ Convert the input (x, y) positions from the original (unrectified) image to the rectified image. Parameters ---------- x, y: float or array-like of float The zero-index pixel coordinates in the original (unrectif...
[ "def", "to_rectified", "(", "self", ",", "x", ",", "y", ")", ":", "return", "self", ".", "_reproject", "(", "self", ".", "wcs_original", ",", "self", ".", "wcs_rectified", ")", "(", "x", ",", "y", ")" ]
Convert the input (x, y) positions from the original (unrectified) image to the rectified image. Parameters ---------- x, y: float or array-like of float The zero-index pixel coordinates in the original (unrectified) image. Returns ------- ...
[ "Convert", "the", "input", "(", "x", "y", ")", "positions", "from", "the", "original", "(", "unrectified", ")", "image", "to", "the", "rectified", "image", "." ]
python
train
linkhub-sdk/popbill.py
popbill/faxService.py
https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/faxService.py#L389-L417
def resendFaxRN(self, CorpNum, OrgRequestNum, SenderNum, SenderName, ReceiverNum, ReceiverName, ReserveDT=None, UserID=None, title=None, RequestNum=None): """ 팩스 단건 전송 args CorpNum : 팝빌회원 사업자번호 OrgRequestNum : 원본 팩스 전송시 할당한 전송요청번호 R...
[ "def", "resendFaxRN", "(", "self", ",", "CorpNum", ",", "OrgRequestNum", ",", "SenderNum", ",", "SenderName", ",", "ReceiverNum", ",", "ReceiverName", ",", "ReserveDT", "=", "None", ",", "UserID", "=", "None", ",", "title", "=", "None", ",", "RequestNum", ...
팩스 단건 전송 args CorpNum : 팝빌회원 사업자번호 OrgRequestNum : 원본 팩스 전송시 할당한 전송요청번호 ReceiptNum : 팩스 접수번호 SenderNum : 발신자 번호 SenderName : 발신자명 ReceiverNum : 수신번호 ReceiverName : 수신자명 ReserveDT :...
[ "팩스", "단건", "전송", "args", "CorpNum", ":", "팝빌회원", "사업자번호", "OrgRequestNum", ":", "원본", "팩스", "전송시", "할당한", "전송요청번호", "ReceiptNum", ":", "팩스", "접수번호", "SenderNum", ":", "발신자", "번호", "SenderName", ":", "발신자명", "ReceiverNum", ":", "수신번호", "ReceiverName", ":",...
python
train
mottosso/be
be/vendor/requests/sessions.py
https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/requests/sessions.py#L92-L201
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Receives a Response. Returns a generator of Responses.""" i = 0 hist = [] # keep track of history while resp.is_redirect: prepared_request ...
[ "def", "resolve_redirects", "(", "self", ",", "resp", ",", "req", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "i", "=", "0", "hist", "=", "...
Receives a Response. Returns a generator of Responses.
[ "Receives", "a", "Response", ".", "Returns", "a", "generator", "of", "Responses", "." ]
python
train
NORDUnet/python-norduniclient
norduniclient/core.py
https://github.com/NORDUnet/python-norduniclient/blob/ee5084a6f45caac614b4fda4a023749ca52f786c/norduniclient/core.py#L117-L135
def get_db_driver(uri, username=None, password=None, encrypted=True, max_pool_size=50, trust=0): """ :param uri: Bolt uri :type uri: str :param username: Neo4j username :type username: str :param password: Neo4j password :type password: str :param encrypted: Use TLS :type encrypted: ...
[ "def", "get_db_driver", "(", "uri", ",", "username", "=", "None", ",", "password", "=", "None", ",", "encrypted", "=", "True", ",", "max_pool_size", "=", "50", ",", "trust", "=", "0", ")", ":", "return", "GraphDatabase", ".", "driver", "(", "uri", ",",...
:param uri: Bolt uri :type uri: str :param username: Neo4j username :type username: str :param password: Neo4j password :type password: str :param encrypted: Use TLS :type encrypted: Boolean :param max_pool_size: Maximum number of idle sessions :type max_pool_size: Integer :param...
[ ":", "param", "uri", ":", "Bolt", "uri", ":", "type", "uri", ":", "str", ":", "param", "username", ":", "Neo4j", "username", ":", "type", "username", ":", "str", ":", "param", "password", ":", "Neo4j", "password", ":", "type", "password", ":", "str", ...
python
train
chemlab/chemlab
chemlab/core/base.py
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L575-L634
def where(self, inplace=False, **kwargs): """Return indices over every dimension that met the conditions. Condition syntax: *attribute* = value Return indices that satisfy the condition where the attribute is equal to the value e.g. ty...
[ "def", "where", "(", "self", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "masks", "=", "{", "k", ":", "np", ".", "ones", "(", "v", ",", "dtype", "=", "'bool'", ")", "for", "k", ",", "v", "in", "self", ".", "dimensions", "...
Return indices over every dimension that met the conditions. Condition syntax: *attribute* = value Return indices that satisfy the condition where the attribute is equal to the value e.g. type_array = 'H' *attribute* = list(va...
[ "Return", "indices", "over", "every", "dimension", "that", "met", "the", "conditions", ".", "Condition", "syntax", ":", "*", "attribute", "*", "=", "value", "Return", "indices", "that", "satisfy", "the", "condition", "where", "the", "attribute", "is", "equal",...
python
train
DataDog/integrations-core
datadog_checks_dev/datadog_checks/dev/tooling/commands/agent/integrations.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_dev/datadog_checks/dev/tooling/commands/agent/integrations.py#L25-L59
def integrations(since, to, write, force): """ Generates a markdown file containing the list of integrations shipped in a given Agent release. Agent version numbers are derived inspecting tags on `integrations-core` so running this tool might provide unexpected results if the repo is not up to date ...
[ "def", "integrations", "(", "since", ",", "to", ",", "write", ",", "force", ")", ":", "agent_tags", "=", "get_agent_tags", "(", "since", ",", "to", ")", "# get the list of integrations shipped with the agent from the requirements file", "req_file_name", "=", "os", "."...
Generates a markdown file containing the list of integrations shipped in a given Agent release. Agent version numbers are derived inspecting tags on `integrations-core` so running this tool might provide unexpected results if the repo is not up to date with the Agent release process. If neither `--sinc...
[ "Generates", "a", "markdown", "file", "containing", "the", "list", "of", "integrations", "shipped", "in", "a", "given", "Agent", "release", ".", "Agent", "version", "numbers", "are", "derived", "inspecting", "tags", "on", "integrations", "-", "core", "so", "ru...
python
train
log2timeline/plaso
plaso/analysis/windows_services.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/windows_services.py#L171-L186
def AddService(self, new_service): """Add a new service to the list of ones we know about. Args: new_service (WindowsService): the service to add. """ for service in self._services: if new_service == service: # If this service is the same as one we already know about, we # j...
[ "def", "AddService", "(", "self", ",", "new_service", ")", ":", "for", "service", "in", "self", ".", "_services", ":", "if", "new_service", "==", "service", ":", "# If this service is the same as one we already know about, we", "# just want to add where it came from.", "s...
Add a new service to the list of ones we know about. Args: new_service (WindowsService): the service to add.
[ "Add", "a", "new", "service", "to", "the", "list", "of", "ones", "we", "know", "about", "." ]
python
train
leancloud/python-sdk
leancloud/message.py
https://github.com/leancloud/python-sdk/blob/fea3240257ce65e6a32c7312a5cee1f94a51a587/leancloud/message.py#L75-L95
def find_by_client(cls, from_client, limit=None, before_time=None, before_message_id=None): # type: (str, Optional[int], Optional[Union[datetime, float]], Optional[str]) -> List[Message] """获取某个 client 的聊天记录 :param from_client: 要获取聊天记录的 client id :param limit: 返回条数限制,可选,服务端默认 100 条,最大 1...
[ "def", "find_by_client", "(", "cls", ",", "from_client", ",", "limit", "=", "None", ",", "before_time", "=", "None", ",", "before_message_id", "=", "None", ")", ":", "# type: (str, Optional[int], Optional[Union[datetime, float]], Optional[str]) -> List[Message]", "query_par...
获取某个 client 的聊天记录 :param from_client: 要获取聊天记录的 client id :param limit: 返回条数限制,可选,服务端默认 100 条,最大 1000 条 :param before_time: 查询起始的时间戳,返回小于这个时间(不包含)的记录,服务端默认是当前时间 :param before_message_id: 起始的消息 id,使用时必须加上对应消息的时间 before_time 参数,一起作为查询的起点 :return: 符合条件的聊天记录
[ "获取某个", "client", "的聊天记录" ]
python
train
DeepHorizons/iarm
iarm/arm_instructions/data_movement.py
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/data_movement.py#L11-L25
def MOV(self, params): """ MOV Rx, Ry MOV PC, Ry Move the value of Ry into Rx or PC """ Rx, Ry = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params) self.check_arguments(any_registers=(Rx, Ry)) def MOV_func(): self.register[R...
[ "def", "MOV", "(", "self", ",", "params", ")", ":", "Rx", ",", "Ry", "=", "self", ".", "get_two_parameters", "(", "self", ".", "TWO_PARAMETER_COMMA_SEPARATED", ",", "params", ")", "self", ".", "check_arguments", "(", "any_registers", "=", "(", "Rx", ",", ...
MOV Rx, Ry MOV PC, Ry Move the value of Ry into Rx or PC
[ "MOV", "Rx", "Ry", "MOV", "PC", "Ry" ]
python
train
dlintott/gns3-converter
gns3converter/converter.py
https://github.com/dlintott/gns3-converter/blob/acbc55da51de86388dc5b5f6da55809b3c86b7ca/gns3converter/converter.py#L318-L332
def device_id_from_name(device_name, nodes): """ Get the device ID when given a device name :param str device_name: device name :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: device ID :rtype: int """ device_id = None for...
[ "def", "device_id_from_name", "(", "device_name", ",", "nodes", ")", ":", "device_id", "=", "None", "for", "node", "in", "nodes", ":", "if", "device_name", "==", "node", "[", "'properties'", "]", "[", "'name'", "]", ":", "device_id", "=", "node", "[", "'...
Get the device ID when given a device name :param str device_name: device name :param list nodes: list of nodes from :py:meth:`generate_nodes` :return: device ID :rtype: int
[ "Get", "the", "device", "ID", "when", "given", "a", "device", "name" ]
python
train
google/apitools
apitools/base/py/encoding_helper.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/encoding_helper.py#L137-L147
def DictToAdditionalPropertyMessage(properties, additional_property_type, sort_items=False): """Convert the given dictionary to an AdditionalProperty message.""" items = properties.items() if sort_items: items = sorted(items) map_ = [] for key, value in it...
[ "def", "DictToAdditionalPropertyMessage", "(", "properties", ",", "additional_property_type", ",", "sort_items", "=", "False", ")", ":", "items", "=", "properties", ".", "items", "(", ")", "if", "sort_items", ":", "items", "=", "sorted", "(", "items", ")", "ma...
Convert the given dictionary to an AdditionalProperty message.
[ "Convert", "the", "given", "dictionary", "to", "an", "AdditionalProperty", "message", "." ]
python
train
jbeluch/xbmcswift2
xbmcswift2/cli/create.py
https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/create.py#L60-L63
def validate_pluginid(value): '''Returns True if the provided value is a valid pluglin id''' valid = string.ascii_letters + string.digits + '.' return all(c in valid for c in value)
[ "def", "validate_pluginid", "(", "value", ")", ":", "valid", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'.'", "return", "all", "(", "c", "in", "valid", "for", "c", "in", "value", ")" ]
Returns True if the provided value is a valid pluglin id
[ "Returns", "True", "if", "the", "provided", "value", "is", "a", "valid", "pluglin", "id" ]
python
train
Hackerfleet/hfos
hfos/ui/auth.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/auth.py#L277-L302
def _get_profile(self, user_account): """Retrieves a user's profile""" try: # TODO: Load active profile, not just any user_profile = objectmodels['profile'].find_one( {'owner': str(user_account.uuid)}) self.log("Profile: ", user_profile, ...
[ "def", "_get_profile", "(", "self", ",", "user_account", ")", ":", "try", ":", "# TODO: Load active profile, not just any", "user_profile", "=", "objectmodels", "[", "'profile'", "]", ".", "find_one", "(", "{", "'owner'", ":", "str", "(", "user_account", ".", "u...
Retrieves a user's profile
[ "Retrieves", "a", "user", "s", "profile" ]
python
train
saltstack/salt
salt/modules/pyenv.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pyenv.py#L105-L117
def install(runas=None, path=None): ''' Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install ''' path = path or _pyenv_path(runas) path = os.path.expanduser(path) return _install_pyenv(path, runas)
[ "def", "install", "(", "runas", "=", "None", ",", "path", "=", "None", ")", ":", "path", "=", "path", "or", "_pyenv_path", "(", "runas", ")", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "return", "_install_pyenv", "(", "path"...
Install pyenv systemwide CLI Example: .. code-block:: bash salt '*' pyenv.install
[ "Install", "pyenv", "systemwide" ]
python
train
rosenbrockc/fortpy
fortpy/isense/classes.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/isense/classes.py#L155-L165
def _type_description(self): """Gets the completion description for a TypeExecutable.""" #This is a little tricker because the docstring is housed #inside of the module that contains the actual executable. #These TypeExecutables are just pointers. iexec = self._element.target ...
[ "def", "_type_description", "(", "self", ")", ":", "#This is a little tricker because the docstring is housed", "#inside of the module that contains the actual executable.", "#These TypeExecutables are just pointers.", "iexec", "=", "self", ".", "_element", ".", "target", "if", "ie...
Gets the completion description for a TypeExecutable.
[ "Gets", "the", "completion", "description", "for", "a", "TypeExecutable", "." ]
python
train
vtemian/buffpy
buffpy/managers/profiles.py
https://github.com/vtemian/buffpy/blob/6c9236fd3b6a8f9e2d70dbf1bc01529242b73075/buffpy/managers/profiles.py#L27-L40
def filter(self, **kwargs): ''' Based on some criteria, filter the profiles and return a new Profiles Manager containing only the chosen items If the manager doen't have any items, get all the profiles from Buffer ''' if not len(self): self.all() new_list = filter(lambda item:...
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "len", "(", "self", ")", ":", "self", ".", "all", "(", ")", "new_list", "=", "filter", "(", "lambda", "item", ":", "[", "True", "for", "arg", "in", "kwargs", "if", "i...
Based on some criteria, filter the profiles and return a new Profiles Manager containing only the chosen items If the manager doen't have any items, get all the profiles from Buffer
[ "Based", "on", "some", "criteria", "filter", "the", "profiles", "and", "return", "a", "new", "Profiles", "Manager", "containing", "only", "the", "chosen", "items" ]
python
valid
limodou/uliweb
uliweb/contrib/auth/__init__.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/auth/__init__.py#L40-L51
def check_password(raw_password, enc_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ l = enc_password.split('$') #only password of built-in user can split to 3 if len(l)==3: algo, salt, hsh = l ...
[ "def", "check_password", "(", "raw_password", ",", "enc_password", ")", ":", "l", "=", "enc_password", ".", "split", "(", "'$'", ")", "#only password of built-in user can split to 3\r", "if", "len", "(", "l", ")", "==", "3", ":", "algo", ",", "salt", ",", "h...
Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes.
[ "Returns", "a", "boolean", "of", "whether", "the", "raw_password", "was", "correct", ".", "Handles", "encryption", "formats", "behind", "the", "scenes", "." ]
python
train
sdispater/eloquent
eloquent/schema/grammars/grammar.py
https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/schema/grammars/grammar.py#L125-L135
def _add_modifiers(self, sql, blueprint, column): """ Add the column modifiers to the deifinition """ for modifier in self._modifiers: method = '_modify_%s' % modifier if hasattr(self, method): sql += getattr(self, method)(blueprint, column) ...
[ "def", "_add_modifiers", "(", "self", ",", "sql", ",", "blueprint", ",", "column", ")", ":", "for", "modifier", "in", "self", ".", "_modifiers", ":", "method", "=", "'_modify_%s'", "%", "modifier", "if", "hasattr", "(", "self", ",", "method", ")", ":", ...
Add the column modifiers to the deifinition
[ "Add", "the", "column", "modifiers", "to", "the", "deifinition" ]
python
train
pylast/pylast
src/pylast/__init__.py
https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L976-L984
def execute(self, cacheable=False): """Returns the XML DOM response of the POST Request from the server""" if self.network.is_caching_enabled() and cacheable: response = self._get_cached_response() else: response = self._download_response() return minidom.parseS...
[ "def", "execute", "(", "self", ",", "cacheable", "=", "False", ")", ":", "if", "self", ".", "network", ".", "is_caching_enabled", "(", ")", "and", "cacheable", ":", "response", "=", "self", ".", "_get_cached_response", "(", ")", "else", ":", "response", ...
Returns the XML DOM response of the POST Request from the server
[ "Returns", "the", "XML", "DOM", "response", "of", "the", "POST", "Request", "from", "the", "server" ]
python
train
pgjones/quart
quart/blueprints.py
https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/blueprints.py#L220-L235
def add_app_template_filter(self, func: Callable, name: Optional[str]=None) -> None: """Add an application wide template filter. This is designed to be used on the blueprint directly, and has the same arguments as :meth:`~quart.Quart.add_template_filter`. An example usage, .. c...
[ "def", "add_app_template_filter", "(", "self", ",", "func", ":", "Callable", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "self", ".", "record_once", "(", "lambda", "state", ":", "state", ".", "register_template_filte...
Add an application wide template filter. This is designed to be used on the blueprint directly, and has the same arguments as :meth:`~quart.Quart.add_template_filter`. An example usage, .. code-block:: python def filter(): ... blueprint = Bluep...
[ "Add", "an", "application", "wide", "template", "filter", "." ]
python
train
cosven/feeluown-core
fuocore/player.py
https://github.com/cosven/feeluown-core/blob/62dc64638f62971b16be0a75c0b8c7ae2999869e/fuocore/player.py#L296-L303
def state(self, value): """set player state, emit state changed signal outer object should not set state directly, use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead. """ self._state = value self.state_changed.emit(value)
[ "def", "state", "(", "self", ",", "value", ")", ":", "self", ".", "_state", "=", "value", "self", ".", "state_changed", ".", "emit", "(", "value", ")" ]
set player state, emit state changed signal outer object should not set state directly, use ``pause`` / ``resume`` / ``stop`` / ``play`` method instead.
[ "set", "player", "state", "emit", "state", "changed", "signal" ]
python
train
spyder-ide/spyder
spyder/utils/workers.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/workers.py#L249-L289
def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Thre...
[ "def", "_start", "(", "self", ",", "worker", "=", "None", ")", ":", "if", "worker", ":", "self", ".", "_queue_workers", ".", "append", "(", "worker", ")", "if", "self", ".", "_queue_workers", "and", "self", ".", "_running_threads", "<", "self", ".", "_...
Start threads and check for inactive workers.
[ "Start", "threads", "and", "check", "for", "inactive", "workers", "." ]
python
train
ZELLMECHANIK-DRESDEN/dclab
dclab/downsampling.py
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/downsampling.py#L72-L167
def downsample_grid(a, b, samples, ret_idx=False): """Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays ...
[ "def", "downsample_grid", "(", "a", ",", "b", ",", "samples", ",", "ret_idx", "=", "False", ")", ":", "# fixed random state for this method", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", "=", "47", ")", ".", "get_state", "(", ")", "sa...
Content-based downsampling for faster visualization The arrays `a` and `b` make up a 2D scatter plot with high and low density values. This method takes out points at indices with high density. Parameters ---------- a, b: 1d ndarrays The input arrays to downsample samples: int ...
[ "Content", "-", "based", "downsampling", "for", "faster", "visualization" ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fourier.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fourier.py#L59-L69
def fft_freqs(n_fft, fs): """Return frequencies for DFT Parameters ---------- n_fft : int Number of points in the FFT. fs : float The sampling rate. """ return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)
[ "def", "fft_freqs", "(", "n_fft", ",", "fs", ")", ":", "return", "np", ".", "arange", "(", "0", ",", "(", "n_fft", "//", "2", "+", "1", ")", ")", "/", "float", "(", "n_fft", ")", "*", "float", "(", "fs", ")" ]
Return frequencies for DFT Parameters ---------- n_fft : int Number of points in the FFT. fs : float The sampling rate.
[ "Return", "frequencies", "for", "DFT" ]
python
train
smdabdoub/phylotoast
bin/diversity.py
https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/diversity.py#L54-L66
def print_MannWhitneyU(div_calc): """ Compute the Mann-Whitney U test for unequal group sample sizes. """ try: x = div_calc.values()[0].values() y = div_calc.values()[1].values() except: return "Error setting up input arrays for Mann-Whitney U Test. Skipping "\ ...
[ "def", "print_MannWhitneyU", "(", "div_calc", ")", ":", "try", ":", "x", "=", "div_calc", ".", "values", "(", ")", "[", "0", "]", ".", "values", "(", ")", "y", "=", "div_calc", ".", "values", "(", ")", "[", "1", "]", ".", "values", "(", ")", "e...
Compute the Mann-Whitney U test for unequal group sample sizes.
[ "Compute", "the", "Mann", "-", "Whitney", "U", "test", "for", "unequal", "group", "sample", "sizes", "." ]
python
train
go-macaroon-bakery/py-macaroon-bakery
macaroonbakery/httpbakery/_client.py
https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L123-L156
def acquire_discharge(self, cav, payload): ''' Request a discharge macaroon from the caveat location as an HTTP URL. @param cav Third party {pymacaroons.Caveat} to be discharged. @param payload External caveat data {bytes}. @return The acquired macaroon {macaroonbakery.Macaroon} ...
[ "def", "acquire_discharge", "(", "self", ",", "cav", ",", "payload", ")", ":", "resp", "=", "self", ".", "_acquire_discharge_with_token", "(", "cav", ",", "payload", ",", "None", ")", "# TODO Fabrice what is the other http response possible ??", "if", "resp", ".", ...
Request a discharge macaroon from the caveat location as an HTTP URL. @param cav Third party {pymacaroons.Caveat} to be discharged. @param payload External caveat data {bytes}. @return The acquired macaroon {macaroonbakery.Macaroon}
[ "Request", "a", "discharge", "macaroon", "from", "the", "caveat", "location", "as", "an", "HTTP", "URL", "." ]
python
train
wummel/linkchecker
linkcheck/__init__.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/__init__.py#L114-L133
def init_i18n (loc=None): """Initialize i18n with the configured locale dir. The environment variable LOCPATH can also specify a locale dir. @return: None """ if 'LOCPATH' in os.environ: locdir = os.environ['LOCPATH'] else: locdir = os.path.join(get_install_data(), 'share', 'loc...
[ "def", "init_i18n", "(", "loc", "=", "None", ")", ":", "if", "'LOCPATH'", "in", "os", ".", "environ", ":", "locdir", "=", "os", ".", "environ", "[", "'LOCPATH'", "]", "else", ":", "locdir", "=", "os", ".", "path", ".", "join", "(", "get_install_data"...
Initialize i18n with the configured locale dir. The environment variable LOCPATH can also specify a locale dir. @return: None
[ "Initialize", "i18n", "with", "the", "configured", "locale", "dir", ".", "The", "environment", "variable", "LOCPATH", "can", "also", "specify", "a", "locale", "dir", "." ]
python
train
mathiasertl/django-ca
ca/django_ca/models.py
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L598-L606
def get_authority_key_identifier(self): """Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.""" try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIde...
[ "def", "get_authority_key_identifier", "(", "self", ")", ":", "try", ":", "ski", "=", "self", ".", "x509", ".", "extensions", ".", "get_extension_for_class", "(", "x509", ".", "SubjectKeyIdentifier", ")", "except", "x509", ".", "ExtensionNotFound", ":", "return"...
Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.
[ "Return", "the", "AuthorityKeyIdentifier", "extension", "used", "in", "certificates", "signed", "by", "this", "CA", "." ]
python
train
dbcli/athenacli
athenacli/packages/prompt_utils.py
https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/prompt_utils.py#L22-L27
def confirm(*args, **kwargs): """Prompt for confirmation (yes/no) and handle any abort exceptions.""" try: return click.confirm(*args, **kwargs) except click.Abort: return False
[ "def", "confirm", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "click", ".", "confirm", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "click", ".", "Abort", ":", "return", "False" ]
Prompt for confirmation (yes/no) and handle any abort exceptions.
[ "Prompt", "for", "confirmation", "(", "yes", "/", "no", ")", "and", "handle", "any", "abort", "exceptions", "." ]
python
train
spookylukey/django-paypal
paypal/pro/helpers.py
https://github.com/spookylukey/django-paypal/blob/b07d0a3ad91b5c5fe7bb27be3e5d70aabcdef76f/paypal/pro/helpers.py#L66-L75
def express_endpoint_for_token(token, commit=False): """ Returns the PayPal Express Checkout endpoint for a token. Pass 'commit=True' if you will not prompt for confirmation when the user returns to your site. """ pp_params = dict(token=token) if commit: pp_params['useraction'] = 'co...
[ "def", "express_endpoint_for_token", "(", "token", ",", "commit", "=", "False", ")", ":", "pp_params", "=", "dict", "(", "token", "=", "token", ")", "if", "commit", ":", "pp_params", "[", "'useraction'", "]", "=", "'commit'", "return", "express_endpoint", "(...
Returns the PayPal Express Checkout endpoint for a token. Pass 'commit=True' if you will not prompt for confirmation when the user returns to your site.
[ "Returns", "the", "PayPal", "Express", "Checkout", "endpoint", "for", "a", "token", ".", "Pass", "commit", "=", "True", "if", "you", "will", "not", "prompt", "for", "confirmation", "when", "the", "user", "returns", "to", "your", "site", "." ]
python
train
apache/incubator-mxnet
python/mxnet/gluon/trainer.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L429-L456
def save_states(self, fname): """Saves trainer states (e.g. optimizer, momentum) to a file. Parameters ---------- fname : str Path to output states file. Note ---- `optimizer.param_dict`, which contains Parameter information (such as `lr_mul...
[ "def", "save_states", "(", "self", ",", "fname", ")", ":", "assert", "self", ".", "_optimizer", "is", "not", "None", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "sel...
Saves trainer states (e.g. optimizer, momentum) to a file. Parameters ---------- fname : str Path to output states file. Note ---- `optimizer.param_dict`, which contains Parameter information (such as `lr_mult` and `wd_mult`) will not be saved.
[ "Saves", "trainer", "states", "(", "e", ".", "g", ".", "optimizer", "momentum", ")", "to", "a", "file", "." ]
python
train
praekeltfoundation/seed-stage-based-messaging
subscriptions/views.py
https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/views.py#L125-L153
def post(self, request, *args, **kwargs): """ Validates subscription data before creating Subscription message """ # Ensure that we check for the 'data' key in the request object before # attempting to reference it if "data" in request.data: # This is a workaround for...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Ensure that we check for the 'data' key in the request object before", "# attempting to reference it", "if", "\"data\"", "in", "request", ".", "data", ":", "# This is a...
Validates subscription data before creating Subscription message
[ "Validates", "subscription", "data", "before", "creating", "Subscription", "message" ]
python
train
hobson/pug-invest
pug/invest/sandbox/sim.py
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L103-L140
def chart( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1 normalize=True, ): """Display a graph of the price history for the list of ticker symbols provided Arguments: symbols...
[ "def", "chart", "(", "symbols", "=", "(", "\"AAPL\"", ",", "\"GLD\"", ",", "\"GOOG\"", ",", "\"$SPX\"", ",", "\"XOM\"", ",", "\"msft\"", ")", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "da...
Display a graph of the price history for the list of ticker symbols provided Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc start (datetime): The date at the start of the period being analyzed. end (datetime): The date at the end of the period being analyzed. nor...
[ "Display", "a", "graph", "of", "the", "price", "history", "for", "the", "list", "of", "ticker", "symbols", "provided" ]
python
train
HPAC/matchpy
matchpy/matching/one_to_one.py
https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/one_to_one.py#L179-L216
def _build_full_partition( optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation ) -> List[Sequence[Expression]]: """Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how ma...
[ "def", "_build_full_partition", "(", "optional_parts", ",", "sequence_var_partition", ":", "Sequence", "[", "int", "]", ",", "subjects", ":", "Sequence", "[", "Expression", "]", ",", "operation", ":", "Operation", ")", "->", "List", "[", "Sequence", "[", "Expr...
Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence variable gets assigned).
[ "Distribute", "subject", "operands", "among", "pattern", "operands", "." ]
python
train
wandb/client
wandb/vendor/prompt_toolkit/layout/containers.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/containers.py#L1508-L1585
def _scroll_without_linewrapping(self, ui_content, width, height, cli): """ Scroll to make sure the cursor position is visible and that we maintain the requested scroll offset. Set `self.horizontal_scroll/vertical_scroll`. """ cursor_position = ui_content.cursor_position...
[ "def", "_scroll_without_linewrapping", "(", "self", ",", "ui_content", ",", "width", ",", "height", ",", "cli", ")", ":", "cursor_position", "=", "ui_content", ".", "cursor_position", "or", "Point", "(", "0", ",", "0", ")", "# Without line wrapping, we will never ...
Scroll to make sure the cursor position is visible and that we maintain the requested scroll offset. Set `self.horizontal_scroll/vertical_scroll`.
[ "Scroll", "to", "make", "sure", "the", "cursor", "position", "is", "visible", "and", "that", "we", "maintain", "the", "requested", "scroll", "offset", "." ]
python
train
twilio/twilio-python
twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py#L36-L47
def get(self): """ Constructs a TaskQueueStatisticsContext :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext """ ...
[ "def", "get", "(", "self", ")", ":", "return", "TaskQueueStatisticsContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "task_queue_sid", "=", "self", ".", "_solution", "[", "'task_queue...
Constructs a TaskQueueStatisticsContext :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsContext
[ "Constructs", "a", "TaskQueueStatisticsContext" ]
python
train
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pgen2/conv.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pgen2/conv.py#L47-L51
def run(self, graminit_h, graminit_c): """Load the grammar tables from the text files written by pgen.""" self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off()
[ "def", "run", "(", "self", ",", "graminit_h", ",", "graminit_c", ")", ":", "self", ".", "parse_graminit_h", "(", "graminit_h", ")", "self", ".", "parse_graminit_c", "(", "graminit_c", ")", "self", ".", "finish_off", "(", ")" ]
Load the grammar tables from the text files written by pgen.
[ "Load", "the", "grammar", "tables", "from", "the", "text", "files", "written", "by", "pgen", "." ]
python
train
ANTsX/ANTsPy
ants/utils/crop_image.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/crop_image.py#L14-L56
def crop_image(image, label_image=None, label=1): """ Use a label image to crop a smaller ANTsImage from within a larger ANTsImage ANTsR function: `cropImage` Arguments --------- image : ANTsImage image to crop label_image : ANTsImage image with label values. If ...
[ "def", "crop_image", "(", "image", ",", "label_image", "=", "None", ",", "label", "=", "1", ")", ":", "inpixeltype", "=", "image", ".", "pixeltype", "ndim", "=", "image", ".", "dimension", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", ...
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage ANTsR function: `cropImage` Arguments --------- image : ANTsImage image to crop label_image : ANTsImage image with label values. If not supplied, estimated from data. label : integer ...
[ "Use", "a", "label", "image", "to", "crop", "a", "smaller", "ANTsImage", "from", "within", "a", "larger", "ANTsImage" ]
python
train
lago-project/lago
lago/plugins/vm.py
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/plugins/vm.py#L464-L468
def extract_paths(self, paths, *args, **kwargs): """ Thin method that just uses the provider """ return self.provider.extract_paths(paths, *args, **kwargs)
[ "def", "extract_paths", "(", "self", ",", "paths", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "provider", ".", "extract_paths", "(", "paths", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Thin method that just uses the provider
[ "Thin", "method", "that", "just", "uses", "the", "provider" ]
python
train
totalgood/nlpia
src/nlpia/book/examples/ch09.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L479-L486
def create_dicts(data): """ Modified from Keras LSTM example""" chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
[ "def", "create_dicts", "(", "data", ")", ":", "chars", "=", "set", "(", ")", "for", "sample", "in", "data", ":", "chars", ".", "update", "(", "set", "(", "sample", ")", ")", "char_indices", "=", "dict", "(", "(", "c", ",", "i", ")", "for", "i", ...
Modified from Keras LSTM example
[ "Modified", "from", "Keras", "LSTM", "example" ]
python
train
KarchinLab/probabilistic2020
prob2020/python/permutation.py
https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/permutation.py#L99-L207
def position_permutation(obs_stat, context_counts, context_to_mut, seq_context, gene_seq, gene_vest=None, num_permutations=10000, stop_criteria=1...
[ "def", "position_permutation", "(", "obs_stat", ",", "context_counts", ",", "context_to_mut", ",", "seq_context", ",", "gene_seq", ",", "gene_vest", "=", "None", ",", "num_permutations", "=", "10000", ",", "stop_criteria", "=", "100", ",", "pseudo_count", "=", "...
Performs null-permutations for position-based mutation statistics in a single gene. Parameters ---------- obs_stat : tuple, (recur ct, entropy, delta entropy, mean vest) tuple containing the observed statistics context_counts : pd.Series number of mutations for each context cont...
[ "Performs", "null", "-", "permutations", "for", "position", "-", "based", "mutation", "statistics", "in", "a", "single", "gene", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofilemanagermenu.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanagermenu.py#L68-L79
def saveProfileAs( self ): """ Saves the current profile as a new profile to the manager. """ name, ok = QInputDialog.getText(self, 'Create Profile', 'Name:') if ( not name ): return manager = self.parent() prof = manager.viewWidget().saveP...
[ "def", "saveProfileAs", "(", "self", ")", ":", "name", ",", "ok", "=", "QInputDialog", ".", "getText", "(", "self", ",", "'Create Profile'", ",", "'Name:'", ")", "if", "(", "not", "name", ")", ":", "return", "manager", "=", "self", ".", "parent", "(", ...
Saves the current profile as a new profile to the manager.
[ "Saves", "the", "current", "profile", "as", "a", "new", "profile", "to", "the", "manager", "." ]
python
train
apacha/OMR-Datasets
omrdatasettools/converters/csv_to_crop_object_conversion.py
https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/converters/csv_to_crop_object_conversion.py#L14-L48
def convert_csv_annotations_to_cropobject(annotations_path: str, image_path: str) -> List[CropObject]: """ Converts a normalized dataset of objects into crop-objects. :param annotations_path: Path to the csv-file that contains bounding boxes in the following format for a single ...
[ "def", "convert_csv_annotations_to_cropobject", "(", "annotations_path", ":", "str", ",", "image_path", ":", "str", ")", "->", "List", "[", "CropObject", "]", ":", "annotations", "=", "pd", ".", "read_csv", "(", "annotations_path", ")", "image", "=", "Image", ...
Converts a normalized dataset of objects into crop-objects. :param annotations_path: Path to the csv-file that contains bounding boxes in the following format for a single image: image_name,top,left,bottom,right,class_name,confidence CVC-MUSCIMA_W-01_N-10...
[ "Converts", "a", "normalized", "dataset", "of", "objects", "into", "crop", "-", "objects", ".", ":", "param", "annotations_path", ":", "Path", "to", "the", "csv", "-", "file", "that", "contains", "bounding", "boxes", "in", "the", "following", "format", "for"...
python
train
ThreatConnect-Inc/tcex
tcex/tcex_playbook.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L1089-L1101
def indicator_arrays(tc_entity_array): """Convert TCEntityArray to Indicator Type dictionary. Args: tc_entity_array (dictionary): The TCEntityArray to convert. Returns: (dictionary): Dictionary containing arrays of indicators for each indicator type. """ ...
[ "def", "indicator_arrays", "(", "tc_entity_array", ")", ":", "type_dict", "=", "{", "}", "for", "ea", "in", "tc_entity_array", ":", "type_dict", ".", "setdefault", "(", "ea", "[", "'type'", "]", ",", "[", "]", ")", ".", "append", "(", "ea", "[", "'valu...
Convert TCEntityArray to Indicator Type dictionary. Args: tc_entity_array (dictionary): The TCEntityArray to convert. Returns: (dictionary): Dictionary containing arrays of indicators for each indicator type.
[ "Convert", "TCEntityArray", "to", "Indicator", "Type", "dictionary", "." ]
python
train
svetlyak40wt/python-repr
src/magic_repr/__init__.py
https://github.com/svetlyak40wt/python-repr/blob/49e358e77b97d74f29f4977ea009ab2d64c254e8/src/magic_repr/__init__.py#L125-L177
def format_value(value): """This function should return unicode representation of the value """ value_id = id(value) if value_id in recursion_breaker.processed: return u'<recursion>' recursion_breaker.processed.add(value_id) try: if isinstance(value, six.binary_type): ...
[ "def", "format_value", "(", "value", ")", ":", "value_id", "=", "id", "(", "value", ")", "if", "value_id", "in", "recursion_breaker", ".", "processed", ":", "return", "u'<recursion>'", "recursion_breaker", ".", "processed", ".", "add", "(", "value_id", ")", ...
This function should return unicode representation of the value
[ "This", "function", "should", "return", "unicode", "representation", "of", "the", "value" ]
python
valid
hhatto/pgmagick
pgmagick/api.py
https://github.com/hhatto/pgmagick/blob/5dce5fa4681400b4c059431ad69233e6a3e5799a/pgmagick/api.py#L868-L875
def matte(self, x, y, paint_method): """ :param paint_method: 'point' or 'replace' or 'floodfill' or 'filltoborder' or 'reset' :type paint_method: str or pgmagick.PaintMethod """ paint_method = _convert_paintmethod(paint_method) self.drawer.ap...
[ "def", "matte", "(", "self", ",", "x", ",", "y", ",", "paint_method", ")", ":", "paint_method", "=", "_convert_paintmethod", "(", "paint_method", ")", "self", ".", "drawer", ".", "append", "(", "pgmagick", ".", "DrawableMatte", "(", "x", ",", "y", ",", ...
:param paint_method: 'point' or 'replace' or 'floodfill' or 'filltoborder' or 'reset' :type paint_method: str or pgmagick.PaintMethod
[ ":", "param", "paint_method", ":", "point", "or", "replace", "or", "floodfill", "or", "filltoborder", "or", "reset", ":", "type", "paint_method", ":", "str", "or", "pgmagick", ".", "PaintMethod" ]
python
valid
gem/oq-engine
openquake/calculators/export/hazard.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L223-L235
def export_hmaps_csv(key, dest, sitemesh, array, comment): """ Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param co...
[ "def", "export_hmaps_csv", "(", "key", ",", "dest", ",", "sitemesh", ",", "array", ",", "comment", ")", ":", "curves", "=", "util", ".", "compose_arrays", "(", "sitemesh", ",", "array", ")", "writers", ".", "write_csv", "(", "dest", ",", "curves", ",", ...
Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param comment: comment to use as header of the exported CSV file
[ "Export", "the", "hazard", "maps", "of", "the", "given", "realization", "into", "CSV", "." ]
python
train
cocaine/cocaine-tools
cocaine/tools/cli.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/cli.py#L245-L250
def loop(self): """Lazy event loop initialization""" if not self._loop: self._loop = IOLoop.current() return self._loop return self._loop
[ "def", "loop", "(", "self", ")", ":", "if", "not", "self", ".", "_loop", ":", "self", ".", "_loop", "=", "IOLoop", ".", "current", "(", ")", "return", "self", ".", "_loop", "return", "self", ".", "_loop" ]
Lazy event loop initialization
[ "Lazy", "event", "loop", "initialization" ]
python
train
saltstack/salt
salt/modules/pip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L259-L274
def _resolve_requirements_chain(requirements): ''' Return an array of requirements file paths that can be used to complete the no_chown==False && user != None conundrum ''' chain = [] if isinstance(requirements, six.string_types): requirements = [requirements] for req_file in requ...
[ "def", "_resolve_requirements_chain", "(", "requirements", ")", ":", "chain", "=", "[", "]", "if", "isinstance", "(", "requirements", ",", "six", ".", "string_types", ")", ":", "requirements", "=", "[", "requirements", "]", "for", "req_file", "in", "requiremen...
Return an array of requirements file paths that can be used to complete the no_chown==False && user != None conundrum
[ "Return", "an", "array", "of", "requirements", "file", "paths", "that", "can", "be", "used", "to", "complete", "the", "no_chown", "==", "False", "&&", "user", "!", "=", "None", "conundrum" ]
python
train
casebeer/audiogen
audiogen/util.py
https://github.com/casebeer/audiogen/blob/184dee2ca32c2bb4315a0f18e62288728fcd7881/audiogen/util.py#L252-L266
def channelize(gen, channels): ''' Break multi-channel generator into one sub-generator per channel Takes a generator producing n-tuples of samples and returns n generators, each producing samples for a single channel. Since multi-channel generators are the only reasonable way to synchronize samples across chan...
[ "def", "channelize", "(", "gen", ",", "channels", ")", ":", "def", "pick", "(", "g", ",", "channel", ")", ":", "for", "samples", "in", "g", ":", "yield", "samples", "[", "channel", "]", "return", "[", "pick", "(", "gen_copy", ",", "channel", ")", "...
Break multi-channel generator into one sub-generator per channel Takes a generator producing n-tuples of samples and returns n generators, each producing samples for a single channel. Since multi-channel generators are the only reasonable way to synchronize samples across channels, and the sampler functions only ...
[ "Break", "multi", "-", "channel", "generator", "into", "one", "sub", "-", "generator", "per", "channel" ]
python
train
quantmind/pulsar
pulsar/apps/wsgi/content.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L168-L182
def http_response(self, request): '''Return a :class:`.WsgiResponse` or a :class:`~asyncio.Future`. This method asynchronously wait for :meth:`stream` and subsequently returns a :class:`.WsgiResponse`. ''' content_types = request.content_types if not content_types or sel...
[ "def", "http_response", "(", "self", ",", "request", ")", ":", "content_types", "=", "request", ".", "content_types", "if", "not", "content_types", "or", "self", ".", "_content_type", "in", "content_types", ":", "response", "=", "request", ".", "response", "re...
Return a :class:`.WsgiResponse` or a :class:`~asyncio.Future`. This method asynchronously wait for :meth:`stream` and subsequently returns a :class:`.WsgiResponse`.
[ "Return", "a", ":", "class", ":", ".", "WsgiResponse", "or", "a", ":", "class", ":", "~asyncio", ".", "Future", "." ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/bpmn/parser/TaskParser.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/TaskParser.py#L158-L170
def connect_outgoing(self, outgoing_task, outgoing_task_node, sequence_flow_node, is_default): """ Connects this task to the indicating outgoing task, with the details in the sequence flow. A subclass can override this method to get extra information from the nod...
[ "def", "connect_outgoing", "(", "self", ",", "outgoing_task", ",", "outgoing_task_node", ",", "sequence_flow_node", ",", "is_default", ")", ":", "self", ".", "task", ".", "connect_outgoing", "(", "outgoing_task", ",", "sequence_flow_node", ".", "get", "(", "'id'",...
Connects this task to the indicating outgoing task, with the details in the sequence flow. A subclass can override this method to get extra information from the node.
[ "Connects", "this", "task", "to", "the", "indicating", "outgoing", "task", "with", "the", "details", "in", "the", "sequence", "flow", ".", "A", "subclass", "can", "override", "this", "method", "to", "get", "extra", "information", "from", "the", "node", "." ]
python
valid
pyblish/pyblish-nuke
pyblish_nuke/vendor/Qt.py
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/vendor/Qt.py#L77-L108
def _remap(object, name, value, safe=True): """Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that ...
[ "def", "_remap", "(", "object", ",", "name", ",", "value", ",", "safe", "=", "True", ")", ":", "if", "os", ".", "getenv", "(", "\"QT_TESTING\"", ")", "is", "not", "None", "and", "safe", ":", "# Cannot alter original binding.", "if", "hasattr", "(", "obje...
Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that the new attribute was not overwritten. ...
[ "Prevent", "accidental", "assignment", "of", "existing", "members" ]
python
train
ddorn/GUI
GUI/gui_examples/bezier.py
https://github.com/ddorn/GUI/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/gui_examples/bezier.py#L17-L105
def gui(): """Main function""" # ####### # setup all objects # ####### zones = [ALL] last_zones = [] COLORS.remove(WHITE) screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF) pygame.display.set_caption('Bezier simulator') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTT...
[ "def", "gui", "(", ")", ":", "# #######", "# setup all objects", "# #######", "zones", "=", "[", "ALL", "]", "last_zones", "=", "[", "]", "COLORS", ".", "remove", "(", "WHITE", ")", "screen", "=", "pygame", ".", "display", ".", "set_mode", "(", "SCREEN_S...
Main function
[ "Main", "function" ]
python
train
google/grr
grr/core/grr_response_core/lib/util/filesystem.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/util/filesystem.py#L187-L211
def Get(self, path, follow_symlink = True): """Stats given file or returns a cached result if available. Args: path: A path to the file to perform `stat` on. follow_symlink: True if `stat` of a symlink should be returned instead of a file that it points to. For non-symlinks this setting has...
[ "def", "Get", "(", "self", ",", "path", ",", "follow_symlink", "=", "True", ")", ":", "key", "=", "self", ".", "_Key", "(", "path", "=", "path", ",", "follow_symlink", "=", "follow_symlink", ")", "try", ":", "return", "self", ".", "_cache", "[", "key...
Stats given file or returns a cached result if available. Args: path: A path to the file to perform `stat` on. follow_symlink: True if `stat` of a symlink should be returned instead of a file that it points to. For non-symlinks this setting has no effect. Returns: `Stat` object corre...
[ "Stats", "given", "file", "or", "returns", "a", "cached", "result", "if", "available", "." ]
python
train
seequent/properties
properties/images.py
https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/images.py#L86-L97
def to_json(value, **kwargs): """Convert a PNG Image to base64-encoded JSON to_json assumes that value has passed validation. """ b64rep = base64.b64encode(value.read()) value.seek(0) jsonrep = '{preamble}{b64}'.format( preamble=PNG_PREAMBLE, b64=...
[ "def", "to_json", "(", "value", ",", "*", "*", "kwargs", ")", ":", "b64rep", "=", "base64", ".", "b64encode", "(", "value", ".", "read", "(", ")", ")", "value", ".", "seek", "(", "0", ")", "jsonrep", "=", "'{preamble}{b64}'", ".", "format", "(", "p...
Convert a PNG Image to base64-encoded JSON to_json assumes that value has passed validation.
[ "Convert", "a", "PNG", "Image", "to", "base64", "-", "encoded", "JSON" ]
python
train
belbio/bel
bel/lang/semantics.py
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L46-L88
def validate_functions(ast: BELAst, bo): """Recursively validate function signatures Determine if function matches one of the available signatures. Also, 1. Add entity types to AST NSArg, e.g. Abundance, ... 2. Add optional to AST Arg (optional means it is not a fixed, required argument and n...
[ "def", "validate_functions", "(", "ast", ":", "BELAst", ",", "bo", ")", ":", "if", "isinstance", "(", "ast", ",", "Function", ")", ":", "log", ".", "debug", "(", "f\"Validating: {ast.name}, {ast.function_type}, {ast.args}\"", ")", "function_signatures", "=", "bo",...
Recursively validate function signatures Determine if function matches one of the available signatures. Also, 1. Add entity types to AST NSArg, e.g. Abundance, ... 2. Add optional to AST Arg (optional means it is not a fixed, required argument and needs to be sorted for canonicalization, ...
[ "Recursively", "validate", "function", "signatures" ]
python
train