nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
glorotxa/SME | a1aa9fdb790fd356a17cd13d2b7b75feba2d8c82 | model.py | python | SimFnIdx | (fnsim, embeddings, leftop, rightop) | return theano.function([idxl, idxr, idxo], [simi],
on_unused_input='ignore') | This function returns a Theano function to measure the similarity score
for a given triplet of entity indexes.
:param fnsim: similarity function (on Theano variables).
:param embeddings: an Embeddings instance.
:param leftop: class for the 'left' operator.
:param rightop: class for the 'right' operator. | This function returns a Theano function to measure the similarity score
for a given triplet of entity indexes. | [
"This",
"function",
"returns",
"a",
"Theano",
"function",
"to",
"measure",
"the",
"similarity",
"score",
"for",
"a",
"given",
"triplet",
"of",
"entity",
"indexes",
"."
] | def SimFnIdx(fnsim, embeddings, leftop, rightop):
"""
This function returns a Theano function to measure the similarity score
for a given triplet of entity indexes.
:param fnsim: similarity function (on Theano variables).
:param embeddings: an Embeddings instance.
:param leftop: class for the 'left' operator.
:param rightop: class for the 'right' operator.
"""
embedding, relationl, relationr = parse_embeddings(embeddings)
# Inputs
idxo = T.iscalar('idxo')
idxr = T.iscalar('idxr')
idxl = T.iscalar('idxl')
# Graph
lhs = (embedding.E[:, idxl]).reshape((1, embedding.D))
rhs = (embedding.E[:, idxr]).reshape((1, embedding.D))
rell = (relationl.E[:, idxo]).reshape((1, relationl.D))
relr = (relationr.E[:, idxo]).reshape((1, relationr.D))
simi = fnsim(leftop(lhs, rell), rightop(rhs, relr))
"""
Theano function inputs.
:input idxl: index value of the 'left' member.
:input idxr: index value of the 'right' member.
:input idxo: index value of the relation member.
Theano function output.
:output simi: score value.
"""
return theano.function([idxl, idxr, idxo], [simi],
on_unused_input='ignore') | [
"def",
"SimFnIdx",
"(",
"fnsim",
",",
"embeddings",
",",
"leftop",
",",
"rightop",
")",
":",
"embedding",
",",
"relationl",
",",
"relationr",
"=",
"parse_embeddings",
"(",
"embeddings",
")",
"# Inputs",
"idxo",
"=",
"T",
".",
"iscalar",
"(",
"'idxo'",
")",... | https://github.com/glorotxa/SME/blob/a1aa9fdb790fd356a17cd13d2b7b75feba2d8c82/model.py#L544-L576 | |
google/grr | 8ad8a4d2c5a93c92729206b7771af19d92d4f915 | grr/server/grr_response_server/gui/api_plugins/flow.py | python | ApiListFlowDescriptorsHandler.Handle | (self, args, context=None) | return ApiListFlowDescriptorsResult(items=result) | Renders list of descriptors for all the flows. | Renders list of descriptors for all the flows. | [
"Renders",
"list",
"of",
"descriptors",
"for",
"all",
"the",
"flows",
"."
] | def Handle(self, args, context=None):
"""Renders list of descriptors for all the flows."""
result = []
for name, cls in sorted(registry.FlowRegistry.FLOW_REGISTRY.items()):
# Flows without a category do not show up in the GUI.
if not getattr(cls, "category", None):
continue
# Only show flows that the user is allowed to start.
try:
if self.access_check_fn:
self.access_check_fn(context.username, name)
except access_control.UnauthorizedAccess:
continue
result.append(ApiFlowDescriptor().InitFromFlowClass(cls, context=context))
return ApiListFlowDescriptorsResult(items=result) | [
"def",
"Handle",
"(",
"self",
",",
"args",
",",
"context",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"for",
"name",
",",
"cls",
"in",
"sorted",
"(",
"registry",
".",
"FlowRegistry",
".",
"FLOW_REGISTRY",
".",
"items",
"(",
")",
")",
":",
"# F... | https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_plugins/flow.py#L1257-L1276 | |
pulp/pulp | a0a28d804f997b6f81c391378aff2e4c90183df9 | repoauth/pulp/repoauth/repo_cert_utils.py | python | RepoCertUtils.validate_certificate_pem | (self, cert_pem, ca_pem, log_func=None) | return self.x509_verify_cert(cert, ca_chain, log_func=log_func) | Validates a certificate against a CA certificate.
Input expects PEM encoded strings.
@param cert_pem: PEM encoded certificate
@type cert_pem: str
@param ca_pem: PEM encoded CA certificates, allows chain of CA certificates if
concatenated together
@type ca_pem: str
@param log_func: a function to log debug messages
@param log_func: a function accepting a single string
@return: true if the certificate was signed by the given CA; false otherwise
@rtype: boolean | Validates a certificate against a CA certificate.
Input expects PEM encoded strings. | [
"Validates",
"a",
"certificate",
"against",
"a",
"CA",
"certificate",
".",
"Input",
"expects",
"PEM",
"encoded",
"strings",
"."
] | def validate_certificate_pem(self, cert_pem, ca_pem, log_func=None):
'''
Validates a certificate against a CA certificate.
Input expects PEM encoded strings.
@param cert_pem: PEM encoded certificate
@type cert_pem: str
@param ca_pem: PEM encoded CA certificates, allows chain of CA certificates if
concatenated together
@type ca_pem: str
@param log_func: a function to log debug messages
@param log_func: a function accepting a single string
@return: true if the certificate was signed by the given CA; false otherwise
@rtype: boolean
'''
if not log_func:
log_func = LOG.info
cert = X509.load_cert_string(cert_pem)
ca_chain = self.get_certs_from_string(ca_pem, log_func)
return self.x509_verify_cert(cert, ca_chain, log_func=log_func) | [
"def",
"validate_certificate_pem",
"(",
"self",
",",
"cert_pem",
",",
"ca_pem",
",",
"log_func",
"=",
"None",
")",
":",
"if",
"not",
"log_func",
":",
"log_func",
"=",
"LOG",
".",
"info",
"cert",
"=",
"X509",
".",
"load_cert_string",
"(",
"cert_pem",
")",
... | https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/repoauth/pulp/repoauth/repo_cert_utils.py#L268-L290 | |
Calysto/calysto_scheme | 15bf81987870bcae1264e5a0a06feb9a8ee12b8b | calysto_scheme/scheme.py | python | exception_object_q | (x) | return (list_q(x)) and (numeric_equal(length(x), 7)) and (((x).car) is (symbol_exception_object)) and (valid_exception_type_q((x).cdr.car)) and (string_q((x).cdr.car)) | [] | def exception_object_q(x):
return (list_q(x)) and (numeric_equal(length(x), 7)) and (((x).car) is (symbol_exception_object)) and (valid_exception_type_q((x).cdr.car)) and (string_q((x).cdr.car)) | [
"def",
"exception_object_q",
"(",
"x",
")",
":",
"return",
"(",
"list_q",
"(",
"x",
")",
")",
"and",
"(",
"numeric_equal",
"(",
"length",
"(",
"x",
")",
",",
"7",
")",
")",
"and",
"(",
"(",
"(",
"x",
")",
".",
"car",
")",
"is",
"(",
"symbol_exc... | https://github.com/Calysto/calysto_scheme/blob/15bf81987870bcae1264e5a0a06feb9a8ee12b8b/calysto_scheme/scheme.py#L8244-L8245 | |||
lohriialo/photoshop-scripting-python | 6b97da967a5d0a45e54f7c99631b29773b923f09 | api_reference/photoshop_2020.py | python | CountItem.__iter__ | (self) | return win32com.client.util.Iterator(ob, None) | Return a Python iterator for this object | Return a Python iterator for this object | [
"Return",
"a",
"Python",
"iterator",
"for",
"this",
"object"
] | def __iter__(self):
"Return a Python iterator for this object"
try:
ob = self._oleobj_.InvokeTypes(-4,LCID,3,(13, 10),())
except pythoncom.error:
raise TypeError("This object does not support enumeration")
return win32com.client.util.Iterator(ob, None) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"try",
":",
"ob",
"=",
"self",
".",
"_oleobj_",
".",
"InvokeTypes",
"(",
"-",
"4",
",",
"LCID",
",",
"3",
",",
"(",
"13",
",",
"10",
")",
",",
"(",
")",
")",
"except",
"pythoncom",
".",
"error",
":",
... | https://github.com/lohriialo/photoshop-scripting-python/blob/6b97da967a5d0a45e54f7c99631b29773b923f09/api_reference/photoshop_2020.py#L1492-L1498 | |
svpcom/wifibroadcast | 51251b8c484b8c4f548aa3bbb1633e0edbb605dc | telemetry/mavlink.py | python | MAVLink.osd_param_config_reply_send | (self, request_id, result, force_mavlink1=False) | return self.send(self.osd_param_config_reply_encode(request_id, result), force_mavlink1=force_mavlink1) | Configure OSD parameter reply.
request_id : Request ID - copied from request. (type:uint32_t)
result : Config error type. (type:uint8_t, values:OSD_PARAM_CONFIG_ERROR) | Configure OSD parameter reply. | [
"Configure",
"OSD",
"parameter",
"reply",
"."
] | def osd_param_config_reply_send(self, request_id, result, force_mavlink1=False):
'''
Configure OSD parameter reply.
request_id : Request ID - copied from request. (type:uint32_t)
result : Config error type. (type:uint8_t, values:OSD_PARAM_CONFIG_ERROR)
'''
return self.send(self.osd_param_config_reply_encode(request_id, result), force_mavlink1=force_mavlink1) | [
"def",
"osd_param_config_reply_send",
"(",
"self",
",",
"request_id",
",",
"result",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"osd_param_config_reply_encode",
"(",
"request_id",
",",
"result",
")",
",",
"f... | https://github.com/svpcom/wifibroadcast/blob/51251b8c484b8c4f548aa3bbb1633e0edbb605dc/telemetry/mavlink.py#L21969-L21977 | |
w3h/isf | 6faf0a3df185465ec17369c90ccc16e2a03a1870 | lib/thirdparty/scapy/contrib/igmp.py | python | isValidMCAddr | (ip) | return (FirstOct >= 224) and (FirstOct <= 239) | convert dotted quad string to long and check the first octet | convert dotted quad string to long and check the first octet | [
"convert",
"dotted",
"quad",
"string",
"to",
"long",
"and",
"check",
"the",
"first",
"octet"
] | def isValidMCAddr(ip):
"""convert dotted quad string to long and check the first octet"""
FirstOct=atol(ip)>>24 & 0xFF
return (FirstOct >= 224) and (FirstOct <= 239) | [
"def",
"isValidMCAddr",
"(",
"ip",
")",
":",
"FirstOct",
"=",
"atol",
"(",
"ip",
")",
">>",
"24",
"&",
"0xFF",
"return",
"(",
"FirstOct",
">=",
"224",
")",
"and",
"(",
"FirstOct",
"<=",
"239",
")"
] | https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/scapy/contrib/igmp.py#L13-L16 | |
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/twisted/python/_shellcomp.py | python | ZshArgumentsGenerator.writeHeader | (self) | This is the start of the code that calls _arguments
@return: C{None} | This is the start of the code that calls _arguments | [
"This",
"is",
"the",
"start",
"of",
"the",
"code",
"that",
"calls",
"_arguments"
] | def writeHeader(self):
"""
This is the start of the code that calls _arguments
@return: C{None}
"""
self.file.write('#compdef %s\n\n'
'_arguments -s -A "-*" \\\n' % (self.cmdName,)) | [
"def",
"writeHeader",
"(",
"self",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"'#compdef %s\\n\\n'",
"'_arguments -s -A \"-*\" \\\\\\n'",
"%",
"(",
"self",
".",
"cmdName",
",",
")",
")"
] | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/python/_shellcomp.py#L349-L355 | ||
CLUEbenchmark/CLUE | 5bd39732734afecb490cf18a5212e692dbf2c007 | baselines/models/xlnet/model_utils.py | python | avg_checkpoints | (model_dir, output_model_dir, last_k) | [] | def avg_checkpoints(model_dir, output_model_dir, last_k):
tf.reset_default_graph()
checkpoint_state = tf.train.get_checkpoint_state(model_dir)
checkpoints = checkpoint_state.all_model_checkpoint_paths[- last_k:]
var_list = tf.contrib.framework.list_variables(checkpoints[0])
var_values, var_dtypes = {}, {}
for (name, shape) in var_list:
if not name.startswith("global_step"):
var_values[name] = np.zeros(shape)
for checkpoint in checkpoints:
reader = tf.contrib.framework.load_checkpoint(checkpoint)
for name in var_values:
tensor = reader.get_tensor(name)
var_dtypes[name] = tensor.dtype
var_values[name] += tensor
tf.logging.info("Read from checkpoint %s", checkpoint)
for name in var_values: # Average.
var_values[name] /= len(checkpoints)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
tf_vars = [
tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[v])
for v in var_values
]
placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]
assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]
global_step = tf.Variable(
0, name="global_step", trainable=False, dtype=tf.int64)
saver = tf.train.Saver(tf.all_variables())
# Build a model consisting only of variables, set them to the average values.
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for p, assign_op, (name, value) in zip(placeholders, assign_ops,
six.iteritems(var_values)):
sess.run(assign_op, {p: value})
# Use the built saver to save the averaged checkpoint.
saver.save(sess, join(output_model_dir, "model.ckpt"),
global_step=global_step) | [
"def",
"avg_checkpoints",
"(",
"model_dir",
",",
"output_model_dir",
",",
"last_k",
")",
":",
"tf",
".",
"reset_default_graph",
"(",
")",
"checkpoint_state",
"=",
"tf",
".",
"train",
".",
"get_checkpoint_state",
"(",
"model_dir",
")",
"checkpoints",
"=",
"checkp... | https://github.com/CLUEbenchmark/CLUE/blob/5bd39732734afecb490cf18a5212e692dbf2c007/baselines/models/xlnet/model_utils.py#L224-L263 | ||||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/customizer_attribute_service/client.py | python | CustomizerAttributeServiceClient.transport | (self) | return self._transport | Return the transport used by the client instance.
Returns:
CustomizerAttributeServiceTransport: The transport used by the client instance. | Return the transport used by the client instance. | [
"Return",
"the",
"transport",
"used",
"by",
"the",
"client",
"instance",
"."
] | def transport(self) -> CustomizerAttributeServiceTransport:
"""Return the transport used by the client instance.
Returns:
CustomizerAttributeServiceTransport: The transport used by the client instance.
"""
return self._transport | [
"def",
"transport",
"(",
"self",
")",
"->",
"CustomizerAttributeServiceTransport",
":",
"return",
"self",
".",
"_transport"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/customizer_attribute_service/client.py#L158-L164 | |
myles/django-contacts | 4648bce0b0d1455981b2b059f3bf679e376d2737 | contacts/views/company.py | python | detail | (request, pk, slug=None, template='contacts/company/detail.html') | return render_to_response(template, kwvars, RequestContext(request)) | Detail of a company.
:param template: Add a custom template. | Detail of a company. | [
"Detail",
"of",
"a",
"company",
"."
] | def detail(request, pk, slug=None, template='contacts/company/detail.html'):
"""Detail of a company.
:param template: Add a custom template.
"""
try:
company = Company.objects.get(pk__iexact=pk)
except Company.DoesNotExist:
raise Http404
kwvars = {
'object': company,
}
return render_to_response(template, kwvars, RequestContext(request)) | [
"def",
"detail",
"(",
"request",
",",
"pk",
",",
"slug",
"=",
"None",
",",
"template",
"=",
"'contacts/company/detail.html'",
")",
":",
"try",
":",
"company",
"=",
"Company",
".",
"objects",
".",
"get",
"(",
"pk__iexact",
"=",
"pk",
")",
"except",
"Compa... | https://github.com/myles/django-contacts/blob/4648bce0b0d1455981b2b059f3bf679e376d2737/contacts/views/company.py#L51-L66 | |
upsert/lutron-caseta-pro | f5955c991c88c003752fee4df2d65ca028285d75 | custom_components/lutron_caseta_pro/__init__.py | python | Caseta.__getattr__ | (self, name) | return getattr(self.instance, name) | Return getter on the instance. | Return getter on the instance. | [
"Return",
"getter",
"on",
"the",
"instance",
"."
] | def __getattr__(self, name):
"""Return getter on the instance."""
return getattr(self.instance, name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"instance",
",",
"name",
")"
] | https://github.com/upsert/lutron-caseta-pro/blob/f5955c991c88c003752fee4df2d65ca028285d75/custom_components/lutron_caseta_pro/__init__.py#L388-L390 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/interfaces/maxima_lib.py | python | MaximaLib.lisp | (self, cmd) | return ecl_eval(cmd) | Send a lisp command to maxima.
INPUT:
- ``cmd`` - string
OUTPUT: ECL object
.. note::
The output of this command is very raw - not pretty.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.lisp("(+ 2 17)")
<ECL: 19> | Send a lisp command to maxima. | [
"Send",
"a",
"lisp",
"command",
"to",
"maxima",
"."
] | def lisp(self, cmd):
"""
Send a lisp command to maxima.
INPUT:
- ``cmd`` - string
OUTPUT: ECL object
.. note::
The output of this command is very raw - not pretty.
EXAMPLES::
sage: from sage.interfaces.maxima_lib import maxima_lib
sage: maxima_lib.lisp("(+ 2 17)")
<ECL: 19>
"""
return ecl_eval(cmd) | [
"def",
"lisp",
"(",
"self",
",",
"cmd",
")",
":",
"return",
"ecl_eval",
"(",
"cmd",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/interfaces/maxima_lib.py#L472-L492 | |
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/analysis/energy_models.py | python | SymmetryModel.__init__ | (self, symprec=0.1, angle_tolerance=5) | Args:
symprec (float): Symmetry tolerance. Defaults to 0.1.
angle_tolerance (float): Tolerance for angles. Defaults to 5 degrees. | Args:
symprec (float): Symmetry tolerance. Defaults to 0.1.
angle_tolerance (float): Tolerance for angles. Defaults to 5 degrees. | [
"Args",
":",
"symprec",
"(",
"float",
")",
":",
"Symmetry",
"tolerance",
".",
"Defaults",
"to",
"0",
".",
"1",
".",
"angle_tolerance",
"(",
"float",
")",
":",
"Tolerance",
"for",
"angles",
".",
"Defaults",
"to",
"5",
"degrees",
"."
] | def __init__(self, symprec=0.1, angle_tolerance=5):
"""
Args:
symprec (float): Symmetry tolerance. Defaults to 0.1.
angle_tolerance (float): Tolerance for angles. Defaults to 5 degrees.
"""
self.symprec = symprec
self.angle_tolerance = angle_tolerance | [
"def",
"__init__",
"(",
"self",
",",
"symprec",
"=",
"0.1",
",",
"angle_tolerance",
"=",
"5",
")",
":",
"self",
".",
"symprec",
"=",
"symprec",
"self",
".",
"angle_tolerance",
"=",
"angle_tolerance"
] | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/energy_models.py#L110-L117 | ||
richardaecn/class-balanced-loss | 1d7857208a2abc03d84e35a9d5383af8225d4b4d | tpu/models/experimental/resnet50_keras/resnet50.py | python | learning_rate_schedule | (current_epoch, current_batch) | return learning_rate | Handles linear scaling rule, gradual warmup, and LR decay.
The learning rate starts at 0, then it increases linearly per step.
After 5 epochs we reach the base learning rate (scaled to account
for batch size).
After 30, 60 and 80 epochs the learning rate is divided by 10.
After 90 epochs training stops and the LR is set to 0. This ensures
that we train for exactly 90 epochs for reproducibility.
Args:
current_epoch: integer, current epoch indexed from 0.
current_batch: integer, current batch in the current epoch, indexed from 0.
Returns:
Adjusted learning rate. | Handles linear scaling rule, gradual warmup, and LR decay. | [
"Handles",
"linear",
"scaling",
"rule",
"gradual",
"warmup",
"and",
"LR",
"decay",
"."
] | def learning_rate_schedule(current_epoch, current_batch):
"""Handles linear scaling rule, gradual warmup, and LR decay.
The learning rate starts at 0, then it increases linearly per step.
After 5 epochs we reach the base learning rate (scaled to account
for batch size).
After 30, 60 and 80 epochs the learning rate is divided by 10.
After 90 epochs training stops and the LR is set to 0. This ensures
that we train for exactly 90 epochs for reproducibility.
Args:
current_epoch: integer, current epoch indexed from 0.
current_batch: integer, current batch in the current epoch, indexed from 0.
Returns:
Adjusted learning rate.
"""
epoch = current_epoch + float(current_batch) / TRAINING_STEPS_PER_EPOCH
warmup_lr_multiplier, warmup_end_epoch = LR_SCHEDULE[0]
if epoch < warmup_end_epoch:
# Learning rate increases linearly per step.
return BASE_LEARNING_RATE * warmup_lr_multiplier * epoch / warmup_end_epoch
for mult, start_epoch in LR_SCHEDULE:
if epoch >= start_epoch:
learning_rate = BASE_LEARNING_RATE * mult
else:
break
return learning_rate | [
"def",
"learning_rate_schedule",
"(",
"current_epoch",
",",
"current_batch",
")",
":",
"epoch",
"=",
"current_epoch",
"+",
"float",
"(",
"current_batch",
")",
"/",
"TRAINING_STEPS_PER_EPOCH",
"warmup_lr_multiplier",
",",
"warmup_end_epoch",
"=",
"LR_SCHEDULE",
"[",
"0... | https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/experimental/resnet50_keras/resnet50.py#L88-L115 | |
entropy1337/infernal-twin | 10995cd03312e39a48ade0f114ebb0ae3a711bb8 | Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/ipaddress.py | python | IPv4Address.is_unspecified | (self) | return self == self._constants._unspecified_address | Test if the address is unspecified.
Returns:
A boolean, True if this is the unspecified address as defined in
RFC 5735 3. | Test if the address is unspecified. | [
"Test",
"if",
"the",
"address",
"is",
"unspecified",
"."
] | def is_unspecified(self):
"""Test if the address is unspecified.
Returns:
A boolean, True if this is the unspecified address as defined in
RFC 5735 3.
"""
return self == self._constants._unspecified_address | [
"def",
"is_unspecified",
"(",
"self",
")",
":",
"return",
"self",
"==",
"self",
".",
"_constants",
".",
"_unspecified_address"
] | https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/build/lib.linux-i686-2.7/pip/_vendor/ipaddress.py#L1444-L1452 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/printing/pretty/pretty_symbology.py | python | line_width | (line) | return len(line.translate(_remove_combining)) | Unicode combining symbols (modifiers) are not ever displayed as
separate symbols and thus shouldn't be counted | Unicode combining symbols (modifiers) are not ever displayed as
separate symbols and thus shouldn't be counted | [
"Unicode",
"combining",
"symbols",
"(",
"modifiers",
")",
"are",
"not",
"ever",
"displayed",
"as",
"separate",
"symbols",
"and",
"thus",
"shouldn",
"t",
"be",
"counted"
] | def line_width(line):
"""Unicode combining symbols (modifiers) are not ever displayed as
separate symbols and thus shouldn't be counted
"""
return len(line.translate(_remove_combining)) | [
"def",
"line_width",
"(",
"line",
")",
":",
"return",
"len",
"(",
"line",
".",
"translate",
"(",
"_remove_combining",
")",
")"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/printing/pretty/pretty_symbology.py#L635-L639 | |
robclewley/pydstool | 939e3abc9dd1f180d35152bacbde57e24c85ff26 | PyDSTool/Toolbox/dssrt.py | python | plot_psis | (da, cols=None, do_vars=None, do_log=True, use_prefix=True) | da is a dssrt_assistant object.
cols is an optional dictionary mapping names of Psi entries to specific color/style character codes.
Pass do_vars list of Psi names to restrict, otherwise all will be plotted.
Option to plot on vertical log scale.
Option to switch off 'psi_' + da's focus_var as prefix for coordnames.
Requires matplotlib. | da is a dssrt_assistant object.
cols is an optional dictionary mapping names of Psi entries to specific color/style character codes.
Pass do_vars list of Psi names to restrict, otherwise all will be plotted.
Option to plot on vertical log scale. | [
"da",
"is",
"a",
"dssrt_assistant",
"object",
".",
"cols",
"is",
"an",
"optional",
"dictionary",
"mapping",
"names",
"of",
"Psi",
"entries",
"to",
"specific",
"color",
"/",
"style",
"character",
"codes",
".",
"Pass",
"do_vars",
"list",
"of",
"Psi",
"names",
... | def plot_psis(da, cols=None, do_vars=None, do_log=True, use_prefix=True):
"""da is a dssrt_assistant object.
cols is an optional dictionary mapping names of Psi entries to specific color/style character codes.
Pass do_vars list of Psi names to restrict, otherwise all will be plotted.
Option to plot on vertical log scale.
Option to switch off 'psi_' + da's focus_var as prefix for coordnames.
Requires matplotlib.
"""
from PyDSTool.matplotlib_import import plot
pts=da.psi_pts
if use_prefix:
root = 'psi_'+da.focus_var+'_'
else:
root = ''
ts = pts['t']
if do_vars is None:
do_vars = [c[len(root):] for c in pts.coordnames if root in c]
if cols is None:
colvals = ['g', 'r', 'k', 'b', 'c', 'y', 'm']
styles = ['-', ':', '--']
cols = []
for s in styles:
for c in colvals:
cols.append(c+s)
if len(do_vars) > len(cols):
raise ValueError("Max number of permitted variables for these colors/styles is %i"%len(cols))
print("Color scheme:")
if do_log:
for i, v in enumerate(do_vars):
if root+v in pts.coordnames:
print(" %s %s" % (v, cols[i]))
plot(ts, np.log(pts[root+v]), cols[i])
else:
for i, v in enumerate(do_vars):
if root+v in pts.coordnames:
print(" %s %s" % (v, cols[i]))
plot(ts, pts[root+v], cols[i]) | [
"def",
"plot_psis",
"(",
"da",
",",
"cols",
"=",
"None",
",",
"do_vars",
"=",
"None",
",",
"do_log",
"=",
"True",
",",
"use_prefix",
"=",
"True",
")",
":",
"from",
"PyDSTool",
".",
"matplotlib_import",
"import",
"plot",
"pts",
"=",
"da",
".",
"psi_pts"... | https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/Toolbox/dssrt.py#L1893-L1931 | ||
cupy/cupy | a47ad3105f0fe817a4957de87d98ddccb8c7491f | cupyx/scipy/sparse/construct.py | python | eye | (m, n=None, k=0, dtype='d', format=None) | return spdiags(diags, k, m, n).asformat(format) | Creates a sparse matrix with ones on diagonal.
Args:
m (int): Number of rows.
n (int or None): Number of columns. If it is ``None``,
it makes a square matrix.
k (int): Diagonal to place ones on.
dtype: Type of a matrix to create.
format (str or None): Format of the result, e.g. ``format="csr"``.
Returns:
cupyx.scipy.sparse.spmatrix: Created sparse matrix.
.. seealso:: :func:`scipy.sparse.eye` | Creates a sparse matrix with ones on diagonal. | [
"Creates",
"a",
"sparse",
"matrix",
"with",
"ones",
"on",
"diagonal",
"."
] | def eye(m, n=None, k=0, dtype='d', format=None):
"""Creates a sparse matrix with ones on diagonal.
Args:
m (int): Number of rows.
n (int or None): Number of columns. If it is ``None``,
it makes a square matrix.
k (int): Diagonal to place ones on.
dtype: Type of a matrix to create.
format (str or None): Format of the result, e.g. ``format="csr"``.
Returns:
cupyx.scipy.sparse.spmatrix: Created sparse matrix.
.. seealso:: :func:`scipy.sparse.eye`
"""
if n is None:
n = m
m, n = int(m), int(n)
if m == n and k == 0:
if format in ['csr', 'csc']:
indptr = cupy.arange(n + 1, dtype='i')
indices = cupy.arange(n, dtype='i')
data = cupy.ones(n, dtype=dtype)
if format == 'csr':
cls = csr.csr_matrix
else:
cls = csc.csc_matrix
return cls((data, indices, indptr), (n, n))
elif format == 'coo':
row = cupy.arange(n, dtype='i')
col = cupy.arange(n, dtype='i')
data = cupy.ones(n, dtype=dtype)
return coo.coo_matrix((data, (row, col)), (n, n))
diags = cupy.ones((1, max(0, min(m + k, n))), dtype=dtype)
return spdiags(diags, k, m, n).asformat(format) | [
"def",
"eye",
"(",
"m",
",",
"n",
"=",
"None",
",",
"k",
"=",
"0",
",",
"dtype",
"=",
"'d'",
",",
"format",
"=",
"None",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"m",
"m",
",",
"n",
"=",
"int",
"(",
"m",
")",
",",
"int",
"(",
... | https://github.com/cupy/cupy/blob/a47ad3105f0fe817a4957de87d98ddccb8c7491f/cupyx/scipy/sparse/construct.py#L10-L49 | |
un1t/django-cleanup | 2b02f61c151296571e104670c017db98f3d621f9 | django_cleanup/handlers.py | python | connect | () | Connect signals to the cleanup models | Connect signals to the cleanup models | [
"Connect",
"signals",
"to",
"the",
"cleanup",
"models"
] | def connect():
'''Connect signals to the cleanup models'''
for model in cache.cleanup_models():
key = '{{}}_django_cleanup_{}'.format(cache.get_model_name(model))
post_init.connect(cache_original_post_init, sender=model,
dispatch_uid=key.format('post_init'))
pre_save.connect(fallback_pre_save, sender=model,
dispatch_uid=key.format('pre_save'))
post_save.connect(delete_old_post_save, sender=model,
dispatch_uid=key.format('post_save'))
post_delete.connect(delete_all_post_delete, sender=model,
dispatch_uid=key.format('post_delete')) | [
"def",
"connect",
"(",
")",
":",
"for",
"model",
"in",
"cache",
".",
"cleanup_models",
"(",
")",
":",
"key",
"=",
"'{{}}_django_cleanup_{}'",
".",
"format",
"(",
"cache",
".",
"get_model_name",
"(",
"model",
")",
")",
"post_init",
".",
"connect",
"(",
"c... | https://github.com/un1t/django-cleanup/blob/2b02f61c151296571e104670c017db98f3d621f9/django_cleanup/handlers.py#L108-L119 | ||
googledatalab/pydatalab | 1c86e26a0d24e3bc8097895ddeab4d0607be4c40 | datalab/bigquery/_api.py | python | Api.datasets_delete | (self, dataset_name, delete_contents) | return datalab.utils.Http.request(url, method='DELETE', args=args,
credentials=self._credentials, raw_response=True) | Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be raised.
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation. | Issues a request to delete a dataset. | [
"Issues",
"a",
"request",
"to",
"delete",
"a",
"dataset",
"."
] | def datasets_delete(self, dataset_name, delete_contents):
"""Issues a request to delete a dataset.
Args:
dataset_name: the name of the dataset to delete.
delete_contents: if True, any tables in the dataset will be deleted. If False and the
dataset is non-empty an exception will be raised.
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation.
"""
url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name)
args = {}
if delete_contents:
args['deleteContents'] = True
return datalab.utils.Http.request(url, method='DELETE', args=args,
credentials=self._credentials, raw_response=True) | [
"def",
"datasets_delete",
"(",
"self",
",",
"dataset_name",
",",
"delete_contents",
")",
":",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_DATASETS_PATH",
"%",
"dataset_name",
")",
"args",
"=",
"{",
"}",
"if",
"delete_contents",
":",
"args"... | https://github.com/googledatalab/pydatalab/blob/1c86e26a0d24e3bc8097895ddeab4d0607be4c40/datalab/bigquery/_api.py#L281-L298 | |
neulab/xnmt | d93f8f3710f986f36eb54e9ff3976a6b683da2a4 | xnmt/losses.py | python | BaseFactoredLossExpr.get_factored_loss_val | (self, comb_method: str = "sum") | Create factored loss values by calling ``.value()`` for each DyNet loss expression and applying batch combination.
Args:
comb_method: method for combining loss across batch elements ('sum' or 'avg').
Returns:
Factored loss values. | Create factored loss values by calling ``.value()`` for each DyNet loss expression and applying batch combination. | [
"Create",
"factored",
"loss",
"values",
"by",
"calling",
".",
"value",
"()",
"for",
"each",
"DyNet",
"loss",
"expression",
"and",
"applying",
"batch",
"combination",
"."
] | def get_factored_loss_val(self, comb_method: str = "sum") -> 'FactoredLossVal':
"""
Create factored loss values by calling ``.value()`` for each DyNet loss expression and applying batch combination.
Args:
comb_method: method for combining loss across batch elements ('sum' or 'avg').
Returns:
Factored loss values.
"""
raise NotImplementedError() | [
"def",
"get_factored_loss_val",
"(",
"self",
",",
"comb_method",
":",
"str",
"=",
"\"sum\"",
")",
"->",
"'FactoredLossVal'",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/neulab/xnmt/blob/d93f8f3710f986f36eb54e9ff3976a6b683da2a4/xnmt/losses.py#L72-L82 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/rings/asymptotic/misc.py | python | split_str_by_op | (string, op, strip_parentheses=True) | return tuple(strip(f) for f in factors) | r"""
Split the given string into a tuple of substrings arising by
splitting by ``op`` and taking care of parentheses.
INPUT:
- ``string`` -- a string.
- ``op`` -- a string. This is used by
:python:`str.split <library/stdtypes.html#str.split>`.
Thus, if this is ``None``, then any whitespace string is a
separator and empty strings are removed from the result.
- ``strip_parentheses`` -- (default: ``True``) a boolean.
OUTPUT:
A tuple of strings.
TESTS::
sage: from sage.rings.asymptotic.misc import split_str_by_op
sage: split_str_by_op('x^ZZ', '*')
('x^ZZ',)
sage: split_str_by_op('log(x)^ZZ * y^QQ', '*')
('log(x)^ZZ', 'y^QQ')
sage: split_str_by_op('log(x)**ZZ * y**QQ', '*')
('log(x)**ZZ', 'y**QQ')
sage: split_str_by_op('a^b * * c^d', '*')
Traceback (most recent call last):
...
ValueError: 'a^b * * c^d' is invalid since a '*' follows a '*'.
sage: split_str_by_op('a^b * (c*d^e)', '*')
('a^b', 'c*d^e')
::
sage: split_str_by_op('(a^b)^c', '^')
('a^b', 'c')
sage: split_str_by_op('a^(b^c)', '^')
('a', 'b^c')
::
sage: split_str_by_op('(a) + (b)', op='+', strip_parentheses=True)
('a', 'b')
sage: split_str_by_op('(a) + (b)', op='+', strip_parentheses=False)
('(a)', '(b)')
sage: split_str_by_op(' ( t ) ', op='+', strip_parentheses=False)
('( t )',)
::
sage: split_str_by_op(' ( t ) ', op=None)
('t',)
sage: split_str_by_op(' ( t )s', op=None)
('(t)s',)
sage: split_str_by_op(' ( t ) s', op=None)
('t', 's')
::
sage: split_str_by_op('(e^(n*log(n)))^SR.subring(no_variables=True)', '*')
('(e^(n*log(n)))^SR.subring(no_variables=True)',) | r"""
Split the given string into a tuple of substrings arising by
splitting by ``op`` and taking care of parentheses. | [
"r",
"Split",
"the",
"given",
"string",
"into",
"a",
"tuple",
"of",
"substrings",
"arising",
"by",
"splitting",
"by",
"op",
"and",
"taking",
"care",
"of",
"parentheses",
"."
] | def split_str_by_op(string, op, strip_parentheses=True):
r"""
Split the given string into a tuple of substrings arising by
splitting by ``op`` and taking care of parentheses.
INPUT:
- ``string`` -- a string.
- ``op`` -- a string. This is used by
:python:`str.split <library/stdtypes.html#str.split>`.
Thus, if this is ``None``, then any whitespace string is a
separator and empty strings are removed from the result.
- ``strip_parentheses`` -- (default: ``True``) a boolean.
OUTPUT:
A tuple of strings.
TESTS::
sage: from sage.rings.asymptotic.misc import split_str_by_op
sage: split_str_by_op('x^ZZ', '*')
('x^ZZ',)
sage: split_str_by_op('log(x)^ZZ * y^QQ', '*')
('log(x)^ZZ', 'y^QQ')
sage: split_str_by_op('log(x)**ZZ * y**QQ', '*')
('log(x)**ZZ', 'y**QQ')
sage: split_str_by_op('a^b * * c^d', '*')
Traceback (most recent call last):
...
ValueError: 'a^b * * c^d' is invalid since a '*' follows a '*'.
sage: split_str_by_op('a^b * (c*d^e)', '*')
('a^b', 'c*d^e')
::
sage: split_str_by_op('(a^b)^c', '^')
('a^b', 'c')
sage: split_str_by_op('a^(b^c)', '^')
('a', 'b^c')
::
sage: split_str_by_op('(a) + (b)', op='+', strip_parentheses=True)
('a', 'b')
sage: split_str_by_op('(a) + (b)', op='+', strip_parentheses=False)
('(a)', '(b)')
sage: split_str_by_op(' ( t ) ', op='+', strip_parentheses=False)
('( t )',)
::
sage: split_str_by_op(' ( t ) ', op=None)
('t',)
sage: split_str_by_op(' ( t )s', op=None)
('(t)s',)
sage: split_str_by_op(' ( t ) s', op=None)
('t', 's')
::
sage: split_str_by_op('(e^(n*log(n)))^SR.subring(no_variables=True)', '*')
('(e^(n*log(n)))^SR.subring(no_variables=True)',)
"""
def is_balanced(s):
open = 0
for l in s:
if l == '(':
open += 1
elif l == ')':
open -= 1
if open < 0:
return False
return bool(open == 0)
factors = list()
balanced = True
if string and op is not None and string.startswith(op):
raise ValueError("'%s' is invalid since it starts with a '%s'." %
(string, op))
for s in string.split(op):
if not s:
factors[-1] += op
balanced = False
continue
if not s.strip():
raise ValueError("'%s' is invalid since a '%s' follows a '%s'." %
(string, op, op))
if not balanced:
s = factors.pop() + (op if op else '') + s
balanced = is_balanced(s)
factors.append(s)
if not balanced:
raise ValueError("Parentheses in '%s' are not balanced." % (string,))
def strip(s):
s = s.strip()
if not s:
return s
if strip_parentheses and s[0] == '(' and s[-1] == ')':
t = s[1:-1]
if is_balanced(t):
s = t
return s.strip()
return tuple(strip(f) for f in factors) | [
"def",
"split_str_by_op",
"(",
"string",
",",
"op",
",",
"strip_parentheses",
"=",
"True",
")",
":",
"def",
"is_balanced",
"(",
"s",
")",
":",
"open",
"=",
"0",
"for",
"l",
"in",
"s",
":",
"if",
"l",
"==",
"'('",
":",
"open",
"+=",
"1",
"elif",
"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/asymptotic/misc.py#L189-L297 | |
PyTorchLightning/pytorch-lightning | 5914fb748fb53d826ab337fc2484feab9883a104 | pytorch_lightning/core/hooks.py | python | ModelHooks.on_train_end | (self) | Called at the end of training before logger experiment is closed. | Called at the end of training before logger experiment is closed. | [
"Called",
"at",
"the",
"end",
"of",
"training",
"before",
"logger",
"experiment",
"is",
"closed",
"."
] | def on_train_end(self) -> None:
"""Called at the end of training before logger experiment is closed.""" | [
"def",
"on_train_end",
"(",
"self",
")",
"->",
"None",
":"
] | https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/core/hooks.py#L43-L44 | ||
cmdmnt/commandment | 17c1dbe3f5301eab0f950f82608c231c15a3ff43 | commandment/vpp/vpp.py | python | VPP.edit_user | (self, client_user_id: str = None, facilitator_member_id: str = None,
email: str = None, managed_apple_id: str = None,
user_id: str = None) | return res.json() | Edit a user's VPP record.
Args:
client_user_id (str): A unique string, usually a UUID to identify the user in the MDM. You can use this OR
the user_id to identify the user.
facilitator_member_id: Currently unused
email (str): Supply an E-mail address to update the current address.
user_id (int): User ID which uniquely identifies the user with the iTunes store.
managed_apple_id (str): Managed Apple ID
Returns:
dict: Containing the reply from the service. | Edit a user's VPP record.
Args:
client_user_id (str): A unique string, usually a UUID to identify the user in the MDM. You can use this OR
the user_id to identify the user.
facilitator_member_id: Currently unused
email (str): Supply an E-mail address to update the current address.
user_id (int): User ID which uniquely identifies the user with the iTunes store.
managed_apple_id (str): Managed Apple ID | [
"Edit",
"a",
"user",
"s",
"VPP",
"record",
".",
"Args",
":",
"client_user_id",
"(",
"str",
")",
":",
"A",
"unique",
"string",
"usually",
"a",
"UUID",
"to",
"identify",
"the",
"user",
"in",
"the",
"MDM",
".",
"You",
"can",
"use",
"this",
"OR",
"the",
... | def edit_user(self, client_user_id: str = None, facilitator_member_id: str = None,
email: str = None, managed_apple_id: str = None,
user_id: str = None):
"""
Edit a user's VPP record.
Args:
client_user_id (str): A unique string, usually a UUID to identify the user in the MDM. You can use this OR
the user_id to identify the user.
facilitator_member_id: Currently unused
email (str): Supply an E-mail address to update the current address.
user_id (int): User ID which uniquely identifies the user with the iTunes store.
managed_apple_id (str): Managed Apple ID
Returns:
dict: Containing the reply from the service.
"""
request_body = {'sToken': self._stoken}
if user_id is not None:
request_body['userId'] = user_id
else:
request_body['clientUserIdStr'] = client_user_id
if email is not None:
request_body['email'] = email
if managed_apple_id is not None:
request_body['managedAppleIDStr'] = managed_apple_id
res = self._session.post(self._service_config['editUserSrvUrl'], data=json.dumps(request_body))
return res.json() | [
"def",
"edit_user",
"(",
"self",
",",
"client_user_id",
":",
"str",
"=",
"None",
",",
"facilitator_member_id",
":",
"str",
"=",
"None",
",",
"email",
":",
"str",
"=",
"None",
",",
"managed_apple_id",
":",
"str",
"=",
"None",
",",
"user_id",
":",
"str",
... | https://github.com/cmdmnt/commandment/blob/17c1dbe3f5301eab0f950f82608c231c15a3ff43/commandment/vpp/vpp.py#L388-L418 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/pexpect/pxssh.py | python | pxssh.logout | (self) | Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice. | Sends exit to the remote shell. | [
"Sends",
"exit",
"to",
"the",
"remote",
"shell",
"."
] | def logout (self):
'''Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice.
'''
self.sendline("exit")
index = self.expect([EOF, "(?i)there are stopped jobs"])
if index==1:
self.sendline("exit")
self.expect(EOF)
self.close() | [
"def",
"logout",
"(",
"self",
")",
":",
"self",
".",
"sendline",
"(",
"\"exit\"",
")",
"index",
"=",
"self",
".",
"expect",
"(",
"[",
"EOF",
",",
"\"(?i)there are stopped jobs\"",
"]",
")",
"if",
"index",
"==",
"1",
":",
"self",
".",
"sendline",
"(",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pexpect/pxssh.py#L437-L447 | ||
PyTorchLightning/pytorch-lightning | 5914fb748fb53d826ab337fc2484feab9883a104 | pytorch_lightning/strategies/strategy.py | python | Strategy.setup | (self, trainer: "pl.Trainer") | Setup plugins for the trainer fit and creates optimizers.
Args:
trainer: the trainer instance | Setup plugins for the trainer fit and creates optimizers. | [
"Setup",
"plugins",
"for",
"the",
"trainer",
"fit",
"and",
"creates",
"optimizers",
"."
] | def setup(self, trainer: "pl.Trainer") -> None:
"""Setup plugins for the trainer fit and creates optimizers.
Args:
trainer: the trainer instance
"""
self.accelerator.setup(trainer)
self.setup_optimizers(trainer)
self.setup_precision_plugin()
self._move_optimizer_state() | [
"def",
"setup",
"(",
"self",
",",
"trainer",
":",
"\"pl.Trainer\"",
")",
"->",
"None",
":",
"self",
".",
"accelerator",
".",
"setup",
"(",
"trainer",
")",
"self",
".",
"setup_optimizers",
"(",
"trainer",
")",
"self",
".",
"setup_precision_plugin",
"(",
")"... | https://github.com/PyTorchLightning/pytorch-lightning/blob/5914fb748fb53d826ab337fc2484feab9883a104/pytorch_lightning/strategies/strategy.py#L111-L120 | ||
yuxiaokui/Intranet-Penetration | f57678a204840c83cbf3308e3470ae56c5ff514b | proxy/XX-Net/code/default/python27/1.0/lib/logging/__init__.py | python | Logger.callHandlers | (self, record) | Pass a record to all relevant handlers.
Loop through all handlers for this logger and its parents in the
logger hierarchy. If no handler was found, output a one-off error
message to sys.stderr. Stop searching up the hierarchy whenever a
logger with the "propagate" attribute set to zero is found - that
will be the last logger whose handlers are called. | Pass a record to all relevant handlers. | [
"Pass",
"a",
"record",
"to",
"all",
"relevant",
"handlers",
"."
] | def callHandlers(self, record):
"""
Pass a record to all relevant handlers.
Loop through all handlers for this logger and its parents in the
logger hierarchy. If no handler was found, output a one-off error
message to sys.stderr. Stop searching up the hierarchy whenever a
logger with the "propagate" attribute set to zero is found - that
will be the last logger whose handlers are called.
"""
c = self
found = 0
while c:
for hdlr in c.handlers:
found = found + 1
if record.levelno >= hdlr.level:
hdlr.handle(record)
if not c.propagate:
c = None #break out
else:
c = c.parent
if (found == 0) and raiseExceptions and not self.manager.emittedNoHandlerWarning:
sys.stderr.write("No handlers could be found for logger"
" \"%s\"\n" % self.name)
self.manager.emittedNoHandlerWarning = 1 | [
"def",
"callHandlers",
"(",
"self",
",",
"record",
")",
":",
"c",
"=",
"self",
"found",
"=",
"0",
"while",
"c",
":",
"for",
"hdlr",
"in",
"c",
".",
"handlers",
":",
"found",
"=",
"found",
"+",
"1",
"if",
"record",
".",
"levelno",
">=",
"hdlr",
".... | https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/logging/__init__.py#L1312-L1336 | ||
baidu/Youtube-8M | 5ad9f3957ebedc2d1d572dea48c1fbcb55365249 | fast_forward_gru/data_provider.py | python | Dequantize | (feat_vector, max_quantized_value=2, min_quantized_value=-2) | return feat_vector * scalar + bias | Dequantize the feature from the byte format to the float format | Dequantize the feature from the byte format to the float format | [
"Dequantize",
"the",
"feature",
"from",
"the",
"byte",
"format",
"to",
"the",
"float",
"format"
] | def Dequantize(feat_vector, max_quantized_value=2, min_quantized_value=-2):
"""
Dequantize the feature from the byte format to the float format
"""
assert max_quantized_value > min_quantized_value
quantized_range = max_quantized_value - min_quantized_value
scalar = quantized_range / 255.0
bias = (quantized_range / 512.0) + min_quantized_value
return feat_vector * scalar + bias | [
"def",
"Dequantize",
"(",
"feat_vector",
",",
"max_quantized_value",
"=",
"2",
",",
"min_quantized_value",
"=",
"-",
"2",
")",
":",
"assert",
"max_quantized_value",
">",
"min_quantized_value",
"quantized_range",
"=",
"max_quantized_value",
"-",
"min_quantized_value",
... | https://github.com/baidu/Youtube-8M/blob/5ad9f3957ebedc2d1d572dea48c1fbcb55365249/fast_forward_gru/data_provider.py#L30-L40 | |
lightbulb-framework/lightbulb-framework | 9e8d6f37f28c784963dba3d726a0c8022a605baf | lightbulb/core/utils/SimpleWebServer.py | python | SimpleWebServer.__init__ | (self, host, port, handler, delay, wsport) | Args:
host (str): The IP address for the websockets
port (int): The port for the websockets
handler (SocketHandler): The handler for the communication over websockets
Returns:
None | Args:
host (str): The IP address for the websockets
port (int): The port for the websockets
handler (SocketHandler): The handler for the communication over websockets
Returns:
None | [
"Args",
":",
"host",
"(",
"str",
")",
":",
"The",
"IP",
"address",
"for",
"the",
"websockets",
"port",
"(",
"int",
")",
":",
"The",
"port",
"for",
"the",
"websockets",
"handler",
"(",
"SocketHandler",
")",
":",
"The",
"handler",
"for",
"the",
"communic... | def __init__(self, host, port, handler, delay, wsport):
"""
Args:
host (str): The IP address for the websockets
port (int): The port for the websockets
handler (SocketHandler): The handler for the communication over websockets
Returns:
None
"""
self.websocketclass = handler
SocketServer.TCPServer.allow_reuse_address = True
self.httpd = SocketServer.TCPServer((host, port), self.websocketclass)
self.httpd.myhost = host
self.httpd.delay = delay
self.httpd.myport = wsport | [
"def",
"__init__",
"(",
"self",
",",
"host",
",",
"port",
",",
"handler",
",",
"delay",
",",
"wsport",
")",
":",
"self",
".",
"websocketclass",
"=",
"handler",
"SocketServer",
".",
"TCPServer",
".",
"allow_reuse_address",
"=",
"True",
"self",
".",
"httpd",... | https://github.com/lightbulb-framework/lightbulb-framework/blob/9e8d6f37f28c784963dba3d726a0c8022a605baf/lightbulb/core/utils/SimpleWebServer.py#L9-L24 | ||
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/plugins/obsolete/swing_gui.py | python | swingGui.eventChar | (self,event,c=None) | return event and event.char or '' | Return the char field of an event. | Return the char field of an event. | [
"Return",
"the",
"char",
"field",
"of",
"an",
"event",
"."
] | def eventChar (self,event,c=None):
'''Return the char field of an event.'''
return event and event.char or '' | [
"def",
"eventChar",
"(",
"self",
",",
"event",
",",
"c",
"=",
"None",
")",
":",
"return",
"event",
"and",
"event",
".",
"char",
"or",
"''"
] | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/obsolete/swing_gui.py#L6762-L6764 | |
hugapi/hug | 8b5ac00632543addfdcecc326d0475a685a0cba7 | hug/introspect.py | python | arguments | (function, extra_arguments=0) | return function.__code__.co_varnames[: function.__code__.co_argcount + extra_arguments] | Returns the name of all arguments a function takes | Returns the name of all arguments a function takes | [
"Returns",
"the",
"name",
"of",
"all",
"arguments",
"a",
"function",
"takes"
] | def arguments(function, extra_arguments=0):
"""Returns the name of all arguments a function takes"""
if not hasattr(function, "__code__"):
return ()
return function.__code__.co_varnames[: function.__code__.co_argcount + extra_arguments] | [
"def",
"arguments",
"(",
"function",
",",
"extra_arguments",
"=",
"0",
")",
":",
"if",
"not",
"hasattr",
"(",
"function",
",",
"\"__code__\"",
")",
":",
"return",
"(",
")",
"return",
"function",
".",
"__code__",
".",
"co_varnames",
"[",
":",
"function",
... | https://github.com/hugapi/hug/blob/8b5ac00632543addfdcecc326d0475a685a0cba7/hug/introspect.py#L43-L48 | |
yandex/yandex-tank | b41bcc04396c4ed46fc8b28a261197320854fd33 | yandextank/common/util.py | python | AsyncSession.exit_status | (self) | return self.session.recv_exit_status() | [] | def exit_status(self):
return self.session.recv_exit_status() | [
"def",
"exit_status",
"(",
"self",
")",
":",
"return",
"self",
".",
"session",
".",
"recv_exit_status",
"(",
")"
] | https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/common/util.py#L193-L194 | |||
Komodo/KomodoEdit | 61edab75dce2bdb03943b387b0608ea36f548e8e | src/codeintel/lib/codeintel2/database/langlib.py | python | LangZone.get_lib | (self, name, dirs) | return langdirslib | Dev Notes:
We make a lib for a particular sequence of dirs a singleton because:
1. The sequence of dirs for a language's import path tends to
not change, so the same object will tend to get used.
2. This allows caching of filesystem lookups to be done naturally
on the LangDirsLib instance.
To ensure that this cache doesn't grow unboundedly we only allow
there to be N cached LangDirsLib's. A good value for N is when
there are relatively few cache misses. Ideally we'd want to
count the number of cache misses (i.e. LangDirsLib instance
creations) for a number of "typical" uses of codeintel -- i.e. a
long running Komodo profile. Failing that we'll just use N=10. | Dev Notes:
We make a lib for a particular sequence of dirs a singleton because:
1. The sequence of dirs for a language's import path tends to
not change, so the same object will tend to get used.
2. This allows caching of filesystem lookups to be done naturally
on the LangDirsLib instance. | [
"Dev",
"Notes",
":",
"We",
"make",
"a",
"lib",
"for",
"a",
"particular",
"sequence",
"of",
"dirs",
"a",
"singleton",
"because",
":",
"1",
".",
"The",
"sequence",
"of",
"dirs",
"for",
"a",
"language",
"s",
"import",
"path",
"tends",
"to",
"not",
"change... | def get_lib(self, name, dirs):
"""
Dev Notes:
We make a lib for a particular sequence of dirs a singleton because:
1. The sequence of dirs for a language's import path tends to
not change, so the same object will tend to get used.
2. This allows caching of filesystem lookups to be done naturally
on the LangDirsLib instance.
To ensure that this cache doesn't grow unboundedly we only allow
there to be N cached LangDirsLib's. A good value for N is when
there are relatively few cache misses. Ideally we'd want to
count the number of cache misses (i.e. LangDirsLib instance
creations) for a number of "typical" uses of codeintel -- i.e. a
long running Komodo profile. Failing that we'll just use N=10.
"""
assert isinstance(dirs, (tuple, list))
canon_dirs = tuple(set(abspath(normpath(expanduser(d))) for d in dirs))
if canon_dirs in self._dirslib_cache:
return self._dirslib_cache[canon_dirs]
langdirslib = LangDirsLib(self, self._lock, self.lang, name,
canon_dirs)
# Ensure that these directories are all *up-to-date*.
langdirslib.ensure_all_dirs_scanned()
self._dirslib_cache[canon_dirs] = langdirslib
return langdirslib | [
"def",
"get_lib",
"(",
"self",
",",
"name",
",",
"dirs",
")",
":",
"assert",
"isinstance",
"(",
"dirs",
",",
"(",
"tuple",
",",
"list",
")",
")",
"canon_dirs",
"=",
"tuple",
"(",
"set",
"(",
"abspath",
"(",
"normpath",
"(",
"expanduser",
"(",
"d",
... | https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/lib/codeintel2/database/langlib.py#L1457-L1485 | |
CouchPotato/CouchPotatoServer | 7260c12f72447ddb6f062367c6dfbda03ecd4e9c | libs/xmpp/auth.py | python | Bind.FeaturesHandler | (self,conn,feats) | Determine if server supports resource binding and set some internal attributes accordingly. | Determine if server supports resource binding and set some internal attributes accordingly. | [
"Determine",
"if",
"server",
"supports",
"resource",
"binding",
"and",
"set",
"some",
"internal",
"attributes",
"accordingly",
"."
] | def FeaturesHandler(self,conn,feats):
""" Determine if server supports resource binding and set some internal attributes accordingly. """
if not feats.getTag('bind',namespace=NS_BIND):
self.bound='failure'
self.DEBUG('Server does not requested binding.','error')
return
if feats.getTag('session',namespace=NS_SESSION): self.session=1
else: self.session=-1
self.bound=[] | [
"def",
"FeaturesHandler",
"(",
"self",
",",
"conn",
",",
"feats",
")",
":",
"if",
"not",
"feats",
".",
"getTag",
"(",
"'bind'",
",",
"namespace",
"=",
"NS_BIND",
")",
":",
"self",
".",
"bound",
"=",
"'failure'",
"self",
".",
"DEBUG",
"(",
"'Server does... | https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/xmpp/auth.py#L230-L238 | ||
tensorflow/tfx | b4a6b83269815ed12ba9df9e9154c7376fef2ea0 | tfx/orchestration/kubeflow/container_entrypoint.py | python | _dump_ui_metadata | (
node: pipeline_pb2.PipelineNode,
execution_info: data_types.ExecutionInfo,
ui_metadata_path: str = '/mlpipeline-ui-metadata.json') | Dump KFP UI metadata json file for visualization purpose.
For general components we just render a simple Markdown file for
exec_properties/inputs/outputs.
Args:
node: associated TFX node.
execution_info: runtime execution info for this component, including
materialized inputs/outputs/execution properties and id.
ui_metadata_path: path to dump ui metadata. | Dump KFP UI metadata json file for visualization purpose. | [
"Dump",
"KFP",
"UI",
"metadata",
"json",
"file",
"for",
"visualization",
"purpose",
"."
] | def _dump_ui_metadata(
node: pipeline_pb2.PipelineNode,
execution_info: data_types.ExecutionInfo,
ui_metadata_path: str = '/mlpipeline-ui-metadata.json') -> None:
"""Dump KFP UI metadata json file for visualization purpose.
For general components we just render a simple Markdown file for
exec_properties/inputs/outputs.
Args:
node: associated TFX node.
execution_info: runtime execution info for this component, including
materialized inputs/outputs/execution properties and id.
ui_metadata_path: path to dump ui metadata.
"""
exec_properties_list = [
'**{}**: {}'.format(
_sanitize_underscore(name), _sanitize_underscore(exec_property))
for name, exec_property in execution_info.exec_properties.items()
]
src_str_exec_properties = '# Execution properties:\n{}'.format(
'\n\n'.join(exec_properties_list) or 'No execution property.')
def _dump_input_populated_artifacts(
node_inputs: MutableMapping[str, pipeline_pb2.InputSpec],
name_to_artifacts: Dict[str, List[artifact.Artifact]]) -> List[str]:
"""Dump artifacts markdown string for inputs.
Args:
node_inputs: maps from input name to input sepc proto.
name_to_artifacts: maps from input key to list of populated artifacts.
Returns:
A list of dumped markdown string, each of which represents a channel.
"""
rendered_list = []
for name, spec in node_inputs.items():
# Need to look for materialized artifacts in the execution decision.
rendered_artifacts = ''.join([
_render_artifact_as_mdstr(single_artifact)
for single_artifact in name_to_artifacts.get(name, [])
])
# There must be at least a channel in a input, and all channels in a input
# share the same artifact type.
artifact_type = spec.channels[0].artifact_query.type.name
rendered_list.append(
'## {name}\n\n**Type**: {channel_type}\n\n{artifacts}'.format(
name=_sanitize_underscore(name),
channel_type=_sanitize_underscore(artifact_type),
artifacts=rendered_artifacts))
return rendered_list
def _dump_output_populated_artifacts(
node_outputs: MutableMapping[str, pipeline_pb2.OutputSpec],
name_to_artifacts: Dict[str, List[artifact.Artifact]]) -> List[str]:
"""Dump artifacts markdown string for outputs.
Args:
node_outputs: maps from output name to output sepc proto.
name_to_artifacts: maps from output key to list of populated artifacts.
Returns:
A list of dumped markdown string, each of which represents a channel.
"""
rendered_list = []
for name, spec in node_outputs.items():
# Need to look for materialized artifacts in the execution decision.
rendered_artifacts = ''.join([
_render_artifact_as_mdstr(single_artifact)
for single_artifact in name_to_artifacts.get(name, [])
])
# There must be at least a channel in a input, and all channels in a input
# share the same artifact type.
artifact_type = spec.artifact_spec.type.name
rendered_list.append(
'## {name}\n\n**Type**: {channel_type}\n\n{artifacts}'.format(
name=_sanitize_underscore(name),
channel_type=_sanitize_underscore(artifact_type),
artifacts=rendered_artifacts))
return rendered_list
src_str_inputs = '# Inputs:\n{}'.format(''.join(
_dump_input_populated_artifacts(
node_inputs=node.inputs.inputs,
name_to_artifacts=execution_info.input_dict or {})) or 'No input.')
src_str_outputs = '# Outputs:\n{}'.format(''.join(
_dump_output_populated_artifacts(
node_outputs=node.outputs.outputs,
name_to_artifacts=execution_info.output_dict or {})) or 'No output.')
outputs = [{
'storage':
'inline',
'source':
'{exec_properties}\n\n{inputs}\n\n{outputs}'.format(
exec_properties=src_str_exec_properties,
inputs=src_str_inputs,
outputs=src_str_outputs),
'type':
'markdown',
}]
# Add Tensorboard view for ModelRun outpus.
for name, spec in node.outputs.outputs.items():
if spec.artifact_spec.type.name == standard_artifacts.ModelRun.TYPE_NAME:
output_model = execution_info.output_dict[name][0]
# Add Tensorboard view.
tensorboard_output = {'type': 'tensorboard', 'source': output_model.uri}
outputs.append(tensorboard_output)
metadata_dict = {'outputs': outputs}
with open(ui_metadata_path, 'w') as f:
json.dump(metadata_dict, f) | [
"def",
"_dump_ui_metadata",
"(",
"node",
":",
"pipeline_pb2",
".",
"PipelineNode",
",",
"execution_info",
":",
"data_types",
".",
"ExecutionInfo",
",",
"ui_metadata_path",
":",
"str",
"=",
"'/mlpipeline-ui-metadata.json'",
")",
"->",
"None",
":",
"exec_properties_list... | https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/kubeflow/container_entrypoint.py#L237-L353 | ||
google/compare_gan | 19922d3004b675c1a49c4d7515c06f6f75acdcc8 | compare_gan/architectures/resnet5.py | python | Generator.apply | (self, z, y, is_training) | return net | Build the generator network for the given inputs.
Args:
z: `Tensor` of shape [batch_size, z_dim] with latent code.
y: `Tensor` of shape [batch_size, num_classes] with one hot encoded
labels.
is_training: boolean, are we in train or eval model.
Returns:
A tensor of size [batch_size] + self._image_shape with values in [0, 1]. | Build the generator network for the given inputs. | [
"Build",
"the",
"generator",
"network",
"for",
"the",
"given",
"inputs",
"."
] | def apply(self, z, y, is_training):
"""Build the generator network for the given inputs.
Args:
z: `Tensor` of shape [batch_size, z_dim] with latent code.
y: `Tensor` of shape [batch_size, num_classes] with one hot encoded
labels.
is_training: boolean, are we in train or eval model.
Returns:
A tensor of size [batch_size] + self._image_shape with values in [0, 1].
"""
# Each block upscales by a factor of 2.
seed_size = 4
image_size = self._image_shape[0]
# Map noise to the actual seed.
net = ops.linear(
z,
self._ch * self._channels[0] * seed_size * seed_size,
scope="fc_noise")
# Reshape the seed to be a rank-4 Tensor.
net = tf.reshape(
net,
[-1, seed_size, seed_size, self._ch * self._channels[0]],
name="fc_reshaped")
up_layers = np.log2(float(image_size) / seed_size)
if not up_layers.is_integer():
raise ValueError("log2({}/{}) must be an integer.".format(
image_size, seed_size))
if up_layers < 0 or up_layers > 5:
raise ValueError("Invalid image_size {}.".format(image_size))
up_layers = int(up_layers)
for block_idx in range(5):
block = self._resnet_block(
name="B{}".format(block_idx + 1),
in_channels=self._ch * self._channels[block_idx],
out_channels=self._ch * self._channels[block_idx + 1],
scale="up" if block_idx < up_layers else "none")
net = block(net, z=z, y=y, is_training=is_training)
net = self.batch_norm(
net, z=z, y=y, is_training=is_training, name="final_norm")
net = tf.nn.relu(net)
net = ops.conv2d(net, output_dim=self._image_shape[2],
k_h=3, k_w=3, d_h=1, d_w=1, name="final_conv")
net = tf.nn.sigmoid(net)
return net | [
"def",
"apply",
"(",
"self",
",",
"z",
",",
"y",
",",
"is_training",
")",
":",
"# Each block upscales by a factor of 2.",
"seed_size",
"=",
"4",
"image_size",
"=",
"self",
".",
"_image_shape",
"[",
"0",
"]",
"# Map noise to the actual seed.",
"net",
"=",
"ops",
... | https://github.com/google/compare_gan/blob/19922d3004b675c1a49c4d7515c06f6f75acdcc8/compare_gan/architectures/resnet5.py#L44-L93 | |
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/ext/makerbot_driver/profile.py | python | _getprofiledir | (profiledir) | return profiledir | [] | def _getprofiledir(profiledir):
if None is profiledir:
profiledir = os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'profiles') # Path of the profiles directory
return profiledir | [
"def",
"_getprofiledir",
"(",
"profiledir",
")",
":",
"if",
"None",
"is",
"profiledir",
":",
"profiledir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",... | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_driver/profile.py#L11-L15 | |||
shidenggui/easytrader | dbb166564c6c73da3446588a19d2692ad52716cb | easytrader/xqtrader.py | python | XueQiuTrader._search_stock_info | (self, code) | return stock | 通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
u'hasexist': None, u'flag': 1, u'ind_name': u'房地产', u'type': None,
u'enName': None}
** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4) | 通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
u'hasexist': None, u'flag': 1, u'ind_name': u'房地产', u'type': None,
u'enName': None}
** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4) | [
"通过雪球的接口获取股票详细信息",
":",
"param",
"code",
":",
"股票代码",
"000001",
":",
"return",
":",
"查询到的股票",
"{",
"u",
"stock_id",
":",
"1000279",
"u",
"code",
":",
"u",
"SH600325",
"u",
"name",
":",
"u",
"华发股份",
"u",
"ind_color",
":",
"u",
"#d9633b",
"u",
"chg",
"... | def _search_stock_info(self, code):
"""
通过雪球的接口获取股票详细信息
:param code: 股票代码 000001
:return: 查询到的股票 {u'stock_id': 1000279, u'code': u'SH600325',
u'name': u'华发股份', u'ind_color': u'#d9633b', u'chg': -1.09,
u'ind_id': 100014, u'percent': -9.31, u'current': 10.62,
u'hasexist': None, u'flag': 1, u'ind_name': u'房地产', u'type': None,
u'enName': None}
** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4)
"""
data = {
"code": str(code),
"size": "300",
"key": "47bce5c74f",
"market": self.account_config["portfolio_market"],
}
r = self.s.get(self.config["search_stock_url"], params=data)
stocks = json.loads(r.text)
stocks = stocks["stocks"]
stock = None
if len(stocks) > 0:
stock = stocks[0]
return stock | [
"def",
"_search_stock_info",
"(",
"self",
",",
"code",
")",
":",
"data",
"=",
"{",
"\"code\"",
":",
"str",
"(",
"code",
")",
",",
"\"size\"",
":",
"\"300\"",
",",
"\"key\"",
":",
"\"47bce5c74f\"",
",",
"\"market\"",
":",
"self",
".",
"account_config",
"[... | https://github.com/shidenggui/easytrader/blob/dbb166564c6c73da3446588a19d2692ad52716cb/easytrader/xqtrader.py#L101-L124 | |
ANSSI-FR/polichombr | e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1 | polichombr/views/apiview.py | python | api_help | () | return response | Try to document the api.
see docs/API.md for more informations | Try to document the api.
see docs/API.md for more informations | [
"Try",
"to",
"document",
"the",
"api",
".",
"see",
"docs",
"/",
"API",
".",
"md",
"for",
"more",
"informations"
] | def api_help():
"""
Try to document the api.
see docs/API.md for more informations
"""
text = """
See docs/API.md for more informations
"""
response = make_response(text)
return response | [
"def",
"api_help",
"(",
")",
":",
"text",
"=",
"\"\"\"\n See docs/API.md for more informations\n \"\"\"",
"response",
"=",
"make_response",
"(",
"text",
")",
"return",
"response"
] | https://github.com/ANSSI-FR/polichombr/blob/e2dc3874ae3d78c3b496e9656c9a6d1b88ae91e1/polichombr/views/apiview.py#L86-L95 | |
veusz/veusz | 5a1e2af5f24df0eb2a2842be51f2997c4999c7fb | veusz/dataimport/defn_fits.py | python | OperationDataImportFITS.readDataFromFile | (self) | return dsread | Read data from fits file and return a dict of names to data. | Read data from fits file and return a dict of names to data. | [
"Read",
"data",
"from",
"fits",
"file",
"and",
"return",
"a",
"dict",
"of",
"names",
"to",
"data",
"."
] | def readDataFromFile(self):
"""Read data from fits file and return a dict of names to data."""
dsread = {}
with fits.open(self.params.filename, 'readonly') as fitsf:
hdunames = fits_hdf5_helpers.getFITSHduNames(fitsf)
for item in self.params.items:
parts = [p.strip() for p in item.split('/') if p.strip()]
if not parts:
# / or empty
self.walkFile(fitsf, hdunames, dsread)
elif len(parts) >= 1:
try:
idx = hdunames.index(parts[0])
except ValueError:
raise RuntimeError(
"Cannot find HDU '%s' in FITS file" % parts[0])
hdu = fitsf[idx]
if len(parts) == 1:
# read whole HDU
self.walkHdu(hdu, '/%s' % parts[0], dsread)
elif len(parts) == 2:
# column of table
self.readTableColumn(
hdu, '/%s/%s' % (parts[0], parts[1]), dsread)
else:
raise RuntimeError(
'Too many parts in FITS dataset name')
return dsread | [
"def",
"readDataFromFile",
"(",
"self",
")",
":",
"dsread",
"=",
"{",
"}",
"with",
"fits",
".",
"open",
"(",
"self",
".",
"params",
".",
"filename",
",",
"'readonly'",
")",
"as",
"fitsf",
":",
"hdunames",
"=",
"fits_hdf5_helpers",
".",
"getFITSHduNames",
... | https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/dataimport/defn_fits.py#L227-L258 | |
python-twitter-tools/twitter | 6a868f43dbc3a05527c339f45d21ea435fa8d1d3 | twitter/api.py | python | TwitterResponse.rate_limit_remaining | (self) | return int(self.headers.get('X-Rate-Limit-Remaining', "0")) | Remaining requests in the current rate-limit. | Remaining requests in the current rate-limit. | [
"Remaining",
"requests",
"in",
"the",
"current",
"rate",
"-",
"limit",
"."
] | def rate_limit_remaining(self):
"""
Remaining requests in the current rate-limit.
"""
return int(self.headers.get('X-Rate-Limit-Remaining', "0")) | [
"def",
"rate_limit_remaining",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"headers",
".",
"get",
"(",
"'X-Rate-Limit-Remaining'",
",",
"\"0\"",
")",
")"
] | https://github.com/python-twitter-tools/twitter/blob/6a868f43dbc3a05527c339f45d21ea435fa8d1d3/twitter/api.py#L111-L115 | |
StackStorm/st2 | 85ae05b73af422efd3097c9c05351f7f1cc8369e | st2common/st2common/transport/announcement.py | python | AnnouncementDispatcher.dispatch | (self, routing_key, payload, trace_context=None) | Method which dispatches the announcement.
:param routing_key: Routing key of the announcement.
:type routing_key: ``str``
:param payload: Announcement payload.
:type payload: ``dict``
:param trace_context: Trace context to associate with Announcement.
:type trace_context: ``TraceContext`` | Method which dispatches the announcement. | [
"Method",
"which",
"dispatches",
"the",
"announcement",
"."
] | def dispatch(self, routing_key, payload, trace_context=None):
"""
Method which dispatches the announcement.
:param routing_key: Routing key of the announcement.
:type routing_key: ``str``
:param payload: Announcement payload.
:type payload: ``dict``
:param trace_context: Trace context to associate with Announcement.
:type trace_context: ``TraceContext``
"""
if not isinstance(payload, (type(None), dict)):
raise TypeError(
f"The payload has a value that is not a dictionary (was {type(payload)})."
)
if not isinstance(trace_context, (type(None), dict, TraceContext)):
raise TypeError(
"The trace context has a value that is not a NoneType or dict or TraceContext"
f" (was {type(trace_context)})."
)
payload = {"payload": payload, TRACE_CONTEXT: trace_context}
self._logger.debug(
"Dispatching announcement (routing_key=%s,payload=%s)", routing_key, payload
)
self._publisher.publish(payload=payload, routing_key=routing_key) | [
"def",
"dispatch",
"(",
"self",
",",
"routing_key",
",",
"payload",
",",
"trace_context",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"payload",
",",
"(",
"type",
"(",
"None",
")",
",",
"dict",
")",
")",
":",
"raise",
"TypeError",
"(",
"f\... | https://github.com/StackStorm/st2/blob/85ae05b73af422efd3097c9c05351f7f1cc8369e/st2common/st2common/transport/announcement.py#L50-L78 | ||
pculture/miro | d8e4594441939514dd2ac29812bf37087bb3aea5 | tv/lib/frontends/widgets/widgetutil.py | python | draw_rounded_icon | (context, icon, x, y, width, height, inset=0, fraction=1.0) | Draw an icon with the corners rounded.
x, y, width, height define where the box is.
inset creates a margin between where the images is drawn and (x, y, width,
height) | Draw an icon with the corners rounded. | [
"Draw",
"an",
"icon",
"with",
"the",
"corners",
"rounded",
"."
] | def draw_rounded_icon(context, icon, x, y, width, height, inset=0, fraction=1.0):
"""Draw an icon with the corners rounded.
x, y, width, height define where the box is.
inset creates a margin between where the images is drawn and (x, y, width,
height)
"""
context.save()
round_rect(context, x + inset, y + inset, width - inset*2,
height - inset*2, 3)
context.clip()
draw_icon_in_rect(context, icon, x, y, width, height, fraction)
context.restore() | [
"def",
"draw_rounded_icon",
"(",
"context",
",",
"icon",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"inset",
"=",
"0",
",",
"fraction",
"=",
"1.0",
")",
":",
"context",
".",
"save",
"(",
")",
"round_rect",
"(",
"context",
",",
"x",
"+",
... | https://github.com/pculture/miro/blob/d8e4594441939514dd2ac29812bf37087bb3aea5/tv/lib/frontends/widgets/widgetutil.py#L120-L133 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/xiaomi_miio/fan.py | python | XiaomiFanP5.operation_mode_class | (self) | return FanOperationMode | Hold operation mode class. | Hold operation mode class. | [
"Hold",
"operation",
"mode",
"class",
"."
] | def operation_mode_class(self):
"""Hold operation mode class."""
return FanOperationMode | [
"def",
"operation_mode_class",
"(",
"self",
")",
":",
"return",
"FanOperationMode"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/xiaomi_miio/fan.py#L889-L891 | |
pyeventsourcing/eventsourcing | f5a36f434ab2631890092b6c7714b8fb8c94dc7c | eventsourcing/interface.py | python | NotificationLogInterface.get_notifications | (
self, start: int, limit: int, topics: Sequence[str] = ()
) | Returns a serialised list of :class:`~eventsourcing.persistence.Notification`
objects from a notification log. | Returns a serialised list of :class:`~eventsourcing.persistence.Notification`
objects from a notification log. | [
"Returns",
"a",
"serialised",
"list",
"of",
":",
"class",
":",
"~eventsourcing",
".",
"persistence",
".",
"Notification",
"objects",
"from",
"a",
"notification",
"log",
"."
] | def get_notifications(
self, start: int, limit: int, topics: Sequence[str] = ()
) -> str:
"""
Returns a serialised list of :class:`~eventsourcing.persistence.Notification`
objects from a notification log.
""" | [
"def",
"get_notifications",
"(",
"self",
",",
"start",
":",
"int",
",",
"limit",
":",
"int",
",",
"topics",
":",
"Sequence",
"[",
"str",
"]",
"=",
"(",
")",
")",
"->",
"str",
":"
] | https://github.com/pyeventsourcing/eventsourcing/blob/f5a36f434ab2631890092b6c7714b8fb8c94dc7c/eventsourcing/interface.py#L25-L31 | ||
SeldomQA/poium | b95b6d49f31084d9a213de2d51e35803733ca136 | poium/wda/__init__.py | python | Page.assert_text_not_equals | (text_1, text_2, describe) | Asserts that two texts are not equal
Args:
text(list): text | Asserts that two texts are not equal | [
"Asserts",
"that",
"two",
"texts",
"are",
"not",
"equal"
] | def assert_text_not_equals(text_1, text_2, describe):
"""
Asserts that two texts are not equal
Args:
text(list): text
"""
logging.info("预期结果: " + text_1 + "," + text_2 + " 不相等")
if text_1 == text_2:
result = [describe, False]
Setting.assert_result.append(result)
logging.warn("预期结果: " + text_1 + "," + text_2 + " 相等")
else:
result = [describe, True]
Setting.assert_result.append(result)
logging.info("预期结果: " + text_1 + "," + text_2 + " 不相等") | [
"def",
"assert_text_not_equals",
"(",
"text_1",
",",
"text_2",
",",
"describe",
")",
":",
"logging",
".",
"info",
"(",
"\"预期结果: \" + text_",
" ",
" \",\" +",
"t",
"xt_",
" ",
" \" 不相等",
")",
"",
"",
"if",
"text_1",
"==",
"text_2",
":",
"result",
"=",
"["... | https://github.com/SeldomQA/poium/blob/b95b6d49f31084d9a213de2d51e35803733ca136/poium/wda/__init__.py#L404-L420 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/nbconvert/filters/markdown_mistune.py | python | markdown2html_mistune | (source) | return MarkdownWithMath(renderer=IPythonRenderer(
escape=False)).render(source) | Convert a markdown string to HTML using mistune | Convert a markdown string to HTML using mistune | [
"Convert",
"a",
"markdown",
"string",
"to",
"HTML",
"using",
"mistune"
] | def markdown2html_mistune(source):
"""Convert a markdown string to HTML using mistune"""
return MarkdownWithMath(renderer=IPythonRenderer(
escape=False)).render(source) | [
"def",
"markdown2html_mistune",
"(",
"source",
")",
":",
"return",
"MarkdownWithMath",
"(",
"renderer",
"=",
"IPythonRenderer",
"(",
"escape",
"=",
"False",
")",
")",
".",
"render",
"(",
"source",
")"
] | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/nbconvert/filters/markdown_mistune.py#L148-L151 | |
git-cola/git-cola | b48b8028e0c3baf47faf7b074b9773737358163d | cola/widgets/completion.py | python | GitRefCompletionModel.__init__ | (self, context, parent) | [] | def __init__(self, context, parent):
GitCompletionModel.__init__(self, context, parent)
model = context.model
model.add_observer(model.message_refs_updated, self.emit_model_updated) | [
"def",
"__init__",
"(",
"self",
",",
"context",
",",
"parent",
")",
":",
"GitCompletionModel",
".",
"__init__",
"(",
"self",
",",
"context",
",",
"parent",
")",
"model",
"=",
"context",
".",
"model",
"model",
".",
"add_observer",
"(",
"model",
".",
"mess... | https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/completion.py#L561-L564 | ||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/whoosh/collectors.py | python | CollapseCollector.collect_matches | (self) | [] | def collect_matches(self):
lists = self.lists
limit = self.limit
keyer = self.keyer
orderer = self.orderer
collapsed_counts = self.collapsed_counts
child = self.child
matcher = child.matcher
offset = child.offset
for sub_docnum in child.matches():
# Collapsing category key
ckey = keyer.key_to_name(keyer.key_for(matcher, sub_docnum))
if not ckey:
# If the document isn't in a collapsing category, just add it
child.collect(sub_docnum)
else:
global_docnum = offset + sub_docnum
if orderer:
# If user specified a collapse order, use it
sortkey = orderer.key_for(child.matcher, sub_docnum)
else:
# Otherwise, use the results order
sortkey = child.sort_key(sub_docnum)
# Current list of best docs for this collapse key
best = lists[ckey]
add = False
if len(best) < limit:
# If the heap is not full yet, just add this document
add = True
elif sortkey < best[-1][0]:
# If the heap is full but this document has a lower sort
# key than the highest key currently on the heap, replace
# the "least-best" document
# Tell the child collector to remove the document
child.remove(best.pop()[1])
add = True
if add:
insort(best, (sortkey, global_docnum))
child.collect(sub_docnum)
else:
# Remember that a document was filtered
collapsed_counts[ckey] += 1
self.collapsed_total += 1 | [
"def",
"collect_matches",
"(",
"self",
")",
":",
"lists",
"=",
"self",
".",
"lists",
"limit",
"=",
"self",
".",
"limit",
"keyer",
"=",
"self",
".",
"keyer",
"orderer",
"=",
"self",
".",
"orderer",
"collapsed_counts",
"=",
"self",
".",
"collapsed_counts",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/whoosh/collectors.py#L950-L996 | ||||
Xilinx/finn | d1cc9cf94f1c33354cc169c5a6517314d0e94e3b | src/finn/custom_op/fpgadataflow/pool_batch.py | python | Pool_Batch.get_nodeattr_types | (self) | return my_attrs | [] | def get_nodeattr_types(self):
my_attrs = {
"Channels": ("i", True, 0),
"PE": ("i", True, 1),
"KernelSize": ("i", True, 0),
# Function:
# - MaxPool
# - QuantAvgPool
# TODO add support for AvgPool and AccPool
"Function": ("s", True, "", {"MaxPool", "QuantAvgPool"}),
"OutImgDim": ("i", True, 0),
# FINN DataTypes for inputs/outputs
"InputDataType": ("s", True, ""),
"OutputDataType": ("s", True, ""),
"AccumBits": ("i", False, 0),
"Size": ("i", False, 1),
"BatchSize": ("i", False, 1),
}
my_attrs.update(super().get_nodeattr_types())
return my_attrs | [
"def",
"get_nodeattr_types",
"(",
"self",
")",
":",
"my_attrs",
"=",
"{",
"\"Channels\"",
":",
"(",
"\"i\"",
",",
"True",
",",
"0",
")",
",",
"\"PE\"",
":",
"(",
"\"i\"",
",",
"True",
",",
"1",
")",
",",
"\"KernelSize\"",
":",
"(",
"\"i\"",
",",
"T... | https://github.com/Xilinx/finn/blob/d1cc9cf94f1c33354cc169c5a6517314d0e94e3b/src/finn/custom_op/fpgadataflow/pool_batch.py#L55-L75 | |||
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py | python | _stochastic_dependencies_map | (fixed_losses, stochastic_tensors=None) | return stoch_dependencies_map | Map stochastic tensors to the fixed losses that depend on them.
Args:
fixed_losses: a list of `Tensor`s.
stochastic_tensors: a list of `StochasticTensor`s to map to fixed losses.
If `None`, all `StochasticTensor`s in the graph will be used.
Returns:
A dict `dependencies` that maps `StochasticTensor` objects to subsets of
`fixed_losses`.
If `loss in dependencies[st]`, for some `loss` in `fixed_losses` then there
is a direct path from `st.value()` to `loss` in the graph. | Map stochastic tensors to the fixed losses that depend on them. | [
"Map",
"stochastic",
"tensors",
"to",
"the",
"fixed",
"losses",
"that",
"depend",
"on",
"them",
"."
] | def _stochastic_dependencies_map(fixed_losses, stochastic_tensors=None):
"""Map stochastic tensors to the fixed losses that depend on them.
Args:
fixed_losses: a list of `Tensor`s.
stochastic_tensors: a list of `StochasticTensor`s to map to fixed losses.
If `None`, all `StochasticTensor`s in the graph will be used.
Returns:
A dict `dependencies` that maps `StochasticTensor` objects to subsets of
`fixed_losses`.
If `loss in dependencies[st]`, for some `loss` in `fixed_losses` then there
is a direct path from `st.value()` to `loss` in the graph.
"""
stoch_value_collection = stochastic_tensors or ops.get_collection(
stochastic_tensor.STOCHASTIC_TENSOR_COLLECTION)
if not stoch_value_collection:
return {}
stoch_value_map = dict(
(node.value(), node) for node in stoch_value_collection)
# Step backwards through the graph to see which surrogate losses correspond
# to which fixed_losses.
#
# TODO(ebrevdo): Ensure that fixed_losses and stochastic values are in the
# same frame.
stoch_dependencies_map = collections.defaultdict(set)
for loss in fixed_losses:
boundary = set([loss])
while boundary:
edge = boundary.pop()
edge_stoch_node = stoch_value_map.get(edge, None)
if edge_stoch_node:
stoch_dependencies_map[edge_stoch_node].add(loss)
boundary.update(edge.op.inputs)
return stoch_dependencies_map | [
"def",
"_stochastic_dependencies_map",
"(",
"fixed_losses",
",",
"stochastic_tensors",
"=",
"None",
")",
":",
"stoch_value_collection",
"=",
"stochastic_tensors",
"or",
"ops",
".",
"get_collection",
"(",
"stochastic_tensor",
".",
"STOCHASTIC_TENSOR_COLLECTION",
")",
"if",... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/bayesflow/python/ops/stochastic_graph.py#L53-L92 | |
p-christ/nn_builder | a79b45d15176b4d333dbed094e78bb3b216ed037 | nn_builder/pytorch/RNN.py | python | RNN.get_activation | (self, activations, ix=None) | return activation | Gets the activation function | Gets the activation function | [
"Gets",
"the",
"activation",
"function"
] | def get_activation(self, activations, ix=None):
"""Gets the activation function"""
if isinstance(activations, list):
activation = self.str_to_activations_converter[str(activations[ix]).lower()]
else:
activation = self.str_to_activations_converter[str(activations).lower()]
return activation | [
"def",
"get_activation",
"(",
"self",
",",
"activations",
",",
"ix",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"activations",
",",
"list",
")",
":",
"activation",
"=",
"self",
".",
"str_to_activations_converter",
"[",
"str",
"(",
"activations",
"[",
... | https://github.com/p-christ/nn_builder/blob/a79b45d15176b4d333dbed094e78bb3b216ed037/nn_builder/pytorch/RNN.py#L143-L149 | |
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | source/addons/document/document.py | python | node_class.full_path | (self) | return s | Return the components of the full path for some
node.
The returned list only contains the names of nodes. | Return the components of the full path for some
node.
The returned list only contains the names of nodes. | [
"Return",
"the",
"components",
"of",
"the",
"full",
"path",
"for",
"some",
"node",
".",
"The",
"returned",
"list",
"only",
"contains",
"the",
"names",
"of",
"nodes",
"."
] | def full_path(self):
""" Return the components of the full path for some
node.
The returned list only contains the names of nodes.
"""
if self.parent:
s = self.parent.full_path()
else:
s = []
if isinstance(self.path,list):
s+=self.path
elif self.path is None:
s.append('')
else:
s.append(self.path)
return s | [
"def",
"full_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"s",
"=",
"self",
".",
"parent",
".",
"full_path",
"(",
")",
"else",
":",
"s",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"path",
",",
"list",
")",
":",
"s",... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/document/document.py#L719-L734 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | opy/compiler2/transformer.py | python | Transformer.atom_lbrace | (self, nodelist) | return self.com_dictorsetmaker(nodelist[1]) | [] | def atom_lbrace(self, nodelist):
if nodelist[1][0] == token.RBRACE:
return Dict((), lineno=nodelist[0][2])
return self.com_dictorsetmaker(nodelist[1]) | [
"def",
"atom_lbrace",
"(",
"self",
",",
"nodelist",
")",
":",
"if",
"nodelist",
"[",
"1",
"]",
"[",
"0",
"]",
"==",
"token",
".",
"RBRACE",
":",
"return",
"Dict",
"(",
"(",
")",
",",
"lineno",
"=",
"nodelist",
"[",
"0",
"]",
"[",
"2",
"]",
")",... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/opy/compiler2/transformer.py#L835-L838 | |||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | research/object_detection/predictors/convolutional_keras_box_predictor.py | python | ConvolutionalBoxPredictor.build | (self, input_shapes) | Creates the variables of the layer. | Creates the variables of the layer. | [
"Creates",
"the",
"variables",
"of",
"the",
"layer",
"."
] | def build(self, input_shapes):
"""Creates the variables of the layer."""
if len(input_shapes) != len(self._prediction_heads[BOX_ENCODINGS]):
raise ValueError('This box predictor was constructed with %d heads,'
'but there are %d inputs.' %
(len(self._prediction_heads[BOX_ENCODINGS]),
len(input_shapes)))
for stack_index, input_shape in enumerate(input_shapes):
net = []
# Add additional conv layers before the class predictor.
features_depth = static_shape.get_depth(input_shape)
depth = max(min(features_depth, self._max_depth), self._min_depth)
tf.logging.info(
'depth of additional conv before box predictor: {}'.format(depth))
if depth > 0 and self._num_layers_before_predictor > 0:
for i in range(self._num_layers_before_predictor):
net.append(keras.Conv2D(depth, [1, 1],
name='SharedConvolutions_%d/Conv2d_%d_1x1_%d'
% (stack_index, i, depth),
padding='SAME',
**self._conv_hyperparams.params()))
net.append(self._conv_hyperparams.build_batch_norm(
training=(self._is_training and not self._freeze_batchnorm),
name='SharedConvolutions_%d/Conv2d_%d_1x1_%d_norm'
% (stack_index, i, depth)))
net.append(self._conv_hyperparams.build_activation_layer(
name='SharedConvolutions_%d/Conv2d_%d_1x1_%d_activation'
% (stack_index, i, depth),
))
# Until certain bugs are fixed in checkpointable lists,
# this net must be appended only once it's been filled with layers
self._shared_nets.append(net)
self.built = True | [
"def",
"build",
"(",
"self",
",",
"input_shapes",
")",
":",
"if",
"len",
"(",
"input_shapes",
")",
"!=",
"len",
"(",
"self",
".",
"_prediction_heads",
"[",
"BOX_ENCODINGS",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'This box predictor was constructed with %d h... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/predictors/convolutional_keras_box_predictor.py#L140-L174 | ||
puremourning/vimspector | bc57b1dd14214cf3e3a476ef75e9dcb56cf0c76d | python3/vimspector/vendor/cpuinfo.py | python | Trace.keys | (self, keys, info, new_info) | [] | def keys(self, keys, info, new_info):
if not self._is_active: return
from inspect import stack
frame = stack()[2]
file = frame[1]
line = frame[2]
# List updated keys
self._output.write("\tChanged keys ({0} {1})\n".format(file, line))
changed_keys = [key for key in keys if key in info and key in new_info and info[key] != new_info[key]]
if changed_keys:
for key in changed_keys:
self._output.write('\t\t{0}: {1} to {2}\n'.format(key, info[key], new_info[key]))
else:
self._output.write('\t\tNone\n')
# List new keys
self._output.write("\tNew keys ({0} {1})\n".format(file, line))
new_keys = [key for key in keys if key in new_info and key not in info]
if new_keys:
for key in new_keys:
self._output.write('\t\t{0}: {1}\n'.format(key, new_info[key]))
else:
self._output.write('\t\tNone\n')
self._output.write('\n')
self._output.flush() | [
"def",
"keys",
"(",
"self",
",",
"keys",
",",
"info",
",",
"new_info",
")",
":",
"if",
"not",
"self",
".",
"_is_active",
":",
"return",
"from",
"inspect",
"import",
"stack",
"frame",
"=",
"stack",
"(",
")",
"[",
"2",
"]",
"file",
"=",
"frame",
"[",... | https://github.com/puremourning/vimspector/blob/bc57b1dd14214cf3e3a476ef75e9dcb56cf0c76d/python3/vimspector/vendor/cpuinfo.py#L125-L152 | ||||
limodou/ulipad | 4c7d590234f39cac80bb1d36dca095b646e287fb | packages/docutils/readers/python/moduleparser.py | python | normalize_parameter_name | (name) | Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'`` | Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'`` | [
"Converts",
"a",
"tuple",
"like",
"(",
"a",
"(",
"b",
"c",
")",
"d",
")",
"into",
"(",
"a",
"(",
"b",
"c",
")",
"d",
")"
] | def normalize_parameter_name(name):
"""
Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'``
"""
if type(name) is tuple:
return '(%s)' % ', '.join([normalize_parameter_name(n) for n in name])
else:
return name | [
"def",
"normalize_parameter_name",
"(",
"name",
")",
":",
"if",
"type",
"(",
"name",
")",
"is",
"tuple",
":",
"return",
"'(%s)'",
"%",
"', '",
".",
"join",
"(",
"[",
"normalize_parameter_name",
"(",
"n",
")",
"for",
"n",
"in",
"name",
"]",
")",
"else",... | https://github.com/limodou/ulipad/blob/4c7d590234f39cac80bb1d36dca095b646e287fb/packages/docutils/readers/python/moduleparser.py#L735-L742 | ||
annoviko/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | pyclustering/nnet/som.py | python | som.show_distance_matrix | (self) | !
@brief Shows gray visualization of U-matrix (distance matrix).
@see get_distance_matrix() | ! | [
"!"
] | def show_distance_matrix(self):
"""!
@brief Shows gray visualization of U-matrix (distance matrix).
@see get_distance_matrix()
"""
distance_matrix = self.get_distance_matrix()
plt.imshow(distance_matrix, cmap=plt.get_cmap('hot'), interpolation='kaiser')
plt.title("U-Matrix")
plt.colorbar()
plt.show() | [
"def",
"show_distance_matrix",
"(",
"self",
")",
":",
"distance_matrix",
"=",
"self",
".",
"get_distance_matrix",
"(",
")",
"plt",
".",
"imshow",
"(",
"distance_matrix",
",",
"cmap",
"=",
"plt",
".",
"get_cmap",
"(",
"'hot'",
")",
",",
"interpolation",
"=",
... | https://github.com/annoviko/pyclustering/blob/bf4f51a472622292627ec8c294eb205585e50f52/pyclustering/nnet/som.py#L703-L715 | ||
tholum/PiBunny | 289563fbd8e5334a2889dc1b5a7391465d212a3b | system.d/library/tools_installer/tools_to_install/impacket/impacket/dot11.py | python | Dot11WPA.set_TSC1 | (self, value) | Set the \'WPA TSC1\' field | Set the \'WPA TSC1\' field | [
"Set",
"the",
"\\",
"WPA",
"TSC1",
"\\",
"field"
] | def set_TSC1(self, value):
'Set the \'WPA TSC1\' field'
# set the bits
nb = (value & 0xFF)
self.header.set_byte(0, nb) | [
"def",
"set_TSC1",
"(",
"self",
",",
"value",
")",
":",
"# set the bits",
"nb",
"=",
"(",
"value",
"&",
"0xFF",
")",
"self",
".",
"header",
".",
"set_byte",
"(",
"0",
",",
"nb",
")"
] | https://github.com/tholum/PiBunny/blob/289563fbd8e5334a2889dc1b5a7391465d212a3b/system.d/library/tools_installer/tools_to_install/impacket/impacket/dot11.py#L1185-L1189 | ||
deanishe/alfred-fakeum | 12a7e64d9c099c0f11416ee99fae064d6360aab2 | src/workflow/update.py | python | Version.__str__ | (self) | return vstr | Return semantic version string. | Return semantic version string. | [
"Return",
"semantic",
"version",
"string",
"."
] | def __str__(self):
"""Return semantic version string."""
vstr = '{0}.{1}.{2}'.format(self.major, self.minor, self.patch)
if self.suffix:
vstr = '{0}-{1}'.format(vstr, self.suffix)
if self.build:
vstr = '{0}+{1}'.format(vstr, self.build)
return vstr | [
"def",
"__str__",
"(",
"self",
")",
":",
"vstr",
"=",
"'{0}.{1}.{2}'",
".",
"format",
"(",
"self",
".",
"major",
",",
"self",
".",
"minor",
",",
"self",
".",
"patch",
")",
"if",
"self",
".",
"suffix",
":",
"vstr",
"=",
"'{0}-{1}'",
".",
"format",
"... | https://github.com/deanishe/alfred-fakeum/blob/12a7e64d9c099c0f11416ee99fae064d6360aab2/src/workflow/update.py#L333-L340 | |
gevent/gevent | ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31 | src/gevent/greenlet.py | python | Greenlet.exception | (self) | return self._exc_info[1] if self._exc_info is not None else None | Holds the exception instance raised by the function if the
greenlet has finished with an error. Otherwise ``None``. | Holds the exception instance raised by the function if the
greenlet has finished with an error. Otherwise ``None``. | [
"Holds",
"the",
"exception",
"instance",
"raised",
"by",
"the",
"function",
"if",
"the",
"greenlet",
"has",
"finished",
"with",
"an",
"error",
".",
"Otherwise",
"None",
"."
] | def exception(self):
"""
Holds the exception instance raised by the function if the
greenlet has finished with an error. Otherwise ``None``.
"""
return self._exc_info[1] if self._exc_info is not None else None | [
"def",
"exception",
"(",
"self",
")",
":",
"return",
"self",
".",
"_exc_info",
"[",
"1",
"]",
"if",
"self",
".",
"_exc_info",
"is",
"not",
"None",
"else",
"None"
] | https://github.com/gevent/gevent/blob/ae2cb5aeb2aea8987efcb90a4c50ca4e1ee12c31/src/gevent/greenlet.py#L568-L573 | |
deepchem/deepchem | 054eb4b2b082e3df8e1a8e77f36a52137ae6e375 | deepchem/models/chemnet_models.py | python | Smiles2Vec.__init__ | (self,
char_to_idx,
n_tasks=10,
max_seq_len=270,
embedding_dim=50,
n_classes=2,
use_bidir=True,
use_conv=True,
filters=192,
kernel_size=3,
strides=1,
rnn_sizes=[224, 384],
rnn_types=["GRU", "GRU"],
mode="regression",
**kwargs) | Parameters
----------
char_to_idx: dict,
char_to_idx contains character to index mapping for SMILES characters
embedding_dim: int, default 50
Size of character embeddings used.
use_bidir: bool, default True
Whether to use BiDirectional RNN Cells
use_conv: bool, default True
Whether to use a conv-layer
kernel_size: int, default 3
Kernel size for convolutions
filters: int, default 192
Number of filters
strides: int, default 1
Strides used in convolution
rnn_sizes: list[int], default [224, 384]
Number of hidden units in the RNN cells
mode: str, default regression
Whether to use model for regression or classification | Parameters
----------
char_to_idx: dict,
char_to_idx contains character to index mapping for SMILES characters
embedding_dim: int, default 50
Size of character embeddings used.
use_bidir: bool, default True
Whether to use BiDirectional RNN Cells
use_conv: bool, default True
Whether to use a conv-layer
kernel_size: int, default 3
Kernel size for convolutions
filters: int, default 192
Number of filters
strides: int, default 1
Strides used in convolution
rnn_sizes: list[int], default [224, 384]
Number of hidden units in the RNN cells
mode: str, default regression
Whether to use model for regression or classification | [
"Parameters",
"----------",
"char_to_idx",
":",
"dict",
"char_to_idx",
"contains",
"character",
"to",
"index",
"mapping",
"for",
"SMILES",
"characters",
"embedding_dim",
":",
"int",
"default",
"50",
"Size",
"of",
"character",
"embeddings",
"used",
".",
"use_bidir",
... | def __init__(self,
char_to_idx,
n_tasks=10,
max_seq_len=270,
embedding_dim=50,
n_classes=2,
use_bidir=True,
use_conv=True,
filters=192,
kernel_size=3,
strides=1,
rnn_sizes=[224, 384],
rnn_types=["GRU", "GRU"],
mode="regression",
**kwargs):
"""
Parameters
----------
char_to_idx: dict,
char_to_idx contains character to index mapping for SMILES characters
embedding_dim: int, default 50
Size of character embeddings used.
use_bidir: bool, default True
Whether to use BiDirectional RNN Cells
use_conv: bool, default True
Whether to use a conv-layer
kernel_size: int, default 3
Kernel size for convolutions
filters: int, default 192
Number of filters
strides: int, default 1
Strides used in convolution
rnn_sizes: list[int], default [224, 384]
Number of hidden units in the RNN cells
mode: str, default regression
Whether to use model for regression or classification
"""
self.char_to_idx = char_to_idx
self.n_classes = n_classes
self.max_seq_len = max_seq_len
self.embedding_dim = embedding_dim
self.use_bidir = use_bidir
self.use_conv = use_conv
if use_conv:
self.kernel_size = kernel_size
self.filters = filters
self.strides = strides
self.rnn_types = rnn_types
self.rnn_sizes = rnn_sizes
assert len(rnn_sizes) == len(
rnn_types), "Should have same number of hidden units as RNNs"
self.n_tasks = n_tasks
self.mode = mode
model, loss, output_types = self._build_graph()
super(Smiles2Vec, self).__init__(
model=model, loss=loss, output_types=output_types, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"char_to_idx",
",",
"n_tasks",
"=",
"10",
",",
"max_seq_len",
"=",
"270",
",",
"embedding_dim",
"=",
"50",
",",
"n_classes",
"=",
"2",
",",
"use_bidir",
"=",
"True",
",",
"use_conv",
"=",
"True",
",",
"filters",
"="... | https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/models/chemnet_models.py#L61-L118 | ||
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/sgmllib.py | python | SGMLParser.__init__ | (self, verbose=0) | Initialize and reset this instance. | Initialize and reset this instance. | [
"Initialize",
"and",
"reset",
"this",
"instance",
"."
] | def __init__(self, verbose=0):
"""Initialize and reset this instance."""
self.verbose = verbose
self.reset() | [
"def",
"__init__",
"(",
"self",
",",
"verbose",
"=",
"0",
")",
":",
"self",
".",
"verbose",
"=",
"verbose",
"self",
".",
"reset",
"(",
")"
] | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/sgmllib.py#L66-L69 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pygments/lexers/templates.py | python | HtmlPhpLexer.analyse_text | (text) | return rv | [] | def analyse_text(text):
rv = PhpLexer.analyse_text(text) - 0.01
if html_doctype_matches(text):
rv += 0.5
return rv | [
"def",
"analyse_text",
"(",
"text",
")",
":",
"rv",
"=",
"PhpLexer",
".",
"analyse_text",
"(",
"text",
")",
"-",
"0.01",
"if",
"html_doctype_matches",
"(",
"text",
")",
":",
"rv",
"+=",
"0.5",
"return",
"rv"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/lexers/templates.py#L1120-L1124 | |||
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | ete3/coretype/tree.py | python | TreeNode.get_sisters | (self) | Returns an independent list of sister nodes. | Returns an independent list of sister nodes. | [
"Returns",
"an",
"independent",
"list",
"of",
"sister",
"nodes",
"."
] | def get_sisters(self):
"""
Returns an independent list of sister nodes.
"""
if self.up is not None:
return [ch for ch in self.up.children if ch!=self]
else:
return [] | [
"def",
"get_sisters",
"(",
"self",
")",
":",
"if",
"self",
".",
"up",
"is",
"not",
"None",
":",
"return",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"up",
".",
"children",
"if",
"ch",
"!=",
"self",
"]",
"else",
":",
"return",
"[",
"]"
] | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/coretype/tree.py#L591-L598 | ||
titusjan/argos | 5a9c31a8a9a2ca825bbf821aa1e685740e3682d7 | argos/utils/masks.py | python | nanPercentileOfSubsampledArrayWithMask | (arrayWithMask, percentiles, subsample, *args, **kwargs) | return _maskedNanPercentile(maskedArray, percentiles, *args, **kwargs) | Sub samples the array and then calls maskedNanPercentile on this.
If subsample is False, no sub sampling is done and it just calls maskedNanPercentile | Sub samples the array and then calls maskedNanPercentile on this. | [
"Sub",
"samples",
"the",
"array",
"and",
"then",
"calls",
"maskedNanPercentile",
"on",
"this",
"."
] | def nanPercentileOfSubsampledArrayWithMask(arrayWithMask, percentiles, subsample, *args, **kwargs):
""" Sub samples the array and then calls maskedNanPercentile on this.
If subsample is False, no sub sampling is done and it just calls maskedNanPercentile
"""
check_class(subsample, bool)
check_class(arrayWithMask, ArrayWithMask)
maskedArray = arrayWithMask.asMaskedArray()
if subsample:
maskedArray = _subsampleArray(maskedArray)
return _maskedNanPercentile(maskedArray, percentiles, *args, **kwargs) | [
"def",
"nanPercentileOfSubsampledArrayWithMask",
"(",
"arrayWithMask",
",",
"percentiles",
",",
"subsample",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"check_class",
"(",
"subsample",
",",
"bool",
")",
"check_class",
"(",
"arrayWithMask",
",",
"ArrayW... | https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/utils/masks.py#L255-L268 | |
cooelf/SemBERT | f849452f864b5dd47f94e2911cffc15e9f6a5a2a | run_scorer.py | python | STSProcessor.get_dev_examples | (self, data_dir) | return self._create_examples(
self._read_tsv(os.path.join(data_dir, "dev.tsv_tag")), "dev") | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_dev_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "dev.tsv_tag")), "dev") | [
"def",
"get_dev_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"return",
"self",
".",
"_create_examples",
"(",
"self",
".",
"_read_tsv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"dev.tsv_tag\"",
")",
")",
",",
"\"dev\"",
")"
] | https://github.com/cooelf/SemBERT/blob/f849452f864b5dd47f94e2911cffc15e9f6a5a2a/run_scorer.py#L110-L113 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/runners/reactor.py | python | set_leader | (value=True) | Set the current reactor to act as a leader (responding to events). Defaults to True
CLI Example:
.. code-block:: bash
salt-run reactor.set_leader True | Set the current reactor to act as a leader (responding to events). Defaults to True | [
"Set",
"the",
"current",
"reactor",
"to",
"act",
"as",
"a",
"leader",
"(",
"responding",
"to",
"events",
")",
".",
"Defaults",
"to",
"True"
] | def set_leader(value=True):
"""
Set the current reactor to act as a leader (responding to events). Defaults to True
CLI Example:
.. code-block:: bash
salt-run reactor.set_leader True
"""
if not _reactor_system_available():
raise CommandExecutionError("Reactor system is not running.")
with salt.utils.event.get_event(
"master",
__opts__["sock_dir"],
__opts__["transport"],
opts=__opts__,
listen=True,
) as sevent:
master_key = salt.utils.master.get_master_key("root", __opts__)
__jid_event__.fire_event(
{"id": __opts__["id"], "value": value, "key": master_key},
"salt/reactors/manage/set_leader",
)
res = sevent.get_event(wait=30, tag="salt/reactors/manage/leader/value")
return res["result"] | [
"def",
"set_leader",
"(",
"value",
"=",
"True",
")",
":",
"if",
"not",
"_reactor_system_available",
"(",
")",
":",
"raise",
"CommandExecutionError",
"(",
"\"Reactor system is not running.\"",
")",
"with",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",
"("... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/runners/reactor.py#L170-L199 | ||
nickstenning/honcho | 279ac41dc8a4dfa90d583b3d1c70da4f7ff38ebc | honcho/environ.py | python | expand_processes | (processes, concurrency=None, env=None, quiet=None, port=None) | return out | Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
of `honcho.process.Process`. | Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number. | [
"Get",
"a",
"list",
"of",
"the",
"processes",
"that",
"need",
"to",
"be",
"started",
"given",
"the",
"specified",
"list",
"of",
"process",
"types",
"concurrency",
"environment",
"quietness",
"and",
"base",
"port",
"number",
"."
] | def expand_processes(processes, concurrency=None, env=None, quiet=None, port=None):
"""
Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
of `honcho.process.Process`.
"""
if env is not None and env.get("PORT") is not None:
port = int(env.get("PORT"))
if quiet is None:
quiet = []
con = defaultdict(lambda: 1)
if concurrency is not None:
con.update(concurrency)
out = []
for name, cmd in processes.items():
for i in range(con[name]):
n = "{0}.{1}".format(name, i + 1)
c = cmd
q = name in quiet
e = {'HONCHO_PROCESS_NAME': n}
if env is not None:
e.update(env)
if port is not None:
e['PORT'] = str(port + i)
params = ProcessParams(n, c, q, e)
out.append(params)
if port is not None:
port += 100
return out | [
"def",
"expand_processes",
"(",
"processes",
",",
"concurrency",
"=",
"None",
",",
"env",
"=",
"None",
",",
"quiet",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"env",
"is",
"not",
"None",
"and",
"env",
".",
"get",
"(",
"\"PORT\"",
")",
... | https://github.com/nickstenning/honcho/blob/279ac41dc8a4dfa90d583b3d1c70da4f7ff38ebc/honcho/environ.py#L88-L126 | |
zopefoundation/Zope | ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb | src/Products/PageTemplates/PageTemplateFile.py | python | PageTemplateFile._prepare_html | (self, text) | return text, type_ | [] | def _prepare_html(self, text):
match = meta_pattern.search(text)
if match is not None:
type_, encoding = (x.decode(self.encoding) for x in match.groups())
# TODO: Shouldn't <meta>/<?xml?> stripping
# be in PageTemplate.__call__()?
text = meta_pattern.sub(b"", text)
else:
type_ = None
encoding = self.encoding
text = text.decode(encoding)
return text, type_ | [
"def",
"_prepare_html",
"(",
"self",
",",
"text",
")",
":",
"match",
"=",
"meta_pattern",
".",
"search",
"(",
"text",
")",
"if",
"match",
"is",
"not",
"None",
":",
"type_",
",",
"encoding",
"=",
"(",
"x",
".",
"decode",
"(",
"self",
".",
"encoding",
... | https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/Products/PageTemplates/PageTemplateFile.py#L173-L184 | |||
bokeh/bokeh | a00e59da76beb7b9f83613533cfd3aced1df5f06 | bokeh/events.py | python | Event.decode_json | (cls, dct: EventJson) | return event | Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError, if the event_name is unknown
Examples:
.. code-block:: python
>>> import json
>>> from bokeh.events import Event
>>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}'
>>> json.loads(data, object_hook=Event.decode_json)
<bokeh.events.Pan object at 0x1040f84a8> | Custom JSON decoder for Events. | [
"Custom",
"JSON",
"decoder",
"for",
"Events",
"."
] | def decode_json(cls, dct: EventJson) -> Event:
''' Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError, if the event_name is unknown
Examples:
.. code-block:: python
>>> import json
>>> from bokeh.events import Event
>>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}'
>>> json.loads(data, object_hook=Event.decode_json)
<bokeh.events.Pan object at 0x1040f84a8>
'''
if not ('event_name' in dct and 'event_values' in dct):
return dct
event_name = dct['event_name']
if event_name not in _CONCRETE_EVENT_CLASSES:
raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name)
event_values = dct['event_values']
model_id = event_values.pop('model', {"id": None})["id"]
event_cls = _CONCRETE_EVENT_CLASSES[event_name]
if issubclass(event_cls, ModelEvent):
event = event_cls(model=None, **event_values)
event._model_id = model_id
else:
event = event_cls(**event_values)
return event | [
"def",
"decode_json",
"(",
"cls",
",",
"dct",
":",
"EventJson",
")",
"->",
"Event",
":",
"if",
"not",
"(",
"'event_name'",
"in",
"dct",
"and",
"'event_values'",
"in",
"dct",
")",
":",
"return",
"dct",
"event_name",
"=",
"dct",
"[",
"'event_name'",
"]",
... | https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/events.py#L152-L192 | |
quartiq/rayopt | 3890c72b8f56253bdce309b0fe42beda91c6d3e0 | rayopt/simplex.py | python | simplex_iter | (d, m) | Yield index tuples covering the m-scaled d+1 simplex (
d+1 cube corner N^d with edge length m - 1. | Yield index tuples covering the m-scaled d+1 simplex (
d+1 cube corner N^d with edge length m - 1. | [
"Yield",
"index",
"tuples",
"covering",
"the",
"m",
"-",
"scaled",
"d",
"+",
"1",
"simplex",
"(",
"d",
"+",
"1",
"cube",
"corner",
"N^d",
"with",
"edge",
"length",
"m",
"-",
"1",
"."
] | def simplex_iter(d, m):
"""Yield index tuples covering the m-scaled d+1 simplex (
d+1 cube corner N^d with edge length m - 1."""
if d == 0:
yield ()
else:
for i in range(m):
for j in simplex_iter(d - 1, i + 1):
yield (i - sum(j),) + j | [
"def",
"simplex_iter",
"(",
"d",
",",
"m",
")",
":",
"if",
"d",
"==",
"0",
":",
"yield",
"(",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"m",
")",
":",
"for",
"j",
"in",
"simplex_iter",
"(",
"d",
"-",
"1",
",",
"i",
"+",
"1",
")",
... | https://github.com/quartiq/rayopt/blob/3890c72b8f56253bdce309b0fe42beda91c6d3e0/rayopt/simplex.py#L53-L61 | ||
YunoHost/yunohost | 08efbbb9045eaed8e64d3dfc3f5e22e6ac0b5ecd | src/yunohost/backup.py | python | BackupMethod.method_name | (self) | Return the string name of a BackupMethod (eg "tar" or "copy") | Return the string name of a BackupMethod (eg "tar" or "copy") | [
"Return",
"the",
"string",
"name",
"of",
"a",
"BackupMethod",
"(",
"eg",
"tar",
"or",
"copy",
")"
] | def method_name(self):
"""Return the string name of a BackupMethod (eg "tar" or "copy")"""
raise YunohostError("backup_abstract_method") | [
"def",
"method_name",
"(",
"self",
")",
":",
"raise",
"YunohostError",
"(",
"\"backup_abstract_method\"",
")"
] | https://github.com/YunoHost/yunohost/blob/08efbbb9045eaed8e64d3dfc3f5e22e6ac0b5ecd/src/yunohost/backup.py#L1653-L1655 | ||
nelson-liu/paraphrase-id-tensorflow | 108e461dea0dd148464e985e47ac5c6c11818fcb | duplicate_questions/data/data_manager.py | python | DataManager.get_validation_data_from_file | (self, filenames, max_instances=None,
max_lengths=None, pad=True, mode="word") | return _get_validation_data_generator, validation_dataset_size | Given a filename or list of filenames, return a generator for producing
individual instances of data ready for use as validation data in a
model read from those file(s).
Given a string path to a file in the format accepted by the instance,
we use a data_indexer previously fitted on train data. Next, we use
this DataIndexer to convert the instance into IndexedInstances
(replacing words with integer indices).
This function returns a function to construct generators that take
these IndexedInstances, pads them to the appropriate lengths (either the
maximum lengths in the dataset, or lengths specified in the constructor),
and then converts them to NumPy arrays suitable for training with
instance.as_validation_data. The generator yields one instance at a time,
represented as tuples of (inputs, labels).
Parameters
----------
filenames: List[str]
A collection of filenames to read the specific self.instance_type
from, line by line.
max_instances: int, default=None
If not None, the maximum number of instances to produce as
training data. If necessary, we will truncate the dataset.
Useful for debugging and making sure things work with small
amounts of data.
max_lengths: dict from str to int, default=None
If not None, the max length of a sequence in a given dimension.
The keys for this dict must be in the same format as
the instances' get_lengths() function. These are the lengths
that the instances are padded or truncated to.
pad: boolean, default=True
If True, pads or truncates the instances to either the input
max_lengths or max_lengths used on the train filenames. If False,
no padding or truncation is applied.
mode: str, optional (default="word")
String describing whether to return the word-level representations,
character-level representations, or both. One of "word",
"character", or "word+character"
Returns
-------
output: returns a function to construct a validation data generator
This returns a function that can be called to produce a tuple of
(instance generator, validation_set_size). The instance generator
outputs instances as generated by the as_validation_data function
of the underlying instance class. The validation_set_size is the number
of instances in the validation set, which can be used to initialize a
progress bar. | Given a filename or list of filenames, return a generator for producing
individual instances of data ready for use as validation data in a
model read from those file(s). | [
"Given",
"a",
"filename",
"or",
"list",
"of",
"filenames",
"return",
"a",
"generator",
"for",
"producing",
"individual",
"instances",
"of",
"data",
"ready",
"for",
"use",
"as",
"validation",
"data",
"in",
"a",
"model",
"read",
"from",
"those",
"file",
"(",
... | def get_validation_data_from_file(self, filenames, max_instances=None,
max_lengths=None, pad=True, mode="word"):
"""
Given a filename or list of filenames, return a generator for producing
individual instances of data ready for use as validation data in a
model read from those file(s).
Given a string path to a file in the format accepted by the instance,
we use a data_indexer previously fitted on train data. Next, we use
this DataIndexer to convert the instance into IndexedInstances
(replacing words with integer indices).
This function returns a function to construct generators that take
these IndexedInstances, pads them to the appropriate lengths (either the
maximum lengths in the dataset, or lengths specified in the constructor),
and then converts them to NumPy arrays suitable for training with
instance.as_validation_data. The generator yields one instance at a time,
represented as tuples of (inputs, labels).
Parameters
----------
filenames: List[str]
A collection of filenames to read the specific self.instance_type
from, line by line.
max_instances: int, default=None
If not None, the maximum number of instances to produce as
training data. If necessary, we will truncate the dataset.
Useful for debugging and making sure things work with small
amounts of data.
max_lengths: dict from str to int, default=None
If not None, the max length of a sequence in a given dimension.
The keys for this dict must be in the same format as
the instances' get_lengths() function. These are the lengths
that the instances are padded or truncated to.
pad: boolean, default=True
If True, pads or truncates the instances to either the input
max_lengths or max_lengths used on the train filenames. If False,
no padding or truncation is applied.
mode: str, optional (default="word")
String describing whether to return the word-level representations,
character-level representations, or both. One of "word",
"character", or "word+character"
Returns
-------
output: returns a function to construct a validation data generator
This returns a function that can be called to produce a tuple of
(instance generator, validation_set_size). The instance generator
outputs instances as generated by the as_validation_data function
of the underlying instance class. The validation_set_size is the number
of instances in the validation set, which can be used to initialize a
progress bar.
"""
logger.info("Getting validation data from {}".format(filenames))
validation_dataset = TextDataset.read_from_file(filenames,
self.instance_type)
if max_instances:
logger.info("Truncating the validation dataset "
"to {} instances".format(max_instances))
validation_dataset = validation_dataset.truncate(max_instances)
validation_dataset_size = len(validation_dataset.instances)
# With our fitted data indexer, we we convert the dataset
# from string tokens to numeric int indices.
logger.info("Indexing validation dataset with "
"DataIndexer fit on train data.")
indexed_validation_dataset = validation_dataset.to_indexed_dataset(
self.data_indexer)
# We now need to check if the user specified max_lengths for
# the instance, and accordingly truncate or pad if applicable. If
# max_lengths is None for a given string key, we assume that no
# truncation is to be done and the max lengths should be taken from
# the train dataset.
if not pad and max_lengths:
raise ValueError("Passed in max_lengths {}, but set pad to false. "
"Did you mean to do this?".format(max_lengths))
if pad:
# Get max lengths from the train dataset
training_data_max_lengths = self.training_data_max_lengths
logger.info("Max lengths in training "
"data: {}".format(training_data_max_lengths))
max_lengths_to_use = training_data_max_lengths
# If the user set max lengths, iterate over the
# dictionary provided and verify that they did not
# pass any keys to truncate that are not in the instance.
if max_lengths is not None:
for input_dimension, length in max_lengths.items():
if input_dimension in training_data_max_lengths:
max_lengths_to_use[input_dimension] = length
else:
raise ValueError("Passed a value for the max_lengths "
"that does not exist in the "
"instance. Improper input length "
"dimension (key) we found was {}, "
"lengths dimensions in the instance "
"are {}".format(
input_dimension,
training_data_max_lengths.keys()))
logger.info("Padding lengths to "
"length: {}".format(str(max_lengths_to_use)))
# This is a hack to get the function to run the code above immediately,
# instead of doing the standard python generator lazy-ish evaluation.
# This is necessary to set the class variables ASAP.
def _get_validation_data_generator():
for indexed_val_instance in indexed_validation_dataset.instances:
# For each instance, we want to pad or truncate if applicable
if pad:
indexed_val_instance.pad(max_lengths_to_use)
# Now, we want to take the instance and convert it into
# NumPy arrays suitable for validation.
inputs, labels = indexed_val_instance.as_training_data(mode=mode)
yield inputs, labels
return _get_validation_data_generator, validation_dataset_size | [
"def",
"get_validation_data_from_file",
"(",
"self",
",",
"filenames",
",",
"max_instances",
"=",
"None",
",",
"max_lengths",
"=",
"None",
",",
"pad",
"=",
"True",
",",
"mode",
"=",
"\"word\"",
")",
":",
"logger",
".",
"info",
"(",
"\"Getting validation data f... | https://github.com/nelson-liu/paraphrase-id-tensorflow/blob/108e461dea0dd148464e985e47ac5c6c11818fcb/duplicate_questions/data/data_manager.py#L209-L330 | |
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py | python | MatrixSVG.__init__ | (self, tricomplex=None) | Initialize. | Initialize. | [
"Initialize",
"."
] | def __init__(self, tricomplex=None):
"Initialize."
self.tricomplex = tricomplex | [
"def",
"__init__",
"(",
"self",
",",
"tricomplex",
"=",
"None",
")",
":",
"self",
".",
"tricomplex",
"=",
"tricomplex"
] | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/svg_reader.py#L549-L551 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/rest/data.py | python | RestData.__init__ | (
self,
hass,
method,
resource,
auth,
headers,
params,
data,
verify_ssl,
timeout=DEFAULT_TIMEOUT,
) | Initialize the data object. | Initialize the data object. | [
"Initialize",
"the",
"data",
"object",
"."
] | def __init__(
self,
hass,
method,
resource,
auth,
headers,
params,
data,
verify_ssl,
timeout=DEFAULT_TIMEOUT,
):
"""Initialize the data object."""
self._hass = hass
self._method = method
self._resource = resource
self._auth = auth
self._headers = headers
self._params = params
self._request_data = data
self._timeout = timeout
self._verify_ssl = verify_ssl
self._async_client = None
self.data = None
self.last_exception = None
self.headers = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"method",
",",
"resource",
",",
"auth",
",",
"headers",
",",
"params",
",",
"data",
",",
"verify_ssl",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/rest/data.py#L17-L42 | ||
jeetsukumaran/DendroPy | 29fd294bf05d890ebf6a8d576c501e471db27ca1 | src/dendropy/utility/container.py | python | ItemAttributeProxyList.__init__ | (self, attr_name, *args) | __init__ calls the list.__init__ with all unnamed args.
``attr_name`` is the name of the attribute or property that should be
returned. | __init__ calls the list.__init__ with all unnamed args. | [
"__init__",
"calls",
"the",
"list",
".",
"__init__",
"with",
"all",
"unnamed",
"args",
"."
] | def __init__(self, attr_name, *args):
"""
__init__ calls the list.__init__ with all unnamed args.
``attr_name`` is the name of the attribute or property that should be
returned.
"""
self.bound_attr_name = attr_name
list.__init__(self, *args) | [
"def",
"__init__",
"(",
"self",
",",
"attr_name",
",",
"*",
"args",
")",
":",
"self",
".",
"bound_attr_name",
"=",
"attr_name",
"list",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/jeetsukumaran/DendroPy/blob/29fd294bf05d890ebf6a8d576c501e471db27ca1/src/dendropy/utility/container.py#L1108-L1116 | ||
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pandas/core/nanops.py | python | nanargmin | (values, axis=None, skipna=True) | return result | Returns -1 in the NA case | Returns -1 in the NA case | [
"Returns",
"-",
"1",
"in",
"the",
"NA",
"case"
] | def nanargmin(values, axis=None, skipna=True):
"""
Returns -1 in the NA case
"""
values, mask, dtype, _ = _get_values(values, skipna, fill_value_typ='+inf',
isfinite=True)
result = values.argmin(axis)
result = _maybe_arg_null_out(result, axis, mask, skipna)
return result | [
"def",
"nanargmin",
"(",
"values",
",",
"axis",
"=",
"None",
",",
"skipna",
"=",
"True",
")",
":",
"values",
",",
"mask",
",",
"dtype",
",",
"_",
"=",
"_get_values",
"(",
"values",
",",
"skipna",
",",
"fill_value_typ",
"=",
"'+inf'",
",",
"isfinite",
... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/nanops.py#L484-L492 | |
wenhuchen/Table-Fact-Checking | b77519177ea663deef68b46617d44086385b6e9f | code/run_BERT.py | python | DataProcessor.get_dev_examples | (self, data_dir) | Gets a collection of `InputExample`s for the dev set. | Gets a collection of `InputExample`s for the dev set. | [
"Gets",
"a",
"collection",
"of",
"InputExample",
"s",
"for",
"the",
"dev",
"set",
"."
] | def get_dev_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the dev set."""
raise NotImplementedError() | [
"def",
"get_dev_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/wenhuchen/Table-Fact-Checking/blob/b77519177ea663deef68b46617d44086385b6e9f/code/run_BERT.py#L87-L89 | ||
GoogleCloudPlatform/PerfKitBenchmarker | 6e3412d7d5e414b8ca30ed5eaf970cef1d919a67 | perfkitbenchmarker/providers/kubernetes/kubernetes_virtual_machine.py | python | KubernetesVirtualMachine.__init__ | (self, vm_spec) | Initialize a Kubernetes virtual machine.
Args:
vm_spec: KubernetesPodSpec object of the vm. | Initialize a Kubernetes virtual machine. | [
"Initialize",
"a",
"Kubernetes",
"virtual",
"machine",
"."
] | def __init__(self, vm_spec):
"""Initialize a Kubernetes virtual machine.
Args:
vm_spec: KubernetesPodSpec object of the vm.
"""
super(KubernetesVirtualMachine, self).__init__(vm_spec)
self.num_scratch_disks = 0
self.name = self.name.replace('_', '-')
self.user_name = FLAGS.username
self.image = self.image or self.DEFAULT_IMAGE
self.resource_limits = vm_spec.resource_limits
self.resource_requests = vm_spec.resource_requests | [
"def",
"__init__",
"(",
"self",
",",
"vm_spec",
")",
":",
"super",
"(",
"KubernetesVirtualMachine",
",",
"self",
")",
".",
"__init__",
"(",
"vm_spec",
")",
"self",
".",
"num_scratch_disks",
"=",
"0",
"self",
".",
"name",
"=",
"self",
".",
"name",
".",
... | https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/providers/kubernetes/kubernetes_virtual_machine.py#L62-L74 | ||
cdr-stats/cdr-stats | 9c4b7868d44024ab4fca24de6f03d64f62d56e26 | cdr_stats/voip_billing/function_def.py | python | prefix_allowed_to_call | (destination_number, voipplan_id) | return True | Check destination number with ban prefix & voip_plan | Check destination number with ban prefix & voip_plan | [
"Check",
"destination",
"number",
"with",
"ban",
"prefix",
"&",
"voip_plan"
] | def prefix_allowed_to_call(destination_number, voipplan_id):
"""
Check destination number with ban prefix & voip_plan
"""
destination_prefix_list = prefix_list_string(destination_number)
# Cache the voipplan_id & banned_prefix query set
cachekey = "banned_prefix_list_%s" % (str(voipplan_id))
banned_prefix_list = cache.get(cachekey)
if banned_prefix_list is None:
banned_prefix_list = banned_prefix_qs(voipplan_id)
cache.set(cachekey, banned_prefix_list, 60)
flag = False
for j in eval(destination_prefix_list):
for i in banned_prefix_list:
# Banned Prefix - VoIP call is not allowed
if i['prefix'] == j:
flag = True
break
# flag is false then calls are not allowed
if flag:
return False
return True | [
"def",
"prefix_allowed_to_call",
"(",
"destination_number",
",",
"voipplan_id",
")",
":",
"destination_prefix_list",
"=",
"prefix_list_string",
"(",
"destination_number",
")",
"# Cache the voipplan_id & banned_prefix query set",
"cachekey",
"=",
"\"banned_prefix_list_%s\"",
"%",
... | https://github.com/cdr-stats/cdr-stats/blob/9c4b7868d44024ab4fca24de6f03d64f62d56e26/cdr_stats/voip_billing/function_def.py#L82-L104 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/modulefinder.py | python | ModuleFinder.replace_paths_in_code | (self, co) | return co.replace(co_consts=tuple(consts), co_filename=new_filename) | [] | def replace_paths_in_code(self, co):
new_filename = original_filename = os.path.normpath(co.co_filename)
for f, r in self.replace_paths:
if original_filename.startswith(f):
new_filename = r + original_filename[len(f):]
break
if self.debug and original_filename not in self.processed_paths:
if new_filename != original_filename:
self.msgout(2, "co_filename %r changed to %r" \
% (original_filename,new_filename,))
else:
self.msgout(2, "co_filename %r remains unchanged" \
% (original_filename,))
self.processed_paths.append(original_filename)
consts = list(co.co_consts)
for i in range(len(consts)):
if isinstance(consts[i], type(co)):
consts[i] = self.replace_paths_in_code(consts[i])
return co.replace(co_consts=tuple(consts), co_filename=new_filename) | [
"def",
"replace_paths_in_code",
"(",
"self",
",",
"co",
")",
":",
"new_filename",
"=",
"original_filename",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"co",
".",
"co_filename",
")",
"for",
"f",
",",
"r",
"in",
"self",
".",
"replace_paths",
":",
"if",
... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/modulefinder.py#L598-L619 | |||
retresco/Spyder | 9a2de6ec4c25d4dc85802305d5675a52c3ebb750 | src/spyder/core/sqlitequeues.py | python | SQLiteMultipleHostUriQueue.all_uris | (self, queue=None) | A generator for iterating over all available urls.
Note: does not return the full uri object, only the url. This will be
used to refill the unique uri filter upon restart. | A generator for iterating over all available urls. | [
"A",
"generator",
"for",
"iterating",
"over",
"all",
"available",
"urls",
"."
] | def all_uris(self, queue=None):
"""
A generator for iterating over all available urls.
Note: does not return the full uri object, only the url. This will be
used to refill the unique uri filter upon restart.
"""
if queue:
self._cursor.execute("""SELECT url FROM queues WHERE queue=?""",
queue)
else:
self._cursor.execute("""SELECT url FROM queues""")
for row in self._cursor:
yield row['url'] | [
"def",
"all_uris",
"(",
"self",
",",
"queue",
"=",
"None",
")",
":",
"if",
"queue",
":",
"self",
".",
"_cursor",
".",
"execute",
"(",
"\"\"\"SELECT url FROM queues WHERE queue=?\"\"\"",
",",
"queue",
")",
"else",
":",
"self",
".",
"_cursor",
".",
"execute",
... | https://github.com/retresco/Spyder/blob/9a2de6ec4c25d4dc85802305d5675a52c3ebb750/src/spyder/core/sqlitequeues.py#L351-L364 | ||
nfvlabs/openmano | b09eabec0a168aeda8adc3ea99f734e45e810205 | openmano/httpserver.py | python | http_delete_scenario_id | (tenant_id, scenario_id) | delete a scenario from database, can use both uuid or name | delete a scenario from database, can use both uuid or name | [
"delete",
"a",
"scenario",
"from",
"database",
"can",
"use",
"both",
"uuid",
"or",
"name"
] | def http_delete_scenario_id(tenant_id, scenario_id):
'''delete a scenario from database, can use both uuid or name'''
#check valid tenant_id
if tenant_id != "any" and not nfvo.check_tenant(mydb, tenant_id):
print "httpserver.http_delete_scenario_id() tenant '%s' not found" % tenant_id
bottle.abort(HTTP_Not_Found, "Tenant '%s' not found" % tenant_id)
return
#obtain data
result, data = mydb.delete_scenario(scenario_id, tenant_id)
if result < 0:
print "http_delete_scenario_id error %d %s" % (-result, data)
bottle.abort(-result, data)
else:
#print json.dumps(data, indent=4)
return format_out({"result":"scenario " + data + " deleted"}) | [
"def",
"http_delete_scenario_id",
"(",
"tenant_id",
",",
"scenario_id",
")",
":",
"#check valid tenant_id",
"if",
"tenant_id",
"!=",
"\"any\"",
"and",
"not",
"nfvo",
".",
"check_tenant",
"(",
"mydb",
",",
"tenant_id",
")",
":",
"print",
"\"httpserver.http_delete_sce... | https://github.com/nfvlabs/openmano/blob/b09eabec0a168aeda8adc3ea99f734e45e810205/openmano/httpserver.py#L935-L949 | ||
bookwyrm-social/bookwyrm | 0c2537e27a2cdbc0136880dfbbf170d5fec72986 | bookwyrm/views/follow.py | python | unfollow | (request) | return redirect(request.headers.get("Referer", "/")) | unfollow a user | unfollow a user | [
"unfollow",
"a",
"user"
] | def unfollow(request):
"""unfollow a user"""
username = request.POST["user"]
to_unfollow = get_user_from_username(request.user, username)
try:
models.UserFollows.objects.get(
user_subject=request.user, user_object=to_unfollow
).delete()
except models.UserFollows.DoesNotExist:
pass
try:
models.UserFollowRequest.objects.get(
user_subject=request.user, user_object=to_unfollow
).delete()
except models.UserFollowRequest.DoesNotExist:
pass
# this is handled with ajax so it shouldn't really matter
return redirect(request.headers.get("Referer", "/")) | [
"def",
"unfollow",
"(",
"request",
")",
":",
"username",
"=",
"request",
".",
"POST",
"[",
"\"user\"",
"]",
"to_unfollow",
"=",
"get_user_from_username",
"(",
"request",
".",
"user",
",",
"username",
")",
"try",
":",
"models",
".",
"UserFollows",
".",
"obj... | https://github.com/bookwyrm-social/bookwyrm/blob/0c2537e27a2cdbc0136880dfbbf170d5fec72986/bookwyrm/views/follow.py#L42-L62 | |
ahmetcemturan/SFACT | 7576e29ba72b33e5058049b77b7b558875542747 | skeinforge_application/skeinforge_plugins/craft_plugins/raft.py | python | getCraftedText | ( fileName, text='', repository=None) | return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) | Raft the file or text. | Raft the file or text. | [
"Raft",
"the",
"file",
"or",
"text",
"."
] | def getCraftedText( fileName, text='', repository=None):
'Raft the file or text.'
return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) | [
"def",
"getCraftedText",
"(",
"fileName",
",",
"text",
"=",
"''",
",",
"repository",
"=",
"None",
")",
":",
"return",
"getCraftedTextFromText",
"(",
"archive",
".",
"getTextIfEmpty",
"(",
"fileName",
",",
"text",
")",
",",
"repository",
")"
] | https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_plugins/craft_plugins/raft.py#L224-L226 | |
semontesdeoca/MNPR | 8acf9862e38b709eba63a978d35cc658754ec9e9 | scripts/mnpr_nFX.py | python | getNodeNames | (fx, idx) | return controlNodes[fx.controlSet][channelIdx] | Get node names of fx operation for procedural effects
Args:
fx (obj): MNPR_FX object
e.g. MNPR_FX("distortion", "Substrate distortion", "controlSetB", [[1, 0, 0, 0]], ["distort", "revert"], ["noise"])
idx (int): index of fx operation in case two operations are found in the same fx object
Returns:
(obj): FxNodes object containing the node names that control each procedural operation | Get node names of fx operation for procedural effects
Args:
fx (obj): MNPR_FX object
e.g. MNPR_FX("distortion", "Substrate distortion", "controlSetB", [[1, 0, 0, 0]], ["distort", "revert"], ["noise"])
idx (int): index of fx operation in case two operations are found in the same fx object | [
"Get",
"node",
"names",
"of",
"fx",
"operation",
"for",
"procedural",
"effects",
"Args",
":",
"fx",
"(",
"obj",
")",
":",
"MNPR_FX",
"object",
"e",
".",
"g",
".",
"MNPR_FX",
"(",
"distortion",
"Substrate",
"distortion",
"controlSetB",
"[[",
"1",
"0",
"0"... | def getNodeNames(fx, idx):
"""
Get node names of fx operation for procedural effects
Args:
fx (obj): MNPR_FX object
e.g. MNPR_FX("distortion", "Substrate distortion", "controlSetB", [[1, 0, 0, 0]], ["distort", "revert"], ["noise"])
idx (int): index of fx operation in case two operations are found in the same fx object
Returns:
(obj): FxNodes object containing the node names that control each procedural operation
"""
# get RGBA channel
channelIdx = 0
for channel in fx.channels[idx]:
if channel:
channelIdx = fx.channels[idx].index(channel)
break
# return node names
return controlNodes[fx.controlSet][channelIdx] | [
"def",
"getNodeNames",
"(",
"fx",
",",
"idx",
")",
":",
"# get RGBA channel",
"channelIdx",
"=",
"0",
"for",
"channel",
"in",
"fx",
".",
"channels",
"[",
"idx",
"]",
":",
"if",
"channel",
":",
"channelIdx",
"=",
"fx",
".",
"channels",
"[",
"idx",
"]",
... | https://github.com/semontesdeoca/MNPR/blob/8acf9862e38b709eba63a978d35cc658754ec9e9/scripts/mnpr_nFX.py#L144-L163 | |
DxCx/plugin.video.9anime | 34358c2f701e5ddf19d3276926374a16f63f7b6a | resources/lib/ui/js2py/es6/babel.py | python | PyJs_anonymous_1_ | (require, module, exports, this, arguments, var=var) | [] | def PyJs_anonymous_1_(require, module, exports, this, arguments, var=var):
var = Scope({u'this':this, u'require':require, u'exports':exports, u'module':module, u'arguments':arguments}, var)
var.registers([u'babel', u'require', u'babelPresetEs2015', u'exports', u'module'])
Js(u'use strict')
var.put(u'babel', var.get(u'require')(Js(u'babel-core')))
var.put(u'babelPresetEs2015', var.get(u'require')(Js(u'babel-preset-es2015')))
var.get(u'Object').put(u'babelPresetEs2015', var.get(u'babelPresetEs2015'))
var.get(u'Object').put(u'babel', var.get(u'babel')) | [
"def",
"PyJs_anonymous_1_",
"(",
"require",
",",
"module",
",",
"exports",
",",
"this",
",",
"arguments",
",",
"var",
"=",
"var",
")",
":",
"var",
"=",
"Scope",
"(",
"{",
"u'this'",
":",
"this",
",",
"u'require'",
":",
"require",
",",
"u'exports'",
":"... | https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/es6/babel.py#L13-L20 | ||||
demisto/content | 5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07 | Packs/Exabeam/Integrations/Exabeam/Exabeam.py | python | contents_append_notable_session_details | (session) | return content | Appends a dictionary of data to the base list
Args:
session: session object
Returns:
A contents list with the relevant notable session details | Appends a dictionary of data to the base list | [
"Appends",
"a",
"dictionary",
"of",
"data",
"to",
"the",
"base",
"list"
] | def contents_append_notable_session_details(session) -> Dict:
"""Appends a dictionary of data to the base list
Args:
session: session object
Returns:
A contents list with the relevant notable session details
"""
content = {
'SessionID': session.get('sessionId'),
'InitialRiskScore': session.get('initialRiskScore'),
'LoginHost': session.get('loginHost'),
'Accounts': session.get('accounts'),
}
return content | [
"def",
"contents_append_notable_session_details",
"(",
"session",
")",
"->",
"Dict",
":",
"content",
"=",
"{",
"'SessionID'",
":",
"session",
".",
"get",
"(",
"'sessionId'",
")",
",",
"'InitialRiskScore'",
":",
"session",
".",
"get",
"(",
"'initialRiskScore'",
"... | https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Exabeam/Integrations/Exabeam/Exabeam.py#L848-L863 | |
h5py/h5py | aa31f03bef99e5807d1d6381e36233325d944279 | h5py/_hl/dataset.py | python | Dataset.fletcher32 | (self) | return 'fletcher32' in self._filters | Fletcher32 filter is present (T/F) | Fletcher32 filter is present (T/F) | [
"Fletcher32",
"filter",
"is",
"present",
"(",
"T",
"/",
"F",
")"
] | def fletcher32(self):
"""Fletcher32 filter is present (T/F)"""
return 'fletcher32' in self._filters | [
"def",
"fletcher32",
"(",
"self",
")",
":",
"return",
"'fletcher32'",
"in",
"self",
".",
"_filters"
] | https://github.com/h5py/h5py/blob/aa31f03bef99e5807d1d6381e36233325d944279/h5py/_hl/dataset.py#L521-L523 | |
thespianpy/Thespian | f35e5a74ae99ee3401eb9fc7757620a1cf043ee2 | examples/multi_system/act3/encoder.py | python | Encoder.encode | (self, rawstr) | return rawstr | Override this method to change the encoding | Override this method to change the encoding | [
"Override",
"this",
"method",
"to",
"change",
"the",
"encoding"
] | def encode(self, rawstr):
"Override this method to change the encoding"
return rawstr | [
"def",
"encode",
"(",
"self",
",",
"rawstr",
")",
":",
"return",
"rawstr"
] | https://github.com/thespianpy/Thespian/blob/f35e5a74ae99ee3401eb9fc7757620a1cf043ee2/examples/multi_system/act3/encoder.py#L34-L36 | |
lixinsu/RCZoo | 37fcb7962fbd4c751c561d4a0c84173881ea8339 | reader/qanet/vector.py | python | vectorize | (ex, model, single_answer=False) | return document, document_char, question, question_char, start, end, ex['id'] | Torchify a single example. | Torchify a single example. | [
"Torchify",
"a",
"single",
"example",
"."
] | def vectorize(ex, model, single_answer=False):
"""Torchify a single example."""
args = model.args
args.word_len = 15
word_dict = model.word_dict
char_dict = model.char_dict
feature_dict = model.feature_dict
# Index words
document = torch.LongTensor([word_dict[w] for w in ex['document']])
question = torch.LongTensor([word_dict[w] for w in ex['question']])
dc = [[char_dict[c] for c in w] for w in ex['document']]
for i in range(len(dc)):
if len(dc[i]) < args.word_len:
dc[i] = dc[i] + [0] * (args.word_len - len(dc[i]))
dc[i] = dc[i][:args.word_len]
document_char = torch.LongTensor(dc)
qc = [[char_dict[c] for c in w] for w in ex['question']]
for i in range(len(qc)):
if len(qc[i]) < args.word_len:
qc[i] = qc[i] + [0] * (args.word_len - len(qc[i]))
qc[i] = qc[i][:args.word_len]
question_char = torch.LongTensor(qc)
# Create extra features vector
if len(feature_dict) > 0:
features = torch.zeros(len(ex['document']), len(feature_dict))
else:
features = None
# f_{exact_match}
if args.use_in_question:
q_words_cased = {w for w in ex['question']}
q_words_uncased = {w.lower() for w in ex['question']}
q_lemma = {w for w in ex['qlemma']} if args.use_lemma else None
for i in range(len(ex['document'])):
if ex['document'][i] in q_words_cased:
features[i][feature_dict['in_question']] = 1.0
if ex['document'][i].lower() in q_words_uncased:
features[i][feature_dict['in_question_uncased']] = 1.0
if q_lemma and ex['lemma'][i] in q_lemma:
features[i][feature_dict['in_question_lemma']] = 1.0
# f_{token} (POS)
if args.use_pos:
for i, w in enumerate(ex['pos']):
f = 'pos=%s' % w
if f in feature_dict:
features[i][feature_dict[f]] = 1.0
# f_{token} (NER)
if args.use_ner:
for i, w in enumerate(ex['ner']):
f = 'ner=%s' % w
if f in feature_dict:
features[i][feature_dict[f]] = 1.0
# f_{token} (TF)
if args.use_tf:
counter = Counter([w.lower() for w in ex['document']])
l = len(ex['document'])
for i, w in enumerate(ex['document']):
features[i][feature_dict['tf']] = counter[w.lower()] * 1.0 / l
# Maybe return without target
start = torch.LongTensor(1).fill_(ex['answers'][0][0])
end = torch.LongTensor(1).fill_(ex['answers'][0][1])
return document, document_char, question, question_char, start, end, ex['id'] | [
"def",
"vectorize",
"(",
"ex",
",",
"model",
",",
"single_answer",
"=",
"False",
")",
":",
"args",
"=",
"model",
".",
"args",
"args",
".",
"word_len",
"=",
"15",
"word_dict",
"=",
"model",
".",
"word_dict",
"char_dict",
"=",
"model",
".",
"char_dict",
... | https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/reader/qanet/vector.py#L13-L83 | |
digidotcom/xbee-python | 0757f4be0017530c205175fbee8f9f61be9614d1 | digi/xbee/packets/socket.py | python | SocketStatePacket.socket_id | (self) | return self.__socket_id | Returns the socket ID.
Returns:
Integer: the socket ID. | Returns the socket ID. | [
"Returns",
"the",
"socket",
"ID",
"."
] | def socket_id(self):
"""
Returns the socket ID.
Returns:
Integer: the socket ID.
"""
return self.__socket_id | [
"def",
"socket_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"__socket_id"
] | https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/packets/socket.py#L3044-L3051 | |
smellslikeml/ActionAI | 8f562ba0ce979e6d82abedb112055e8055937b15 | experimental/person.py | python | PersonTracker.set_pose | (self, pose_dict) | return | Used to encode pose estimates
over a time window | Used to encode pose estimates
over a time window | [
"Used",
"to",
"encode",
"pose",
"estimates",
"over",
"a",
"time",
"window"
] | def set_pose(self, pose_dict):
'''
Used to encode pose estimates
over a time window
'''
self.pose_dict = pose_dict
ft_vec = np.zeros(cfg.pose_vec_dim)
for ky in pose_dict:
idx = cfg.body_idx[ky]
ft_vec[2 * idx: 2 * (idx + 1)] = 2 * (np.array(pose_dict[ky]) - \
np.array(self.centroid)) / \
np.array((self.h, self.w))
self.q.append(ft_vec)
return | [
"def",
"set_pose",
"(",
"self",
",",
"pose_dict",
")",
":",
"self",
".",
"pose_dict",
"=",
"pose_dict",
"ft_vec",
"=",
"np",
".",
"zeros",
"(",
"cfg",
".",
"pose_vec_dim",
")",
"for",
"ky",
"in",
"pose_dict",
":",
"idx",
"=",
"cfg",
".",
"body_idx",
... | https://github.com/smellslikeml/ActionAI/blob/8f562ba0ce979e6d82abedb112055e8055937b15/experimental/person.py#L50-L63 | |
mher/flower | 47a0eb937a1a132a9cb5b2e137d96b93e4cdc89e | setup.py | python | get_package_version | () | returns package version without importing it | returns package version without importing it | [
"returns",
"package",
"version",
"without",
"importing",
"it"
] | def get_package_version():
"returns package version without importing it"
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "flower/__init__.py")) as initf:
for line in initf:
m = version.match(line.strip())
if not m:
continue
return ".".join(m.groups()[0].split(", ")) | [
"def",
"get_package_version",
"(",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"\"flower/__init__.... | https://github.com/mher/flower/blob/47a0eb937a1a132a9cb5b2e137d96b93e4cdc89e/setup.py#L11-L19 | ||
horazont/aioxmpp | c701e6399c90a6bb9bec0349018a03bd7b644cde | aioxmpp/stringprep.py | python | resourceprep | (string, allow_unassigned=False) | return "".join(chars) | Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised. | Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised. | [
"Process",
"the",
"given",
"string",
"using",
"the",
"Resourceprep",
"(",
"RFC",
"6122",
"_",
")",
"profile",
".",
"In",
"the",
"error",
"cases",
"defined",
"in",
"RFC",
"3454",
"_",
"(",
"stringprep",
")",
"a",
":",
"class",
":",
"ValueError",
"is",
"... | def resourceprep(string, allow_unassigned=False):
"""
Process the given `string` using the Resourceprep (`RFC 6122`_) profile. In
the error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError`
is raised.
"""
chars = list(string)
_resourceprep_do_mapping(chars)
do_normalization(chars)
check_prohibited_output(
chars,
(
stringprep.in_table_c12,
stringprep.in_table_c21,
stringprep.in_table_c22,
stringprep.in_table_c3,
stringprep.in_table_c4,
stringprep.in_table_c5,
stringprep.in_table_c6,
stringprep.in_table_c7,
stringprep.in_table_c8,
stringprep.in_table_c9,
))
check_bidi(chars)
if not allow_unassigned:
check_unassigned(
chars,
(
stringprep.in_table_a1,
)
)
return "".join(chars) | [
"def",
"resourceprep",
"(",
"string",
",",
"allow_unassigned",
"=",
"False",
")",
":",
"chars",
"=",
"list",
"(",
"string",
")",
"_resourceprep_do_mapping",
"(",
"chars",
")",
"do_normalization",
"(",
"chars",
")",
"check_prohibited_output",
"(",
"chars",
",",
... | https://github.com/horazont/aioxmpp/blob/c701e6399c90a6bb9bec0349018a03bd7b644cde/aioxmpp/stringprep.py#L198-L232 | |
marionette-tg/marionette | bb40a334a18c82728eec01c9b56330bcb91a28da | marionette_tg/dsl.py | python | t_NULL_KWD | (t) | return t | r'NULL | r'NULL | [
"r",
"NULL"
] | def t_NULL_KWD(t):
r'NULL'
return t | [
"def",
"t_NULL_KWD",
"(",
"t",
")",
":",
"return",
"t"
] | https://github.com/marionette-tg/marionette/blob/bb40a334a18c82728eec01c9b56330bcb91a28da/marionette_tg/dsl.py#L81-L83 | |
Cadene/tensorflow-model-zoo.torch | 990b10ffc22d4c8eacb2a502f20415b4f70c74c2 | models/research/slim/preprocessing/vgg_preprocessing.py | python | _mean_image_subtraction | (image, means) | return tf.concat(axis=2, values=channels) | Subtracts the given means from each image channel.
For example:
means = [123.68, 116.779, 103.939]
image = _mean_image_subtraction(image, means)
Note that the rank of `image` must be known.
Args:
image: a tensor of size [height, width, C].
means: a C-vector of values to subtract from each channel.
Returns:
the centered image.
Raises:
ValueError: If the rank of `image` is unknown, if `image` has a rank other
than three or if the number of channels in `image` doesn't match the
number of values in `means`. | Subtracts the given means from each image channel. | [
"Subtracts",
"the",
"given",
"means",
"from",
"each",
"image",
"channel",
"."
] | def _mean_image_subtraction(image, means):
"""Subtracts the given means from each image channel.
For example:
means = [123.68, 116.779, 103.939]
image = _mean_image_subtraction(image, means)
Note that the rank of `image` must be known.
Args:
image: a tensor of size [height, width, C].
means: a C-vector of values to subtract from each channel.
Returns:
the centered image.
Raises:
ValueError: If the rank of `image` is unknown, if `image` has a rank other
than three or if the number of channels in `image` doesn't match the
number of values in `means`.
"""
if image.get_shape().ndims != 3:
raise ValueError('Input must be of size [height, width, C>0]')
num_channels = image.get_shape().as_list()[-1]
if len(means) != num_channels:
raise ValueError('len(means) must match the number of channels')
channels = tf.split(axis=2, num_or_size_splits=num_channels, value=image)
for i in range(num_channels):
channels[i] -= means[i]
return tf.concat(axis=2, values=channels) | [
"def",
"_mean_image_subtraction",
"(",
"image",
",",
"means",
")",
":",
"if",
"image",
".",
"get_shape",
"(",
")",
".",
"ndims",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'Input must be of size [height, width, C>0]'",
")",
"num_channels",
"=",
"image",
".",
... | https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/slim/preprocessing/vgg_preprocessing.py#L198-L228 | |
hylang/hy | 699640f64a89eb90b470a9d536efbb1ace5cc9ec | hy/compiler.py | python | HyASTCompiler._compile_branch | (self, exprs) | return ret | Make a branch out of an iterable of Result objects
This generates a Result from the given sequence of Results, forcing each
expression context as a statement before the next result is used.
We keep the expression context of the last argument for the returned Result | Make a branch out of an iterable of Result objects | [
"Make",
"a",
"branch",
"out",
"of",
"an",
"iterable",
"of",
"Result",
"objects"
] | def _compile_branch(self, exprs):
"""Make a branch out of an iterable of Result objects
This generates a Result from the given sequence of Results, forcing each
expression context as a statement before the next result is used.
We keep the expression context of the last argument for the returned Result
"""
ret = Result()
for x in map(self.compile, exprs[:-1]):
ret += x
ret += x.expr_as_stmt()
if exprs:
ret += self.compile(exprs[-1])
return ret | [
"def",
"_compile_branch",
"(",
"self",
",",
"exprs",
")",
":",
"ret",
"=",
"Result",
"(",
")",
"for",
"x",
"in",
"map",
"(",
"self",
".",
"compile",
",",
"exprs",
"[",
":",
"-",
"1",
"]",
")",
":",
"ret",
"+=",
"x",
"ret",
"+=",
"x",
".",
"ex... | https://github.com/hylang/hy/blob/699640f64a89eb90b470a9d536efbb1ace5cc9ec/hy/compiler.py#L414-L428 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.