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
mozilla/treeherder
treeherder/services/pulse/exchange.py
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/services/pulse/exchange.py#L4-L20
def get_exchange(connection, name, create=False): """ Get a Kombu Exchange object using the passed in name. Can create an Exchange but this is typically not wanted in production-like environments and only useful for testing. """ exchange = Exchange(name, type="topic", passive=not create) #...
[ "def", "get_exchange", "(", "connection", ",", "name", ",", "create", "=", "False", ")", ":", "exchange", "=", "Exchange", "(", "name", ",", "type", "=", "\"topic\"", ",", "passive", "=", "not", "create", ")", "# bind the exchange to our connection so operations...
Get a Kombu Exchange object using the passed in name. Can create an Exchange but this is typically not wanted in production-like environments and only useful for testing.
[ "Get", "a", "Kombu", "Exchange", "object", "using", "the", "passed", "in", "name", "." ]
python
train
annayqho/TheCannon
code/lamost/li_giants/residuals.py
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/li_giants/residuals.py#L212-L227
def run_all(): """ Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects. """ DATA_DIR = "/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels" dates = os.listdir("/home/share/LAMOST/DR2/DR2_release") dates = np.array(dates) dates = np.delete(date...
[ "def", "run_all", "(", ")", ":", "DATA_DIR", "=", "\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels\"", "dates", "=", "os", ".", "listdir", "(", "\"/home/share/LAMOST/DR2/DR2_release\"", ")", "dates", "=", "np", ".", "array", "(", "dates", ")", "dates", "=...
Load the data that we're using to search for Li-rich giants. Store it in dataset and model objects.
[ "Load", "the", "data", "that", "we", "re", "using", "to", "search", "for", "Li", "-", "rich", "giants", ".", "Store", "it", "in", "dataset", "and", "model", "objects", "." ]
python
train
spacetelescope/stsci.tools
lib/stsci/tools/fileutil.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L643-L664
def updateKeyword(filename, key, value,show=yes): """Add/update keyword to header with given value.""" _fname, _extn = parseFilename(filename) # Open image whether it is FITS or GEIS _fimg = openImage(_fname, mode='update') # Address the correct header _hdr = getExtn(_fimg, _extn).header ...
[ "def", "updateKeyword", "(", "filename", ",", "key", ",", "value", ",", "show", "=", "yes", ")", ":", "_fname", ",", "_extn", "=", "parseFilename", "(", "filename", ")", "# Open image whether it is FITS or GEIS", "_fimg", "=", "openImage", "(", "_fname", ",", ...
Add/update keyword to header with given value.
[ "Add", "/", "update", "keyword", "to", "header", "with", "given", "value", "." ]
python
train
JarryShaw/PyPCAPKit
src/utilities/validations.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L156-L165
def info_check(*args, func=None): """Check if arguments are Info instance.""" from pcapkit.corekit.infoclass import Info func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, Info): name = type(var).__name__ raise InfoError( f'Funct...
[ "def", "info_check", "(", "*", "args", ",", "func", "=", "None", ")", ":", "from", "pcapkit", ".", "corekit", ".", "infoclass", "import", "Info", "func", "=", "func", "or", "inspect", ".", "stack", "(", ")", "[", "2", "]", "[", "3", "]", "for", "...
Check if arguments are Info instance.
[ "Check", "if", "arguments", "are", "Info", "instance", "." ]
python
train
luckydonald/pytgbot
code_generation/output/pytgbot/api_types/receivable/media.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/pytgbot/api_types/receivable/media.py#L924-L948
def to_array(self): """ Serializes this Animation to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Animation, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str array[...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "Animation", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'file_id'", "]", "=", "u", "(", "self", ".", "file_id", ")", "# py2: type unicode, py3: type str", "array", "["...
Serializes this Animation to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "Animation", "to", "a", "dictionary", "." ]
python
train
wandb/client
wandb/__init__.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L96-L140
def watch(models, criterion=None, log="gradients", log_freq=100): """ Hooks into the torch model to collect gradients and the topology. Should be extended to accept arbitrary ML models. :param (torch.Module) models: The model to hook, can be a tuple :param (torch.F) criterion: An optional loss val...
[ "def", "watch", "(", "models", ",", "criterion", "=", "None", ",", "log", "=", "\"gradients\"", ",", "log_freq", "=", "100", ")", ":", "global", "watch_called", "if", "run", "is", "None", ":", "raise", "ValueError", "(", "\"You must call `wandb.init` before ca...
Hooks into the torch model to collect gradients and the topology. Should be extended to accept arbitrary ML models. :param (torch.Module) models: The model to hook, can be a tuple :param (torch.F) criterion: An optional loss value being optimized :param (str) log: One of "gradients", "parameters", "al...
[ "Hooks", "into", "the", "torch", "model", "to", "collect", "gradients", "and", "the", "topology", ".", "Should", "be", "extended", "to", "accept", "arbitrary", "ML", "models", "." ]
python
train
praekeltfoundation/marathon-acme
marathon_acme/cli.py
https://github.com/praekeltfoundation/marathon-acme/blob/b1b71e3dde0ba30e575089280658bd32890e3325/marathon_acme/cli.py#L30-L143
def main(reactor, argv=sys.argv[1:], env=os.environ, acme_url=LETSENCRYPT_DIRECTORY.asText()): """ A tool to automatically request, renew and distribute Let's Encrypt certificates for apps running on Marathon and served by marathon-lb. """ parser = argparse.ArgumentParser( descripti...
[ "def", "main", "(", "reactor", ",", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", ",", "env", "=", "os", ".", "environ", ",", "acme_url", "=", "LETSENCRYPT_DIRECTORY", ".", "asText", "(", ")", ")", ":", "parser", "=", "argparse", ".", "Argum...
A tool to automatically request, renew and distribute Let's Encrypt certificates for apps running on Marathon and served by marathon-lb.
[ "A", "tool", "to", "automatically", "request", "renew", "and", "distribute", "Let", "s", "Encrypt", "certificates", "for", "apps", "running", "on", "Marathon", "and", "served", "by", "marathon", "-", "lb", "." ]
python
valid
IdentityPython/pysaml2
example/idp2/idp_uwsgi.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp_uwsgi.py#L391-L410
def post(self): """ The HTTP-Post endpoint """ logger.info("--- In SSO POST ---") saml_msg = self.unpack_either() self.req_info = IDP.parse_authn_request( saml_msg["SAMLRequest"], BINDING_HTTP_POST) _req = self.req_info.message if self.user: ...
[ "def", "post", "(", "self", ")", ":", "logger", ".", "info", "(", "\"--- In SSO POST ---\"", ")", "saml_msg", "=", "self", ".", "unpack_either", "(", ")", "self", ".", "req_info", "=", "IDP", ".", "parse_authn_request", "(", "saml_msg", "[", "\"SAMLRequest\"...
The HTTP-Post endpoint
[ "The", "HTTP", "-", "Post", "endpoint" ]
python
train
DreamLab/VmShepherd
src/vmshepherd/http/rpc_api.py
https://github.com/DreamLab/VmShepherd/blob/709a412c372b897d53808039c5c64a8b69c12c8d/src/vmshepherd/http/rpc_api.py#L44-L64
async def list_vms(self, preset): """ Listing virtual machines in a given preset :arg string preset: preset name :return: (Size of a preset, list of virtual machines) - first element of a tuple is a size of virtual machines in a preset - second element is a dic...
[ "async", "def", "list_vms", "(", "self", ",", "preset", ")", ":", "vmshepherd", "=", "self", ".", "request", ".", "app", ".", "vmshepherd", "preset", "=", "vmshepherd", ".", "preset_manager", ".", "get_preset", "(", "preset", ")", "result_vms", "=", "{", ...
Listing virtual machines in a given preset :arg string preset: preset name :return: (Size of a preset, list of virtual machines) - first element of a tuple is a size of virtual machines in a preset - second element is a dict which contains all Virtual Machines, where every ele...
[ "Listing", "virtual", "machines", "in", "a", "given", "preset" ]
python
train
AguaClara/aide_document-DEPRECATED
aide_document/combine.py
https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/combine.py#L5-L37
def render_document(template_name, data_name, output_name): """ Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact ...
[ "def", "render_document", "(", "template_name", ",", "data_name", ",", "output_name", ")", ":", "# Set up environment and load templates from pip package", "env", "=", "Environment", "(", "loader", "=", "PackageLoader", "(", "'aide_document'", ")", ")", "#TODO: add custom...
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates fold...
[ "Combines", "a", "MarkDown", "template", "file", "from", "the", "aide_document", "package", "with", "a", "local", "associated", "YAML", "data", "file", "then", "outputs", "the", "rendered", "combination", "to", "a", "local", "MarkDown", "output", "file", "." ]
python
train
saltstack/salt
salt/engines/libvirt_events.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L595-L608
def _callbacks_cleanup(cnx, callback_ids): ''' Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister ''' for obj, ids in callback_ids.items(): ...
[ "def", "_callbacks_cleanup", "(", "cnx", ",", "callback_ids", ")", ":", "for", "obj", ",", "ids", "in", "callback_ids", ".", "items", "(", ")", ":", "register_name", "=", "REGISTER_FUNCTIONS", "[", "obj", "]", "deregister_name", "=", "register_name", ".", "r...
Unregister all the registered callbacks :param cnx: libvirt connection :param callback_ids: dictionary mapping a libvirt object type to an ID list of callbacks to deregister
[ "Unregister", "all", "the", "registered", "callbacks" ]
python
train
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2942-L2957
def send_confirmation_email(self, confirmation_id, email_dict): """ Sends an confirmation by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param confirmation_id: the confirmation id ...
[ "def", "send_confirmation_email", "(", "self", ",", "confirmation_id", ",", "email_dict", ")", ":", "return", "self", ".", "_create_post_request", "(", "resource", "=", "CONFIRMATIONS", ",", "billomat_id", "=", "confirmation_id", ",", "send_data", "=", "email_dict",...
Sends an confirmation by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param confirmation_id: the confirmation id :param email_dict: the email dict :return dict
[ "Sends", "an", "confirmation", "by", "email", "If", "you", "want", "to", "send", "your", "email", "to", "more", "than", "one", "persons", "do", ":", "recipients", ":", "{", "to", ":", "[", "bykof@me", ".", "com", "mbykovski@seibert", "-", "media", ".", ...
python
train
juju/charm-helpers
charmhelpers/fetch/ubuntu.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L415-L437
def _dearmor_gpg_key(key_asc): """Converts a GPG key in the ASCII armor format to the binary format. :param key_asc: A GPG key in ASCII armor format. :type key_asc: (str, bytes) :returns: A GPG key in binary format :rtype: (str, bytes) :raises: GPGKeyError """ ps = subprocess.Popen(['gp...
[ "def", "_dearmor_gpg_key", "(", "key_asc", ")", ":", "ps", "=", "subprocess", ".", "Popen", "(", "[", "'gpg'", ",", "'--dearmor'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "su...
Converts a GPG key in the ASCII armor format to the binary format. :param key_asc: A GPG key in ASCII armor format. :type key_asc: (str, bytes) :returns: A GPG key in binary format :rtype: (str, bytes) :raises: GPGKeyError
[ "Converts", "a", "GPG", "key", "in", "the", "ASCII", "armor", "format", "to", "the", "binary", "format", "." ]
python
train
ToucanToco/toucan-data-sdk
toucan_data_sdk/utils/postprocess/cumsum.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/cumsum.py#L5-L21
def cumsum(df, new_column: str, column: str, index: list, date_column: str, date_format: str): """ DEPRECATED - please use `compute_cumsum` instead """ logging.getLogger(__name__).warning(f"DEPRECATED: use compute_cumsum") date_temp = '__date_temp__' if isinstance(index, str): index = [i...
[ "def", "cumsum", "(", "df", ",", "new_column", ":", "str", ",", "column", ":", "str", ",", "index", ":", "list", ",", "date_column", ":", "str", ",", "date_format", ":", "str", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "warnin...
DEPRECATED - please use `compute_cumsum` instead
[ "DEPRECATED", "-", "please", "use", "compute_cumsum", "instead" ]
python
test
nooperpudd/weibopy
weibopy/auth.py
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/auth.py#L168-L183
def revoke_auth_access(self, access_token): """ 授权回收接口,帮助开发者主动取消用户的授权。 应用下线时,清空所有用户的授权 应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权 开发者调试应用,需要反复调试授权功能 应用内实现类似登出微博帐号的功能 并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间 :param access_token: :return...
[ "def", "revoke_auth_access", "(", "self", ",", "access_token", ")", ":", "result", "=", "self", ".", "request", "(", "\"post\"", ",", "\"revokeoauth2\"", ",", "data", "=", "{", "\"access_token\"", ":", "access_token", "}", ")", "return", "bool", "(", "result...
授权回收接口,帮助开发者主动取消用户的授权。 应用下线时,清空所有用户的授权 应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权 开发者调试应用,需要反复调试授权功能 应用内实现类似登出微博帐号的功能 并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间 :param access_token: :return: bool
[ "授权回收接口,帮助开发者主动取消用户的授权。" ]
python
train
ToucanToco/toucan-data-sdk
toucan_data_sdk/utils/postprocess/filter_by_date.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/filter_by_date.py#L37-L65
def add_offset(dateobj, hr_offset: str, sign: str): """add a human readable offset to `dateobj` and return corresponding date. rely on `pandas.Timedelta` and add the following extra shortcuts: - "w", "week" and "weeks" for a week (i.e. 7days) - "month', "months" for a month (i.e. no day computation, ju...
[ "def", "add_offset", "(", "dateobj", ",", "hr_offset", ":", "str", ",", "sign", ":", "str", ")", ":", "sign_coeff", "=", "1", "if", "sign", "==", "'+'", "else", "-", "1", "try", ":", "return", "dateobj", "+", "sign_coeff", "*", "pd", ".", "Timedelta"...
add a human readable offset to `dateobj` and return corresponding date. rely on `pandas.Timedelta` and add the following extra shortcuts: - "w", "week" and "weeks" for a week (i.e. 7days) - "month', "months" for a month (i.e. no day computation, just increment the month) - "y", "year', "years" for a ye...
[ "add", "a", "human", "readable", "offset", "to", "dateobj", "and", "return", "corresponding", "date", "." ]
python
test
saltstack/salt
salt/modules/boto_vpc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L695-L747
def describe(vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash ...
[ "def", "describe", "(", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "any", "(", "(", "vpc_id", ",", "vpc_...
Given a VPC ID describe its properties. Returns a dictionary of interesting properties. .. versionchanged:: 2015.8.0 Added vpc_name argument CLI Example: .. code-block:: bash salt myminion boto_vpc.describe vpc_id=vpc-123456 salt myminion boto_vpc.describe vpc_name=myvpc
[ "Given", "a", "VPC", "ID", "describe", "its", "properties", "." ]
python
train
robert-b-clarke/nre-darwin-py
nredarwin/webservice.py
https://github.com/robert-b-clarke/nre-darwin-py/blob/6b0b181770e085dc7f71fbd2eb3fe779f653da62/nredarwin/webservice.py#L123-L137
def get_service_details(self, service_id): """ Get the details of an individual service and return a ServiceDetails instance. Positional arguments: service_id: A Darwin LDB service id """ service_query = \ self._soap_client.service['LDBServiceSoap']['...
[ "def", "get_service_details", "(", "self", ",", "service_id", ")", ":", "service_query", "=", "self", ".", "_soap_client", ".", "service", "[", "'LDBServiceSoap'", "]", "[", "'GetServiceDetails'", "]", "try", ":", "soap_response", "=", "service_query", "(", "ser...
Get the details of an individual service and return a ServiceDetails instance. Positional arguments: service_id: A Darwin LDB service id
[ "Get", "the", "details", "of", "an", "individual", "service", "and", "return", "a", "ServiceDetails", "instance", "." ]
python
train
coghost/izen
izen/helper.py
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L272-L281
def copy_to_clipboard(dat): """ 复制 ``dat`` 内容到 剪切板中 :return: None """ p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE) p.stdin.write(to_bytes(dat)) p.stdin.close() p.communicate()
[ "def", "copy_to_clipboard", "(", "dat", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'pbcopy'", "]", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "p", ".", "stdin", ".", "write", "(", "to_bytes", "(", "dat", ")", ")", "p", ".", ...
复制 ``dat`` 内容到 剪切板中 :return: None
[ "复制", "dat", "内容到", "剪切板中" ]
python
train
wbond/asn1crypto
dev/deps.py
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/dev/deps.py#L22-L53
def run(): """ Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data. """ deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) os.mkdir(...
[ "def", "run", "(", ")", ":", "deps_dir", "=", "os", ".", "path", ".", "join", "(", "build_root", ",", "'modularcrypto-deps'", ")", "if", "os", ".", "path", ".", "exists", "(", "deps_dir", ")", ":", "shutil", ".", "rmtree", "(", "deps_dir", ",", "igno...
Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data.
[ "Installs", "required", "development", "dependencies", ".", "Uses", "git", "to", "checkout", "other", "modularcrypto", "repos", "for", "more", "accurate", "coverage", "data", "." ]
python
train
LordSputnik/mutagen
mutagen/aiff.py
https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/aiff.py#L303-L309
def delete(self, filename=None): """Completely removes the ID3 chunk from the AIFF file""" if filename is None: filename = self.filename delete(filename) self.clear()
[ "def", "delete", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "filename", "delete", "(", "filename", ")", "self", ".", "clear", "(", ")" ]
Completely removes the ID3 chunk from the AIFF file
[ "Completely", "removes", "the", "ID3", "chunk", "from", "the", "AIFF", "file" ]
python
test
hosford42/xcs
xcs/scenarios.py
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/scenarios.py#L730-L750
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
[ "def", "execute", "(", "self", ",", "action", ")", ":", "reward", "=", "self", ".", "reward_function", "(", "action", ",", "self", ".", "classifications", "[", "self", ".", "steps", "]", ")", "self", ".", "total_reward", "+=", "reward", "self", ".", "s...
Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be executed within the current situation. ...
[ "Execute", "the", "indicated", "action", "within", "the", "environment", "and", "return", "the", "resulting", "immediate", "reward", "dictated", "by", "the", "reward", "program", "." ]
python
train
danijar/layered
layered/network.py
https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L154-L167
def feed(self, weights, data): """ Evaluate the network with alternative weights on the input data and return the output activation. """ assert len(data) == self.layers[0].size self.layers[0].apply(data) # Propagate trough the remaining layers. connections...
[ "def", "feed", "(", "self", ",", "weights", ",", "data", ")", ":", "assert", "len", "(", "data", ")", "==", "self", ".", "layers", "[", "0", "]", ".", "size", "self", ".", "layers", "[", "0", "]", ".", "apply", "(", "data", ")", "# Propagate trou...
Evaluate the network with alternative weights on the input data and return the output activation.
[ "Evaluate", "the", "network", "with", "alternative", "weights", "on", "the", "input", "data", "and", "return", "the", "output", "activation", "." ]
python
train
nitipit/appkit
appkit/api/v0_2_4/app.py
https://github.com/nitipit/appkit/blob/08eeaf45a9ca884bf5fe105d47a81269d44b1412/appkit/api/v0_2_4/app.py#L250-L260
def make_response(response): """Make response tuple Potential features to be added - Parameters validation """ if isinstance(response, unicode) or \ isinstance(response, str): response = (response, 'text/html') return response
[ "def", "make_response", "(", "response", ")", ":", "if", "isinstance", "(", "response", ",", "unicode", ")", "or", "isinstance", "(", "response", ",", "str", ")", ":", "response", "=", "(", "response", ",", "'text/html'", ")", "return", "response" ]
Make response tuple Potential features to be added - Parameters validation
[ "Make", "response", "tuple" ]
python
train
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/database.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/database.py#L664-L678
def process_read_batch(self, batch): """Process a single, partitioned read. :type batch: mapping :param batch: one of the mappings returned from an earlier call to :meth:`generate_read_batches`. :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet...
[ "def", "process_read_batch", "(", "self", ",", "batch", ")", ":", "kwargs", "=", "copy", ".", "deepcopy", "(", "batch", "[", "\"read\"", "]", ")", "keyset_dict", "=", "kwargs", ".", "pop", "(", "\"keyset\"", ")", "kwargs", "[", "\"keyset\"", "]", "=", ...
Process a single, partitioned read. :type batch: mapping :param batch: one of the mappings returned from an earlier call to :meth:`generate_read_batches`. :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` :returns: a result set instance which ...
[ "Process", "a", "single", "partitioned", "read", "." ]
python
train
opencivicdata/pupa
pupa/utils/topsort.py
https://github.com/opencivicdata/pupa/blob/18e0ddc4344804987ee0f2227bf600375538dbd5/pupa/utils/topsort.py#L45-L53
def leaf_nodes(self): """ Return an interable of nodes with no edges pointing at them. This is helpful to find all nodes without dependencies. """ # Now contains all nodes that contain dependencies. deps = {item for sublist in self.edges.values() for item in sublist} ...
[ "def", "leaf_nodes", "(", "self", ")", ":", "# Now contains all nodes that contain dependencies.", "deps", "=", "{", "item", "for", "sublist", "in", "self", ".", "edges", ".", "values", "(", ")", "for", "item", "in", "sublist", "}", "# contains all nodes *without*...
Return an interable of nodes with no edges pointing at them. This is helpful to find all nodes without dependencies.
[ "Return", "an", "interable", "of", "nodes", "with", "no", "edges", "pointing", "at", "them", ".", "This", "is", "helpful", "to", "find", "all", "nodes", "without", "dependencies", "." ]
python
train
aiogram/aiogram
aiogram/dispatcher/webhook.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/dispatcher/webhook.py#L392-L409
def to(self, target: typing.Union[types.Message, types.Chat, types.base.Integer, types.base.String]): """ Send to chat :param target: message or chat or id :return: """ if isinstance(target, types.Message): chat_id = target.chat.id elif isinstance(tar...
[ "def", "to", "(", "self", ",", "target", ":", "typing", ".", "Union", "[", "types", ".", "Message", ",", "types", ".", "Chat", ",", "types", ".", "base", ".", "Integer", ",", "types", ".", "base", ".", "String", "]", ")", ":", "if", "isinstance", ...
Send to chat :param target: message or chat or id :return:
[ "Send", "to", "chat" ]
python
train
COLORFULBOARD/revision
revision/file_transfer.py
https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/file_transfer.py#L56-L89
def upload(self, url, method="POST", file_path=None): """ :param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str """ if not os.path.exists(file_path): ...
[ "def", "upload", "(", "self", ",", "url", ",", "method", "=", "\"POST\"", ",", "file_path", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "raise", "RuntimeError", "(", "\"\"", ")", "with", "open_fil...
:param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str
[ ":", "param", "url", ":", ":", "type", "url", ":", "str", ":", "param", "method", ":", ":", "type", "method", ":", "str", ":", "param", "file_path", ":", ":", "type", "file_path", ":", "str" ]
python
train
materialsproject/pymatgen
pymatgen/core/structure.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L446-L461
def add_spin_by_element(self, spins): """ Add spin states to a structure. Args: spisn (dict): Dict of spins associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5} """ for site in self.sites: new_sp = {} for sp, occu in s...
[ "def", "add_spin_by_element", "(", "self", ",", "spins", ")", ":", "for", "site", "in", "self", ".", "sites", ":", "new_sp", "=", "{", "}", "for", "sp", ",", "occu", "in", "site", ".", "species", ".", "items", "(", ")", ":", "sym", "=", "sp", "."...
Add spin states to a structure. Args: spisn (dict): Dict of spins associated with elements or species, e.g. {"Ni":+5} or {"Ni2+":5}
[ "Add", "spin", "states", "to", "a", "structure", "." ]
python
train
jbasko/configmanager
configmanager/sections.py
https://github.com/jbasko/configmanager/blob/1d7229ce367143c7210d8e5f0782de03945a1721/configmanager/sections.py#L506-L534
def dump_values(self, with_defaults=True, dict_cls=dict, flat=False): """ Export values of all items contained in this section to a dictionary. Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded. Returns: dict: A dictionary of key-valu...
[ "def", "dump_values", "(", "self", ",", "with_defaults", "=", "True", ",", "dict_cls", "=", "dict", ",", "flat", "=", "False", ")", ":", "values", "=", "dict_cls", "(", ")", "if", "flat", ":", "for", "str_path", ",", "item", "in", "self", ".", "iter_...
Export values of all items contained in this section to a dictionary. Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded. Returns: dict: A dictionary of key-value pairs, where for sections values are dictionaries of their contents.
[ "Export", "values", "of", "all", "items", "contained", "in", "this", "section", "to", "a", "dictionary", "." ]
python
train
python-cmd2/cmd2
examples/async_printing.py
https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/async_printing.py#L70-L77
def do_start_alerts(self, _): """ Starts the alerter thread """ if self._alerter_thread.is_alive(): print("The alert thread is already started") else: self._stop_thread = False self._alerter_thread = threading.Thread(name='alerter', target=self._alerter_thread...
[ "def", "do_start_alerts", "(", "self", ",", "_", ")", ":", "if", "self", ".", "_alerter_thread", ".", "is_alive", "(", ")", ":", "print", "(", "\"The alert thread is already started\"", ")", "else", ":", "self", ".", "_stop_thread", "=", "False", "self", "."...
Starts the alerter thread
[ "Starts", "the", "alerter", "thread" ]
python
train
HPENetworking/PYHPEIMC
pyhpeimc/plat/system.py
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/system.py#L242-L284
def modify_telnet_template(auth, url, telnet_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a telnet template. :param auth: :param url: :param telnet_template: Human readable label which ...
[ "def", "modify_telnet_template", "(", "auth", ",", "url", ",", "telnet_template", ",", "template_name", "=", "None", ",", "template_id", "=", "None", ")", ":", "if", "template_name", "is", "None", ":", "template_name", "=", "telnet_template", "[", "'name'", "]...
Function takes input of a dictionry containing the required key/value pair for the modification of a telnet template. :param auth: :param url: :param telnet_template: Human readable label which is the name of the specific telnet template :param template_id Internal IMC number which designates the s...
[ "Function", "takes", "input", "of", "a", "dictionry", "containing", "the", "required", "key", "/", "value", "pair", "for", "the", "modification", "of", "a", "telnet", "template", "." ]
python
train
aio-libs/aiohttp
aiohttp/payload.py
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/payload.py#L187-L193
def set_content_disposition(self, disptype: str, quote_fields: bool=True, **params: Any) -> None: """Sets ``Content-Disposition`` header.""" self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_heade...
[ "def", "set_content_disposition", "(", "self", ",", "disptype", ":", "str", ",", "quote_fields", ":", "bool", "=", "True", ",", "*", "*", "params", ":", "Any", ")", "->", "None", ":", "self", ".", "_headers", "[", "hdrs", ".", "CONTENT_DISPOSITION", "]",...
Sets ``Content-Disposition`` header.
[ "Sets", "Content", "-", "Disposition", "header", "." ]
python
train
wonambi-python/wonambi
wonambi/widgets/utils.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L572-L598
def get_value(self, default=None): """Get selection from widget. Parameters ---------- default : str str for use by widget Returns ------- str selected item from the combobox """ if default is None: default = ...
[ "def", "get_value", "(", "self", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "''", "try", ":", "text", "=", "self", ".", "currentText", "(", ")", "except", "ValueError", ":", "lg", ".", "debug", "(", "...
Get selection from widget. Parameters ---------- default : str str for use by widget Returns ------- str selected item from the combobox
[ "Get", "selection", "from", "widget", "." ]
python
train
limix/chiscore
chiscore/_optimal.py
https://github.com/limix/chiscore/blob/c3e774648b8166a5161df86e6bcad34af3cec95c/chiscore/_optimal.py#L9-L77
def optimal_davies_pvalue(q, mu, var, kur, w, remain_var, df, trho, grid, pmin=None): r"""Joint significance of statistics derived from chi2-squared distributions. Parameters ---------- q : array_like Most significant of the independent test statistics, qₘᵢₙ(𝜌ᵥ) [1]. mu : float Mea...
[ "def", "optimal_davies_pvalue", "(", "q", ",", "mu", ",", "var", ",", "kur", ",", "w", ",", "remain_var", ",", "df", ",", "trho", ",", "grid", ",", "pmin", "=", "None", ")", ":", "q", "=", "asarray", "(", "q", ",", "float", ")", "mu", "=", "flo...
r"""Joint significance of statistics derived from chi2-squared distributions. Parameters ---------- q : array_like Most significant of the independent test statistics, qₘᵢₙ(𝜌ᵥ) [1]. mu : float Mean of the linear combination of the chi-squared distributions. var : float Vari...
[ "r", "Joint", "significance", "of", "statistics", "derived", "from", "chi2", "-", "squared", "distributions", "." ]
python
train
rameshg87/pyremotevbox
pyremotevbox/ZSI/TC.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TC.py#L1675-L1696
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw): '''elt -- the current DOMWrapper element sw -- soapWriter object pyobj -- python object to serialize ''' if pyobj is not None and type(pyobj) not in _seqtypes: raise EvaluateException, 'expecting ...
[ "def", "serialize", "(", "self", ",", "elt", ",", "sw", ",", "pyobj", ",", "name", "=", "None", ",", "orig", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "pyobj", "is", "not", "None", "and", "type", "(", "pyobj", ")", "not", "in", "_seqtyp...
elt -- the current DOMWrapper element sw -- soapWriter object pyobj -- python object to serialize
[ "elt", "--", "the", "current", "DOMWrapper", "element", "sw", "--", "soapWriter", "object", "pyobj", "--", "python", "object", "to", "serialize" ]
python
train
DataONEorg/d1_python
lib_common/src/d1_common/date_time.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/date_time.py#L191-L238
def are_equal(a_dt, b_dt, round_sec=1): """Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or flo...
[ "def", "are_equal", "(", "a_dt", ",", "b_dt", ",", "round_sec", "=", "1", ")", ":", "ra_dt", "=", "round_to_nearest", "(", "a_dt", ",", "round_sec", ")", "rb_dt", "=", "round_to_nearest", "(", "b_dt", ",", "round_sec", ")", "logger", ".", "debug", "(", ...
Determine if two datetimes are equal with fuzz factor. A naive datetime (no timezone information) is assumed to be in in UTC. Args: a_dt: datetime Timestamp to compare. b_dt: datetime Timestamp to compare. round_sec: int or float Round the timestamps to the closest ...
[ "Determine", "if", "two", "datetimes", "are", "equal", "with", "fuzz", "factor", "." ]
python
train
swharden/SWHLab
swhlab/common.py
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L133-L139
def list_move_to_back(l,value='other'): """if the value is in the list, move it to the back and return it.""" l=list(l) if value in l: l.remove(value) l.append(value) return l
[ "def", "list_move_to_back", "(", "l", ",", "value", "=", "'other'", ")", ":", "l", "=", "list", "(", "l", ")", "if", "value", "in", "l", ":", "l", ".", "remove", "(", "value", ")", "l", ".", "append", "(", "value", ")", "return", "l" ]
if the value is in the list, move it to the back and return it.
[ "if", "the", "value", "is", "in", "the", "list", "move", "it", "to", "the", "back", "and", "return", "it", "." ]
python
valid
nutechsoftware/alarmdecoder
alarmdecoder/decoder.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/decoder.py#L856-L886
def _update_fire_status(self, message=None, status=None): """ Uses the provided message to update the fire alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: fire status, overrides message bits :...
[ "def", "_update_fire_status", "(", "self", ",", "message", "=", "None", ",", "status", "=", "None", ")", ":", "fire_status", "=", "status", "last_status", "=", "self", ".", "_fire_status", "if", "isinstance", "(", "message", ",", "Message", ")", ":", "# Qu...
Uses the provided message to update the fire alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: fire status, overrides message bits :type status: bool :returns: boolean indicating the new status
[ "Uses", "the", "provided", "message", "to", "update", "the", "fire", "alarm", "state", "." ]
python
train
splunk/splunk-sdk-python
examples/custom_search/bin/usercount.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/custom_search/bin/usercount.py#L79-L103
def output_results(results, mvdelim = '\n', output = sys.stdout): """Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline""" # We collect all the unique field names, as well as # c...
[ "def", "output_results", "(", "results", ",", "mvdelim", "=", "'\\n'", ",", "output", "=", "sys", ".", "stdout", ")", ":", "# We collect all the unique field names, as well as ", "# convert all multivalue keys to the right form", "fields", "=", "set", "(", ")", "for", ...
Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline
[ "Given", "a", "list", "of", "dictionaries", "each", "representing", "a", "single", "result", "and", "an", "optional", "list", "of", "fields", "output", "those", "results", "to", "stdout", "for", "consumption", "by", "the", "Splunk", "pipeline" ]
python
train
Blueqat/Blueqat
blueqat/backends/backendbase.py
https://github.com/Blueqat/Blueqat/blob/2ac8592c79e7acf4f385d982af82fbd68dafa5cc/blueqat/backends/backendbase.py#L55-L73
def _run(self, gates, n_qubits, args, kwargs): """Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in ba...
[ "def", "_run", "(", "self", ",", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", ":", "gates", ",", "ctx", "=", "self", ".", "_preprocess_run", "(", "gates", ",", "n_qubits", ",", "args", ",", "kwargs", ")", "self", ".", "_run_gates", "(",...
Default implementation of `Backend.run`. Backend developer shouldn't override this function, but override `run` instead of this. The default flow of running is: 1. preprocessing 2. call the gate action which defined in backend 3. postprocessing Backend devel...
[ "Default", "implementation", "of", "Backend", ".", "run", ".", "Backend", "developer", "shouldn", "t", "override", "this", "function", "but", "override", "run", "instead", "of", "this", "." ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L2893-L3189
def pandas_udf(f=None, returnType=None, functionType=None): """ Creates a vectorized user defined function (UDF). :param f: user-defined function. A python function if used as a standalone function :param returnType: the return type of the user-defined function. The value can be either a :class...
[ "def", "pandas_udf", "(", "f", "=", "None", ",", "returnType", "=", "None", ",", "functionType", "=", "None", ")", ":", "# The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that", "# are not yet visible to the user. Some of behaviors are buggy an...
Creates a vectorized user defined function (UDF). :param f: user-defined function. A python function if used as a standalone function :param returnType: the return type of the user-defined function. The value can be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. ...
[ "Creates", "a", "vectorized", "user", "defined", "function", "(", "UDF", ")", "." ]
python
train
ThePlasmaRailgun/py-rolldice
rolldice/rolldice.py
https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L167-L177
def _eval_num(self, node): """ Evaluate a numerical node :param node: Node to eval :return: Result of node """ if self.floats: return node.n else: return int(node.n)
[ "def", "_eval_num", "(", "self", ",", "node", ")", ":", "if", "self", ".", "floats", ":", "return", "node", ".", "n", "else", ":", "return", "int", "(", "node", ".", "n", ")" ]
Evaluate a numerical node :param node: Node to eval :return: Result of node
[ "Evaluate", "a", "numerical", "node" ]
python
train
etingof/pysnmp
pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py#L366-L564
def bulkCmd(snmpDispatcher, authData, transportTarget, nonRepeaters, maxRepetitions, *varBinds, **options): """Creates a generator to perform one or more SNMP GETBULK queries. On each iteration, new SNMP GETBULK request is send (:RFC:`1905#section-4.2.3`). The iterator blocks waiting for respon...
[ "def", "bulkCmd", "(", "snmpDispatcher", ",", "authData", ",", "transportTarget", ",", "nonRepeaters", ",", "maxRepetitions", ",", "*", "varBinds", ",", "*", "*", "options", ")", ":", "def", "cbFun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", ...
Creates a generator to perform one or more SNMP GETBULK queries. On each iteration, new SNMP GETBULK request is send (:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher...
[ "Creates", "a", "generator", "to", "perform", "one", "or", "more", "SNMP", "GETBULK", "queries", "." ]
python
train
etcher-be/elib_run
elib_run/_run/_capture_output.py
https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_capture_output.py#L15-L30
def filter_line(line: str, context: RunContext) -> typing.Optional[str]: """ Filters out lines that match a given regex :param line: line to filter :type line: str :param context: run context :type context: _RunContext :return: line if it doesn't match the filter :rtype: optional str ...
[ "def", "filter_line", "(", "line", ":", "str", ",", "context", ":", "RunContext", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "if", "context", ".", "filters", "is", "not", "None", ":", "for", "filter_", "in", "context", ".", "filters", ...
Filters out lines that match a given regex :param line: line to filter :type line: str :param context: run context :type context: _RunContext :return: line if it doesn't match the filter :rtype: optional str
[ "Filters", "out", "lines", "that", "match", "a", "given", "regex" ]
python
train
juicer/juicer
juicer/admin/JuicerAdmin.py
https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/admin/JuicerAdmin.py#L268-L340
def export_repos(self, envs=[]): """Dump JuicerRepo() objects for all repos in all environments. Note that this has undefined results should a repo exist with different configurations in different environments. """ all_envs = envs juicer.utils.Log.log_notice("Only export...
[ "def", "export_repos", "(", "self", ",", "envs", "=", "[", "]", ")", ":", "all_envs", "=", "envs", "juicer", ".", "utils", ".", "Log", ".", "log_notice", "(", "\"Only exporting repos in environment(s): %s\"", ",", "\", \"", ".", "join", "(", "all_envs", ")",...
Dump JuicerRepo() objects for all repos in all environments. Note that this has undefined results should a repo exist with different configurations in different environments.
[ "Dump", "JuicerRepo", "()", "objects", "for", "all", "repos", "in", "all", "environments", "." ]
python
train
urinieto/msaf
msaf/pymf/nmf.py
https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/pymf/nmf.py#L100-L114
def frobenius_norm(self): """ Frobenius norm (||data - WH||) of a data matrix and a low rank approximation given by WH Returns: frobenius norm: F = ||data - WH|| """ # check if W and H exist if hasattr(self,'H') and hasattr(self,'W') and not scipy.sparse.iss...
[ "def", "frobenius_norm", "(", "self", ")", ":", "# check if W and H exist", "if", "hasattr", "(", "self", ",", "'H'", ")", "and", "hasattr", "(", "self", ",", "'W'", ")", "and", "not", "scipy", ".", "sparse", ".", "issparse", "(", "self", ".", "data", ...
Frobenius norm (||data - WH||) of a data matrix and a low rank approximation given by WH Returns: frobenius norm: F = ||data - WH||
[ "Frobenius", "norm", "(", "||data", "-", "WH||", ")", "of", "a", "data", "matrix", "and", "a", "low", "rank", "approximation", "given", "by", "WH" ]
python
test
projectatomic/atomic-reactor
atomic_reactor/util.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L858-L883
def guess_manifest_media_type(content): """ Guess the media type for the given manifest content :param content: JSON content of manifest (bytes) :return: media type (str), or None if unable to guess """ encoding = guess_json_utf(content) try: manifest = json.loads(content.decode(enc...
[ "def", "guess_manifest_media_type", "(", "content", ")", ":", "encoding", "=", "guess_json_utf", "(", "content", ")", "try", ":", "manifest", "=", "json", ".", "loads", "(", "content", ".", "decode", "(", "encoding", ")", ")", "except", "(", "ValueError", ...
Guess the media type for the given manifest content :param content: JSON content of manifest (bytes) :return: media type (str), or None if unable to guess
[ "Guess", "the", "media", "type", "for", "the", "given", "manifest", "content" ]
python
train
hayd/pep8radius
pep8radius/radius.py
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/pep8radius/radius.py#L237-L262
def fix_line_range(source_code, start, end, options): """Apply autopep8 (and docformatter) between the lines start and end of source.""" # TODO confirm behaviour outside range (indexing starts at 1) start = max(start, 1) options.line_range = [start, end] from autopep8 import fix_code fixed ...
[ "def", "fix_line_range", "(", "source_code", ",", "start", ",", "end", ",", "options", ")", ":", "# TODO confirm behaviour outside range (indexing starts at 1)", "start", "=", "max", "(", "start", ",", "1", ")", "options", ".", "line_range", "=", "[", "start", "...
Apply autopep8 (and docformatter) between the lines start and end of source.
[ "Apply", "autopep8", "(", "and", "docformatter", ")", "between", "the", "lines", "start", "and", "end", "of", "source", "." ]
python
train
DataDog/integrations-core
couch/datadog_checks/couch/couch.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/couch/datadog_checks/couch/couch.py#L30-L68
def get(self, url, instance, service_check_tags, run_check=False): "Hit a given URL and return the parsed json" self.log.debug('Fetching CouchDB stats at url: %s' % url) auth = None if 'user' in instance and 'password' in instance: auth = (instance['user'], instance['passwor...
[ "def", "get", "(", "self", ",", "url", ",", "instance", ",", "service_check_tags", ",", "run_check", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'Fetching CouchDB stats at url: %s'", "%", "url", ")", "auth", "=", "None", "if", "'user'",...
Hit a given URL and return the parsed json
[ "Hit", "a", "given", "URL", "and", "return", "the", "parsed", "json" ]
python
train
HttpRunner/HttpRunner
httprunner/parser.py
https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/parser.py#L613-L640
def parse_lazy_data(content, variables_mapping=None): """ parse lazy data with evaluated variables mapping. Notice: variables_mapping should not contain any variable or function. """ # TODO: refactor type check if content is None or isinstance(content, (numeric_types, bool, type)): retur...
[ "def", "parse_lazy_data", "(", "content", ",", "variables_mapping", "=", "None", ")", ":", "# TODO: refactor type check", "if", "content", "is", "None", "or", "isinstance", "(", "content", ",", "(", "numeric_types", ",", "bool", ",", "type", ")", ")", ":", "...
parse lazy data with evaluated variables mapping. Notice: variables_mapping should not contain any variable or function.
[ "parse", "lazy", "data", "with", "evaluated", "variables", "mapping", ".", "Notice", ":", "variables_mapping", "should", "not", "contain", "any", "variable", "or", "function", "." ]
python
train
kata198/indexedredis
IndexedRedis/__init__.py
https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1763-L1808
def getMultiple(self, pks, cascadeFetch=False): ''' getMultiple - Gets multiple objects with a single atomic operation @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @...
[ "def", "getMultiple", "(", "self", ",", "pks", ",", "cascadeFetch", "=", "False", ")", ":", "if", "type", "(", "pks", ")", "==", "set", ":", "pks", "=", "list", "(", "pks", ")", "if", "len", "(", "pks", ")", "==", "1", ":", "# Optimization to not p...
getMultiple - Gets multiple objects with a single atomic operation @param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model will be fetched immediately. If False, foreign objects will be fetched on-access. @param pks - list of internal keys
[ "getMultiple", "-", "Gets", "multiple", "objects", "with", "a", "single", "atomic", "operation" ]
python
valid
LionelAuroux/pyrser
pyrser/dsl.py
https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L510-L513
def add_ruleclause_name(self, ns_name, rid) -> bool: """Create a tree.Rule""" ns_name.parser_tree = parsing.Rule(self.value(rid)) return True
[ "def", "add_ruleclause_name", "(", "self", ",", "ns_name", ",", "rid", ")", "->", "bool", ":", "ns_name", ".", "parser_tree", "=", "parsing", ".", "Rule", "(", "self", ".", "value", "(", "rid", ")", ")", "return", "True" ]
Create a tree.Rule
[ "Create", "a", "tree", ".", "Rule" ]
python
test
Nic30/hwt
hwt/hdl/statements.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/hdl/statements.py#L245-L273
def _on_merge(self, other): """ After merging statements update IO, sensitivity and context :attention: rank is not updated """ self._inputs.extend(other._inputs) self._outputs.extend(other._outputs) if self._sensitivity is not None: self._sensitivit...
[ "def", "_on_merge", "(", "self", ",", "other", ")", ":", "self", ".", "_inputs", ".", "extend", "(", "other", ".", "_inputs", ")", "self", ".", "_outputs", ".", "extend", "(", "other", ".", "_outputs", ")", "if", "self", ".", "_sensitivity", "is", "n...
After merging statements update IO, sensitivity and context :attention: rank is not updated
[ "After", "merging", "statements", "update", "IO", "sensitivity", "and", "context" ]
python
test
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379
def format_item(self, item): """Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects """ # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identi...
[ "def", "format_item", "(", "self", ",", "item", ")", ":", "# http://jsonapi.org/format/#document-top-level", "# Primary data MUST be either... a single resource object, a single resource", "# identifier object, or null, for requests that target single resources", "if", "not", "item", ":"...
Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects
[ "Format", "a", "single", "datum", "as", "a", "Resource", "object", "." ]
python
train
federico123579/Trading212-API
tradingAPI/low_level.py
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/low_level.py#L90-L94
def css(self, css_path, dom=None): """css find function abbreviation""" if dom is None: dom = self.browser return expect(dom.find_by_css, args=[css_path])
[ "def", "css", "(", "self", ",", "css_path", ",", "dom", "=", "None", ")", ":", "if", "dom", "is", "None", ":", "dom", "=", "self", ".", "browser", "return", "expect", "(", "dom", ".", "find_by_css", ",", "args", "=", "[", "css_path", "]", ")" ]
css find function abbreviation
[ "css", "find", "function", "abbreviation" ]
python
train
lavr/flask-emails
flask_emails/message.py
https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/message.py#L47-L63
def send(self, smtp=None, **kw): """ Sends message. :param smtp: When set, parameters from this dictionary overwrite options from config. See `emails.Message.send` for more information. :param kwargs: Parameters for `emails.Message.send` :return: Response ...
[ "def", "send", "(", "self", ",", "smtp", "=", "None", ",", "*", "*", "kw", ")", ":", "smtp_options", "=", "{", "}", "smtp_options", ".", "update", "(", "self", ".", "config", ".", "smtp_options", ")", "if", "smtp", ":", "smtp_options", ".", "update",...
Sends message. :param smtp: When set, parameters from this dictionary overwrite options from config. See `emails.Message.send` for more information. :param kwargs: Parameters for `emails.Message.send` :return: Response objects from emails backend. For def...
[ "Sends", "message", "." ]
python
train
dropbox/stone
stone/cli_helpers.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/cli_helpers.py#L84-L90
def t_ID(self, token): r'[a-zA-Z_][a-zA-Z0-9_-]*' if token.value in self.KEYWORDS: token.type = self.KEYWORDS[token.value] return token else: return token
[ "def", "t_ID", "(", "self", ",", "token", ")", ":", "if", "token", ".", "value", "in", "self", ".", "KEYWORDS", ":", "token", ".", "type", "=", "self", ".", "KEYWORDS", "[", "token", ".", "value", "]", "return", "token", "else", ":", "return", "tok...
r'[a-zA-Z_][a-zA-Z0-9_-]*
[ "r", "[", "a", "-", "zA", "-", "Z_", "]", "[", "a", "-", "zA", "-", "Z0", "-", "9_", "-", "]", "*" ]
python
train
pavoni/pyvera
pyvera/__init__.py
https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L455-L469
def set_service_value(self, service_id, set_name, parameter_name, value): """Set a variable on the vera device. This will call the Vera api to change device state. """ payload = { 'id': 'lu_action', 'action': 'Set' + set_name, 'serviceId': service_id,...
[ "def", "set_service_value", "(", "self", ",", "service_id", ",", "set_name", ",", "parameter_name", ",", "value", ")", ":", "payload", "=", "{", "'id'", ":", "'lu_action'", ",", "'action'", ":", "'Set'", "+", "set_name", ",", "'serviceId'", ":", "service_id"...
Set a variable on the vera device. This will call the Vera api to change device state.
[ "Set", "a", "variable", "on", "the", "vera", "device", "." ]
python
train
slundberg/shap
shap/benchmark/metrics.py
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L403-L410
def batch_keep_absolute_retrain__r2(X, y, model_generator, method_name, num_fcounts=11): """ Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 13 """ return __run_batch_abs_metric(measures.batch_keep_retrain, X, y, model_gen...
[ "def", "batch_keep_absolute_retrain__r2", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_batch_abs_metric", "(", "measures", ".", "batch_keep_retrain", ",", "X", ",", "y", ",", "model_gen...
Batch Keep Absolute (retrain) xlabel = "Fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 13
[ "Batch", "Keep", "Absolute", "(", "retrain", ")", "xlabel", "=", "Fraction", "of", "features", "kept", "ylabel", "=", "R^2", "transform", "=", "identity", "sort_order", "=", "13" ]
python
train
mbr/simplekv
simplekv/cache.py
https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L138-L148
def put_file(self, key, file): """Implementation of :meth:`~simplekv.KeyValueStore.put_file`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it. """ try: return self....
[ "def", "put_file", "(", "self", ",", "key", ",", "file", ")", ":", "try", ":", "return", "self", ".", "_dstore", ".", "put_file", "(", "key", ",", "file", ")", "finally", ":", "self", ".", "cache", ".", "delete", "(", "key", ")" ]
Implementation of :meth:`~simplekv.KeyValueStore.put_file`. Will store the value in the backing store. After a successful or unsuccessful store, the cache will be invalidated by deleting the key from it.
[ "Implementation", "of", ":", "meth", ":", "~simplekv", ".", "KeyValueStore", ".", "put_file", "." ]
python
train
saltstack/salt
salt/modules/solr.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L803-L838
def replication_details(host=None, core_name=None): ''' Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you...
[ "def", "replication_details", "(", "host", "=", "None", ",", "core_name", "=", "None", ")", ":", "ret", "=", "_get_return_dict", "(", ")", "if", "_get_none_or_value", "(", "core_name", ")", "is", "None", ":", "success", "=", "True", "for", "name", "in", ...
Get the full replication details. host : str (None) The solr host to query. __opts__['host'] is default. core_name : str (None) The name of the solr core if using cores. Leave this blank if you are not using cores or if you want to check all cores. Return : dict<str,obj>:: ...
[ "Get", "the", "full", "replication", "details", "." ]
python
train
xtrementl/focus
focus/environment/io.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/io.py#L95-L110
def prompt(self, prompt_msg=None, newline=False): """ Writes prompt message to output stream and reads line from standard input stream. `prompt_msg` Message to write. `newline` Append newline character to prompt message before writing. ...
[ "def", "prompt", "(", "self", ",", "prompt_msg", "=", "None", ",", "newline", "=", "False", ")", ":", "if", "prompt_msg", "is", "not", "None", ":", "self", ".", "write", "(", "prompt_msg", ",", "newline", ")", "return", "self", ".", "_input", ".", "r...
Writes prompt message to output stream and reads line from standard input stream. `prompt_msg` Message to write. `newline` Append newline character to prompt message before writing. Return string.
[ "Writes", "prompt", "message", "to", "output", "stream", "and", "reads", "line", "from", "standard", "input", "stream", "." ]
python
train
awacha/sastool
sastool/misc/basicfit.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/misc/basicfit.py#L181-L265
def findpeak_asymmetric(x, y, dy=None, curve='Lorentz', return_x=None, init_parameters=None): """Find an asymmetric Lorentzian peak. Inputs: x: numpy array of the abscissa y: numpy array of the ordinate dy: numpy array of the errors in y (or None if not present) curve: string (c...
[ "def", "findpeak_asymmetric", "(", "x", ",", "y", ",", "dy", "=", "None", ",", "curve", "=", "'Lorentz'", ",", "return_x", "=", "None", ",", "init_parameters", "=", "None", ")", ":", "idx", "=", "np", ".", "logical_and", "(", "np", ".", "isfinite", "...
Find an asymmetric Lorentzian peak. Inputs: x: numpy array of the abscissa y: numpy array of the ordinate dy: numpy array of the errors in y (or None if not present) curve: string (case insensitive): if starts with "Lorentz", a Lorentzian curve will be fitted. If starts ...
[ "Find", "an", "asymmetric", "Lorentzian", "peak", "." ]
python
train
PyCQA/pylint
pylint/lint.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/lint.py#L1228-L1253
def generate_reports(self): """close the whole package /module, it's time to make reports ! if persistent run, pickle results for later comparison """ # Display whatever messages are left on the reporter. self.reporter.display_messages(report_nodes.Section()) if self.fi...
[ "def", "generate_reports", "(", "self", ")", ":", "# Display whatever messages are left on the reporter.", "self", ".", "reporter", ".", "display_messages", "(", "report_nodes", ".", "Section", "(", ")", ")", "if", "self", ".", "file_state", ".", "base_name", "is", ...
close the whole package /module, it's time to make reports ! if persistent run, pickle results for later comparison
[ "close", "the", "whole", "package", "/", "module", "it", "s", "time", "to", "make", "reports", "!" ]
python
test
deepmipt/DeepPavlov
deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/spelling_correction/levenshtein/tabled_trie.py#L61-L82
def save(self, outfile): """ Сохраняет дерево для дальнейшего использования """ with open(outfile, "w", encoding="utf8") as fout: attr_values = [getattr(self, attr) for attr in Trie.ATTRS] attr_values.append(any(x is not None for x in self.data)) fout....
[ "def", "save", "(", "self", ",", "outfile", ")", ":", "with", "open", "(", "outfile", ",", "\"w\"", ",", "encoding", "=", "\"utf8\"", ")", "as", "fout", ":", "attr_values", "=", "[", "getattr", "(", "self", ",", "attr", ")", "for", "attr", "in", "T...
Сохраняет дерево для дальнейшего использования
[ "Сохраняет", "дерево", "для", "дальнейшего", "использования" ]
python
test
a2liu/mr-clean
mr_clean/core/stats/regression.py
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/core/stats/regression.py#L7-L36
def corr_matrix(df,method = 'pearson'): """ Returns a matrix of correlations between columns of a DataFrame. For categorical columns, it first changes those to a set of dummy variable columns. Booleans are converted to numerical as well. Also ignores any indexes set on the DataFrame Parameters: df -...
[ "def", "corr_matrix", "(", "df", ",", "method", "=", "'pearson'", ")", ":", "# Remove all but categoricals,booleans, and numerics", "df", "=", "df", ".", "reset_index", "(", "drop", "=", "True", ")", "cat_cols", "=", "df", ".", "select_dtypes", "(", "include", ...
Returns a matrix of correlations between columns of a DataFrame. For categorical columns, it first changes those to a set of dummy variable columns. Booleans are converted to numerical as well. Also ignores any indexes set on the DataFrame Parameters: df - DataFrame DataFrame to analyze meth...
[ "Returns", "a", "matrix", "of", "correlations", "between", "columns", "of", "a", "DataFrame", ".", "For", "categorical", "columns", "it", "first", "changes", "those", "to", "a", "set", "of", "dummy", "variable", "columns", ".", "Booleans", "are", "converted", ...
python
train
tensorpack/tensorpack
tensorpack/models/nonlin.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/nonlin.py#L39-L60
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable ...
[ "def", "PReLU", "(", "x", ",", "init", "=", "0.001", ",", "name", "=", "'output'", ")", ":", "init", "=", "tfv1", ".", "constant_initializer", "(", "init", ")", "alpha", "=", "tfv1", ".", "get_variable", "(", "'alpha'", ",", "[", "]", ",", "initializ...
Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable slope. name (str): name of the output. V...
[ "Parameterized", "ReLU", "as", "in", "the", "paper", "Delving", "Deep", "into", "Rectifiers", ":", "Surpassing", "Human", "-", "Level", "Performance", "on", "ImageNet", "Classification", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1502", ".", ...
python
train
googleapis/gax-python
google/gapic/longrunning/operations_client.py
https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gapic/longrunning/operations_client.py#L298-L322
def delete_operation(self, name, options=None): """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns ``google.rpc.Code.U...
[ "def", "delete_operation", "(", "self", ",", "name", ",", "options", "=", "None", ")", ":", "# Create the request object.", "request", "=", "operations_pb2", ".", "DeleteOperationRequest", "(", "name", "=", "name", ")", "self", ".", "_delete_operation", "(", "re...
Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns ``google.rpc.Code.UNIMPLEMENTED``. Example: >>> from google.gapic.lo...
[ "Deletes", "a", "long", "-", "running", "operation", ".", "This", "method", "indicates", "that", "the", "client", "is", "no", "longer", "interested", "in", "the", "operation", "result", ".", "It", "does", "not", "cancel", "the", "operation", ".", "If", "th...
python
train
monim67/django-bootstrap-datepicker-plus
bootstrap_datepicker_plus/_compatibility.py
https://github.com/monim67/django-bootstrap-datepicker-plus/blob/55819bf12507c98dba91c702e224afd9bae3ef9a/bootstrap_datepicker_plus/_compatibility.py#L37-L44
def engine(self): """Return Render Engine.""" return self.backend({ 'APP_DIRS': True, 'DIRS': [str(ROOT / self.backend.app_dirname)], 'NAME': 'djangoforms', 'OPTIONS': {}, })
[ "def", "engine", "(", "self", ")", ":", "return", "self", ".", "backend", "(", "{", "'APP_DIRS'", ":", "True", ",", "'DIRS'", ":", "[", "str", "(", "ROOT", "/", "self", ".", "backend", ".", "app_dirname", ")", "]", ",", "'NAME'", ":", "'djangoforms'"...
Return Render Engine.
[ "Return", "Render", "Engine", "." ]
python
train
facelessuser/backrefs
backrefs/uniprops/__init__.py
https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/uniprops/__init__.py#L215-L226
def get_nfc_quick_check_property(value, is_bytes=False): """Get `NFC QUICK CHECK` property.""" obj = unidata.ascii_nfc_quick_check if is_bytes else unidata.unicode_nfc_quick_check if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['nfcquickcheck'].get(negated...
[ "def", "get_nfc_quick_check_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_nfc_quick_check", "if", "is_bytes", "else", "unidata", ".", "unicode_nfc_quick_check", "if", "value", ".", "startswith", "(", "'^'", ...
Get `NFC QUICK CHECK` property.
[ "Get", "NFC", "QUICK", "CHECK", "property", "." ]
python
train
EventRegistry/event-registry-python
eventregistry/TopicPage.py
https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/TopicPage.py#L254-L261
def addSourceLocation(self, sourceLocationUri, weight): """ add a list of relevant sources by identifying them by their geographic location @param sourceLocationUri: uri of the location where the sources should be geographically located @param weight: importance of the provided list of s...
[ "def", "addSourceLocation", "(", "self", ",", "sourceLocationUri", ",", "weight", ")", ":", "assert", "isinstance", "(", "weight", ",", "(", "float", ",", "int", ")", ")", ",", "\"weight value has to be a positive or negative integer\"", "self", ".", "topicPage", ...
add a list of relevant sources by identifying them by their geographic location @param sourceLocationUri: uri of the location where the sources should be geographically located @param weight: importance of the provided list of sources (typically in range 1 - 50)
[ "add", "a", "list", "of", "relevant", "sources", "by", "identifying", "them", "by", "their", "geographic", "location" ]
python
train
gwastro/pycbc
pycbc/events/coinc_rate.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc_rate.py#L17-L62
def multiifo_noise_coinc_rate(rates, slop): """ Calculate the expected rate of noise coincidences for multiple detectors Parameters ---------- rates: dict Dictionary keyed on ifo string Value is a sequence of single-detector trigger rates, units assumed to be Hz slop: fl...
[ "def", "multiifo_noise_coinc_rate", "(", "rates", ",", "slop", ")", ":", "ifos", "=", "numpy", ".", "array", "(", "sorted", "(", "rates", ".", "keys", "(", ")", ")", ")", "rates_raw", "=", "list", "(", "rates", "[", "ifo", "]", "for", "ifo", "in", ...
Calculate the expected rate of noise coincidences for multiple detectors Parameters ---------- rates: dict Dictionary keyed on ifo string Value is a sequence of single-detector trigger rates, units assumed to be Hz slop: float time added to maximum time-of-flight between...
[ "Calculate", "the", "expected", "rate", "of", "noise", "coincidences", "for", "multiple", "detectors" ]
python
train
GoogleCloudPlatform/datastore-ndb-python
ndb/model.py
https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/cf4cab3f1f69cd04e1a9229871be466b53729f3f/ndb/model.py#L3074-L3082
def _reset_kind_map(cls): """Clear the kind map. Useful for testing.""" # Preserve "system" kinds, like __namespace__ keep = {} for name, value in cls._kind_map.iteritems(): if name.startswith('__') and name.endswith('__'): keep[name] = value cls._kind_map.clear() cls._kind_map.up...
[ "def", "_reset_kind_map", "(", "cls", ")", ":", "# Preserve \"system\" kinds, like __namespace__", "keep", "=", "{", "}", "for", "name", ",", "value", "in", "cls", ".", "_kind_map", ".", "iteritems", "(", ")", ":", "if", "name", ".", "startswith", "(", "'__'...
Clear the kind map. Useful for testing.
[ "Clear", "the", "kind", "map", ".", "Useful", "for", "testing", "." ]
python
train
heuer/segno
segno/encoder.py
https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1429-L1443
def find_mode(data): """\ Returns the appropriate QR Code mode (an integer constant) for the provided `data`. :param bytes data: Data to check. :rtype: int """ if data.isdigit(): return consts.MODE_NUMERIC if is_alphanumeric(data): return consts.MODE_ALPHANUMERIC if ...
[ "def", "find_mode", "(", "data", ")", ":", "if", "data", ".", "isdigit", "(", ")", ":", "return", "consts", ".", "MODE_NUMERIC", "if", "is_alphanumeric", "(", "data", ")", ":", "return", "consts", ".", "MODE_ALPHANUMERIC", "if", "is_kanji", "(", "data", ...
\ Returns the appropriate QR Code mode (an integer constant) for the provided `data`. :param bytes data: Data to check. :rtype: int
[ "\\", "Returns", "the", "appropriate", "QR", "Code", "mode", "(", "an", "integer", "constant", ")", "for", "the", "provided", "data", "." ]
python
train
tilde-lab/tilde
tilde/core/symmetry.py
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/symmetry.py#L36-L46
def refine_cell(self, tilde_obj): ''' NB only used for perovskite_tilting app ''' try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance) except Exception as ex: self.error = 'Symmetr...
[ "def", "refine_cell", "(", "self", ",", "tilde_obj", ")", ":", "try", ":", "lattice", ",", "positions", ",", "numbers", "=", "spg", ".", "refine_cell", "(", "tilde_obj", "[", "'structures'", "]", "[", "-", "1", "]", ",", "symprec", "=", "self", ".", ...
NB only used for perovskite_tilting app
[ "NB", "only", "used", "for", "perovskite_tilting", "app" ]
python
train
klen/aioauth-client
aioauth_client.py
https://github.com/klen/aioauth-client/blob/54f58249496c26965adb4f752f2b24cfe18d0084/aioauth_client.py#L326-L356
async def get_access_token(self, code, loop=None, redirect_uri=None, **payload): """Get an access_token from OAuth provider. :returns: (access_token, provider_data) """ # Possibility to provide REQUEST DATA to the method payload.setdefault('grant_type', 'authorization_code') ...
[ "async", "def", "get_access_token", "(", "self", ",", "code", ",", "loop", "=", "None", ",", "redirect_uri", "=", "None", ",", "*", "*", "payload", ")", ":", "# Possibility to provide REQUEST DATA to the method", "payload", ".", "setdefault", "(", "'grant_type'", ...
Get an access_token from OAuth provider. :returns: (access_token, provider_data)
[ "Get", "an", "access_token", "from", "OAuth", "provider", "." ]
python
train
CamDavidsonPilon/lifelines
lifelines/fitters/log_normal_aft_fitter.py
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/log_normal_aft_fitter.py#L189-L220
def predict_cumulative_hazard(self, X, times=None, ancillary_X=None): """ Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns ...
[ "def", "predict_cumulative_hazard", "(", "self", ",", "X", ",", "times", "=", "None", ",", "ancillary_X", "=", "None", ")", ":", "import", "numpy", "as", "np", "times", "=", "coalesce", "(", "times", ",", "self", ".", "timeline", ",", "np", ".", "uniqu...
Return the cumulative hazard rate of subjects in X at time points. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order ...
[ "Return", "the", "cumulative", "hazard", "rate", "of", "subjects", "in", "X", "at", "time", "points", "." ]
python
train
kyuupichan/aiorpcX
aiorpcx/curio.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/curio.py#L362-L381
def timeout_at(clock, coro=None, *args): '''Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as an a...
[ "def", "timeout_at", "(", "clock", ",", "coro", "=", "None", ",", "*", "args", ")", ":", "if", "coro", ":", "return", "_timeout_after_func", "(", "clock", ",", "True", ",", "coro", ",", "args", ")", "return", "TimeoutAfter", "(", "clock", ",", "absolut...
Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as an asynchronous context manager that applies a timeo...
[ "Execute", "the", "specified", "coroutine", "and", "return", "its", "result", ".", "However", "issue", "a", "cancellation", "request", "to", "the", "calling", "task", "after", "seconds", "have", "elapsed", ".", "When", "this", "happens", "a", "TaskTimeout", "e...
python
train
timothydmorton/simpledist
simpledist/distributions.py
https://github.com/timothydmorton/simpledist/blob/d9807c90a935bd125213445ffed6255af558f1ca/simpledist/distributions.py#L982-L995
def resample(self,N,**kwargs): """Random resampling of the doublegauss distribution """ lovals = self.mu - np.absolute(rand.normal(size=N)*self.siglo) hivals = self.mu + np.absolute(rand.normal(size=N)*self.sighi) u = rand.random(size=N) hi = (u < float(self.sighi)/(self...
[ "def", "resample", "(", "self", ",", "N", ",", "*", "*", "kwargs", ")", ":", "lovals", "=", "self", ".", "mu", "-", "np", ".", "absolute", "(", "rand", ".", "normal", "(", "size", "=", "N", ")", "*", "self", ".", "siglo", ")", "hivals", "=", ...
Random resampling of the doublegauss distribution
[ "Random", "resampling", "of", "the", "doublegauss", "distribution" ]
python
train
ff0000/scarlet
scarlet/assets/crops.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/assets/crops.py#L46-L94
def get_crop_spec(self, im, x=None, x2=None, y=None, y2=None): """ Returns the default crop points for this image. """ w, h = [float(v) for v in im.size] upscale = self.upscale if x is not None and x2 and y is not None and y2: upscale = True w = fl...
[ "def", "get_crop_spec", "(", "self", ",", "im", ",", "x", "=", "None", ",", "x2", "=", "None", ",", "y", "=", "None", ",", "y2", "=", "None", ")", ":", "w", ",", "h", "=", "[", "float", "(", "v", ")", "for", "v", "in", "im", ".", "size", ...
Returns the default crop points for this image.
[ "Returns", "the", "default", "crop", "points", "for", "this", "image", "." ]
python
train
Erotemic/utool
utool/util_win32.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_win32.py#L60-L91
def add_to_win32_PATH(script_fpath, *add_path_list): r""" Writes a registery script to update the PATH variable into the sync registry CommandLine: python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin" Example: >>> # DISABLE_DOCTEST ...
[ "def", "add_to_win32_PATH", "(", "script_fpath", ",", "*", "add_path_list", ")", ":", "import", "utool", "as", "ut", "write_dir", "=", "dirname", "(", "script_fpath", ")", "key", "=", "'[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment]'"...
r""" Writes a registery script to update the PATH variable into the sync registry CommandLine: python -m utool.util_win32 --test-add_to_win32_PATH --newpath "C:\Program Files (x86)\Graphviz2.38\bin" Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_win32 impor...
[ "r", "Writes", "a", "registery", "script", "to", "update", "the", "PATH", "variable", "into", "the", "sync", "registry" ]
python
train
huntrar/scrape
scrape/scrape.py
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L193-L201
def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): args['files'].append(arg) else: args['urls'].append(arg.strip('/'))
[ "def", "split_input", "(", "args", ")", ":", "args", "[", "'files'", "]", "=", "[", "]", "args", "[", "'urls'", "]", "=", "[", "]", "for", "arg", "in", "args", "[", "'query'", "]", ":", "if", "os", ".", "path", ".", "isfile", "(", "arg", ")", ...
Split query input into local files and URLs.
[ "Split", "query", "input", "into", "local", "files", "and", "URLs", "." ]
python
train
titusjan/argos
argos/repo/registry.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/registry.py#L54-L59
def asDict(self): """ Returns a dictionary for serialization. """ dct = super(RtiRegItem, self).asDict() dct['extensions'] = self.extensions return dct
[ "def", "asDict", "(", "self", ")", ":", "dct", "=", "super", "(", "RtiRegItem", ",", "self", ")", ".", "asDict", "(", ")", "dct", "[", "'extensions'", "]", "=", "self", ".", "extensions", "return", "dct" ]
Returns a dictionary for serialization.
[ "Returns", "a", "dictionary", "for", "serialization", "." ]
python
train
contentful/contentful-management.py
contentful_management/space_membership.py
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/space_membership.py#L28-L38
def to_json(self): """ Returns the JSON representation of the space membership. """ result = super(SpaceMembership, self).to_json() result.update({ 'admin': self.admin, 'roles': self.roles }) return result
[ "def", "to_json", "(", "self", ")", ":", "result", "=", "super", "(", "SpaceMembership", ",", "self", ")", ".", "to_json", "(", ")", "result", ".", "update", "(", "{", "'admin'", ":", "self", ".", "admin", ",", "'roles'", ":", "self", ".", "roles", ...
Returns the JSON representation of the space membership.
[ "Returns", "the", "JSON", "representation", "of", "the", "space", "membership", "." ]
python
train
cartoonist/pystream-protobuf
stream/stream.py
https://github.com/cartoonist/pystream-protobuf/blob/40e70b932436887b748905e5e0a82839e4c559f0/stream/stream.py#L191-L196
def close(self): """Close the stream.""" self.flush() if self._myfd is not None: self._myfd.close() self._myfd = None
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "if", "self", ".", "_myfd", "is", "not", "None", ":", "self", ".", "_myfd", ".", "close", "(", ")", "self", ".", "_myfd", "=", "None" ]
Close the stream.
[ "Close", "the", "stream", "." ]
python
test
eqcorrscan/EQcorrscan
eqcorrscan/utils/picker.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/picker.py#L100-L183
def cross_net(stream, env=False, debug=0, master=False): """ Generate picks using a simple envelope cross-correlation. Picks are made for each channel based on optimal moveout defined by maximum cross-correlation with master trace. Master trace will be the first trace in the stream if not set. Re...
[ "def", "cross_net", "(", "stream", ",", "env", "=", "False", ",", "debug", "=", "0", ",", "master", "=", "False", ")", ":", "event", "=", "Event", "(", ")", "event", ".", "origins", ".", "append", "(", "Origin", "(", ")", ")", "event", ".", "crea...
Generate picks using a simple envelope cross-correlation. Picks are made for each channel based on optimal moveout defined by maximum cross-correlation with master trace. Master trace will be the first trace in the stream if not set. Requires good inter-station coherance. :type stream: obspy.cor...
[ "Generate", "picks", "using", "a", "simple", "envelope", "cross", "-", "correlation", "." ]
python
train
aaronn/django-rest-framework-passwordless
drfpasswordless/utils.py
https://github.com/aaronn/django-rest-framework-passwordless/blob/cd3f229cbc24de9c4b65768395ab5ba8ac1aaf1a/drfpasswordless/utils.py#L80-L93
def verify_user_alias(user, token): """ Marks a user's contact point as verified depending on accepted token type. """ if token.to_alias_type == 'EMAIL': if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME): setattr(user, api_settings.PASSWORDLESS_USER_...
[ "def", "verify_user_alias", "(", "user", ",", "token", ")", ":", "if", "token", ".", "to_alias_type", "==", "'EMAIL'", ":", "if", "token", ".", "to_alias", "==", "getattr", "(", "user", ",", "api_settings", ".", "PASSWORDLESS_USER_EMAIL_FIELD_NAME", ")", ":", ...
Marks a user's contact point as verified depending on accepted token type.
[ "Marks", "a", "user", "s", "contact", "point", "as", "verified", "depending", "on", "accepted", "token", "type", "." ]
python
train
apache/spark
python/pyspark/mllib/common.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/common.py#L126-L130
def callMLlibFunc(name, *args): """ Call API in PythonMLLibAPI """ sc = SparkContext.getOrCreate() api = getattr(sc._jvm.PythonMLLibAPI(), name) return callJavaFunc(sc, api, *args)
[ "def", "callMLlibFunc", "(", "name", ",", "*", "args", ")", ":", "sc", "=", "SparkContext", ".", "getOrCreate", "(", ")", "api", "=", "getattr", "(", "sc", ".", "_jvm", ".", "PythonMLLibAPI", "(", ")", ",", "name", ")", "return", "callJavaFunc", "(", ...
Call API in PythonMLLibAPI
[ "Call", "API", "in", "PythonMLLibAPI" ]
python
train
anjishnu/ask-alexa-pykit
examples/twitter/lambda_function.py
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/examples/twitter/lambda_function.py#L198-L221
def focused_on_tweet(request): """ Return index if focused on tweet False if couldn't """ slots = request.get_slot_map() if "Index" in slots and slots["Index"]: index = int(slots['Index']) elif "Ordinal" in slots and slots["Index"]: parse_ordinal = lambda inp : int("".join([l fo...
[ "def", "focused_on_tweet", "(", "request", ")", ":", "slots", "=", "request", ".", "get_slot_map", "(", ")", "if", "\"Index\"", "in", "slots", "and", "slots", "[", "\"Index\"", "]", ":", "index", "=", "int", "(", "slots", "[", "'Index'", "]", ")", "eli...
Return index if focused on tweet False if couldn't
[ "Return", "index", "if", "focused", "on", "tweet", "False", "if", "couldn", "t" ]
python
train
a2liu/mr-clean
mr_clean/core/functions/basics.py
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/core/functions/basics.py#L105-L120
def col_to_numeric(df,col_name, dest = False): """ Coerces a column in a DataFrame to numeric Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. ...
[ "def", "col_to_numeric", "(", "df", ",", "col_name", ",", "dest", "=", "False", ")", ":", "new_col", "=", "_pd", ".", "to_numeric", "(", "df", "[", "col_name", "]", ",", "errors", "=", "'coerce'", ")", "if", "dest", ":", "set_col", "(", "df", ",", ...
Coerces a column in a DataFrame to numeric Parameters: df - DataFrame DataFrame to operate on col_name - string Name of column to coerce dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
[ "Coerces", "a", "column", "in", "a", "DataFrame", "to", "numeric", "Parameters", ":", "df", "-", "DataFrame", "DataFrame", "to", "operate", "on", "col_name", "-", "string", "Name", "of", "column", "to", "coerce", "dest", "-", "bool", "default", "False", "W...
python
train
pywbem/pywbem
try/run_central_instances.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L167-L204
def print_table(title, headers, rows, sort_columns=None): """ Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each ...
[ "def", "print_table", "(", "title", ",", "headers", ",", "rows", ",", "sort_columns", "=", "None", ")", ":", "if", "sort_columns", "is", "not", "None", ":", "if", "isinstance", "(", "sort_columns", ",", "int", ")", ":", "rows", "=", "sorted", "(", "row...
Print a table of rows with headers using tabulate. Parameters: title (:term: string): String that will be output before the Table. headers (list or tuple): List of strings that defines the header for each row. Each string in this list may be multiline by inserting...
[ "Print", "a", "table", "of", "rows", "with", "headers", "using", "tabulate", "." ]
python
train
cogniteev/docido-python-sdk
docido_sdk/toolbox/google_ext.py
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/google_ext.py#L22-L51
def refresh_token(token, session=None): """Refresh Google OAuth token. :param OAuthToken token: the token to refresh :param requests.Session session: Optional `requests` session to use. """ session = session or HTTP_SESSION refresh_data = dict( refresh_token=token.refresh_t...
[ "def", "refresh_token", "(", "token", ",", "session", "=", "None", ")", ":", "session", "=", "session", "or", "HTTP_SESSION", "refresh_data", "=", "dict", "(", "refresh_token", "=", "token", ".", "refresh_token", ",", "client_id", "=", "token", ".", "consume...
Refresh Google OAuth token. :param OAuthToken token: the token to refresh :param requests.Session session: Optional `requests` session to use.
[ "Refresh", "Google", "OAuth", "token", "." ]
python
train
Fortran-FOSS-Programmers/ford
ford/graphs.py
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/graphs.py#L755-L772
def add_nodes(self, nodes, nesting=1): """ Adds edges showing dependencies between source files listed in the nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(le...
[ "def", "add_nodes", "(", "self", ",", "nodes", ",", "nesting", "=", "1", ")", ":", "hopNodes", "=", "set", "(", ")", "# nodes in this hop", "hopEdges", "=", "[", "]", "# edges in this hop", "# get nodes and edges for this hop", "for", "i", ",", "n", "in", "z...
Adds edges showing dependencies between source files listed in the nodes.
[ "Adds", "edges", "showing", "dependencies", "between", "source", "files", "listed", "in", "the", "nodes", "." ]
python
train
wright-group/WrightTools
WrightTools/data/_channel.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L115-L133
def normalize(self, mag=1.): """Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1. """ def f(dataset, s, null, mag): dataset[s] -= null dataset...
[ "def", "normalize", "(", "self", ",", "mag", "=", "1.", ")", ":", "def", "f", "(", "dataset", ",", "s", ",", "null", ",", "mag", ")", ":", "dataset", "[", "s", "]", "-=", "null", "dataset", "[", "s", "]", "/=", "mag", "if", "self", ".", "sign...
Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1.
[ "Normalize", "a", "Channel", "set", "null", "to", "0", "and", "the", "mag", "to", "given", "value", "." ]
python
train
arista-eosplus/pyeapi
pyeapi/api/stp.py
https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/api/stp.py#L132-L156
def set_mode(self, value=None, default=False, disable=False): """Configures the global spanning-tree mode Note: This configuration parameter is not defaultable Args: value (string): The value to configure the global spanning-tree mode of operation. Vali...
[ "def", "set_mode", "(", "self", ",", "value", "=", "None", ",", "default", "=", "False", ",", "disable", "=", "False", ")", ":", "if", "not", "default", "and", "not", "disable", ":", "if", "value", "not", "in", "[", "'mstp'", ",", "'none'", "]", ":...
Configures the global spanning-tree mode Note: This configuration parameter is not defaultable Args: value (string): The value to configure the global spanning-tree mode of operation. Valid values include 'mstp', 'none' default (bool): Set the globa...
[ "Configures", "the", "global", "spanning", "-", "tree", "mode" ]
python
train
sendgrid/sendgrid-python
sendgrid/helpers/mail/mail.py
https://github.com/sendgrid/sendgrid-python/blob/266c2abde7a35dfcce263e06bedc6a0bbdebeac9/sendgrid/helpers/mail/mail.py#L211-L236
def to(self, to_emails, global_substitutions=None, is_multiple=False, p=0): """Adds To objects to the Personalization object :param to_emails: An To or list of To objects :type to_emails: To, list(To), str, tuple :param global_substitutions: A dict of substitutions for all recipients ...
[ "def", "to", "(", "self", ",", "to_emails", ",", "global_substitutions", "=", "None", ",", "is_multiple", "=", "False", ",", "p", "=", "0", ")", ":", "if", "isinstance", "(", "to_emails", ",", "list", ")", ":", "for", "email", "in", "to_emails", ":", ...
Adds To objects to the Personalization object :param to_emails: An To or list of To objects :type to_emails: To, list(To), str, tuple :param global_substitutions: A dict of substitutions for all recipients :type global_substitutions: dict :param is_multiple: Create a new personi...
[ "Adds", "To", "objects", "to", "the", "Personalization", "object" ]
python
train
Unidata/siphon
siphon/cdmr/coveragedataset.py
https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/cdmr/coveragedataset.py#L45-L48
def _read_header(self): """Get the needed header information to initialize dataset.""" self._header = self.cdmrf.fetch_header() self.load_from_stream(self._header)
[ "def", "_read_header", "(", "self", ")", ":", "self", ".", "_header", "=", "self", ".", "cdmrf", ".", "fetch_header", "(", ")", "self", ".", "load_from_stream", "(", "self", ".", "_header", ")" ]
Get the needed header information to initialize dataset.
[ "Get", "the", "needed", "header", "information", "to", "initialize", "dataset", "." ]
python
train
tensorflow/lucid
lucid/scratch/atlas_pipeline/grid.py
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/scratch/atlas_pipeline/grid.py#L12-L68
def grid(metadata, layout, params): """ layout: numpy arrays x, y metadata: user-defined numpy arrays with metadata n_layer: number of cells in the layer (squared) n_tile: number of cells in the tile (squared) """ x = layout["x"] y = layout["y"] x_min = np.min(x) x_max = np.max(x) y_min = np.min(y...
[ "def", "grid", "(", "metadata", ",", "layout", ",", "params", ")", ":", "x", "=", "layout", "[", "\"x\"", "]", "y", "=", "layout", "[", "\"y\"", "]", "x_min", "=", "np", ".", "min", "(", "x", ")", "x_max", "=", "np", ".", "max", "(", "x", ")"...
layout: numpy arrays x, y metadata: user-defined numpy arrays with metadata n_layer: number of cells in the layer (squared) n_tile: number of cells in the tile (squared)
[ "layout", ":", "numpy", "arrays", "x", "y", "metadata", ":", "user", "-", "defined", "numpy", "arrays", "with", "metadata", "n_layer", ":", "number", "of", "cells", "in", "the", "layer", "(", "squared", ")", "n_tile", ":", "number", "of", "cells", "in", ...
python
train
savoirfairelinux/num2words
num2words/lang_JA.py
https://github.com/savoirfairelinux/num2words/blob/f4b2bac098ae8e4850cf2f185f6ff52a5979641f/num2words/lang_JA.py#L45-L85
def rendaku_merge_pairs(lpair, rpair): """Merge lpair < rpair while applying semi-irregular rendaku rules""" ltext, lnum = lpair rtext, rnum = rpair if lnum > rnum: raise ValueError if rpair == ("ひゃく", 100): if lpair == ("さん", 3): rtext = "びゃく" elif lpair == ("ろく...
[ "def", "rendaku_merge_pairs", "(", "lpair", ",", "rpair", ")", ":", "ltext", ",", "lnum", "=", "lpair", "rtext", ",", "rnum", "=", "rpair", "if", "lnum", ">", "rnum", ":", "raise", "ValueError", "if", "rpair", "==", "(", "\"ひゃく\", 100)", ":", "", "", ...
Merge lpair < rpair while applying semi-irregular rendaku rules
[ "Merge", "lpair", "<", "rpair", "while", "applying", "semi", "-", "irregular", "rendaku", "rules" ]
python
test