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)
# bind the exchange to our connection so operations can be performed on it
bound_exchange = exchange(connection)
# ensure the exchange exists. Throw an error if it was created with
# passive=True and it doesn't exist.
bound_exchange.declare()
return bound_exchange | [
"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(dates, np.where(dates=='.directory')[0][0])
dates = np.delete(dates, np.where(dates=='all_folders.list')[0][0])
dates = np.delete(dates, np.where(dates=='dr2.lis')[0][0])
for date in dates:
if glob.glob("*%s*.txt" %date):
print("%s done" %date)
else:
print("running %s" %date)
run_one_date(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
# Assign a new value or add new keyword here.
try:
_hdr[key] = value
except KeyError:
if show:
print('Adding new keyword ', key, '=', value)
_hdr[key] = value
# Close image
_fimg.close()
del _fimg | [
"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'Function {func} expected Info instance, {name} got instead.') | [
"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['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return 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 value being optimized
:param (str) log: One of "gradients", "parameters", "all", or None
:param (int) log_freq: log gradients and parameters every N batches
:return: (wandb.Graph) The graph object that will populate after the first backward pass
"""
global watch_called
if run is None:
raise ValueError(
"You must call `wandb.init` before calling watch")
if watch_called:
raise ValueError(
"You can only call `wandb.watch` once per process. If you want to watch multiple models, pass them in as a tuple."
)
watch_called = True
log_parameters = False
log_gradients = True
if log == "all":
log_parameters = True
elif log == "parameters":
log_parameters = True
log_gradients = False
elif log is None:
log_gradients = False
if not isinstance(models, (tuple, list)):
models = (models,)
graphs = []
prefix = ''
for idx, model in enumerate(models):
if idx > 0:
prefix = "graph_%i" % idx
run.history.torch.add_log_hooks_to_pytorch_module(
model, log_parameters=log_parameters, log_gradients=log_gradients, prefix=prefix, log_freq=log_freq)
graph = wandb_torch.TorchGraph.hook_torch(model, criterion, graph_idx=idx)
graphs.append(graph)
# NOTE: the graph is set in run.summary by hook_torch on the backward pass
return graphs | [
"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", "all", or None
:param (int) log_freq: log gradients and parameters every N batches
:return: (wandb.Graph) The graph object that will populate after the first backward pass | [
"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(
description='Automatically manage ACME certificates for Marathon apps')
parser.add_argument('-a', '--acme',
help='The address for the ACME Directory Resource '
'(default: %(default)s)',
default=acme_url)
parser.add_argument('-e', '--email',
help='An email address to register with the ACME '
'service (optional)')
parser.add_argument('-m', '--marathon', metavar='MARATHON[,MARATHON,...]',
help='The addresses for the Marathon HTTP API '
'(default: %(default)s)',
default='http://marathon.mesos:8080')
parser.add_argument('-l', '--lb', metavar='LB[,LB,...]',
help='The addresses for the marathon-lb HTTP API '
'(default: %(default)s)',
default='http://marathon-lb.marathon.mesos:9090')
parser.add_argument('-g', '--group',
help='The marathon-lb group to issue certificates for '
'(default: %(default)s)',
default='external')
parser.add_argument('--allow-multiple-certs',
help=('Allow multiple certificates for a single app '
'port. This allows multiple domains for an app, '
'but is not recommended.'),
action='store_true')
parser.add_argument('--listen',
help='The address for the port to listen on (default: '
'%(default)s)',
default=':8000')
parser.add_argument('--marathon-timeout',
help=('Amount of time in seconds to wait for HTTP '
'response headers to be received for all '
'requests to Marathon. Set to 0 to disable. '
'(default: %(default)s)'),
type=float,
default=10)
parser.add_argument('--sse-timeout',
help=('Amount of time in seconds to wait for some '
'event data to be received from Marathon. Set '
'to 0 to disable. (default: %(default)s)'),
type=float,
default=60)
parser.add_argument('--log-level',
help='The minimum severity level to log messages at '
'(default: %(default)s)',
choices=['debug', 'info', 'warn', 'error', 'critical'],
default='info'),
parser.add_argument('--vault',
help=('Enable storage of certificates in Vault. This '
'can be further configured with VAULT_-style '
'environment variables.'),
action='store_true')
parser.add_argument('storage_path', metavar='storage-path',
help=('Path for storing certificates. If --vault is '
'used then this is the mount path for the '
'key/value engine in Vault. If not, this is the '
'path to a directory.'))
parser.add_argument('--version', action='version', version=__version__)
args = parser.parse_args(argv)
# Set up logging
init_logging(args.log_level)
# Set up marathon-acme
marathon_addrs = args.marathon.split(',')
mlb_addrs = args.lb.split(',')
sse_timeout = args.sse_timeout if args.sse_timeout > 0 else None
acme_url = URL.fromText(_to_unicode(args.acme))
endpoint_description = parse_listen_addr(args.listen)
log_args = [
('storage-path', args.storage_path),
('vault', args.vault),
('acme', acme_url),
('email', args.email),
('allow-multiple-certs', args.allow_multiple_certs),
('marathon', marathon_addrs),
('sse-timeout', sse_timeout),
('lb', mlb_addrs),
('group', args.group),
('endpoint-description', endpoint_description),
]
log_args = ['{}={!r}'.format(k, v) for k, v in log_args]
log.info('Starting marathon-acme {} with: {}'.format(
__version__, ', '.join(log_args)))
if args.vault:
key_d, cert_store = init_vault_storage(
reactor, env, args.storage_path)
else:
key_d, cert_store = init_file_storage(args.storage_path)
# Once we have the client key, create the txacme client creator
key_d.addCallback(create_txacme_client_creator, reactor, acme_url)
# Once we have the client creator, create the service
key_d.addCallback(
create_marathon_acme, cert_store, args.email,
args.allow_multiple_certs, marathon_addrs, args.marathon_timeout,
sse_timeout, mlb_addrs, args.group, reactor)
# Finally, run the thing
return key_d.addCallback(lambda ma: ma.run(endpoint_description)) | [
"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:
if _req.force_authn:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context)
else:
return self.operation(saml_msg, BINDING_HTTP_POST)
else:
saml_msg["req_info"] = self.req_info
key = self._store_request(saml_msg)
return self.not_authn(key, _req.requested_authn_context) | [
"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 dict which contains all Virtual Machines, where every element of this dict looks like that:
``{ "VIRTUAL_MACHINE_ID": { "ip": "IP_ADDR", "state": "VM_STATE" }``
:rtype: tuple
Sample response:
``( 1, {'180aa486-ee46-4628-ab1c-f4554b63231': {'ip': '172.1.1.2', 'state': 'running'}} )``
"""
vmshepherd = self.request.app.vmshepherd
preset = vmshepherd.preset_manager.get_preset(preset)
result_vms = {vm.id: {'ip': vm.ip[0], 'state': vm.state.value} for vm in preset.vms}
return preset.count, result_vms | [
"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 element of this dict looks like that:
``{ "VIRTUAL_MACHINE_ID": { "ip": "IP_ADDR", "state": "VM_STATE" }``
:rtype: tuple
Sample response:
``( 1, {'180aa486-ee46-4628-ab1c-f4554b63231': {'ip': '172.1.1.2', 'state': 'running'}} )`` | [
"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 name of the MarkDown template file from the aide_document/templates folder. Do not use the file path.
data_name : String
Relative file path from where this method is called to the location of the YAML data file to be used.
output_name : String
Relative file path from where this method is called to the location to which the output file is written.
Examples
========
Suppose we have template.md in aide_document and a directory as follows:
data/
params.yaml
To render the document:
>>> from aide_document import combine
>>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md')
This will then combine the data and template files and write to a new output file within data/.
"""
# Set up environment and load templates from pip package
env = Environment(loader=PackageLoader('aide_document')) #TODO: add custom path to templates
# Create output file, open template and data files, then combine
with open(output_name, 'w') as output_file:
output = env.get_template(template_name).render(yaml.load(open(data_name)))
output_file.write(output) | [
"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 folder. Do not use the file path.
data_name : String
Relative file path from where this method is called to the location of the YAML data file to be used.
output_name : String
Relative file path from where this method is called to the location to which the output file is written.
Examples
========
Suppose we have template.md in aide_document and a directory as follows:
data/
params.yaml
To render the document:
>>> from aide_document import combine
>>> combine.render_document('template.md', 'data/params.yaml', 'data/output.md')
This will then combine the data and template files and write to a new output file within data/. | [
"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():
register_name = REGISTER_FUNCTIONS[obj]
deregister_name = register_name.replace('Reg', 'Dereg')
deregister = getattr(cnx, deregister_name)
for callback_id in ids:
deregister(callback_id) | [
"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
:param email_dict: the email dict
:return dict
"""
return self._create_post_request(
resource=CONFIRMATIONS,
billomat_id=confirmation_id,
send_data=email_dict,
command=EMAIL,
) | [
"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(['gpg', '--dearmor'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out, err = ps.communicate(input=key_asc)
# no need to decode output as it is binary (invalid utf-8), only error
if six.PY3:
err = err.decode('utf-8')
if 'gpg: no valid OpenPGP data found.' in err:
raise GPGKeyError('Invalid GPG key material. Check your network setup'
' (MTU, routing, DNS) and/or proxy server settings'
' as well as destination keyserver status.')
else:
return out | [
"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 = [index]
levels = list(range(0, len(index)))
df[date_temp] = pd.to_datetime(df[date_column], format=date_format)
reference_cols = [date_temp, date_column]
df = df.groupby(index + reference_cols).sum()
df[new_column] = df.groupby(level=levels)[column].cumsum()
df.reset_index(inplace=True)
del df[date_temp]
return df | [
"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: bool
"""
result = self.request("post", "revokeoauth2", data={"access_token": access_token})
return bool(result.get("result")) | [
"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, just increment the month)
- "y", "year', "years" for a year (i.e. no day computation, just increment the year)
"""
sign_coeff = 1 if sign == '+' else -1
try:
return dateobj + sign_coeff * pd.Timedelta(hr_offset)
except ValueError:
# pd.Timedelta could not parse the offset, let's try harder
match = TIMEDELTA_RGX.match(hr_offset)
if match is not None:
groups = match.groupdict()
unit = groups['unit'].lower()[0]
num = sign_coeff * int(groups['num'])
# is it a week ?
if unit == 'w':
return dateobj + num * timedelta(weeks=1)
# or a month ?
if unit == 'm':
return add_months(dateobj, num)
# or a year ?
if unit == 'y':
return add_years(dateobj, num)
# we did what we could, just re-raise the original exception
raise | [
"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 year (i.e. no day computation, just increment the year) | [
"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
salt myminion boto_vpc.describe vpc_id=vpc-123456
salt myminion boto_vpc.describe vpc_name=myvpc
'''
if not any((vpc_id, vpc_name)):
raise SaltInvocationError('A valid vpc id or name needs to be specified.')
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
vpc_id = check_vpc(vpc_id, vpc_name, region, key, keyid, profile)
except BotoServerError as err:
boto_err = __utils__['boto.get_error'](err)
if boto_err.get('aws', {}).get('code') == 'InvalidVpcID.NotFound':
# VPC was not found: handle the error and return None.
return {'vpc': None}
return {'error': boto_err}
if not vpc_id:
return {'vpc': None}
filter_parameters = {'vpc_ids': vpc_id}
try:
vpcs = conn.get_all_vpcs(**filter_parameters)
except BotoServerError as err:
return {'error': __utils__['boto.get_error'](err)}
if vpcs:
vpc = vpcs[0] # Found!
log.debug('Found VPC: %s', vpc.id)
keys = ('id', 'cidr_block', 'is_default', 'state', 'tags',
'dhcp_options_id', 'instance_tenancy')
_r = dict([(k, getattr(vpc, k)) for k in keys])
_r.update({'region': getattr(vpc, 'region').name})
return {'vpc': _r}
else:
return {'vpc': None} | [
"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']['GetServiceDetails']
try:
soap_response = service_query(serviceID=service_id)
except WebFault:
raise WebServiceError
return ServiceDetails(soap_response) | [
"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(deps_dir)
try:
print("Staging ci dependencies")
_stage_requirements(deps_dir, os.path.join(package_root, 'requires', 'ci'))
print("Checking out modularcrypto packages for coverage")
for other_package in other_packages:
pkg_url = 'https://github.com/wbond/%s.git' % other_package
pkg_dir = os.path.join(build_root, other_package)
if os.path.exists(pkg_dir):
print("%s is already present" % other_package)
continue
print("Cloning %s" % pkg_url)
_execute(['git', 'clone', pkg_url], build_root)
print()
except (Exception):
if os.path.exists(deps_dir):
shutil.rmtree(deps_dir, ignore_errors=True)
raise
return True | [
"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 executed within the current situation.
Return:
A float, the reward received for the action that was executed,
or None if no reward is offered.
"""
reward = self.reward_function(
action,
self.classifications[self.steps]
)
self.total_reward += reward
self.steps += 1
return reward | [
"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.
Return:
A float, the reward received for the action that was executed,
or None if no reward is offered. | [
"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 = zip(self.layers[:-1], weights, self.layers[1:])
for previous, weight, current in connections:
incoming = self.forward(weight, previous.outgoing)
current.apply(incoming)
# Return the activations of the output layer.
return self.layers[-1].outgoing | [
"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`
:returns: a result set instance which can be used to consume rows.
"""
kwargs = copy.deepcopy(batch["read"])
keyset_dict = kwargs.pop("keyset")
kwargs["keyset"] = KeySet._from_dict(keyset_dict)
return self._get_snapshot().read(partition=batch["partition"], **kwargs) | [
"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 can be used to consume rows. | [
"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}
# contains all nodes *without* any dependencies (leaf nodes)
return self.nodes - deps | [
"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(target, types.Chat):
chat_id = target.id
elif isinstance(target, (int, str)):
chat_id = target
else:
raise TypeError(f"Bad type of target. ({type(target)})")
setattr(self, 'chat_id', chat_id)
return self | [
"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):
raise RuntimeError("")
with open_file(file_path, 'rb') as file:
size = os.path.getsize(file_path)
label = "Uploading {filename} ({size:.2f}MB)".format(
filename=os.path.basename(file_path),
size=size / float(self.chunk_size) / self.chunk_size
)
if method == "PUT":
resp = put(url, data=file)
elif method == "POST":
resp = post(url, data=file)
content_iter = resp.iter_content(chunk_size=self.chunk_size)
with progressbar(content_iter,
length=size / self.chunk_size,
label=label) as bar:
for _ in bar:
pass | [
"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 site.species.items():
sym = sp.symbol
oxi_state = getattr(sp, "oxi_state", None)
new_sp[Specie(sym, oxidation_state=oxi_state,
properties={'spin': spins.get(str(sp), spins.get(sym, None))})] = occu
site.species = new_sp | [
"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-value pairs, where for sections values are dictionaries
of their contents.
"""
values = dict_cls()
if flat:
for str_path, item in self.iter_items(recursive=True, key='str_path'):
if item.has_value:
if with_defaults or not item.is_default:
values[str_path] = item.value
else:
for item_name, item in self._tree.items():
if is_config_section(item):
section_values = item.dump_values(with_defaults=with_defaults, dict_cls=dict_cls)
if section_values:
values[item_name] = section_values
else:
if item.has_value:
if with_defaults or not item.is_default:
values[item.name] = item.value
return values | [
"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_func)
self._alerter_thread.start() | [
"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 is the name of the specific telnet template
:param template_id Internal IMC number which designates the specific telnet template
:return: int value of HTTP response code 201 for proper creation or 404 for failed creation
:rtype int
Sample of proper KV pairs. Please see documentation for valid values for different fields.
telnet_template = {"type": "0",
"name": "User_with_Enable",
"authType": "4",
"userName": "newadmin",
"userPassword": "newpassword",
"superPassword": "newpassword",
"authTypeStr": "Username + Password + Super/Manager Password",
"timeout": "4",
"retries": "1",
"port": "23",
"version": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""}
"""
if template_name is None:
template_name = telnet_template['name']
if template_id is None:
telnet_templates = get_telnet_template(auth, url)
template_id = None
for template in telnet_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/telnet/"+str(template_id)+"/update"
response = requests.put(f_url, data = json.dumps(telnet_template), auth=auth, headers=HEADERS)
try:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " modify_telnet_template: An Error has occured" | [
"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 specific telnet template
:return: int value of HTTP response code 201 for proper creation or 404 for failed creation
:rtype int
Sample of proper KV pairs. Please see documentation for valid values for different fields.
telnet_template = {"type": "0",
"name": "User_with_Enable",
"authType": "4",
"userName": "newadmin",
"userPassword": "newpassword",
"superPassword": "newpassword",
"authTypeStr": "Username + Password + Super/Manager Password",
"timeout": "4",
"retries": "1",
"port": "23",
"version": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""} | [
"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_header(
disptype, quote_fields=quote_fields, **params) | [
"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 = ''
try:
text = self.currentText()
except ValueError:
lg.debug('Cannot convert "' + str(text) + '" to list. ' +
'Using default ' + str(default))
text = default
self.set_value(text)
return text | [
"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
Mean of the linear combination of the chi-squared distributions.
var : float
Variance of the linear combination of the chi-squared distributions.
kur : float
Kurtosis of the linear combination of the chi-squared distributions.
w : array_like
Weights of the linear combination.
remain_var : float
Remaining variance assigned to a Normal distribution.
df : float
Overall degrees of freedom.
trho : array_like
Weight between the combination of chi-squared distributions and independent
chi-squared distributions.
grid : array_like
Grid parameters.
pmin : float
Boundary of the possible final p-values.
Returns
-------
float
Estimated p-value.
References
----------
[1] Lee, Seunggeun, Michael C. Wu, and Xihong Lin. "Optimal tests for rare variant
effects in sequencing association studies." Biostatistics 13.4 (2012): 762-775.
"""
q = asarray(q, float)
mu = float(mu)
var = float(var)
kur = float(kur)
w = asarray(w, float)
remain_var = float(remain_var)
df = float(df)
trho = asarray(trho, float)
grid = asarray(grid, float)
lambda_threshold = sum(w) * 10 ** 4
chi2s = [ChiSquared(i, 0.0, 1) for i in w]
args = (q, mu, var, kur, lambda_threshold, remain_var, df, trho, grid, chi2s)
try:
u = _find_upper_bound(args)
re = quad(
_davies_function, 0, u, args, limit=1000, epsabs=_EPSABS, full_output=1
)
pvalue = 1 - re[0]
if re[1] > 1e-6:
pvalue = _skat_liu_pvalue(
q, mu, var, kur, w, remain_var, df, trho, grid, pmin
)
except RuntimeError:
pvalue = _skat_liu_pvalue(q, mu, var, kur, w, remain_var, df, trho, grid, pmin)
if pmin is not None:
if pmin * len(grid) < abs(pvalue):
pvalue = pmin * len(grid)
return pvalue | [
"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
Variance of the linear combination of the chi-squared distributions.
kur : float
Kurtosis of the linear combination of the chi-squared distributions.
w : array_like
Weights of the linear combination.
remain_var : float
Remaining variance assigned to a Normal distribution.
df : float
Overall degrees of freedom.
trho : array_like
Weight between the combination of chi-squared distributions and independent
chi-squared distributions.
grid : array_like
Grid parameters.
pmin : float
Boundary of the possible final p-values.
Returns
-------
float
Estimated p-value.
References
----------
[1] Lee, Seunggeun, Michael C. Wu, and Xihong Lin. "Optimal tests for rare variant
effects in sequencing association studies." Biostatistics 13.4 (2012): 762-775. | [
"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 a list or None'
objid = _get_idstr(pyobj)
ns,n = self.get_name(name, objid)
el = elt.createAppendElement(ns, n)
if self.nillable is True and pyobj is None:
self.serialize_as_nil(el)
return None
tc = self.itemTypeCode
s = StringIO(); sep = ' '
for item in pyobj:
s.write(tc.get_formatted_content(item))
s.write(sep)
el.createAppendTextNode(s.getvalue()) | [
"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 float
Round the timestamps to the closest second divisible by this value before
comparing them.
E.g.:
- ``n_round_sec`` = 0.1: nearest 10th of a second.
- ``n_round_sec`` = 1: nearest second.
- ``n_round_sec`` = 30: nearest half minute.
Timestamps may lose resolution or otherwise change slightly as they go through
various transformations and storage systems. This again may cause timestamps
that
have been processed in different systems to fail an exact equality compare even
if
they were initially the same timestamp. This rounding avoids such problems as
long
as the error introduced to the original timestamp is not higher than the
rounding
value. Of course, the rounding also causes a loss in resolution in the values
compared, so should be kept as low as possible. The default value of 1 second
should
be a good tradeoff in most cases.
Returns:
bool
- **True**: If the two datetimes are equal after being rounded by
``round_sec``.
"""
ra_dt = round_to_nearest(a_dt, round_sec)
rb_dt = round_to_nearest(b_dt, round_sec)
logger.debug('Rounded:')
logger.debug('{} -> {}'.format(a_dt, ra_dt))
logger.debug('{} -> {}'.format(b_dt, rb_dt))
return normalize_datetime_to_utc(ra_dt) == normalize_datetime_to_utc(rb_dt) | [
"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 second divisible by this value before
comparing them.
E.g.:
- ``n_round_sec`` = 0.1: nearest 10th of a second.
- ``n_round_sec`` = 1: nearest second.
- ``n_round_sec`` = 30: nearest half minute.
Timestamps may lose resolution or otherwise change slightly as they go through
various transformations and storage systems. This again may cause timestamps
that
have been processed in different systems to fail an exact equality compare even
if
they were initially the same timestamp. This rounding avoids such problems as
long
as the error introduced to the original timestamp is not higher than the
rounding
value. Of course, the rounding also causes a loss in resolution in the values
compared, so should be kept as low as possible. The default value of 1 second
should
be a good tradeoff in most cases.
Returns:
bool
- **True**: If the two datetimes are equal after being rounded by
``round_sec``. | [
"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
:type status: bool
:returns: boolean indicating the new status
"""
fire_status = status
last_status = self._fire_status
if isinstance(message, Message):
# Quirk in Ademco panels. The fire bit drops on "SYSTEM LO BAT" messages.
# FIXME: does not support non english panels.
if self.mode == ADEMCO and message.text.startswith("SYSTEM"):
fire_status = last_status
else:
fire_status = message.fire_alarm
if fire_status is None:
return
if fire_status != self._fire_status:
self._fire_status, old_status = fire_status, self._fire_status
if old_status is not None:
self.on_fire(status=self._fire_status)
return self._fire_status | [
"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
# convert all multivalue keys to the right form
fields = set()
for result in results:
for key in result.keys():
if(isinstance(result[key], list)):
result['__mv_' + key] = encode_mv(result[key])
result[key] = mvdelim.join(result[key])
fields.update(list(result.keys()))
# convert the fields into a list and create a CSV writer
# to output to stdout
fields = sorted(list(fields))
writer = csv.DictWriter(output, fields)
# Write out the fields, and then the actual results
writer.writerow(dict(list(zip(fields, fields))))
writer.writerows(results) | [
"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 backend
3. postprocessing
Backend developer can:
1. Define preprocessing process. Override `_preprocess_run`
2. Define the gate action. Define methods `gate_{gate.lowername}`,
for example, `gate_x` for X gate, `gate_cx` for CX gate.
3. Define postprocessing process (and make return value). Override `_postprocess_run`
Otherwise, the developer can override `run` method if they want to change the flow of run.
"""
gates, ctx = self._preprocess_run(gates, n_qubits, args, kwargs)
self._run_gates(gates, n_qubits, ctx)
return self._postprocess_run(ctx) | [
"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 developer can:
1. Define preprocessing process. Override `_preprocess_run`
2. Define the gate action. Define methods `gate_{gate.lowername}`,
for example, `gate_x` for X gate, `gate_cx` for CX gate.
3. Define postprocessing process (and make return value). Override `_postprocess_run`
Otherwise, the developer can override `run` method if they want to change the flow of run. | [
"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:`pyspark.sql.types.DataType` object or a DDL-formatted type string.
:param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`.
Default: SCALAR.
.. note:: Experimental
The function type of the UDF can be one of the following:
1. SCALAR
A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`.
The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`.
If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`.
:class:`MapType`, nested :class:`StructType` are currently not supported as output types.
Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and
:meth:`pyspark.sql.DataFrame.select`.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> from pyspark.sql.types import IntegerType, StringType
>>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP
>>> @pandas_udf(StringType()) # doctest: +SKIP
... def to_upper(s):
... return s.str.upper()
...
>>> @pandas_udf("integer", PandasUDFType.SCALAR) # doctest: +SKIP
... def add_one(x):
... return x + 1
...
>>> df = spark.createDataFrame([(1, "John Doe", 21)],
... ("id", "name", "age")) # doctest: +SKIP
>>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")) \\
... .show() # doctest: +SKIP
+----------+--------------+------------+
|slen(name)|to_upper(name)|add_one(age)|
+----------+--------------+------------+
| 8| JOHN DOE| 22|
+----------+--------------+------------+
>>> @pandas_udf("first string, last string") # doctest: +SKIP
... def split_expand(n):
... return n.str.split(expand=True)
>>> df.select(split_expand("name")).show() # doctest: +SKIP
+------------------+
|split_expand(name)|
+------------------+
| [John, Doe]|
+------------------+
.. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input
column, but is the length of an internal batch used for each call to the function.
Therefore, this can be used, for example, to ensure the length of each returned
`pandas.Series`, and can not be used as the column length.
2. GROUPED_MAP
A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame`
The returnType should be a :class:`StructType` describing the schema of the returned
`pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match
the field names in the defined returnType schema if specified as strings, or match the
field data types by position if not strings, e.g. integer indices.
The length of the returned `pandas.DataFrame` can be arbitrary.
Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP
... def normalize(pdf):
... v = pdf.v
... return pdf.assign(v=(v - v.mean()) / v.std())
>>> df.groupby("id").apply(normalize).show() # doctest: +SKIP
+---+-------------------+
| id| v|
+---+-------------------+
| 1|-0.7071067811865475|
| 1| 0.7071067811865475|
| 2|-0.8320502943378437|
| 2|-0.2773500981126146|
| 2| 1.1094003924504583|
+---+-------------------+
Alternatively, the user can define a function that takes two arguments.
In this case, the grouping key(s) will be passed as the first argument and the data will
be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy
data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in
as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.
This is useful when the user does not want to hardcode grouping key(s) in the function.
>>> import pandas as pd # doctest: +SKIP
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP
... def mean_udf(key, pdf):
... # key is a tuple of one numpy.int64, which is the value
... # of 'id' for the current group
... return pd.DataFrame([key + (pdf.v.mean(),)])
>>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP
+---+---+
| id| v|
+---+---+
| 1|1.5|
| 2|6.0|
+---+---+
>>> @pandas_udf(
... "id long, `ceil(v / 2)` long, v double",
... PandasUDFType.GROUPED_MAP) # doctest: +SKIP
>>> def sum_udf(key, pdf):
... # key is a tuple of two numpy.int64s, which is the values
... # of 'id' and 'ceil(df.v / 2)' for the current group
... return pd.DataFrame([key + (pdf.v.sum(),)])
>>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP
+---+-----------+----+
| id|ceil(v / 2)| v|
+---+-----------+----+
| 2| 5|10.0|
| 1| 1| 3.0|
| 2| 3| 5.0|
| 2| 2| 3.0|
+---+-----------+----+
.. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is
recommended to explicitly index the columns by name to ensure the positions are correct,
or alternatively use an `OrderedDict`.
For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or
`pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.
.. seealso:: :meth:`pyspark.sql.GroupedData.apply`
3. GROUPED_AGG
A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar
The `returnType` should be a primitive data type, e.g., :class:`DoubleType`.
The returned scalar can be either a python primitive type, e.g., `int` or `float`
or a numpy data type, e.g., `numpy.int64` or `numpy.float64`.
:class:`MapType` and :class:`StructType` are currently not supported as output types.
Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and
:class:`pyspark.sql.Window`
This example shows using grouped aggregated UDFs with groupby:
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v"))
>>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP
... def mean_udf(v):
... return v.mean()
>>> df.groupby("id").agg(mean_udf(df['v'])).show() # doctest: +SKIP
+---+-----------+
| id|mean_udf(v)|
+---+-----------+
| 1| 1.5|
| 2| 6.0|
+---+-----------+
This example shows using grouped aggregated UDFs as window functions.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> from pyspark.sql import Window
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v"))
>>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP
... def mean_udf(v):
... return v.mean()
>>> w = (Window.partitionBy('id')
... .orderBy('v')
... .rowsBetween(-1, 0))
>>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP
+---+----+------+
| id| v|mean_v|
+---+----+------+
| 1| 1.0| 1.0|
| 1| 2.0| 1.5|
| 2| 3.0| 3.0|
| 2| 5.0| 4.0|
| 2|10.0| 7.5|
+---+----+------+
.. note:: For performance reasons, the input series to window functions are not copied.
Therefore, mutating the input series is not allowed and will cause incorrect results.
For the same reason, users should also not rely on the index of the input series.
.. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window`
.. note:: The user-defined functions are considered deterministic by default. Due to
optimization, duplicate invocations may be eliminated or the function may even be invoked
more times than it is present in the query. If your function is not deterministic, call
`asNondeterministic` on the user defined function. E.g.:
>>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP
... def random(v):
... import numpy as np
... import pandas as pd
... return pd.Series(np.random.randn(len(v))
>>> random = random.asNondeterministic() # doctest: +SKIP
.. note:: The user-defined functions do not support conditional expressions or short circuiting
in boolean expressions and it ends up with being executed all internally. If the functions
can fail on special rows, the workaround is to incorporate the condition into the functions.
.. note:: The user-defined functions do not take keyword arguments on the calling side.
.. note:: The data type of returned `pandas.Series` from the user-defined functions should be
matched with defined returnType (see :meth:`types.to_arrow_type` and
:meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do
conversion on returned data. The conversion is not guaranteed to be correct and results
should be checked for accuracy by users.
"""
# 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 and might be changed in the near
# future. The table might have to be eventually documented externally.
# Please see SPARK-25798's PR to see the codes in order to generate the table below.
#
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# |SQL Type \ Pandas Value(Type)|None(object(NoneType))|True(bool)|1(int8)|1(int16)| 1(int32)| 1(int64)|1(uint8)|1(uint16)|1(uint32)|1(uint64)|1.0(float16)|1.0(float32)|1.0(float64)|1970-01-01 00:00:00(datetime64[ns])|1970-01-01 00:00:00-05:00(datetime64[ns, US/Eastern])|a(object(string))| 1(object(Decimal))|[1 2 3](object(array[int32]))|1.0(float128)|(1+0j)(complex64)|(1+0j)(complex128)|A(category)|1 days 00:00:00(timedelta64[ns])| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
# | boolean| None| True| True| True| True| True| True| True| True| True| False| False| False| False| False| X| X| X| False| False| False| X| False| # noqa
# | tinyint| None| 1| 1| 1| 1| 1| X| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| 0| X| # noqa
# | smallint| None| 1| 1| 1| 1| 1| 1| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | int| None| 1| 1| 1| 1| 1| 1| 1| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa
# | bigint| None| 1| 1| 1| 1| 1| 1| 1| 1| X| 1| 1| 1| 0| 18000000000000| X| X| X| X| X| X| X| X| # noqa
# | float| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X|1.401298464324817...| X| X| X| X| X| X| # noqa
# | double| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X| X| X| X| X| X| X| X| # noqa
# | date| None| X| X| X|datetime.date(197...| X| X| X| X| X| X| X| X| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa
# | timestamp| None| X| X| X| X|datetime.datetime...| X| X| X| X| X| X| X| datetime.datetime...| datetime.datetime...| X| X| X| X| X| X| X| X| # noqa
# | string| None| u''|u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u''| u''| u''| X| X| u'a'| X| X| u''| u''| u''| X| X| # noqa
# | decimal(10,0)| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| Decimal('1')| X| X| X| X| X| X| # noqa
# | array<int>| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| [1, 2, 3]| X| X| X| X| X| # noqa
# | map<string,int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | struct<_1:int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# | binary| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa
# +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa
#
# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be
# used in `returnType`.
# Note: The values inside of the table are generated by `repr`.
# Note: Python 2 is used to generate this table since it is used to check the backward
# compatibility often in practice.
# Note: Pandas 0.19.2 and PyArrow 0.9.0 are used.
# Note: Timezone is Singapore timezone.
# Note: 'X' means it throws an exception during the conversion.
# Note: 'binary' type is only supported with PyArrow 0.10.0+ (SPARK-23555).
# decorator @pandas_udf(returnType, functionType)
is_decorator = f is None or isinstance(f, (str, DataType))
if is_decorator:
# If DataType has been passed as a positional argument
# for decorator use it as a returnType
return_type = f or returnType
if functionType is not None:
# @pandas_udf(dataType, functionType=functionType)
# @pandas_udf(returnType=dataType, functionType=functionType)
eval_type = functionType
elif returnType is not None and isinstance(returnType, int):
# @pandas_udf(dataType, functionType)
eval_type = returnType
else:
# @pandas_udf(dataType) or @pandas_udf(returnType=dataType)
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
else:
return_type = returnType
if functionType is not None:
eval_type = functionType
else:
eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF
if return_type is None:
raise ValueError("Invalid returnType: returnType can not be None")
if eval_type not in [PythonEvalType.SQL_SCALAR_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF,
PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]:
raise ValueError("Invalid functionType: "
"functionType must be one the values from PandasUDFType")
if is_decorator:
return functools.partial(_create_udf, returnType=return_type, evalType=eval_type)
else:
return _create_udf(f=f, returnType=return_type, evalType=eval_type) | [
"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.
:param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`.
Default: SCALAR.
.. note:: Experimental
The function type of the UDF can be one of the following:
1. SCALAR
A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`.
The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`.
If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`.
:class:`MapType`, nested :class:`StructType` are currently not supported as output types.
Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and
:meth:`pyspark.sql.DataFrame.select`.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> from pyspark.sql.types import IntegerType, StringType
>>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP
>>> @pandas_udf(StringType()) # doctest: +SKIP
... def to_upper(s):
... return s.str.upper()
...
>>> @pandas_udf("integer", PandasUDFType.SCALAR) # doctest: +SKIP
... def add_one(x):
... return x + 1
...
>>> df = spark.createDataFrame([(1, "John Doe", 21)],
... ("id", "name", "age")) # doctest: +SKIP
>>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")) \\
... .show() # doctest: +SKIP
+----------+--------------+------------+
|slen(name)|to_upper(name)|add_one(age)|
+----------+--------------+------------+
| 8| JOHN DOE| 22|
+----------+--------------+------------+
>>> @pandas_udf("first string, last string") # doctest: +SKIP
... def split_expand(n):
... return n.str.split(expand=True)
>>> df.select(split_expand("name")).show() # doctest: +SKIP
+------------------+
|split_expand(name)|
+------------------+
| [John, Doe]|
+------------------+
.. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input
column, but is the length of an internal batch used for each call to the function.
Therefore, this can be used, for example, to ensure the length of each returned
`pandas.Series`, and can not be used as the column length.
2. GROUPED_MAP
A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame`
The returnType should be a :class:`StructType` describing the schema of the returned
`pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match
the field names in the defined returnType schema if specified as strings, or match the
field data types by position if not strings, e.g. integer indices.
The length of the returned `pandas.DataFrame` can be arbitrary.
Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP
... def normalize(pdf):
... v = pdf.v
... return pdf.assign(v=(v - v.mean()) / v.std())
>>> df.groupby("id").apply(normalize).show() # doctest: +SKIP
+---+-------------------+
| id| v|
+---+-------------------+
| 1|-0.7071067811865475|
| 1| 0.7071067811865475|
| 2|-0.8320502943378437|
| 2|-0.2773500981126146|
| 2| 1.1094003924504583|
+---+-------------------+
Alternatively, the user can define a function that takes two arguments.
In this case, the grouping key(s) will be passed as the first argument and the data will
be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy
data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in
as a `pandas.DataFrame` containing all columns from the original Spark DataFrame.
This is useful when the user does not want to hardcode grouping key(s) in the function.
>>> import pandas as pd # doctest: +SKIP
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v")) # doctest: +SKIP
>>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP
... def mean_udf(key, pdf):
... # key is a tuple of one numpy.int64, which is the value
... # of 'id' for the current group
... return pd.DataFrame([key + (pdf.v.mean(),)])
>>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP
+---+---+
| id| v|
+---+---+
| 1|1.5|
| 2|6.0|
+---+---+
>>> @pandas_udf(
... "id long, `ceil(v / 2)` long, v double",
... PandasUDFType.GROUPED_MAP) # doctest: +SKIP
>>> def sum_udf(key, pdf):
... # key is a tuple of two numpy.int64s, which is the values
... # of 'id' and 'ceil(df.v / 2)' for the current group
... return pd.DataFrame([key + (pdf.v.sum(),)])
>>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP
+---+-----------+----+
| id|ceil(v / 2)| v|
+---+-----------+----+
| 2| 5|10.0|
| 1| 1| 3.0|
| 2| 3| 5.0|
| 2| 2| 3.0|
+---+-----------+----+
.. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is
recommended to explicitly index the columns by name to ensure the positions are correct,
or alternatively use an `OrderedDict`.
For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or
`pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`.
.. seealso:: :meth:`pyspark.sql.GroupedData.apply`
3. GROUPED_AGG
A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar
The `returnType` should be a primitive data type, e.g., :class:`DoubleType`.
The returned scalar can be either a python primitive type, e.g., `int` or `float`
or a numpy data type, e.g., `numpy.int64` or `numpy.float64`.
:class:`MapType` and :class:`StructType` are currently not supported as output types.
Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and
:class:`pyspark.sql.Window`
This example shows using grouped aggregated UDFs with groupby:
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v"))
>>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP
... def mean_udf(v):
... return v.mean()
>>> df.groupby("id").agg(mean_udf(df['v'])).show() # doctest: +SKIP
+---+-----------+
| id|mean_udf(v)|
+---+-----------+
| 1| 1.5|
| 2| 6.0|
+---+-----------+
This example shows using grouped aggregated UDFs as window functions.
>>> from pyspark.sql.functions import pandas_udf, PandasUDFType
>>> from pyspark.sql import Window
>>> df = spark.createDataFrame(
... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)],
... ("id", "v"))
>>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP
... def mean_udf(v):
... return v.mean()
>>> w = (Window.partitionBy('id')
... .orderBy('v')
... .rowsBetween(-1, 0))
>>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP
+---+----+------+
| id| v|mean_v|
+---+----+------+
| 1| 1.0| 1.0|
| 1| 2.0| 1.5|
| 2| 3.0| 3.0|
| 2| 5.0| 4.0|
| 2|10.0| 7.5|
+---+----+------+
.. note:: For performance reasons, the input series to window functions are not copied.
Therefore, mutating the input series is not allowed and will cause incorrect results.
For the same reason, users should also not rely on the index of the input series.
.. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window`
.. note:: The user-defined functions are considered deterministic by default. Due to
optimization, duplicate invocations may be eliminated or the function may even be invoked
more times than it is present in the query. If your function is not deterministic, call
`asNondeterministic` on the user defined function. E.g.:
>>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP
... def random(v):
... import numpy as np
... import pandas as pd
... return pd.Series(np.random.randn(len(v))
>>> random = random.asNondeterministic() # doctest: +SKIP
.. note:: The user-defined functions do not support conditional expressions or short circuiting
in boolean expressions and it ends up with being executed all internally. If the functions
can fail on special rows, the workaround is to incorporate the condition into the functions.
.. note:: The user-defined functions do not take keyword arguments on the calling side.
.. note:: The data type of returned `pandas.Series` from the user-defined functions should be
matched with defined returnType (see :meth:`types.to_arrow_type` and
:meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do
conversion on returned data. The conversion is not guaranteed to be correct and results
should be checked for accuracy by users. | [
"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 response
to arrive or error to occur.
Parameters
----------
snmpDispatcher : :py:class:`~pysnmp.hlapi.snmpDispatcher`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
nonRepeaters : int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions : int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP engine may choose lesser value than
requested.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to \*varBinds[errorIndex-1]
varBinds: tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `bulkCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Setting `maxRepetitions` value to 15..50 might significantly improve
system performance, as many MIB variables get packed into a single
response message at once.
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = bulkCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 25,
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [[(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]])
"""
def cbFun(*args, **kwargs):
response[:] = args + (kwargs.get('nextVarBinds', ()),)
options['cbFun'] = cbFun
lexicographicMode = options.pop('lexicographicMode', True)
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
nullVarBinds = [False] * len(initialVarBinds)
totalRows = totalCalls = 0
errorIndication, errorStatus, errorIndex, varBindTable = None, 0, 0, ()
response = []
stopFlag = False
while not stopFlag:
if not varBinds:
yield (errorIndication, errorStatus, errorIndex, varBinds)
return
if maxRows and totalRows < maxRows:
maxRepetitions = min(maxRepetitions, maxRows - totalRows)
cmdgen.bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions,
*[(x[0], Null('')) for x in varBinds], **options)
snmpDispatcher.transportDispatcher.runDispatcher()
errorIndication, errorStatus, errorIndex, varBindTable, varBinds = response
if errorIndication:
yield (errorIndication, errorStatus, errorIndex, ())
return
elif errorStatus:
if errorStatus == 2:
# Hide SNMPv1 noSuchName error which leaks in here
# from SNMPv1 Agent through internal pysnmp proxy.
errorStatus = errorStatus.clone(0)
errorIndex = errorIndex.clone(0)
yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or [])
return
else:
for rowIdx, varBindRow in enumerate(varBindTable):
stopFlag = True
if len(varBindRow) != len(initialVarBinds):
varBindTable = rowIdx and varBindTable[:rowIdx - 1] or []
break
for colIdx, varBind in enumerate(varBindRow):
name, val = varBind
if nullVarBinds[colIdx]:
varBindRow[colIdx] = name, endOfMibView
continue
stopFlag = False
if isinstance(val, Null):
nullVarBinds[colIdx] = True
elif not lexicographicMode and not initialVarBinds[colIdx][0].isPrefixOf(name):
varBindRow[colIdx] = name, endOfMibView
nullVarBinds[colIdx] = True
if stopFlag:
varBindTable = rowIdx and varBindTable[:rowIdx - 1] or []
break
totalRows += len(varBindTable)
totalCalls += 1
if maxRows and totalRows >= maxRows:
if totalRows > maxRows:
varBindTable = varBindTable[:-(totalRows - maxRows)]
stopFlag = True
if maxCalls and totalCalls >= maxCalls:
stopFlag = True
for varBindRow in varBindTable:
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds) | [
"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`
Class instance representing SNMP engine.
authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
nonRepeaters : int
One MIB variable is requested in response for the first
`nonRepeaters` MIB variables in request.
maxRepetitions : int
`maxRepetitions` MIB variables are requested in response for each
of the remaining MIB variables in the request (e.g. excluding
`nonRepeaters`). Remote SNMP engine may choose lesser value than
requested.
\*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType`
One or more class instances representing MIB variables to place
into SNMP request.
Other Parameters
----------------
\*\*options :
Request options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Default is `True`.
* `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`),
otherwise (if `False`) stop iteration when all response MIB
variables leave the scope of initial MIB variables in
`varBinds`. Default is `True`.
* `ignoreNonIncreasingOid` - continue iteration even if response
MIB variables (OIDs) are not greater then request MIB variables.
Be aware that setting it to `True` may cause infinite loop between
SNMP management and agent applications. Default is `False`.
* `maxRows` - stop iteration once this generator instance processed
`maxRows` of SNMP conceptual table. Default is `0` (no limit).
* `maxCalls` - stop iteration once this generator instance processed
`maxCalls` responses. Default is 0 (no limit).
Yields
------
errorIndication : str
True value indicates SNMP engine error.
errorStatus : str
True value indicates SNMP PDU error.
errorIndex : int
Non-zero value refers to \*varBinds[errorIndex-1]
varBinds: tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `bulkCmd` generator will be exhausted on any of the following
conditions:
* SNMP engine error occurs thus `errorIndication` is `True`
* SNMP PDU `errorStatus` is reported as `True`
* SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values
(also known as *SNMP exception values*) are reported for all
MIB variables in `varBinds`
* *lexicographicMode* option is `True` and SNMP agent reports
end-of-mib or *lexicographicMode* is `False` and all
response MIB variables leave the scope of `varBinds`
At any moment a new sequence of `varBinds` could be send back into
running generator (supported since Python 2.6).
Setting `maxRepetitions` value to 15..50 might significantly improve
system performance, as many MIB variables get packed into a single
response message at once.
Examples
--------
>>> from pysnmp.hlapi.v1arch import *
>>>
>>> g = bulkCmd(snmpDispatcher(),
>>> CommunityData('public'),
>>> UdpTransportTarget(('demo.snmplabs.com', 161)),
>>> 0, 25,
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]])
>>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))])
(None, 0, 0, [[(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]]) | [
"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
"""
if context.filters is not None:
for filter_ in context.filters:
if re.match(filter_, line):
return None
return line | [
"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 exporting repos in environment(s): %s", ", ".join(all_envs))
all_pulp_repo_names = self.list_repos(envs=all_envs)
all_pulp_repo_names_uniqued = set()
num_repos = 0
# Track name of all processed repos. Update when we've found
# all environments a PulpRepo lives in.
repos_processed = []
for env, repos in all_pulp_repo_names.iteritems():
juicer.utils.Log.log_debug("Uniqued environment: %s with %s repos", env, int(len(repos)))
all_pulp_repo_names_uniqued.update(set(repos))
num_repos += len(all_pulp_repo_names_uniqued)
widgets = [
"Exporting: ",
progressbar.Percentage(),
" ",
"(",
progressbar.SimpleProgress(),
") ",
progressbar.ETA()
]
progress_bar = JuiceBar(num_repos, widgets)
# Hacky way to get around not easily being able to pass
# multiple arguments to a function in a multiprocessing pool
lookup_objects = []
for repo in all_pulp_repo_names_uniqued:
lookup_args = juicer.admin.ThreaddedQuery.LookupObject()
setattr(lookup_args, 'progress_bar', progress_bar)
setattr(lookup_args, 'all_pulp_repo_names', all_pulp_repo_names)
setattr(lookup_args, 'all_envs', all_envs)
setattr(lookup_args, 'ja', self)
setattr(lookup_args, 'pulp_repo', repo)
setattr(lookup_args, 'repos_processed', repos_processed)
lookup_objects.append(lookup_args)
# TODO: Add the serial/concurrent logic here
try:
# Make our thread pool
p = ThreadPool()
# Get an AsyncResult object
r = p.map_async(juicer.admin.ThreaddedQuery.concurrent_pulp_lookup, lookup_objects)
# TODO: We should probably use p.apply_async here to avoid the crappy lookup_objects hack
while not r.ready():
r.wait(1)
except KeyboardInterrupt:
juicer.utils.Log.log_error("User pressed ^C during repo export")
juicer.utils.Log.log_error("Terminating %s worker threads and then exiting", len(p._pool))
# Prevents any more tasks from being submitted to the
# pool. Once all the tasks have been completed the worker
# threads will exit.
#p.close()
p.terminate()
p.join()
# XXX: End serial/concurrent logic
progress_bar.finish()
juicer_repos = [pr.to_juicer_repo() for pr in repos_processed]
return sorted(juicer_repos, key=lambda d: d['name'].lower()) | [
"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.issparse(self.data):
err = np.sqrt( np.sum((self.data[:,:] - np.dot(self.W, self.H))**2 ))
else:
err = -123456
return err | [
"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(encoding))
except (ValueError, # Not valid JSON
TypeError, # Not an object
UnicodeDecodeError): # Unable to decode the bytes
logger.exception("Unable to decode JSON")
logger.debug("response content (%s): %r", encoding, content)
return None
try:
return manifest['mediaType']
except KeyError:
# no mediaType key
if manifest.get('schemaVersion') == 1:
return get_manifest_media_type('v1')
logger.warning("no mediaType or schemaVersion=1 in manifest, keys: %s",
manifest.keys()) | [
"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 = fix_code(source_code, options)
try:
if options.docformatter:
from docformatter import format_code
fixed = format_code(
fixed,
summary_wrap_length=options.max_line_length - 1,
description_wrap_length=(options.max_line_length
- 2 * options.indent_size),
pre_summary_newline=options.pre_summary_newline,
post_description_blank=options.post_description_blank,
force_wrap=options.force_wrap,
line_range=[start, end])
except AttributeError: # e.g. using autopep8.parse_args, pragma: no cover
pass
return 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['password'])
# Override Accept request header so that failures are not redirected to the Futon web-ui
request_headers = headers(self.agentConfig)
request_headers['Accept'] = 'text/json'
try:
r = requests.get(
url, auth=auth, headers=request_headers, timeout=int(instance.get('timeout', self.TIMEOUT))
)
r.raise_for_status()
if run_check:
self.service_check(
self.SERVICE_CHECK_NAME,
AgentCheck.OK,
tags=service_check_tags,
message='Connection to %s was successful' % url,
)
except requests.exceptions.Timeout as e:
self.service_check(
self.SERVICE_CHECK_NAME,
AgentCheck.CRITICAL,
tags=service_check_tags,
message="Request timeout: {0}, {1}".format(url, e),
)
raise
except requests.exceptions.HTTPError as e:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
raise
except Exception as e:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
raise
return r.json() | [
"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)):
return content
elif isinstance(content, LazyString):
variables_mapping = utils.ensure_mapping_format(variables_mapping or {})
return content.to_value(variables_mapping)
elif isinstance(content, (list, set, tuple)):
return [
parse_lazy_data(item, variables_mapping)
for item in content
]
elif isinstance(content, dict):
parsed_content = {}
for key, value in content.items():
parsed_key = parse_lazy_data(key, variables_mapping)
parsed_value = parse_lazy_data(value, variables_mapping)
parsed_content[parsed_key] = parsed_value
return parsed_content
return content | [
"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.
@param pks - list of internal keys
'''
if type(pks) == set:
pks = list(pks)
if len(pks) == 1:
# Optimization to not pipeline on 1 id
return IRQueryableList([self.get(pks[0], cascadeFetch=cascadeFetch)], mdl=self.mdl)
conn = self._get_connection()
pipeline = conn.pipeline()
for pk in pks:
key = self._get_key_for_id(pk)
pipeline.hgetall(key)
res = pipeline.execute()
ret = IRQueryableList(mdl=self.mdl)
i = 0
pksLen = len(pks)
while i < pksLen:
if res[i] is None:
ret.append(None)
i += 1
continue
res[i]['_id'] = pks[i]
obj = self._redisResultToObj(res[i])
ret.append(obj)
i += 1
if cascadeFetch is True:
for obj in ret:
if not obj:
continue
self._doCascadeFetch(obj)
return ret | [
"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._sensitivity.extend(other._sensitivity)
else:
assert other._sensitivity is None
if self._enclosed_for is not None:
self._enclosed_for.update(other._enclosed_for)
else:
assert other._enclosed_for is None
other_was_top = other.parentStm is None
if other_was_top:
other._get_rtl_context().statements.remove(other)
for s in other._inputs:
s.endpoints.discard(other)
s.endpoints.append(self)
for s in other._outputs:
s.drivers.discard(other)
s.drivers.append(self) | [
"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
# identifier object, or null, for requests that target single resources
if not item:
return None
ret = self.dict_class()
ret[TYPE] = self.opts.type_
# Get the schema attributes so we can confirm `dump-to` values exist
attributes = {
(get_dump_key(self.fields[field]) or field): field
for field in self.fields
}
for field_name, value in iteritems(item):
attribute = attributes[field_name]
if attribute == ID:
ret[ID] = value
elif isinstance(self.fields[attribute], DocumentMeta):
if not self.document_meta:
self.document_meta = self.dict_class()
self.document_meta.update(value)
elif isinstance(self.fields[attribute], ResourceMeta):
if 'meta' not in ret:
ret['meta'] = self.dict_class()
ret['meta'].update(value)
elif isinstance(self.fields[attribute], BaseRelationship):
if value:
if 'relationships' not in ret:
ret['relationships'] = self.dict_class()
ret['relationships'][self.inflect(field_name)] = value
else:
if 'attributes' not in ret:
ret['attributes'] = self.dict_class()
ret['attributes'][self.inflect(field_name)] = value
links = self.get_resource_links(item)
if links:
ret['links'] = links
return ret | [
"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 objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object.
"""
smtp_options = {}
smtp_options.update(self.config.smtp_options)
if smtp:
smtp_options.update(smtp)
return super(Message, self).send(smtp=smtp_options, **kw) | [
"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 default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object. | [
"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,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %s: %s",
payload, result.text) | [
"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_generator, method_name, sklearn.metrics.r2_score, num_fcounts) | [
"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._dstore.put_file(key, file)
finally:
self.cache.delete(key) | [
"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 want to check all cores.
Return : dict<str,obj>::
{'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
CLI Example:
.. code-block:: bash
salt '*' solr.replication_details music
'''
ret = _get_return_dict()
if _get_none_or_value(core_name) is None:
success = True
for name in __opts__['solr.cores']:
resp = _replication_request('details', host=host, core_name=name)
data = {name: {'data': resp['data']}}
ret = _update_return_dict(ret, success, data,
resp['errors'], resp['warnings'])
else:
resp = _replication_request('details', host=host, core_name=core_name)
if resp['success']:
ret = _update_return_dict(ret, resp['success'], resp['data'],
resp['errors'], resp['warnings'])
else:
return resp
return ret | [
"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>::
{'success':boolean, 'data':dict, 'errors':list, 'warnings':list}
CLI Example:
.. code-block:: bash
salt '*' solr.replication_details music | [
"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.
Return string.
"""
if prompt_msg is not None:
self.write(prompt_msg, newline)
return self._input.readline().rstrip(os.linesep) | [
"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 (case insensitive): if starts with "Lorentz",
a Lorentzian curve will be fitted. If starts with "Gauss",
a Gaussian will be fitted. Otherwise error.
return_x: numpy array of the x values at which the best
fitting peak function should be evaluated and returned
init_parameters: either None, or a list of [amplitude, center,
hwhm_left, hwhm_right, baseline]: initial parameters to
start fitting from.
Results: center, hwhm_left, hwhm_right, baseline, amplitude [, y_fitted]
The fitted parameters are returned as floats if dy was None or
ErrorValue instances if dy was not None.
y_fitted is only returned if return_x was not None
Note:
1) The dataset must contain only the peak.
2) A positive peak will be fitted
3) The peak center must be in the given range
"""
idx = np.logical_and(np.isfinite(x), np.isfinite(y))
if dy is not None:
idx = np.logical_and(idx, np.isfinite(dy))
x=x[idx]
y=y[idx]
if dy is not None:
dy=dy[idx]
if curve.lower().startswith('loren'):
lorentzian = True
elif curve.lower().startswith('gauss'):
lorentzian = False
else:
raise ValueError('Unknown peak type {}'.format(curve))
def peakfunc(pars, x, lorentzian=True):
x0, sigma1, sigma2, C, A = pars
result = np.empty_like(x)
if lorentzian:
result[x < x0] = A * sigma1 ** 2 / (sigma1 ** 2 + (x0 - x[x < x0]) ** 2) + C
result[x >= x0] = A * sigma2 ** 2 / (sigma2 ** 2 + (x0 - x[x >= x0]) ** 2) + C
else:
result[x < x0] = A * np.exp(-(x[x < x0] - x0) ** 2 / (2 * sigma1 ** 2))
result[x >= x0] = A * np.exp(-(x[x >= x0] - x0) ** 2 / (2 * sigma1 ** 2))
return result
def fitfunc(pars, x, y, dy, lorentzian=True):
yfit = peakfunc(pars, x, lorentzian)
if dy is None:
return yfit - y
else:
return (yfit - y) / dy
if init_parameters is not None:
pos, hwhmleft, hwhmright, baseline, amplitude = [float(x) for x in init_parameters]
else:
baseline = y.min()
amplitude = y.max() - baseline
hwhmleft = hwhmright = (x.max() - x.min()) * 0.5
pos = x[np.argmax(y)]
#print([pos,hwhm,hwhm,baseline,amplitude])
result = scipy.optimize.least_squares(fitfunc, [pos, hwhmleft, hwhmright, baseline, amplitude],
args=(x, y, dy, lorentzian),
bounds=([x.min(), 0, 0, -np.inf, 0],
[x.max(), np.inf, np.inf, np.inf, np.inf]))
# print(result.x[0], result.x[1], result.x[2], result.x[3], result.x[4], result.message, result.success)
if not result.success:
raise RuntimeError('Error while peak fitting: {}'.format(result.message))
if dy is None:
ret = (result.x[0], result.x[1], result.x[2], result.x[3], result.x[4])
else:
# noinspection PyTupleAssignmentBalance
_, s, VT = svd(result.jac, full_matrices=False)
threshold = np.finfo(float).eps * max(result.jac.shape) * s[0]
s = s[s > threshold]
VT = VT[:s.size]
pcov = np.dot(VT.T / s ** 2, VT)
ret = tuple([ErrorValue(result.x[i], pcov[i, i] ** 0.5) for i in range(5)])
if return_x is not None:
ret = ret + (peakfunc([float(x) for x in ret], return_x, lorentzian),)
return ret | [
"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 with "Gauss",
a Gaussian will be fitted. Otherwise error.
return_x: numpy array of the x values at which the best
fitting peak function should be evaluated and returned
init_parameters: either None, or a list of [amplitude, center,
hwhm_left, hwhm_right, baseline]: initial parameters to
start fitting from.
Results: center, hwhm_left, hwhm_right, baseline, amplitude [, y_fitted]
The fitted parameters are returned as floats if dy was None or
ErrorValue instances if dy was not None.
y_fitted is only returned if return_x was not None
Note:
1) The dataset must contain only the peak.
2) A positive peak will be fitted
3) The peak center must be in the given range | [
"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.file_state.base_name is not None:
# load previous results if any
previous_stats = config.load_results(self.file_state.base_name)
# XXX code below needs refactoring to be more reporter agnostic
self.reporter.on_close(self.stats, previous_stats)
if self.config.reports:
sect = self.make_reports(self.stats, previous_stats)
else:
sect = report_nodes.Section()
if self.config.reports:
self.reporter.display_reports(sect)
self._report_evaluation()
# save results if persistent run
if self.config.persistent:
config.save_results(self.stats, self.file_state.base_name)
else:
self.reporter.on_close(self.stats, {}) | [
"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.write("{}\n{}\t{}\n".format(
" ".join("T" if x else "F" for x in attr_values),
self.nodes_number, self.root))
fout.write(" ".join(str(a) for a in self.alphabet) + "\n")
for index, label in enumerate(self.final):
letters = self._get_letters(index, return_indexes=True)
children = self._get_children(index)
fout.write("{}\t{}\n".format(
"T" if label else "F", " ".join("{}:{}".format(*elem)
for elem in zip(letters, children))))
if self.precompute_symbols is not None:
for elem in self.data:
fout.write(":".join(",".join(
map(str, symbols)) for symbols in elem) + "\n")
return | [
"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 - DataFrame
DataFrame to analyze
method - {'pearson', 'kendall', 'spearman'}
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
"""
# Remove all but categoricals,booleans, and numerics
df = df.reset_index(drop = True)
cat_cols = df.select_dtypes(include = 'category')
bool_cols = df.select_dtypes(include = 'bool')
df = df.select_dtypes(include = 'number')
if not cols(df) + cols(bool_cols) + cols(cat_cols):
return None # quit if there's none of the possible datatypes present
#Convert categoricals to boolean columns
insert = np.ones(rows(df))
for col_name in cat_cols:
cat_df = pd.concat([cat_cols[[col_name]],pd.Series(insert)],axis = 1) # Add a column of ones as values for the pivot
cat_ptable = cat_df.pivot(columns = col_name).reset_index(drop = True)
cat_ptable.columns = [col_name+ "_{}".format(value) for value in
cat_ptable.columns.get_level_values(col_name)]
df = pd.concat([df,cat_ptable.fillna(0)],axis = 1)
df = pd.concat([df,bool_cols * 1], axis = 1)
return df.corr(method,0) | [
"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
method - {'pearson', 'kendall', 'spearman'}
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation | [
"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 slope.
name (str): name of the output.
Variable Names:
* ``alpha``: learnable slope.
"""
init = tfv1.constant_initializer(init)
alpha = tfv1.get_variable('alpha', [], initializer=init)
x = ((1 + alpha) * x + (1 - alpha) * tf.abs(x))
ret = tf.multiply(x, 0.5, name=name)
ret.variables = VariableHolder(alpha=alpha)
return ret | [
"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.
Variable Names:
* ``alpha``: learnable slope. | [
"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.UNIMPLEMENTED``.
Example:
>>> from google.gapic.longrunning import operations_client
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)
Args:
name (string): The name of the operation resource to be deleted.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.
Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid.
"""
# Create the request object.
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, options) | [
"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.longrunning import operations_client
>>> api = operations_client.OperationsClient()
>>> name = ''
>>> api.delete_operation(name)
Args:
name (string): The name of the operation resource to be deleted.
options (:class:`google.gax.CallOptions`): Overrides the default
settings for this call, e.g, timeout, retries etc.
Raises:
:exc:`google.gax.errors.GaxError` if the RPC is aborted.
:exc:`ValueError` if the parameters are invalid. | [
"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, negated)
else:
value = unidata.unicode_alias['nfcquickcheck'].get(value, value)
return obj[value] | [
"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 sources (typically in range 1 - 50)
"""
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["sourceLocations"].append({"uri": sourceLocationUri, "wgt": weight}) | [
"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: float
time added to maximum time-of-flight between detectors to account
for timing error
Returns
-------
expected_coinc_rates: dict
Dictionary keyed on the ifo combination string
Value is expected coincidence rate in the combination, units Hz
"""
ifos = numpy.array(sorted(rates.keys()))
rates_raw = list(rates[ifo] for ifo in ifos)
expected_coinc_rates = {}
# Calculate coincidence for all-ifo combination
# multiply product of trigger rates by the overlap time
allowed_area = multiifo_noise_coincident_area(ifos, slop)
rateprod = [numpy.prod(rs) for rs in zip(*rates_raw)]
ifostring = ' '.join(ifos)
expected_coinc_rates[ifostring] = allowed_area * numpy.array(rateprod)
# if more than one possible coincidence type exists,
# calculate coincidence for subsets through recursion
if len(ifos) > 2:
# Calculate rate for each 'miss-one-out' detector combination
subsets = itertools.combinations(ifos, len(ifos) - 1)
for subset in subsets:
rates_subset = {}
for ifo in subset:
rates_subset[ifo] = rates[ifo]
sub_coinc_rates = multiifo_noise_coinc_rate(rates_subset, slop)
# add these sub-coincidences to the overall dictionary
for sub_coinc in sub_coinc_rates:
expected_coinc_rates[sub_coinc] = sub_coinc_rates[sub_coinc]
return expected_coinc_rates | [
"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 detectors to account
for timing error
Returns
-------
expected_coinc_rates: dict
Dictionary keyed on the ifo combination string
Value is expected coincidence rate in the combination, units Hz | [
"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.update(keep) | [
"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 is_kanji(data):
return consts.MODE_KANJI
return consts.MODE_BYTE | [
"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 = 'Symmetry finder error: %s' % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell)) | [
"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')
payload.update({'client_id': self.client_id, 'client_secret': self.client_secret})
if not isinstance(code, str) and self.shared_key in code:
code = code[self.shared_key]
payload['refresh_token' if payload['grant_type'] == 'refresh_token' else 'code'] = code
redirect_uri = redirect_uri or self.params.get('redirect_uri')
if redirect_uri:
payload['redirect_uri'] = redirect_uri
self.access_token = None
data = await self.request('POST', self.access_token_url, data=payload, loop=loop)
try:
self.access_token = data['access_token']
except KeyError:
self.logger.error(
'Error when getting the access token.\nData returned by OAuth server: %r',
data,
)
raise web.HTTPBadRequest(reason='Failed to obtain OAuth access token.')
return self.access_token, data | [
"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
can be in any order. If a numpy array, columns must be in the
same order as the training data.
times: iterable, optional
an iterable of increasing times to predict the cumulative hazard at. Default
is the set of all durations (observed and unobserved). Uses a linear interpolation if
points in time are not in the index.
ancillary_X: numpy array or DataFrame, optional
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 as the training data.
Returns
-------
cumulative_hazard_ : DataFrame
the cumulative hazard of individuals over the timeline
"""
import numpy as np
times = coalesce(times, self.timeline, np.unique(self.durations))
exp_mu_, sigma_ = self._prep_inputs_for_prediction_and_return_scores(X, ancillary_X)
mu_ = np.log(exp_mu_)
Z = np.subtract.outer(np.log(times), mu_) / sigma_
return pd.DataFrame(-logsf(Z), columns=_get_index(X), index=times) | [
"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 as the training data.
times: iterable, optional
an iterable of increasing times to predict the cumulative hazard at. Default
is the set of all durations (observed and unobserved). Uses a linear interpolation if
points in time are not in the index.
ancillary_X: numpy array or DataFrame, optional
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 as the training data.
Returns
-------
cumulative_hazard_ : DataFrame
the cumulative hazard of individuals over the timeline | [
"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 asynchronous context manager that applies a timeout to a
block of statements.
timeout_after() may be composed with other timeout_after()
operations (i.e., nested timeouts). If an outer timeout expires
first, then TimeoutCancellationError is raised instead of
TaskTimeout. If an inner timeout expires and fails to properly
TaskTimeout, a UncaughtTimeoutError is raised in the outer
timeout.
'''
if coro:
return _timeout_after_func(clock, True, coro, args)
return TimeoutAfter(clock, absolute=True) | [
"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 timeout to a
block of statements.
timeout_after() may be composed with other timeout_after()
operations (i.e., nested timeouts). If an outer timeout expires
first, then TimeoutCancellationError is raised instead of
TaskTimeout. If an inner timeout expires and fails to properly
TaskTimeout, a UncaughtTimeoutError is raised in the outer
timeout. | [
"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.sighi + self.siglo))
lo = (u >= float(self.sighi)/(self.sighi + self.siglo))
vals = np.zeros(N)
vals[hi] = hivals[hi]
vals[lo] = lovals[lo]
return vals | [
"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 = float(x2)-x
h = float(y2)-y
else:
x = 0
x2 = w
y = 0
y2 = h
if self.width and self.height:
ry = self.height / h
rx = self.width / w
if rx < ry:
ratio = ry
adjust = self._adjust_coordinates(ratio, w, self.width)
x = x + adjust
x2 = x2 - adjust
else:
ratio = rx
adjust = self._adjust_coordinates(ratio, h, self.height)
y = y + adjust
y2 = y2 - adjust
width = self.width
height = self.height
elif self.width:
ratio = self.width / w
width = self.width
height = int(h * ratio)
else:
ratio = self.height / h
width = int(w * ratio)
height = self.height
if ratio > 1 and not upscale:
return
x, x2, y, y2 = int(x), int(x2), int(y), int(y2)
return CropSpec(name=self.name,
editable=self.editable,
width=width, height=height,
x=x, x2=x2, y=y, y2=y2) | [
"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
>>> # SCRIPT
>>> from utool.util_win32 import * # NOQA
>>> script_fpath = join(ut.truepath('~'), 'Sync/win7/registry', 'UPDATE_PATH.reg')
>>> new_path = ut.get_argval('--newpath', str, default=None)
>>> result = add_to_win32_PATH(script_fpath, new_path)
>>> print(result)
"""
import utool as ut
write_dir = dirname(script_fpath)
key = '[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]'
rtype = 'REG_EXPAND_SZ'
# Read current PATH values
win_pathlist = list(os.environ['PATH'].split(os.path.pathsep))
new_path_list = ut.unique_ordered(win_pathlist + list(add_path_list))
#new_path_list = unique_ordered(win_pathlist, rob_pathlist)
print('\n'.join(new_path_list))
pathtxt = pathsep.join(new_path_list)
varval_list = [('Path', pathtxt)]
regfile_str = make_regfile_str(key, varval_list, rtype)
ut.view_directory(write_dir)
print(regfile_str)
ut.writeto(script_fpath, regfile_str, mode='wb')
print('Please have an admin run the script. You may need to restart') | [
"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 import * # NOQA
>>> script_fpath = join(ut.truepath('~'), 'Sync/win7/registry', 'UPDATE_PATH.reg')
>>> new_path = ut.get_argval('--newpath', str, default=None)
>>> result = add_to_win32_PATH(script_fpath, new_path)
>>> print(result) | [
"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. Requires good inter-station
coherance.
:type stream: obspy.core.stream.Stream
:param stream: Stream to pick
:type env: bool
:param env: To compute cross-correlations on the envelope or not.
:type debug: int
:param debug: Debug level from 0-5
:type master: obspy.core.trace.Trace
:param master:
Trace to use as master, if False, will use the first trace in stream.
:returns: :class:`obspy.core.event.event.Event`
.. rubric:: Example
>>> from obspy import read
>>> from eqcorrscan.utils.picker import cross_net
>>> st = read()
>>> event = cross_net(st, env=True)
>>> print(event.creation_info.author)
EQcorrscan
.. warning::
This routine is not designed for accurate picking, rather it can be
used for a first-pass at picks to obtain simple locations. Based on
the waveform-envelope cross-correlation method.
"""
event = Event()
event.origins.append(Origin())
event.creation_info = CreationInfo(author='EQcorrscan',
creation_time=UTCDateTime())
event.comments.append(Comment(text='cross_net'))
samp_rate = stream[0].stats.sampling_rate
if not env:
if debug > 2:
print('Using the raw data')
st = stream.copy()
st.resample(samp_rate)
else:
st = stream.copy()
if debug > 2:
print('Computing envelope')
for tr in st:
tr.resample(samp_rate)
tr.data = envelope(tr.data)
if not master:
master = st[0]
else:
master = master
master.data = np.nan_to_num(master.data)
for i, tr in enumerate(st):
tr.data = np.nan_to_num(tr.data)
if debug > 2:
msg = ' '.join(['Comparing', tr.stats.station, tr.stats.channel,
'with the master'])
print(msg)
shift_len = int(0.3 * len(tr))
if debug > 2:
print('Shift length is set to ' + str(shift_len) + ' samples')
index, cc = xcorr(master, tr, shift_len)
wav_id = WaveformStreamID(station_code=tr.stats.station,
channel_code=tr.stats.channel,
network_code=tr.stats.network)
event.picks.append(Pick(time=tr.stats.starttime +
(index / tr.stats.sampling_rate),
waveform_id=wav_id,
phase_hint='S',
onset='emergent'))
if debug > 2:
print(event.picks[i])
event.origins[0].time = min([pick.time for pick in event.picks]) - 1
# event.origins[0].latitude = float('nan')
# event.origins[0].longitude = float('nan')
# Set arbitrary origin time
del st
return event | [
"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.core.stream.Stream
:param stream: Stream to pick
:type env: bool
:param env: To compute cross-correlations on the envelope or not.
:type debug: int
:param debug: Debug level from 0-5
:type master: obspy.core.trace.Trace
:param master:
Trace to use as master, if False, will use the first trace in stream.
:returns: :class:`obspy.core.event.event.Event`
.. rubric:: Example
>>> from obspy import read
>>> from eqcorrscan.utils.picker import cross_net
>>> st = read()
>>> event = cross_net(st, env=True)
>>> print(event.creation_info.author)
EQcorrscan
.. warning::
This routine is not designed for accurate picking, rather it can be
used for a first-pass at picks to obtain simple locations. Based on
the waveform-envelope cross-correlation method. | [
"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_EMAIL_VERIFIED_FIELD_NAME, True)
elif token.to_alias_type == 'MOBILE':
if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME):
setattr(user, api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME, True)
else:
return False
user.save()
return True | [
"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 for l in inp if l in string.digits]))
index = parse_ordinal(slots['Ordinal'])
else:
return False
index = index - 1 # Going from regular notation to CS notation
user_state = twitter_cache.get_user_state(request.access_token())
queue = user_state['user_queue'].queue()
if index < len(queue):
# Analyze tweet in queue
tweet_to_analyze = queue[index]
user_state['focus_tweet'] = tweet_to_analyze
return index + 1 # Returning to regular notation
twitter_cache.serialize()
return False | [
"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.
True is apply, False is return.
"""
new_col = _pd.to_numeric(df[col_name], errors = 'coerce')
if dest:
set_col(df,col_name,new_col)
else:
return new_col | [
"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 row. Each string
in this list may be multiline by inserting EOL in the string
rows (iterable of iterables)
The outer iterable is the rows. The inner iterables are the colums
for each row
args (int or list of int that defines sort)
Defines the cols that will be sorted. If int, it defines the column
that will be sorted. If list of int, the sort is in sort order of
cols in the list (i.e. minor sorts to the left, major sorts to the
right)
"""
if sort_columns is not None:
if isinstance(sort_columns, int):
rows = sorted(rows, key=itemgetter(sort_columns))
elif isinstance(sort_columns, (list, tuple)):
rows = sorted(rows, key=itemgetter(*sort_columns))
else:
assert False, "Sort_columns must be int or list/tuple of int"
if title:
print('\n%s:' % title)
else:
print('')
print(tabulate.tabulate(rows, headers, tablefmt='simple'))
print('') | [
"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 EOL in the string
rows (iterable of iterables)
The outer iterable is the rows. The inner iterables are the colums
for each row
args (int or list of int that defines sort)
Defines the cols that will be sorted. If int, it defines the column
that will be sorted. If list of int, the sort is in sort order of
cols in the list (i.e. minor sorts to the left, major sorts to the
right) | [
"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_token,
client_id=token.consumer_key,
client_secret=token.consumer_secret,
grant_type='refresh_token'
)
resp = session.post(REFRESH_TOKEN_URL, data=refresh_data)
resp_json = resp.json()
if 'error' in resp_json:
message = resp_json['error']
description = resp_json.get('error_description', '')
if any(description):
message = u'{}: {}'.format(message, description)
raise OAuthTokenExpiredError(message)
return OAuthToken(
access_token=resp_json['access_token'],
refresh_token=token.refresh_token,
consumer_key=token.consumer_key,
consumer_secret=token.consumer_secret
) | [
"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(len(nodes)), nodes):
r, g, b = rainbowcolour(i, len(nodes))
colour = '#%02X%02X%02X' % (r, g, b)
for ne in n.efferent:
if ne not in self.added:
hopNodes.add(ne)
hopEdges.append((ne, n, 'solid', colour))
# add nodes and edges to the graph if maximum number of nodes is not
# exceeded
self.add_to_graph(hopNodes, hopEdges, nesting) | [
"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[s] /= mag
if self.signed:
mag = self.mag() / mag
else:
mag = self.max() / mag
self.chunkwise(f, null=self.null, mag=mag)
self._null = 0 | [
"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. Valid values include 'mstp', 'none'
default (bool): Set the global spanning-tree mode to default.
disable (bool): Negate the global spanning-tree mode.
Returns:
True if the configuration operation succeeds otherwise False
Raises:
ValueError if the value is not in the accepted range
"""
if not default and not disable:
if value not in ['mstp', 'none']:
raise ValueError("Specified value must be one of "
"'mstp', 'none'")
cmds = self.command_builder('spanning-tree mode', value=value,
default=default, disable=disable)
return self.configure(cmds) | [
"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 global spanning-tree mode to default.
disable (bool): Negate the global spanning-tree mode.
Returns:
True if the configuration operation succeeds otherwise False
Raises:
ValueError if the value is not in the accepted range | [
"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
:type global_substitutions: dict
:param is_multiple: Create a new personilization for each recipient
:type is_multiple: bool
:param p: p is the Personalization object or Personalization object
index
:type p: Personalization, integer, optional
"""
if isinstance(to_emails, list):
for email in to_emails:
if isinstance(email, str):
email = To(email, None)
if isinstance(email, tuple):
email = To(email[0], email[1])
self.add_to(email, global_substitutions, is_multiple, p)
else:
if isinstance(to_emails, str):
to_emails = To(to_emails, None)
if isinstance(to_emails, tuple):
to_emails = To(to_emails[0], to_emails[1])
self.add_to(to_emails, global_substitutions, is_multiple, p) | [
"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 personilization for each recipient
:type is_multiple: bool
:param p: p is the Personalization object or Personalization object
index
:type p: Personalization, integer, optional | [
"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)
y_max = np.max(y)
# this creates the grid
bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
xd = np.digitize(x, bins)
bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
yd = np.digitize(y, bins)
# the number of tiles is the number of cells divided by the number of cells in each tile
num_tiles = int(params["n_layer"]/params["n_tile"])
print("num tiles", num_tiles)
# we will save the tiles in an array indexed by the tile coordinates
tiles = {}
for ti in range(num_tiles):
for tj in range(num_tiles):
tiles[(ti,tj)] = {
"x": [],
"y": [],
"ci": [], # cell-space x coordinate
"cj": [], # cell-space y coordinate
"gi": [], # global index
}
for i,xi in enumerate(x):
if(i % 1000 == 0 or i+1 == len(x)):
print("point", i+1, "/", len(x), end="\r")
# layout-space coordinates
yi = y[i]
# grid-space cell coordinates
ci = xd[i]
cj = yd[i]
# tile coordinate
ti = math.floor(ci / params["n_tile"])
tj = math.floor(cj / params["n_tile"])
# TODO: don't append a point if it doesn't match a filter function provided in params
filter = params.get("filter", lambda i,metadata: True)
if(filter(i, metadata=metadata)):
tiles[(ti,tj)]["x"].append(xi)
tiles[(ti,tj)]["y"].append(yi)
tiles[(ti,tj)]["ci"].append(ci)
tiles[(ti,tj)]["cj"].append(cj)
tiles[(ti,tj)]["gi"].append(i)
return tiles | [
"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 == ("ろく", 6):
ltext = "ろっ"
rtext = "ぴゃく"
elif lpair == ("はち", 8):
ltext = "はっ"
rtext = "ぴゃく"
elif rpair == ("せん", 1000):
if lpair == ("さん", 3):
rtext = "ぜん"
elif lpair == ("はち", 8):
ltext = "はっ"
elif rpair == ("ちょう", 10**12):
if lpair == ("いち", 1):
ltext = "いっ"
elif lpair == ("はち", 8):
ltext = "はっ"
elif lpair == ("じゅう", 10):
ltext = "じゅっ"
elif rpair == ("けい", 10**16):
if lpair == ("いち", 1):
ltext = "いっ"
elif lpair == ("ろく", 6):
ltext = "ろっ"
elif lpair == ("はち", 8):
ltext = "はっ"
elif lpair == ("じゅう", 10):
ltext = "じゅっ"
elif lpair == ("ひゃく", 100):
ltext = "ひゃっ"
return ("%s%s" % (ltext, rtext), lnum * rnum) | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.