repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
WhyNotHugo/django-afip | django_afip/models.py | ReceiptQuerySet._assign_numbers | def _assign_numbers(self):
"""
Assign numbers in preparation for validating these receipts.
WARNING: Don't call the method manually unless you know what you're
doing!
"""
first = self.select_related('point_of_sales', 'receipt_type').first()
next_num = Receipt.objects.fetch_last_receipt_number(
first.point_of_sales,
first.receipt_type,
) + 1
for receipt in self.filter(receipt_number__isnull=True):
# Atomically update receipt number
Receipt.objects.filter(
pk=receipt.id,
receipt_number__isnull=True,
).update(
receipt_number=next_num,
)
next_num += 1 | python | def _assign_numbers(self):
"""
Assign numbers in preparation for validating these receipts.
WARNING: Don't call the method manually unless you know what you're
doing!
"""
first = self.select_related('point_of_sales', 'receipt_type').first()
next_num = Receipt.objects.fetch_last_receipt_number(
first.point_of_sales,
first.receipt_type,
) + 1
for receipt in self.filter(receipt_number__isnull=True):
# Atomically update receipt number
Receipt.objects.filter(
pk=receipt.id,
receipt_number__isnull=True,
).update(
receipt_number=next_num,
)
next_num += 1 | [
"def",
"_assign_numbers",
"(",
"self",
")",
":",
"first",
"=",
"self",
".",
"select_related",
"(",
"'point_of_sales'",
",",
"'receipt_type'",
")",
".",
"first",
"(",
")",
"next_num",
"=",
"Receipt",
".",
"objects",
".",
"fetch_last_receipt_number",
"(",
"first... | Assign numbers in preparation for validating these receipts.
WARNING: Don't call the method manually unless you know what you're
doing! | [
"Assign",
"numbers",
"in",
"preparation",
"for",
"validating",
"these",
"receipts",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L704-L726 | train | 47,500 |
WhyNotHugo/django-afip | django_afip/models.py | ReceiptQuerySet.check_groupable | def check_groupable(self):
"""
Checks that all receipts returned by this queryset are groupable.
"Groupable" means that they can be validated together: they have the
same POS and receipt type.
Returns the same queryset is all receipts are groupable, otherwise,
raises :class:`~.CannotValidateTogether`.
"""
types = self.aggregate(
poses=Count('point_of_sales_id', distinct=True),
types=Count('receipt_type', distinct=True),
)
if set(types.values()) > {1}:
raise exceptions.CannotValidateTogether()
return self | python | def check_groupable(self):
"""
Checks that all receipts returned by this queryset are groupable.
"Groupable" means that they can be validated together: they have the
same POS and receipt type.
Returns the same queryset is all receipts are groupable, otherwise,
raises :class:`~.CannotValidateTogether`.
"""
types = self.aggregate(
poses=Count('point_of_sales_id', distinct=True),
types=Count('receipt_type', distinct=True),
)
if set(types.values()) > {1}:
raise exceptions.CannotValidateTogether()
return self | [
"def",
"check_groupable",
"(",
"self",
")",
":",
"types",
"=",
"self",
".",
"aggregate",
"(",
"poses",
"=",
"Count",
"(",
"'point_of_sales_id'",
",",
"distinct",
"=",
"True",
")",
",",
"types",
"=",
"Count",
"(",
"'receipt_type'",
",",
"distinct",
"=",
"... | Checks that all receipts returned by this queryset are groupable.
"Groupable" means that they can be validated together: they have the
same POS and receipt type.
Returns the same queryset is all receipts are groupable, otherwise,
raises :class:`~.CannotValidateTogether`. | [
"Checks",
"that",
"all",
"receipts",
"returned",
"by",
"this",
"queryset",
"are",
"groupable",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L728-L746 | train | 47,501 |
WhyNotHugo/django-afip | django_afip/models.py | ReceiptQuerySet.validate | def validate(self, ticket=None):
"""
Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
queryset are validated properly. Obviously, only successfully validated
receipts will be updated.
Returns a list of errors as returned from AFIP's webservices. An
exception is not raised because partial failures are possible.
Receipts that succesfully validate will have a
:class:`~.ReceiptValidation` object attatched to them with a validation
date and CAE information.
Already-validated receipts are ignored.
Attempting to validate an empty queryset will simply return an empty
list.
"""
# Skip any already-validated ones:
qs = self.filter(validation__isnull=True).check_groupable()
if qs.count() == 0:
return []
qs.order_by('issued_date', 'id')._assign_numbers()
return qs._validate(ticket) | python | def validate(self, ticket=None):
"""
Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
queryset are validated properly. Obviously, only successfully validated
receipts will be updated.
Returns a list of errors as returned from AFIP's webservices. An
exception is not raised because partial failures are possible.
Receipts that succesfully validate will have a
:class:`~.ReceiptValidation` object attatched to them with a validation
date and CAE information.
Already-validated receipts are ignored.
Attempting to validate an empty queryset will simply return an empty
list.
"""
# Skip any already-validated ones:
qs = self.filter(validation__isnull=True).check_groupable()
if qs.count() == 0:
return []
qs.order_by('issued_date', 'id')._assign_numbers()
return qs._validate(ticket) | [
"def",
"validate",
"(",
"self",
",",
"ticket",
"=",
"None",
")",
":",
"# Skip any already-validated ones:",
"qs",
"=",
"self",
".",
"filter",
"(",
"validation__isnull",
"=",
"True",
")",
".",
"check_groupable",
"(",
")",
"if",
"qs",
".",
"count",
"(",
")",... | Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
queryset are validated properly. Obviously, only successfully validated
receipts will be updated.
Returns a list of errors as returned from AFIP's webservices. An
exception is not raised because partial failures are possible.
Receipts that succesfully validate will have a
:class:`~.ReceiptValidation` object attatched to them with a validation
date and CAE information.
Already-validated receipts are ignored.
Attempting to validate an empty queryset will simply return an empty
list. | [
"Validates",
"all",
"receipts",
"matching",
"this",
"queryset",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L748-L777 | train | 47,502 |
WhyNotHugo/django-afip | django_afip/models.py | ReceiptManager.fetch_last_receipt_number | def fetch_last_receipt_number(self, point_of_sales, receipt_type):
"""Returns the number for the last validated receipt."""
client = clients.get_client('wsfe', point_of_sales.owner.is_sandboxed)
response_xml = client.service.FECompUltimoAutorizado(
serializers.serialize_ticket(
point_of_sales.owner.get_or_create_ticket('wsfe')
),
point_of_sales.number,
receipt_type.code,
)
check_response(response_xml)
# TODO XXX: Error handling
# (FERecuperaLastCbteResponse){
# PtoVta = 0
# CbteTipo = 0
# CbteNro = 0
# Errors =
# (ArrayOfErr){
# Err[] =
# (Err){
# Code = 601
# Msg = "CUIT representada no incluida en Token"
# },
# }
# }
return response_xml.CbteNro | python | def fetch_last_receipt_number(self, point_of_sales, receipt_type):
"""Returns the number for the last validated receipt."""
client = clients.get_client('wsfe', point_of_sales.owner.is_sandboxed)
response_xml = client.service.FECompUltimoAutorizado(
serializers.serialize_ticket(
point_of_sales.owner.get_or_create_ticket('wsfe')
),
point_of_sales.number,
receipt_type.code,
)
check_response(response_xml)
# TODO XXX: Error handling
# (FERecuperaLastCbteResponse){
# PtoVta = 0
# CbteTipo = 0
# CbteNro = 0
# Errors =
# (ArrayOfErr){
# Err[] =
# (Err){
# Code = 601
# Msg = "CUIT representada no incluida en Token"
# },
# }
# }
return response_xml.CbteNro | [
"def",
"fetch_last_receipt_number",
"(",
"self",
",",
"point_of_sales",
",",
"receipt_type",
")",
":",
"client",
"=",
"clients",
".",
"get_client",
"(",
"'wsfe'",
",",
"point_of_sales",
".",
"owner",
".",
"is_sandboxed",
")",
"response_xml",
"=",
"client",
".",
... | Returns the number for the last validated receipt. | [
"Returns",
"the",
"number",
"for",
"the",
"last",
"validated",
"receipt",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L836-L863 | train | 47,503 |
WhyNotHugo/django-afip | django_afip/models.py | Receipt.total_vat | def total_vat(self):
"""Returns the sum of all Vat objects."""
q = Vat.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | python | def total_vat(self):
"""Returns the sum of all Vat objects."""
q = Vat.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | [
"def",
"total_vat",
"(",
"self",
")",
":",
"q",
"=",
"Vat",
".",
"objects",
".",
"filter",
"(",
"receipt",
"=",
"self",
")",
".",
"aggregate",
"(",
"total",
"=",
"Sum",
"(",
"'amount'",
")",
")",
"return",
"q",
"[",
"'total'",
"]",
"or",
"0"
] | Returns the sum of all Vat objects. | [
"Returns",
"the",
"sum",
"of",
"all",
"Vat",
"objects",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1031-L1034 | train | 47,504 |
WhyNotHugo/django-afip | django_afip/models.py | Receipt.total_tax | def total_tax(self):
"""Returns the sum of all Tax objects."""
q = Tax.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | python | def total_tax(self):
"""Returns the sum of all Tax objects."""
q = Tax.objects.filter(receipt=self).aggregate(total=Sum('amount'))
return q['total'] or 0 | [
"def",
"total_tax",
"(",
"self",
")",
":",
"q",
"=",
"Tax",
".",
"objects",
".",
"filter",
"(",
"receipt",
"=",
"self",
")",
".",
"aggregate",
"(",
"total",
"=",
"Sum",
"(",
"'amount'",
")",
")",
"return",
"q",
"[",
"'total'",
"]",
"or",
"0"
] | Returns the sum of all Tax objects. | [
"Returns",
"the",
"sum",
"of",
"all",
"Tax",
"objects",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1037-L1040 | train | 47,505 |
WhyNotHugo/django-afip | django_afip/models.py | Receipt.is_validated | def is_validated(self):
"""
Returns True if this instance is validated.
Note that resolving this property requires a DB query, so if you've a
very large amount of receipts you should prefetch (see django's
``select_related``) the ``validation`` field. Even so, a DB query *may*
be triggered.
If you need a large list of validated receipts, you should actually
filter them via a QuerySet::
Receipt.objects.filter(validation__result==RESULT_APPROVED)
:rtype: bool
"""
# Avoid the DB lookup if possible:
if not self.receipt_number:
return False
try:
return self.validation.result == ReceiptValidation.RESULT_APPROVED
except ReceiptValidation.DoesNotExist:
return False | python | def is_validated(self):
"""
Returns True if this instance is validated.
Note that resolving this property requires a DB query, so if you've a
very large amount of receipts you should prefetch (see django's
``select_related``) the ``validation`` field. Even so, a DB query *may*
be triggered.
If you need a large list of validated receipts, you should actually
filter them via a QuerySet::
Receipt.objects.filter(validation__result==RESULT_APPROVED)
:rtype: bool
"""
# Avoid the DB lookup if possible:
if not self.receipt_number:
return False
try:
return self.validation.result == ReceiptValidation.RESULT_APPROVED
except ReceiptValidation.DoesNotExist:
return False | [
"def",
"is_validated",
"(",
"self",
")",
":",
"# Avoid the DB lookup if possible:",
"if",
"not",
"self",
".",
"receipt_number",
":",
"return",
"False",
"try",
":",
"return",
"self",
".",
"validation",
".",
"result",
"==",
"ReceiptValidation",
".",
"RESULT_APPROVED... | Returns True if this instance is validated.
Note that resolving this property requires a DB query, so if you've a
very large amount of receipts you should prefetch (see django's
``select_related``) the ``validation`` field. Even so, a DB query *may*
be triggered.
If you need a large list of validated receipts, you should actually
filter them via a QuerySet::
Receipt.objects.filter(validation__result==RESULT_APPROVED)
:rtype: bool | [
"Returns",
"True",
"if",
"this",
"instance",
"is",
"validated",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1052-L1075 | train | 47,506 |
WhyNotHugo/django-afip | django_afip/models.py | Receipt.validate | def validate(self, ticket=None, raise_=False):
"""
Validates this receipt.
This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same
name. Calling this validates only this instance.
:param AuthTicket ticket: Use this ticket. If None, one will be loaded
or created automatically.
:param bool raise_: If True, an exception will be raised when
validation fails.
"""
# XXX: Maybe actually have this sortcut raise an exception?
rv = Receipt.objects.filter(pk=self.pk).validate(ticket)
# Since we're operating via a queryset, this instance isn't properly
# updated:
self.refresh_from_db()
if raise_ and rv:
raise exceptions.ValidationError(rv[0])
return rv | python | def validate(self, ticket=None, raise_=False):
"""
Validates this receipt.
This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same
name. Calling this validates only this instance.
:param AuthTicket ticket: Use this ticket. If None, one will be loaded
or created automatically.
:param bool raise_: If True, an exception will be raised when
validation fails.
"""
# XXX: Maybe actually have this sortcut raise an exception?
rv = Receipt.objects.filter(pk=self.pk).validate(ticket)
# Since we're operating via a queryset, this instance isn't properly
# updated:
self.refresh_from_db()
if raise_ and rv:
raise exceptions.ValidationError(rv[0])
return rv | [
"def",
"validate",
"(",
"self",
",",
"ticket",
"=",
"None",
",",
"raise_",
"=",
"False",
")",
":",
"# XXX: Maybe actually have this sortcut raise an exception?",
"rv",
"=",
"Receipt",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"."... | Validates this receipt.
This is a shortcut to :class:`~.ReceiptQuerySet`'s method of the same
name. Calling this validates only this instance.
:param AuthTicket ticket: Use this ticket. If None, one will be loaded
or created automatically.
:param bool raise_: If True, an exception will be raised when
validation fails. | [
"Validates",
"this",
"receipt",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1077-L1096 | train | 47,507 |
WhyNotHugo/django-afip | django_afip/models.py | ReceiptPDFManager.create_for_receipt | def create_for_receipt(self, receipt, **kwargs):
"""
Creates a ReceiptPDF object for a given receipt. Does not actually
generate the related PDF file.
All attributes will be completed with the information for the relevant
``TaxPayerProfile`` instance.
:param Receipt receipt: The receipt for the PDF which will be
generated.
"""
try:
profile = TaxPayerProfile.objects.get(
taxpayer__points_of_sales__receipts=receipt,
)
except TaxPayerProfile.DoesNotExist:
raise exceptions.DjangoAfipException(
'Cannot generate a PDF for taxpayer with no profile',
)
pdf = ReceiptPDF.objects.create(
receipt=receipt,
issuing_name=profile.issuing_name,
issuing_address=profile.issuing_address,
issuing_email=profile.issuing_email,
vat_condition=profile.vat_condition,
gross_income_condition=profile.gross_income_condition,
sales_terms=profile.sales_terms,
**kwargs
)
return pdf | python | def create_for_receipt(self, receipt, **kwargs):
"""
Creates a ReceiptPDF object for a given receipt. Does not actually
generate the related PDF file.
All attributes will be completed with the information for the relevant
``TaxPayerProfile`` instance.
:param Receipt receipt: The receipt for the PDF which will be
generated.
"""
try:
profile = TaxPayerProfile.objects.get(
taxpayer__points_of_sales__receipts=receipt,
)
except TaxPayerProfile.DoesNotExist:
raise exceptions.DjangoAfipException(
'Cannot generate a PDF for taxpayer with no profile',
)
pdf = ReceiptPDF.objects.create(
receipt=receipt,
issuing_name=profile.issuing_name,
issuing_address=profile.issuing_address,
issuing_email=profile.issuing_email,
vat_condition=profile.vat_condition,
gross_income_condition=profile.gross_income_condition,
sales_terms=profile.sales_terms,
**kwargs
)
return pdf | [
"def",
"create_for_receipt",
"(",
"self",
",",
"receipt",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"profile",
"=",
"TaxPayerProfile",
".",
"objects",
".",
"get",
"(",
"taxpayer__points_of_sales__receipts",
"=",
"receipt",
",",
")",
"except",
"TaxPayerPro... | Creates a ReceiptPDF object for a given receipt. Does not actually
generate the related PDF file.
All attributes will be completed with the information for the relevant
``TaxPayerProfile`` instance.
:param Receipt receipt: The receipt for the PDF which will be
generated. | [
"Creates",
"a",
"ReceiptPDF",
"object",
"for",
"a",
"given",
"receipt",
".",
"Does",
"not",
"actually",
"generate",
"the",
"related",
"PDF",
"file",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1124-L1153 | train | 47,508 |
WhyNotHugo/django-afip | django_afip/models.py | ReceiptPDF.save_pdf | def save_pdf(self, save_model=True):
"""
Save the receipt as a PDF related to this model.
The related :class:`~.Receipt` should be validated first, of course.
:param bool save_model: If True, immediately save this model instance.
"""
from django_afip.views import ReceiptPDFView
if not self.receipt.is_validated:
raise exceptions.DjangoAfipException(
_('Cannot generate pdf for non-authorized receipt')
)
self.pdf_file = File(BytesIO(), name='{}.pdf'.format(uuid.uuid4().hex))
render_pdf(
template='receipts/code_{}.html'.format(
self.receipt.receipt_type.code,
),
file_=self.pdf_file,
context=ReceiptPDFView.get_context_for_pk(self.receipt_id),
)
if save_model:
self.save() | python | def save_pdf(self, save_model=True):
"""
Save the receipt as a PDF related to this model.
The related :class:`~.Receipt` should be validated first, of course.
:param bool save_model: If True, immediately save this model instance.
"""
from django_afip.views import ReceiptPDFView
if not self.receipt.is_validated:
raise exceptions.DjangoAfipException(
_('Cannot generate pdf for non-authorized receipt')
)
self.pdf_file = File(BytesIO(), name='{}.pdf'.format(uuid.uuid4().hex))
render_pdf(
template='receipts/code_{}.html'.format(
self.receipt.receipt_type.code,
),
file_=self.pdf_file,
context=ReceiptPDFView.get_context_for_pk(self.receipt_id),
)
if save_model:
self.save() | [
"def",
"save_pdf",
"(",
"self",
",",
"save_model",
"=",
"True",
")",
":",
"from",
"django_afip",
".",
"views",
"import",
"ReceiptPDFView",
"if",
"not",
"self",
".",
"receipt",
".",
"is_validated",
":",
"raise",
"exceptions",
".",
"DjangoAfipException",
"(",
... | Save the receipt as a PDF related to this model.
The related :class:`~.Receipt` should be validated first, of course.
:param bool save_model: If True, immediately save this model instance. | [
"Save",
"the",
"receipt",
"as",
"a",
"PDF",
"related",
"to",
"this",
"model",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1230-L1255 | train | 47,509 |
WhyNotHugo/django-afip | django_afip/models.py | Tax.compute_amount | def compute_amount(self):
"""Auto-assign and return the total amount for this tax."""
self.amount = self.base_amount * self.aliquot / 100
return self.amount | python | def compute_amount(self):
"""Auto-assign and return the total amount for this tax."""
self.amount = self.base_amount * self.aliquot / 100
return self.amount | [
"def",
"compute_amount",
"(",
"self",
")",
":",
"self",
".",
"amount",
"=",
"self",
".",
"base_amount",
"*",
"self",
".",
"aliquot",
"/",
"100",
"return",
"self",
".",
"amount"
] | Auto-assign and return the total amount for this tax. | [
"Auto",
"-",
"assign",
"and",
"return",
"the",
"total",
"amount",
"for",
"this",
"tax",
"."
] | 5fb73213f1fe86ca52b501ffd0737911ef26ddb3 | https://github.com/WhyNotHugo/django-afip/blob/5fb73213f1fe86ca52b501ffd0737911ef26ddb3/django_afip/models.py#L1348-L1351 | train | 47,510 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/eps_randomwalk/transition.py | get_label_based_random_walk_matrix | def get_label_based_random_walk_matrix(adjacency_matrix, labelled_nodes, label_absorption_probability):
"""
Returns the label-absorbing random walk transition probability matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
"""
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
# Form the inverse of the diagonal matrix containing the out-degree
for i in np.arange(rw_transition.shape[0]):
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]] =\
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]]/out_degree[i]
out_degree = np.array(out_degree).astype(np.float64).reshape(out_degree.size)
in_degree = np.array(in_degree).astype(np.float64).reshape(in_degree.size)
# When the random walk agent encounters a labelled node, there is a probability that it will be absorbed.
diag = np.zeros_like(out_degree)
diag[labelled_nodes] = 1.0
diag = sparse.dia_matrix((diag, [0]), shape=(in_degree.size, in_degree.size))
diag = sparse.csr_matrix(diag)
rw_transition[labelled_nodes, :] = (1-label_absorption_probability)*rw_transition[labelled_nodes, :] + label_absorption_probability*diag[labelled_nodes, :]
return rw_transition, out_degree, in_degree | python | def get_label_based_random_walk_matrix(adjacency_matrix, labelled_nodes, label_absorption_probability):
"""
Returns the label-absorbing random walk transition probability matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
"""
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
# Form the inverse of the diagonal matrix containing the out-degree
for i in np.arange(rw_transition.shape[0]):
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]] =\
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]]/out_degree[i]
out_degree = np.array(out_degree).astype(np.float64).reshape(out_degree.size)
in_degree = np.array(in_degree).astype(np.float64).reshape(in_degree.size)
# When the random walk agent encounters a labelled node, there is a probability that it will be absorbed.
diag = np.zeros_like(out_degree)
diag[labelled_nodes] = 1.0
diag = sparse.dia_matrix((diag, [0]), shape=(in_degree.size, in_degree.size))
diag = sparse.csr_matrix(diag)
rw_transition[labelled_nodes, :] = (1-label_absorption_probability)*rw_transition[labelled_nodes, :] + label_absorption_probability*diag[labelled_nodes, :]
return rw_transition, out_degree, in_degree | [
"def",
"get_label_based_random_walk_matrix",
"(",
"adjacency_matrix",
",",
"labelled_nodes",
",",
"label_absorption_probability",
")",
":",
"# Turn to sparse.csr_matrix format for faster row access.",
"rw_transition",
"=",
"sparse",
".",
"csr_matrix",
"(",
"adjacency_matrix",
","... | Returns the label-absorbing random walk transition probability matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix. | [
"Returns",
"the",
"label",
"-",
"absorbing",
"random",
"walk",
"transition",
"probability",
"matrix",
"."
] | eda862687aa5a64b79c6b12de1b4dca6ce986dc8 | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/transition.py#L9-L40 | train | 47,511 |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/eps_randomwalk/transition.py | get_natural_random_walk_matrix | def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False):
"""
Returns the natural random walk transition probability matrix given the adjacency matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
"""
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64, copy=True)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
out_degree[out_degree == 0.0] = 1.0
# Form the inverse of the diagonal matrix containing the out-degree
for i in np.arange(rw_transition.shape[0]):
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]] =\
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]]/out_degree[i]
rw_transition.sort_indices()
out_degree = np.array(out_degree).astype(np.float64).reshape(out_degree.size)
in_degree = np.array(in_degree).astype(np.float64).reshape(in_degree.size)
if make_shared:
number_of_nodes = adjacency_matrix.shape[0]
out_degree_c = mp.Array(c.c_double, number_of_nodes)
in_degree_c = mp.Array(c.c_double, number_of_nodes)
out_degree_shared = np.frombuffer(out_degree_c.get_obj(), dtype=np.float64, count=number_of_nodes)
in_degree_shared = np.frombuffer(in_degree_c.get_obj(), dtype=np.float64, count=number_of_nodes)
out_degree_shared[:] = out_degree[:]
in_degree_shared[:] = in_degree[:]
indices_c = mp.Array(c.c_int64, rw_transition.indices.size)
indptr_c = mp.Array(c.c_int64, rw_transition.indptr.size)
data_c = mp.Array(c.c_double, rw_transition.data.size)
indices_shared = np.frombuffer(indices_c.get_obj(), dtype=np.int64, count=rw_transition.indices.size)
indptr_shared = np.frombuffer(indptr_c.get_obj(), dtype=np.int64, count=rw_transition.indptr.size)
data_shared = np.frombuffer(data_c.get_obj(), dtype=np.float64, count=rw_transition.data.size)
indices_shared[:] = rw_transition.indices[:]
indptr_shared[:] = rw_transition.indptr[:]
data_shared[:] = rw_transition.data[:]
rw_transition = sparse.csr_matrix((data_shared,
indices_shared,
indptr_shared),
shape=rw_transition.shape)
return rw_transition, out_degree, in_degree | python | def get_natural_random_walk_matrix(adjacency_matrix, make_shared=False):
"""
Returns the natural random walk transition probability matrix given the adjacency matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix.
"""
# Turn to sparse.csr_matrix format for faster row access.
rw_transition = sparse.csr_matrix(adjacency_matrix, dtype=np.float64, copy=True)
# Sum along the two axes to get out-degree and in-degree, respectively
out_degree = rw_transition.sum(axis=1)
in_degree = rw_transition.sum(axis=0)
out_degree[out_degree == 0.0] = 1.0
# Form the inverse of the diagonal matrix containing the out-degree
for i in np.arange(rw_transition.shape[0]):
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]] =\
rw_transition.data[rw_transition.indptr[i]: rw_transition.indptr[i + 1]]/out_degree[i]
rw_transition.sort_indices()
out_degree = np.array(out_degree).astype(np.float64).reshape(out_degree.size)
in_degree = np.array(in_degree).astype(np.float64).reshape(in_degree.size)
if make_shared:
number_of_nodes = adjacency_matrix.shape[0]
out_degree_c = mp.Array(c.c_double, number_of_nodes)
in_degree_c = mp.Array(c.c_double, number_of_nodes)
out_degree_shared = np.frombuffer(out_degree_c.get_obj(), dtype=np.float64, count=number_of_nodes)
in_degree_shared = np.frombuffer(in_degree_c.get_obj(), dtype=np.float64, count=number_of_nodes)
out_degree_shared[:] = out_degree[:]
in_degree_shared[:] = in_degree[:]
indices_c = mp.Array(c.c_int64, rw_transition.indices.size)
indptr_c = mp.Array(c.c_int64, rw_transition.indptr.size)
data_c = mp.Array(c.c_double, rw_transition.data.size)
indices_shared = np.frombuffer(indices_c.get_obj(), dtype=np.int64, count=rw_transition.indices.size)
indptr_shared = np.frombuffer(indptr_c.get_obj(), dtype=np.int64, count=rw_transition.indptr.size)
data_shared = np.frombuffer(data_c.get_obj(), dtype=np.float64, count=rw_transition.data.size)
indices_shared[:] = rw_transition.indices[:]
indptr_shared[:] = rw_transition.indptr[:]
data_shared[:] = rw_transition.data[:]
rw_transition = sparse.csr_matrix((data_shared,
indices_shared,
indptr_shared),
shape=rw_transition.shape)
return rw_transition, out_degree, in_degree | [
"def",
"get_natural_random_walk_matrix",
"(",
"adjacency_matrix",
",",
"make_shared",
"=",
"False",
")",
":",
"# Turn to sparse.csr_matrix format for faster row access.",
"rw_transition",
"=",
"sparse",
".",
"csr_matrix",
"(",
"adjacency_matrix",
",",
"dtype",
"=",
"np",
... | Returns the natural random walk transition probability matrix given the adjacency matrix.
Input: - A: A sparse matrix that contains the adjacency matrix of the graph.
Output: - W: A sparse matrix that contains the natural random walk transition probability matrix. | [
"Returns",
"the",
"natural",
"random",
"walk",
"transition",
"probability",
"matrix",
"given",
"the",
"adjacency",
"matrix",
"."
] | eda862687aa5a64b79c6b12de1b4dca6ce986dc8 | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/eps_randomwalk/transition.py#L43-L99 | train | 47,512 |
matheuscas/pyIE | ie/pe.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Pernanbuco state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 8
for i in range(len(st_reg_number)-2):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
digit_first = divisor - rest_division
if rest_division < 2:
digit_first = 0
if rest_division > 1:
digit_first = 11 - rest_division
num = 0
peso = 9
mult = 10000000
for i in range(len(st_reg_number)-2):
num = num + int(st_reg_number[i]) * mult
mult = mult/10
num = num + digit_first
new_st = str(num)
sum_total = 0
peso = 9
for i in range(len(new_st)-1):
sum_total = sum_total + int(new_st[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
if rest_division < 2:
digit_secund = 0
if rest_division > 1:
digit_secund = divisor - rest_division
if digit_secund == int(st_reg_number[len(st_reg_number)-1]) and digit_first == int(st_reg_number[len(st_reg_number)-2]):
return True
else:
return False | python | def start(st_reg_number):
"""Checks the number valiaty for the Pernanbuco state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 8
for i in range(len(st_reg_number)-2):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
digit_first = divisor - rest_division
if rest_division < 2:
digit_first = 0
if rest_division > 1:
digit_first = 11 - rest_division
num = 0
peso = 9
mult = 10000000
for i in range(len(st_reg_number)-2):
num = num + int(st_reg_number[i]) * mult
mult = mult/10
num = num + digit_first
new_st = str(num)
sum_total = 0
peso = 9
for i in range(len(new_st)-1):
sum_total = sum_total + int(new_st[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
if rest_division < 2:
digit_secund = 0
if rest_division > 1:
digit_secund = divisor - rest_division
if digit_secund == int(st_reg_number[len(st_reg_number)-1]) and digit_first == int(st_reg_number[len(st_reg_number)-2]):
return True
else:
return False | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"divisor",
"=",
"11",
"if",
"len",
"(",
"st_reg_number",
")",
">",
"9",
":",
"return",
"False",
"if",
"len",
"(",
"st_reg_number",
")",
"<",
"9",
":",
"return",
"False",
"sum_total",
"=",
"0",
"peso",
"... | Checks the number valiaty for the Pernanbuco state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Pernanbuco",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/pe.py#L5-L57 | train | 47,513 |
matheuscas/pyIE | ie/ba.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Bahia state"""
weights_second_digit = range(len(st_reg_number)-1, 1, -1)
weights_first_digit = range(len(st_reg_number), 1, -1)
second_digits = st_reg_number[-1:]
number_state_registration = st_reg_number[0:len(st_reg_number) - 2]
digits_state_registration = st_reg_number[-2:]
sum_second_digit = 0
sum_first_digit = 0
if len(st_reg_number) != 8 and len(st_reg_number) != 9:
return False
if st_reg_number[-8] in ['0', '1', '2', '3', '4', '5', '8']:
for i in weights_second_digit:
sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1])
second_digits_check = 10 - (sum_second_digit % 10)
if sum_second_digit % 10 == 0 or sum_second_digit % 11 == 1:
second_digits_check = '0'
if str(second_digits_check) != second_digits:
return False
digit_two = number_state_registration + str(second_digits_check)
for i in weights_first_digit:
sum_first_digit = sum_first_digit + i*int(digit_two[-i+1])
first_digits_check = 10 - (sum_first_digit % 10)
if sum_first_digit % 10 == 0 or sum_first_digit % 10 == 1:
first_digits_check = '0'
digits_calculated = str(first_digits_check) + str(second_digits_check)
return digits_calculated == digits_state_registration
elif st_reg_number[-8] in ['6', '7', '9']:
for i in weights_second_digit:
sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1])
second_digits_check = 11 - (sum_second_digit % 11)
if sum_second_digit % 11 == 0 or sum_second_digit % 11 == 1:
second_digits_check = '0'
if str(second_digits_check) != second_digits:
return False
digit_two = number_state_registration + str(second_digits_check)
for i in weights_first_digit:
sum_first_digit = sum_first_digit + i*int(digit_two[-i+1])
first_digits_check = 11 - (sum_first_digit % 11)
if sum_first_digit % 11 == 0 or sum_first_digit % 11 == 1:
first_digits_check = '0'
digits_calculated = str(first_digits_check) + str(second_digits_check)
return digits_calculated == digits_state_registration | python | def start(st_reg_number):
"""Checks the number valiaty for the Bahia state"""
weights_second_digit = range(len(st_reg_number)-1, 1, -1)
weights_first_digit = range(len(st_reg_number), 1, -1)
second_digits = st_reg_number[-1:]
number_state_registration = st_reg_number[0:len(st_reg_number) - 2]
digits_state_registration = st_reg_number[-2:]
sum_second_digit = 0
sum_first_digit = 0
if len(st_reg_number) != 8 and len(st_reg_number) != 9:
return False
if st_reg_number[-8] in ['0', '1', '2', '3', '4', '5', '8']:
for i in weights_second_digit:
sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1])
second_digits_check = 10 - (sum_second_digit % 10)
if sum_second_digit % 10 == 0 or sum_second_digit % 11 == 1:
second_digits_check = '0'
if str(second_digits_check) != second_digits:
return False
digit_two = number_state_registration + str(second_digits_check)
for i in weights_first_digit:
sum_first_digit = sum_first_digit + i*int(digit_two[-i+1])
first_digits_check = 10 - (sum_first_digit % 10)
if sum_first_digit % 10 == 0 or sum_first_digit % 10 == 1:
first_digits_check = '0'
digits_calculated = str(first_digits_check) + str(second_digits_check)
return digits_calculated == digits_state_registration
elif st_reg_number[-8] in ['6', '7', '9']:
for i in weights_second_digit:
sum_second_digit = sum_second_digit + i*int(st_reg_number[-i-1])
second_digits_check = 11 - (sum_second_digit % 11)
if sum_second_digit % 11 == 0 or sum_second_digit % 11 == 1:
second_digits_check = '0'
if str(second_digits_check) != second_digits:
return False
digit_two = number_state_registration + str(second_digits_check)
for i in weights_first_digit:
sum_first_digit = sum_first_digit + i*int(digit_two[-i+1])
first_digits_check = 11 - (sum_first_digit % 11)
if sum_first_digit % 11 == 0 or sum_first_digit % 11 == 1:
first_digits_check = '0'
digits_calculated = str(first_digits_check) + str(second_digits_check)
return digits_calculated == digits_state_registration | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"weights_second_digit",
"=",
"range",
"(",
"len",
"(",
"st_reg_number",
")",
"-",
"1",
",",
"1",
",",
"-",
"1",
")",
"weights_first_digit",
"=",
"range",
"(",
"len",
"(",
"st_reg_number",
")",
",",
"1",
"... | Checks the number valiaty for the Bahia state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Bahia",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/ba.py#L5-L75 | train | 47,514 |
Riparo/nougat | nougat/asgi.py | send_http_response | async def send_http_response(writer,
http_code: int,
headers: List[Tuple[str, str]],
content: bytes,
http_status: str= None
) -> None:
"""
generate http response payload and send to writer
"""
# generate response payload
if not http_status:
http_status = STATUS_CODES.get(http_code, 'Unknown')
response: bytes = f'HTTP/1.1 {http_code} {http_status}\r\n'.encode()
for k, v in headers:
response += f'{k}: {v}\r\n'.encode()
response += b'\r\n'
response += content
# send payload
writer.write(response)
await writer.drain() | python | async def send_http_response(writer,
http_code: int,
headers: List[Tuple[str, str]],
content: bytes,
http_status: str= None
) -> None:
"""
generate http response payload and send to writer
"""
# generate response payload
if not http_status:
http_status = STATUS_CODES.get(http_code, 'Unknown')
response: bytes = f'HTTP/1.1 {http_code} {http_status}\r\n'.encode()
for k, v in headers:
response += f'{k}: {v}\r\n'.encode()
response += b'\r\n'
response += content
# send payload
writer.write(response)
await writer.drain() | [
"async",
"def",
"send_http_response",
"(",
"writer",
",",
"http_code",
":",
"int",
",",
"headers",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
",",
"content",
":",
"bytes",
",",
"http_status",
":",
"str",
"=",
"None",
")",
"->",
"Non... | generate http response payload and send to writer | [
"generate",
"http",
"response",
"payload",
"and",
"send",
"to",
"writer"
] | 8453bc37e0b782f296952f0a418532ebbbcd74f3 | https://github.com/Riparo/nougat/blob/8453bc37e0b782f296952f0a418532ebbbcd74f3/nougat/asgi.py#L165-L186 | train | 47,515 |
matheuscas/pyIE | ie/pb.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Paraiba state"""
#st_reg_number = str(st_reg_number)
weights = [9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in range(0, 8):
sum_total = sum_total + weights[i] * int(st_reg_number[i])
if sum_total % 11 == 0:
return digit_state_registration[-1] == '0'
digit_check = 11 - sum_total % 11
return str(digit_check) == digit_state_registration | python | def start(st_reg_number):
"""Checks the number valiaty for the Paraiba state"""
#st_reg_number = str(st_reg_number)
weights = [9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in range(0, 8):
sum_total = sum_total + weights[i] * int(st_reg_number[i])
if sum_total % 11 == 0:
return digit_state_registration[-1] == '0'
digit_check = 11 - sum_total % 11
return str(digit_check) == digit_state_registration | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"#st_reg_number = str(st_reg_number)",
"weights",
"=",
"[",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"digit_state_registration",
"=",
"st_reg_number",
"[",
"-",
"1",
... | Checks the number valiaty for the Paraiba state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Paraiba",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/pb.py#L5-L24 | train | 47,516 |
matheuscas/pyIE | ie/mt.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Mato Grosso state"""
#st_reg_number = str(st_reg_number)
weights = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 11:
return False
sum = 0
for i in range(0, 10):
sum = sum + weights[i] * int(st_reg_number[i])
if sum % 11 == 0:
return digit_state_registration[-1] == '0'
digit_check = 11 - sum % 11
return str(digit_check) == digit_state_registration | python | def start(st_reg_number):
"""Checks the number valiaty for the Mato Grosso state"""
#st_reg_number = str(st_reg_number)
weights = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 11:
return False
sum = 0
for i in range(0, 10):
sum = sum + weights[i] * int(st_reg_number[i])
if sum % 11 == 0:
return digit_state_registration[-1] == '0'
digit_check = 11 - sum % 11
return str(digit_check) == digit_state_registration | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"#st_reg_number = str(st_reg_number)",
"weights",
"=",
"[",
"3",
",",
"2",
",",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"digit_state_registration",
"=",
"st_reg_num... | Checks the number valiaty for the Mato Grosso state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Mato",
"Grosso",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/mt.py#L5-L24 | train | 47,517 |
matheuscas/pyIE | ie/se.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Sergipe state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 9
for i in range(len(st_reg_number)-1):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
digit = divisor - rest_division
if digit == 10 or digit == 11:
digit = 0
return digit == int(st_reg_number[len(st_reg_number)-1]) | python | def start(st_reg_number):
"""Checks the number valiaty for the Sergipe state"""
divisor = 11
if len(st_reg_number) > 9:
return False
if len(st_reg_number) < 9:
return False
sum_total = 0
peso = 9
for i in range(len(st_reg_number)-1):
sum_total = sum_total + int(st_reg_number[i]) * peso
peso = peso - 1
rest_division = sum_total % divisor
digit = divisor - rest_division
if digit == 10 or digit == 11:
digit = 0
return digit == int(st_reg_number[len(st_reg_number)-1]) | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"divisor",
"=",
"11",
"if",
"len",
"(",
"st_reg_number",
")",
">",
"9",
":",
"return",
"False",
"if",
"len",
"(",
"st_reg_number",
")",
"<",
"9",
":",
"return",
"False",
"sum_total",
"=",
"0",
"peso",
"... | Checks the number valiaty for the Sergipe state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Sergipe",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/se.py#L5-L28 | train | 47,518 |
matheuscas/pyIE | ie/go.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Espirito Santo state"""
weights = [9, 8, 7, 6, 5, 4, 3, 2]
number_state_registration = st_reg_number[0:len(st_reg_number) - 1]
digit_state_registration = st_reg_number[-1]
if st_reg_number[0:2] not in ['10', '11', '12']:
return False
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in weights:
sum_total = sum_total + i * (int(number_state_registration[-i+1]))
check_number = number_state_registration <= 10119997
if sum_total % 11 == 0:
return '0' == digit_state_registration
elif sum_total % 11 == 1 and (int(number_state_registration) >= 10103105 and check_number):
return '1' == digit_state_registration
elif sum_total % 11 == 1:
return '0' == digit_state_registration
else:
digit_check = 11 - sum_total % 11
return digit_state_registration == str(digit_check)
if number_state_registration == '11094402' and (number_state_registration == '1' or number_state_registration == '0'):
return True | python | def start(st_reg_number):
"""Checks the number valiaty for the Espirito Santo state"""
weights = [9, 8, 7, 6, 5, 4, 3, 2]
number_state_registration = st_reg_number[0:len(st_reg_number) - 1]
digit_state_registration = st_reg_number[-1]
if st_reg_number[0:2] not in ['10', '11', '12']:
return False
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in weights:
sum_total = sum_total + i * (int(number_state_registration[-i+1]))
check_number = number_state_registration <= 10119997
if sum_total % 11 == 0:
return '0' == digit_state_registration
elif sum_total % 11 == 1 and (int(number_state_registration) >= 10103105 and check_number):
return '1' == digit_state_registration
elif sum_total % 11 == 1:
return '0' == digit_state_registration
else:
digit_check = 11 - sum_total % 11
return digit_state_registration == str(digit_check)
if number_state_registration == '11094402' and (number_state_registration == '1' or number_state_registration == '0'):
return True | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"weights",
"=",
"[",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"number_state_registration",
"=",
"st_reg_number",
"[",
"0",
":",
"len",
"(",
"st_reg_number",
")",... | Checks the number valiaty for the Espirito Santo state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Espirito",
"Santo",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/go.py#L5-L39 | train | 47,519 |
matheuscas/pyIE | ie/ac.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Acre state"""
#st_reg_number = str(st_reg_number)
weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digits = st_reg_number[:len(st_reg_number) - 2]
check_digits = st_reg_number[-2:]
divisor = 11
if len(st_reg_number) > 13:
return False
sum_total = 0
for i in range(len(digits)):
sum_total = sum_total + int(digits[i]) * weights[i]
rest_division = sum_total % divisor
first_digit = divisor - rest_division
if first_digit == 10 or first_digit == 11:
first_digit = 0
if str(first_digit) != check_digits[0]:
return False
digits = digits + str(first_digit)
weights = [5] + weights
sum_total = 0
for i in range(len(digits)):
sum_total = sum_total + int(digits[i]) * weights[i]
rest_division = sum_total % divisor
second_digit = divisor - rest_division
if second_digit == 10 or second_digit == 11:
second_digit = 0
return str(first_digit) + str(second_digit) == check_digits | python | def start(st_reg_number):
"""Checks the number valiaty for the Acre state"""
#st_reg_number = str(st_reg_number)
weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
digits = st_reg_number[:len(st_reg_number) - 2]
check_digits = st_reg_number[-2:]
divisor = 11
if len(st_reg_number) > 13:
return False
sum_total = 0
for i in range(len(digits)):
sum_total = sum_total + int(digits[i]) * weights[i]
rest_division = sum_total % divisor
first_digit = divisor - rest_division
if first_digit == 10 or first_digit == 11:
first_digit = 0
if str(first_digit) != check_digits[0]:
return False
digits = digits + str(first_digit)
weights = [5] + weights
sum_total = 0
for i in range(len(digits)):
sum_total = sum_total + int(digits[i]) * weights[i]
rest_division = sum_total % divisor
second_digit = divisor - rest_division
if second_digit == 10 or second_digit == 11:
second_digit = 0
return str(first_digit) + str(second_digit) == check_digits | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"#st_reg_number = str(st_reg_number)",
"weights",
"=",
"[",
"4",
",",
"3",
",",
"2",
",",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"digits",
"=",
"st_reg_number"... | Checks the number valiaty for the Acre state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Acre",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/ac.py#L4-L42 | train | 47,520 |
matheuscas/pyIE | ie/mg.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Minas Gerais state"""
#st_reg_number = str(st_reg_number)
number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2]
weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
first_digit = st_reg_number[-2]
second_digit = st_reg_number[-1]
sum_first_digit = 0
sum_second_digit = 0
sum_result_digit = ''
sum_end = 0
if len(st_reg_number) != 13:
return False
for i in range(0, 12):
sum_first_digit = weights_first_digit[i] * int(number_state_registration_first_digit[i])
sum_result_digit = sum_result_digit + str(sum_first_digit)
for i in range(0, len(sum_result_digit)):
sum_end = sum_end + int(sum_result_digit[i])
if sum_end % 10 == 0:
check_digit_one = 0
elif sum_end < 10:
check_digit_one = 10 - sum_end
elif sum_end > 10:
check_digit_one = (10 - sum_end % 10)
if str(check_digit_one) != first_digit:
return False
number_state_registration_second_digit = st_reg_number + str(check_digit_one)
for i in range(0, 12):
sum_second_digit = sum_second_digit + wights_second_digit[i] * int(number_state_registration_second_digit[i])
check_second_digit = 11 - sum_second_digit % 11
if sum_second_digit == 1 or sum_second_digit == 0:
return second_digit == '0'
else:
return str(check_second_digit) == second_digit | python | def start(st_reg_number):
"""Checks the number valiaty for the Minas Gerais state"""
#st_reg_number = str(st_reg_number)
number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2]
weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
first_digit = st_reg_number[-2]
second_digit = st_reg_number[-1]
sum_first_digit = 0
sum_second_digit = 0
sum_result_digit = ''
sum_end = 0
if len(st_reg_number) != 13:
return False
for i in range(0, 12):
sum_first_digit = weights_first_digit[i] * int(number_state_registration_first_digit[i])
sum_result_digit = sum_result_digit + str(sum_first_digit)
for i in range(0, len(sum_result_digit)):
sum_end = sum_end + int(sum_result_digit[i])
if sum_end % 10 == 0:
check_digit_one = 0
elif sum_end < 10:
check_digit_one = 10 - sum_end
elif sum_end > 10:
check_digit_one = (10 - sum_end % 10)
if str(check_digit_one) != first_digit:
return False
number_state_registration_second_digit = st_reg_number + str(check_digit_one)
for i in range(0, 12):
sum_second_digit = sum_second_digit + wights_second_digit[i] * int(number_state_registration_second_digit[i])
check_second_digit = 11 - sum_second_digit % 11
if sum_second_digit == 1 or sum_second_digit == 0:
return second_digit == '0'
else:
return str(check_second_digit) == second_digit | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"#st_reg_number = str(st_reg_number)",
"number_state_registration_first_digit",
"=",
"st_reg_number",
"[",
"0",
":",
"3",
"]",
"+",
"'0'",
"+",
"st_reg_number",
"[",
"3",
":",
"len",
"(",
"st_reg_number",
")",
"-",
... | Checks the number valiaty for the Minas Gerais state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Minas",
"Gerais",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/mg.py#L5-L61 | train | 47,521 |
matheuscas/pyIE | ie/am.py | start | def start(st_reg_number):
"""Checks the number valiaty for the Amazonas state"""
weights = range(2, 10)
digits = st_reg_number[0:len(st_reg_number) - 1]
control_digit = 11
check_digit = st_reg_number[-1:]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in weights:
sum_total = sum_total + i * int(digits[i-2])
if sum_total < control_digit:
control_digit = 11 - sum_total
return str(digit_calculated) == check_digit
elif sum_total % 11 <= 1:
return '0' == check_digit
else:
digit_calculated = 11 - sum_total % 11
return str(digit_calculated) == check_digit | python | def start(st_reg_number):
"""Checks the number valiaty for the Amazonas state"""
weights = range(2, 10)
digits = st_reg_number[0:len(st_reg_number) - 1]
control_digit = 11
check_digit = st_reg_number[-1:]
if len(st_reg_number) != 9:
return False
sum_total = 0
for i in weights:
sum_total = sum_total + i * int(digits[i-2])
if sum_total < control_digit:
control_digit = 11 - sum_total
return str(digit_calculated) == check_digit
elif sum_total % 11 <= 1:
return '0' == check_digit
else:
digit_calculated = 11 - sum_total % 11
return str(digit_calculated) == check_digit | [
"def",
"start",
"(",
"st_reg_number",
")",
":",
"weights",
"=",
"range",
"(",
"2",
",",
"10",
")",
"digits",
"=",
"st_reg_number",
"[",
"0",
":",
"len",
"(",
"st_reg_number",
")",
"-",
"1",
"]",
"control_digit",
"=",
"11",
"check_digit",
"=",
"st_reg_n... | Checks the number valiaty for the Amazonas state | [
"Checks",
"the",
"number",
"valiaty",
"for",
"the",
"Amazonas",
"state"
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/am.py#L5-L29 | train | 47,522 |
matheuscas/pyIE | ie/checking.py | start | def start(state_registration_number, state_abbreviation):
"""
This function is like a Facade to another modules that
makes their own state validation.
state_registration_number - string brazilian state registration number
state_abbreviation - state abbreviation
AC (Acre)
AL (Alagoas)
AM (Amazonas)
AP (Amapá)
BA (Bahia)
CE (Ceará)
DF (Distrito Federal)
ES (Espírito Santo')
GO (Goias)
MA (Maranhão)
MG (Minas Gerais)
MS (Mato Grosso do Sul)
MT (Mato Grosso)
PA (Pará)
PB (Paraíba)
PE (Pernambuco)
PI (Piauí)
PR (Paraná)
RJ (Rio de Janeiro)
RN (Rio Grande do Norte)
RO (Rondônia)
RR (Roraima)
RS (Rio Grande do Sul)
SC (Santa Catarina)
SE (Sergipe)
SP (São Paulo)
TO (Tocantins)
"""
state_abbreviation = state_abbreviation.upper()
states_validations = {
'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")",
'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")",
'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")",
'AP': "ap.start(" + "\"" + state_registration_number + "\"" + ")",
'BA': "ba.start(" + "\"" + state_registration_number + "\"" + ")",
'CE': "ce.start(" + "\"" + state_registration_number + "\"" + ")",
'DF': "df.start(" + "\"" + state_registration_number + "\"" + ")",
'ES': "es.start(" + "\"" + state_registration_number + "\"" + ")",
'GO': "go.start(" + "\"" + state_registration_number + "\"" + ")",
'MA': "ma.start(" + "\"" + state_registration_number + "\"" + ")",
'MG': "mg.start(" + "\"" + state_registration_number + "\"" + ")",
'MS': "ms.start(" + "\"" + state_registration_number + "\"" + ")",
'MT': "mt.start(" + "\"" + state_registration_number + "\"" + ")",
'PA': "pa.start(" + "\"" + state_registration_number + "\"" + ")",
'PB': "pb.start(" + "\"" + state_registration_number + "\"" + ")",
'PE': "pe.start(" + "\"" + state_registration_number + "\"" + ")",
'PI': "pi.start(" + "\"" + state_registration_number + "\"" + ")",
'PR': "pr.start(" + "\"" + state_registration_number + "\"" + ")",
'RJ': "rj.start(" + "\"" + state_registration_number + "\"" + ")",
'RN': "rn.start(" + "\"" + state_registration_number + "\"" + ")",
'RO': "ro.start(" + "\"" + state_registration_number + "\"" + ")",
'RR': "rr.start(" + "\"" + state_registration_number + "\"" + ")",
'RS': "rs.start(" + "\"" + state_registration_number + "\"" + ")",
'SC': "sc.start(" + "\"" + state_registration_number + "\"" + ")",
'SE': "se.start(" + "\"" + state_registration_number + "\"" + ")",
'SP': "sp.start(" + "\"" + state_registration_number + "\"" + ")",
'TO': "to.start(" + "\"" + state_registration_number + "\"" + ")"
}
exec('validity = ' + states_validations[state_abbreviation])
return validity | python | def start(state_registration_number, state_abbreviation):
"""
This function is like a Facade to another modules that
makes their own state validation.
state_registration_number - string brazilian state registration number
state_abbreviation - state abbreviation
AC (Acre)
AL (Alagoas)
AM (Amazonas)
AP (Amapá)
BA (Bahia)
CE (Ceará)
DF (Distrito Federal)
ES (Espírito Santo')
GO (Goias)
MA (Maranhão)
MG (Minas Gerais)
MS (Mato Grosso do Sul)
MT (Mato Grosso)
PA (Pará)
PB (Paraíba)
PE (Pernambuco)
PI (Piauí)
PR (Paraná)
RJ (Rio de Janeiro)
RN (Rio Grande do Norte)
RO (Rondônia)
RR (Roraima)
RS (Rio Grande do Sul)
SC (Santa Catarina)
SE (Sergipe)
SP (São Paulo)
TO (Tocantins)
"""
state_abbreviation = state_abbreviation.upper()
states_validations = {
'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")",
'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")",
'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")",
'AP': "ap.start(" + "\"" + state_registration_number + "\"" + ")",
'BA': "ba.start(" + "\"" + state_registration_number + "\"" + ")",
'CE': "ce.start(" + "\"" + state_registration_number + "\"" + ")",
'DF': "df.start(" + "\"" + state_registration_number + "\"" + ")",
'ES': "es.start(" + "\"" + state_registration_number + "\"" + ")",
'GO': "go.start(" + "\"" + state_registration_number + "\"" + ")",
'MA': "ma.start(" + "\"" + state_registration_number + "\"" + ")",
'MG': "mg.start(" + "\"" + state_registration_number + "\"" + ")",
'MS': "ms.start(" + "\"" + state_registration_number + "\"" + ")",
'MT': "mt.start(" + "\"" + state_registration_number + "\"" + ")",
'PA': "pa.start(" + "\"" + state_registration_number + "\"" + ")",
'PB': "pb.start(" + "\"" + state_registration_number + "\"" + ")",
'PE': "pe.start(" + "\"" + state_registration_number + "\"" + ")",
'PI': "pi.start(" + "\"" + state_registration_number + "\"" + ")",
'PR': "pr.start(" + "\"" + state_registration_number + "\"" + ")",
'RJ': "rj.start(" + "\"" + state_registration_number + "\"" + ")",
'RN': "rn.start(" + "\"" + state_registration_number + "\"" + ")",
'RO': "ro.start(" + "\"" + state_registration_number + "\"" + ")",
'RR': "rr.start(" + "\"" + state_registration_number + "\"" + ")",
'RS': "rs.start(" + "\"" + state_registration_number + "\"" + ")",
'SC': "sc.start(" + "\"" + state_registration_number + "\"" + ")",
'SE': "se.start(" + "\"" + state_registration_number + "\"" + ")",
'SP': "sp.start(" + "\"" + state_registration_number + "\"" + ")",
'TO': "to.start(" + "\"" + state_registration_number + "\"" + ")"
}
exec('validity = ' + states_validations[state_abbreviation])
return validity | [
"def",
"start",
"(",
"state_registration_number",
",",
"state_abbreviation",
")",
":",
"state_abbreviation",
"=",
"state_abbreviation",
".",
"upper",
"(",
")",
"states_validations",
"=",
"{",
"'AC'",
":",
"\"ac.start(\"",
"+",
"\"\\\"\"",
"+",
"state_registration_numb... | This function is like a Facade to another modules that
makes their own state validation.
state_registration_number - string brazilian state registration number
state_abbreviation - state abbreviation
AC (Acre)
AL (Alagoas)
AM (Amazonas)
AP (Amapá)
BA (Bahia)
CE (Ceará)
DF (Distrito Federal)
ES (Espírito Santo')
GO (Goias)
MA (Maranhão)
MG (Minas Gerais)
MS (Mato Grosso do Sul)
MT (Mato Grosso)
PA (Pará)
PB (Paraíba)
PE (Pernambuco)
PI (Piauí)
PR (Paraná)
RJ (Rio de Janeiro)
RN (Rio Grande do Norte)
RO (Rondônia)
RR (Roraima)
RS (Rio Grande do Sul)
SC (Santa Catarina)
SE (Sergipe)
SP (São Paulo)
TO (Tocantins) | [
"This",
"function",
"is",
"like",
"a",
"Facade",
"to",
"another",
"modules",
"that",
"makes",
"their",
"own",
"state",
"validation",
"."
] | 9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb | https://github.com/matheuscas/pyIE/blob/9e942dd692d0eab8a1e7717ad7ff3fe90d590ffb/ie/checking.py#L36-L106 | train | 47,523 |
paylogic/halogen | halogen/exceptions.py | ValidationError.to_dict | def to_dict(self):
"""Return a dictionary representation of the error.
:return: A dict with the keys:
- attr: Attribute which contains the error, or "<root>" if it refers to the schema root.
- errors: A list of dictionary representations of the errors.
"""
def exception_to_dict(e):
try:
return e.to_dict()
except AttributeError:
return {
"type": e.__class__.__name__,
"error": str(e),
}
result = {
"errors": [exception_to_dict(e) for e in self.errors]
}
if self.index is not None:
result["index"] = self.index
else:
result["attr"] = self.attr if self.attr is not None else "<root>"
return result | python | def to_dict(self):
"""Return a dictionary representation of the error.
:return: A dict with the keys:
- attr: Attribute which contains the error, or "<root>" if it refers to the schema root.
- errors: A list of dictionary representations of the errors.
"""
def exception_to_dict(e):
try:
return e.to_dict()
except AttributeError:
return {
"type": e.__class__.__name__,
"error": str(e),
}
result = {
"errors": [exception_to_dict(e) for e in self.errors]
}
if self.index is not None:
result["index"] = self.index
else:
result["attr"] = self.attr if self.attr is not None else "<root>"
return result | [
"def",
"to_dict",
"(",
"self",
")",
":",
"def",
"exception_to_dict",
"(",
"e",
")",
":",
"try",
":",
"return",
"e",
".",
"to_dict",
"(",
")",
"except",
"AttributeError",
":",
"return",
"{",
"\"type\"",
":",
"e",
".",
"__class__",
".",
"__name__",
",",
... | Return a dictionary representation of the error.
:return: A dict with the keys:
- attr: Attribute which contains the error, or "<root>" if it refers to the schema root.
- errors: A list of dictionary representations of the errors. | [
"Return",
"a",
"dictionary",
"representation",
"of",
"the",
"error",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/exceptions.py#L18-L41 | train | 47,524 |
dhondta/tinyscript | tinyscript/argreparse.py | ArgumentParser._sorted_actions | def _sorted_actions(self):
"""
Generate the sorted list of actions based on the "last" attribute.
"""
for a in filter(lambda _: not _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(lambda _: _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(lambda _: self.is_action(_, 'parsers'),
self._actions):
yield a | python | def _sorted_actions(self):
"""
Generate the sorted list of actions based on the "last" attribute.
"""
for a in filter(lambda _: not _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(lambda _: _.last and \
not self.is_action(_, 'parsers'), self._actions):
yield a
for a in filter(lambda _: self.is_action(_, 'parsers'),
self._actions):
yield a | [
"def",
"_sorted_actions",
"(",
"self",
")",
":",
"for",
"a",
"in",
"filter",
"(",
"lambda",
"_",
":",
"not",
"_",
".",
"last",
"and",
"not",
"self",
".",
"is_action",
"(",
"_",
",",
"'parsers'",
")",
",",
"self",
".",
"_actions",
")",
":",
"yield",... | Generate the sorted list of actions based on the "last" attribute. | [
"Generate",
"the",
"sorted",
"list",
"of",
"actions",
"based",
"on",
"the",
"last",
"attribute",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L407-L419 | train | 47,525 |
dhondta/tinyscript | tinyscript/argreparse.py | ArgumentParser.demo_args | def demo_args(self):
"""
Additional method for replacing input arguments by demo ones.
"""
argv = random.choice(self.examples).replace("--demo", "")
self._reparse_args['pos'] = shlex.split(argv) | python | def demo_args(self):
"""
Additional method for replacing input arguments by demo ones.
"""
argv = random.choice(self.examples).replace("--demo", "")
self._reparse_args['pos'] = shlex.split(argv) | [
"def",
"demo_args",
"(",
"self",
")",
":",
"argv",
"=",
"random",
".",
"choice",
"(",
"self",
".",
"examples",
")",
".",
"replace",
"(",
"\"--demo\"",
",",
"\"\"",
")",
"self",
".",
"_reparse_args",
"[",
"'pos'",
"]",
"=",
"shlex",
".",
"split",
"(",... | Additional method for replacing input arguments by demo ones. | [
"Additional",
"method",
"for",
"replacing",
"input",
"arguments",
"by",
"demo",
"ones",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/argreparse.py#L442-L447 | train | 47,526 |
dhondta/tinyscript | tinyscript/report/__init__.py | output | def output(f):
""" This decorator allows to choose to return an output as text or to save
it to a file. """
def wrapper(self, *args, **kwargs):
try:
text = kwargs.get('text') or args[0]
except IndexError:
text = True
_ = f(self, *args, **kwargs)
if text:
return _
elif _ is not None and isinstance(_, string_types):
filename = "{}.{}".format(self.filename, f.__name__)
while exists(filename):
name, ext = splitext(filename)
try:
name, i = name.split('-')
i = int(i) + 1
except ValueError:
i = 2
filename = "{}-{}".format(name, i) + ext
with open(filename, 'w') as out:
out.write(_)
return wrapper | python | def output(f):
""" This decorator allows to choose to return an output as text or to save
it to a file. """
def wrapper(self, *args, **kwargs):
try:
text = kwargs.get('text') or args[0]
except IndexError:
text = True
_ = f(self, *args, **kwargs)
if text:
return _
elif _ is not None and isinstance(_, string_types):
filename = "{}.{}".format(self.filename, f.__name__)
while exists(filename):
name, ext = splitext(filename)
try:
name, i = name.split('-')
i = int(i) + 1
except ValueError:
i = 2
filename = "{}-{}".format(name, i) + ext
with open(filename, 'w') as out:
out.write(_)
return wrapper | [
"def",
"output",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"text",
"=",
"kwargs",
".",
"get",
"(",
"'text'",
")",
"or",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":"... | This decorator allows to choose to return an output as text or to save
it to a file. | [
"This",
"decorator",
"allows",
"to",
"choose",
"to",
"return",
"an",
"output",
"as",
"text",
"or",
"to",
"save",
"it",
"to",
"a",
"file",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L32-L55 | train | 47,527 |
dhondta/tinyscript | tinyscript/report/__init__.py | Report.html | def html(self, text=TEXT):
""" Generate an HTML file from the report data. """
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
html.append(markdown2.markdown(piece, extras=["tables"]))
elif isinstance(piece, Element):
html.append(piece.html())
return "\n\n".join(html) | python | def html(self, text=TEXT):
""" Generate an HTML file from the report data. """
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
html.append(markdown2.markdown(piece, extras=["tables"]))
elif isinstance(piece, Element):
html.append(piece.html())
return "\n\n".join(html) | [
"def",
"html",
"(",
"self",
",",
"text",
"=",
"TEXT",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Generating the HTML report{}...\"",
".",
"format",
"(",
"[",
"\"\"",
",",
"\" (text only)\"",
"]",
"[",
"text",
"]",
")",
")",
"html",
"=",
"["... | Generate an HTML file from the report data. | [
"Generate",
"an",
"HTML",
"file",
"from",
"the",
"report",
"data",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L133-L143 | train | 47,528 |
dhondta/tinyscript | tinyscript/report/__init__.py | Report.pdf | def pdf(self, text=TEXT):
""" Generate a PDF file from the report data. """
self.logger.debug("Generating the PDF report...")
html = HTML(string=self.html())
css_file = self.css or join(dirname(abspath(__file__)),
"{}.css".format(self.theme))
css = [css_file, CSS(string=PAGE_CSS % self.__dict__)]
html.write_pdf("{}.pdf".format(self.filename), stylesheets=css) | python | def pdf(self, text=TEXT):
""" Generate a PDF file from the report data. """
self.logger.debug("Generating the PDF report...")
html = HTML(string=self.html())
css_file = self.css or join(dirname(abspath(__file__)),
"{}.css".format(self.theme))
css = [css_file, CSS(string=PAGE_CSS % self.__dict__)]
html.write_pdf("{}.pdf".format(self.filename), stylesheets=css) | [
"def",
"pdf",
"(",
"self",
",",
"text",
"=",
"TEXT",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Generating the PDF report...\"",
")",
"html",
"=",
"HTML",
"(",
"string",
"=",
"self",
".",
"html",
"(",
")",
")",
"css_file",
"=",
"self",
".... | Generate a PDF file from the report data. | [
"Generate",
"a",
"PDF",
"file",
"from",
"the",
"report",
"data",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L163-L170 | train | 47,529 |
dhondta/tinyscript | tinyscript/report/__init__.py | Table.csv | def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"):
""" Generate a CSV table from the table data. """
return self._data.to_csv(sep=sep, index=index, float_format=float_fmt) | python | def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"):
""" Generate a CSV table from the table data. """
return self._data.to_csv(sep=sep, index=index, float_format=float_fmt) | [
"def",
"csv",
"(",
"self",
",",
"text",
"=",
"TEXT",
",",
"sep",
"=",
"','",
",",
"index",
"=",
"True",
",",
"float_fmt",
"=",
"\"%.2g\"",
")",
":",
"return",
"self",
".",
"_data",
".",
"to_csv",
"(",
"sep",
"=",
"sep",
",",
"index",
"=",
"index"... | Generate a CSV table from the table data. | [
"Generate",
"a",
"CSV",
"table",
"from",
"the",
"table",
"data",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L191-L193 | train | 47,530 |
dhondta/tinyscript | tinyscript/report/__init__.py | Table.md | def md(self, text=TEXT, float_format="%.2g"):
""" Generate Markdown from the table data. """
cols = self._data.columns
hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols)
df = pd.concat([hl, self._data])
return df.to_csv(sep='|', index=True, float_format=float_format) | python | def md(self, text=TEXT, float_format="%.2g"):
""" Generate Markdown from the table data. """
cols = self._data.columns
hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols)
df = pd.concat([hl, self._data])
return df.to_csv(sep='|', index=True, float_format=float_format) | [
"def",
"md",
"(",
"self",
",",
"text",
"=",
"TEXT",
",",
"float_format",
"=",
"\"%.2g\"",
")",
":",
"cols",
"=",
"self",
".",
"_data",
".",
"columns",
"hl",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"[",
"\"---\"",
"]",
"*",
"len",
"(",
"cols",
")",... | Generate Markdown from the table data. | [
"Generate",
"Markdown",
"from",
"the",
"table",
"data",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L206-L211 | train | 47,531 |
dhondta/tinyscript | tinyscript/report/__init__.py | Table.xml | def xml(self, text=TEXT):
""" Generate an XML output from the report data. """
def convert(line):
xml = " <item>\n"
for f in line.index:
xml += " <field name=\"%s\">%s</field>\n" % (f, line[f])
xml += " </item>\n"
return xml
return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \
"</items>" | python | def xml(self, text=TEXT):
""" Generate an XML output from the report data. """
def convert(line):
xml = " <item>\n"
for f in line.index:
xml += " <field name=\"%s\">%s</field>\n" % (f, line[f])
xml += " </item>\n"
return xml
return "<items>\n" + '\n'.join(self._data.apply(convert, axis=1)) + \
"</items>" | [
"def",
"xml",
"(",
"self",
",",
"text",
"=",
"TEXT",
")",
":",
"def",
"convert",
"(",
"line",
")",
":",
"xml",
"=",
"\" <item>\\n\"",
"for",
"f",
"in",
"line",
".",
"index",
":",
"xml",
"+=",
"\" <field name=\\\"%s\\\">%s</field>\\n\"",
"%",
"(",
"f"... | Generate an XML output from the report data. | [
"Generate",
"an",
"XML",
"output",
"from",
"the",
"report",
"data",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L214-L223 | train | 47,532 |
toumorokoshi/transmute-core | transmute_core/function/signature.py | FunctionSignature.from_argspec | def from_argspec(argspec):
"""
retrieve a FunctionSignature object
from the argspec and the annotations passed.
"""
attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", [])
defaults = argspec.defaults or []
arguments, keywords = [], {}
attribute_list = (
attributes[: -len(defaults)] if len(defaults) != 0 else attributes[:]
)
for name in attribute_list:
if name == "self":
continue
typ = argspec.annotations.get(name)
arguments.append(Argument(name, NoDefault, typ))
if len(defaults) != 0:
for name, default in zip(attributes[-len(defaults) :], defaults):
typ = argspec.annotations.get(name)
keywords[name] = Argument(name, default, typ)
return FunctionSignature(arguments, keywords) | python | def from_argspec(argspec):
"""
retrieve a FunctionSignature object
from the argspec and the annotations passed.
"""
attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", [])
defaults = argspec.defaults or []
arguments, keywords = [], {}
attribute_list = (
attributes[: -len(defaults)] if len(defaults) != 0 else attributes[:]
)
for name in attribute_list:
if name == "self":
continue
typ = argspec.annotations.get(name)
arguments.append(Argument(name, NoDefault, typ))
if len(defaults) != 0:
for name, default in zip(attributes[-len(defaults) :], defaults):
typ = argspec.annotations.get(name)
keywords[name] = Argument(name, default, typ)
return FunctionSignature(arguments, keywords) | [
"def",
"from_argspec",
"(",
"argspec",
")",
":",
"attributes",
"=",
"getattr",
"(",
"argspec",
",",
"\"args\"",
",",
"[",
"]",
")",
"+",
"getattr",
"(",
"argspec",
",",
"\"keywords\"",
",",
"[",
"]",
")",
"defaults",
"=",
"argspec",
".",
"defaults",
"o... | retrieve a FunctionSignature object
from the argspec and the annotations passed. | [
"retrieve",
"a",
"FunctionSignature",
"object",
"from",
"the",
"argspec",
"and",
"the",
"annotations",
"passed",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/signature.py#L38-L62 | train | 47,533 |
toumorokoshi/transmute-core | transmute_core/function/signature.py | FunctionSignature.split_args | def split_args(self, arg_dict):
"""
given a dictionary of arguments, split them into
args and kwargs
note: this destroys the arg_dict passed. if you need it,
create a copy first.
"""
pos_args = []
for arg in self.args:
pos_args.append(arg_dict[arg.name])
del arg_dict[arg.name]
return pos_args, arg_dict | python | def split_args(self, arg_dict):
"""
given a dictionary of arguments, split them into
args and kwargs
note: this destroys the arg_dict passed. if you need it,
create a copy first.
"""
pos_args = []
for arg in self.args:
pos_args.append(arg_dict[arg.name])
del arg_dict[arg.name]
return pos_args, arg_dict | [
"def",
"split_args",
"(",
"self",
",",
"arg_dict",
")",
":",
"pos_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"self",
".",
"args",
":",
"pos_args",
".",
"append",
"(",
"arg_dict",
"[",
"arg",
".",
"name",
"]",
")",
"del",
"arg_dict",
"[",
"arg",
".",... | given a dictionary of arguments, split them into
args and kwargs
note: this destroys the arg_dict passed. if you need it,
create a copy first. | [
"given",
"a",
"dictionary",
"of",
"arguments",
"split",
"them",
"into",
"args",
"and",
"kwargs"
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/signature.py#L70-L82 | train | 47,534 |
agoragames/chai | chai/exception.py | pretty_format_args | def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args]) | python | def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args]) | [
"def",
"pretty_format_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"list",
"(",
"[",
"repr",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",... | Take the args, and kwargs that are passed them and format in a
prototype style. | [
"Take",
"the",
"args",
"and",
"kwargs",
"that",
"are",
"passed",
"them",
"and",
"format",
"in",
"a",
"prototype",
"style",
"."
] | 8148d7b7754226b0d1cabfc2af10cd912612abdc | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/exception.py#L16-L24 | train | 47,535 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/xml_prismjs.py | render | def render(file):
"""Pretty print the XML file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
parsed_xml = xml.dom.minidom.parseString(file_content)
return parsed_xml.toprettyxml(indent=' ', newl='') | python | def render(file):
"""Pretty print the XML file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
parsed_xml = xml.dom.minidom.parseString(file_content)
return parsed_xml.toprettyxml(indent=' ', newl='') | [
"def",
"render",
"(",
"file",
")",
":",
"with",
"file",
".",
"open",
"(",
")",
"as",
"fp",
":",
"encoding",
"=",
"detect_encoding",
"(",
"fp",
",",
"default",
"=",
"'utf-8'",
")",
"file_content",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"("... | Pretty print the XML file for rendering. | [
"Pretty",
"print",
"the",
"XML",
"file",
"for",
"rendering",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/xml_prismjs.py#L22-L28 | train | 47,536 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/xml_prismjs.py | validate_xml | def validate_xml(file):
"""Validate an XML file."""
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
content = fp.read().decode('utf-8')
xml.dom.minidom.parseString(content)
return True
except:
return False | python | def validate_xml(file):
"""Validate an XML file."""
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
content = fp.read().decode('utf-8')
xml.dom.minidom.parseString(content)
return True
except:
return False | [
"def",
"validate_xml",
"(",
"file",
")",
":",
"max_file_size",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'PREVIEWER_MAX_FILE_SIZE_BYTES'",
",",
"1",
"*",
"1024",
"*",
"1024",
")",
"if",
"file",
".",
"size",
">",
"max_file_size",
":",
"return",
"... | Validate an XML file. | [
"Validate",
"an",
"XML",
"file",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/xml_prismjs.py#L31-L44 | train | 47,537 |
paylogic/halogen | halogen/schema.py | _get_context | def _get_context(argspec, kwargs):
"""Prepare a context for the serialization.
:param argspec: The argspec of the serialization function.
:param kwargs: Dict with context
:return: Keywords arguments that function can accept.
"""
if argspec.keywords is not None:
return kwargs
return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs) | python | def _get_context(argspec, kwargs):
"""Prepare a context for the serialization.
:param argspec: The argspec of the serialization function.
:param kwargs: Dict with context
:return: Keywords arguments that function can accept.
"""
if argspec.keywords is not None:
return kwargs
return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs) | [
"def",
"_get_context",
"(",
"argspec",
",",
"kwargs",
")",
":",
"if",
"argspec",
".",
"keywords",
"is",
"not",
"None",
":",
"return",
"kwargs",
"return",
"dict",
"(",
"(",
"arg",
",",
"kwargs",
"[",
"arg",
"]",
")",
"for",
"arg",
"in",
"argspec",
"."... | Prepare a context for the serialization.
:param argspec: The argspec of the serialization function.
:param kwargs: Dict with context
:return: Keywords arguments that function can accept. | [
"Prepare",
"a",
"context",
"for",
"the",
"serialization",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L29-L38 | train | 47,538 |
paylogic/halogen | halogen/schema.py | Accessor.get | def get(self, obj, **kwargs):
"""Get an attribute from a value.
:param obj: Object to get the attribute value from.
:return: Value of object's attribute.
"""
assert self.getter is not None, "Getter accessor is not specified."
if callable(self.getter):
return self.getter(obj, **_get_context(self._getter_argspec, kwargs))
assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separated string."
for attr in self.getter.split("."):
if isinstance(obj, dict):
obj = obj[attr]
else:
obj = getattr(obj, attr)
if callable(obj):
return obj()
return obj | python | def get(self, obj, **kwargs):
"""Get an attribute from a value.
:param obj: Object to get the attribute value from.
:return: Value of object's attribute.
"""
assert self.getter is not None, "Getter accessor is not specified."
if callable(self.getter):
return self.getter(obj, **_get_context(self._getter_argspec, kwargs))
assert isinstance(self.getter, string_types), "Accessor must be a function or a dot-separated string."
for attr in self.getter.split("."):
if isinstance(obj, dict):
obj = obj[attr]
else:
obj = getattr(obj, attr)
if callable(obj):
return obj()
return obj | [
"def",
"get",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"getter",
"is",
"not",
"None",
",",
"\"Getter accessor is not specified.\"",
"if",
"callable",
"(",
"self",
".",
"getter",
")",
":",
"return",
"self",
".",
... | Get an attribute from a value.
:param obj: Object to get the attribute value from.
:return: Value of object's attribute. | [
"Get",
"an",
"attribute",
"from",
"a",
"value",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L54-L75 | train | 47,539 |
paylogic/halogen | halogen/schema.py | Accessor.set | def set(self, obj, value):
"""Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned.
"""
assert self.setter is not None, "Setter accessor is not specified."
if callable(self.setter):
return self.setter(obj, value)
assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string."
def _set(obj, attr, value):
if isinstance(obj, dict):
obj[attr] = value
else:
setattr(obj, attr, value)
return value
path = self.setter.split(".")
for attr in path[:-1]:
obj = _set(obj, attr, {})
_set(obj, path[-1], value) | python | def set(self, obj, value):
"""Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned.
"""
assert self.setter is not None, "Setter accessor is not specified."
if callable(self.setter):
return self.setter(obj, value)
assert isinstance(self.setter, string_types), "Accessor must be a function or a dot-separated string."
def _set(obj, attr, value):
if isinstance(obj, dict):
obj[attr] = value
else:
setattr(obj, attr, value)
return value
path = self.setter.split(".")
for attr in path[:-1]:
obj = _set(obj, attr, {})
_set(obj, path[-1], value) | [
"def",
"set",
"(",
"self",
",",
"obj",
",",
"value",
")",
":",
"assert",
"self",
".",
"setter",
"is",
"not",
"None",
",",
"\"Setter accessor is not specified.\"",
"if",
"callable",
"(",
"self",
".",
"setter",
")",
":",
"return",
"self",
".",
"setter",
"(... | Set value for obj's attribute.
:param obj: Result object or dict to assign the attribute to.
:param value: Value to be assigned. | [
"Set",
"value",
"for",
"obj",
"s",
"attribute",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L77-L100 | train | 47,540 |
paylogic/halogen | halogen/schema.py | Attr.accessor | def accessor(self):
"""Get an attribute's accessor with the getter and the setter.
:return: `Accessor` instance.
"""
if isinstance(self.attr, Accessor):
return self.attr
if callable(self.attr):
return Accessor(getter=self.attr)
attr = self.attr or self.name
return Accessor(getter=attr, setter=attr) | python | def accessor(self):
"""Get an attribute's accessor with the getter and the setter.
:return: `Accessor` instance.
"""
if isinstance(self.attr, Accessor):
return self.attr
if callable(self.attr):
return Accessor(getter=self.attr)
attr = self.attr or self.name
return Accessor(getter=attr, setter=attr) | [
"def",
"accessor",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"attr",
",",
"Accessor",
")",
":",
"return",
"self",
".",
"attr",
"if",
"callable",
"(",
"self",
".",
"attr",
")",
":",
"return",
"Accessor",
"(",
"getter",
"=",
"self",
... | Get an attribute's accessor with the getter and the setter.
:return: `Accessor` instance. | [
"Get",
"an",
"attribute",
"s",
"accessor",
"with",
"the",
"getter",
"and",
"the",
"setter",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L144-L156 | train | 47,541 |
paylogic/halogen | halogen/schema.py | Attr.serialize | def serialize(self, value, **kwargs):
"""Serialize the attribute of the input data.
Gets the attribute value with accessor and converts it using the
type serialization. Schema will place this serialized value into
corresponding compartment of the HAL structure with the name of the
attribute as a key.
:param value: Value to get the attribute value from.
:return: Serialized attribute value.
"""
if types.Type.is_type(self.attr_type):
try:
value = self.accessor.get(value, **kwargs)
except (AttributeError, KeyError):
if not hasattr(self, "default") and self.required:
raise
value = self.default() if callable(self.default) else self.default
return self.attr_type.serialize(value, **_get_context(self._attr_type_serialize_argspec, kwargs))
return self.attr_type | python | def serialize(self, value, **kwargs):
"""Serialize the attribute of the input data.
Gets the attribute value with accessor and converts it using the
type serialization. Schema will place this serialized value into
corresponding compartment of the HAL structure with the name of the
attribute as a key.
:param value: Value to get the attribute value from.
:return: Serialized attribute value.
"""
if types.Type.is_type(self.attr_type):
try:
value = self.accessor.get(value, **kwargs)
except (AttributeError, KeyError):
if not hasattr(self, "default") and self.required:
raise
value = self.default() if callable(self.default) else self.default
return self.attr_type.serialize(value, **_get_context(self._attr_type_serialize_argspec, kwargs))
return self.attr_type | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"types",
".",
"Type",
".",
"is_type",
"(",
"self",
".",
"attr_type",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"accessor",
".",
"get",
"(",
"value",
",... | Serialize the attribute of the input data.
Gets the attribute value with accessor and converts it using the
type serialization. Schema will place this serialized value into
corresponding compartment of the HAL structure with the name of the
attribute as a key.
:param value: Value to get the attribute value from.
:return: Serialized attribute value. | [
"Serialize",
"the",
"attribute",
"of",
"the",
"input",
"data",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L162-L183 | train | 47,542 |
paylogic/halogen | halogen/schema.py | Attr.deserialize | def deserialize(self, value, **kwargs):
"""Deserialize the attribute from a HAL structure.
Get the value from the HAL structure from the attribute's compartment
using the attribute's name as a key, convert it using the attribute's
type. Schema will either return it to parent schema or will assign
to the output value if specified using the attribute's accessor setter.
:param value: HAL structure to get the value from.
:return: Deserialized attribute value.
:raises: ValidationError.
"""
compartment = value
if self.compartment is not None:
compartment = value[self.compartment]
try:
value = self.accessor.get(compartment, **kwargs)
except (KeyError, AttributeError):
if not hasattr(self, "default") and self.required:
raise
return self.default() if callable(self.default) else self.default
return self.attr_type.deserialize(value, **kwargs) | python | def deserialize(self, value, **kwargs):
"""Deserialize the attribute from a HAL structure.
Get the value from the HAL structure from the attribute's compartment
using the attribute's name as a key, convert it using the attribute's
type. Schema will either return it to parent schema or will assign
to the output value if specified using the attribute's accessor setter.
:param value: HAL structure to get the value from.
:return: Deserialized attribute value.
:raises: ValidationError.
"""
compartment = value
if self.compartment is not None:
compartment = value[self.compartment]
try:
value = self.accessor.get(compartment, **kwargs)
except (KeyError, AttributeError):
if not hasattr(self, "default") and self.required:
raise
return self.default() if callable(self.default) else self.default
return self.attr_type.deserialize(value, **kwargs) | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"compartment",
"=",
"value",
"if",
"self",
".",
"compartment",
"is",
"not",
"None",
":",
"compartment",
"=",
"value",
"[",
"self",
".",
"compartment",
"]",
"try",
":",
... | Deserialize the attribute from a HAL structure.
Get the value from the HAL structure from the attribute's compartment
using the attribute's name as a key, convert it using the attribute's
type. Schema will either return it to parent schema or will assign
to the output value if specified using the attribute's accessor setter.
:param value: HAL structure to get the value from.
:return: Deserialized attribute value.
:raises: ValidationError. | [
"Deserialize",
"the",
"attribute",
"from",
"a",
"HAL",
"structure",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L185-L209 | train | 47,543 |
paylogic/halogen | halogen/schema.py | Embedded.key | def key(self):
"""Embedded supports curies."""
if self.curie is None:
return self.name
return ":".join((self.curie.name, self.name)) | python | def key(self):
"""Embedded supports curies."""
if self.curie is None:
return self.name
return ":".join((self.curie.name, self.name)) | [
"def",
"key",
"(",
"self",
")",
":",
"if",
"self",
".",
"curie",
"is",
"None",
":",
"return",
"self",
".",
"name",
"return",
"\":\"",
".",
"join",
"(",
"(",
"self",
".",
"curie",
".",
"name",
",",
"self",
".",
"name",
")",
")"
] | Embedded supports curies. | [
"Embedded",
"supports",
"curies",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L376-L380 | train | 47,544 |
paylogic/halogen | halogen/schema.py | _Schema.deserialize | def deserialize(cls, value, output=None, **kwargs):
"""Deserialize the HAL structure into the output value.
:param value: Dict of already loaded json which will be deserialized by schema attributes.
:param output: If present, the output object will be updated instead of returning the deserialized data.
:returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is
deserialized value from value dict.
:raises: ValidationError.
"""
errors = []
result = {}
for attr in cls.__attrs__.values():
try:
result[attr.name] = attr.deserialize(value, **kwargs)
except NotImplementedError:
# Links don't support deserialization
continue
except ValueError as e:
errors.append(exceptions.ValidationError(e, attr.name))
except exceptions.ValidationError as e:
e.attr = attr.name
errors.append(e)
except (KeyError, AttributeError):
if attr.required:
errors.append(exceptions.ValidationError("Missing attribute.", attr.name))
if errors:
raise exceptions.ValidationError(errors)
if output is None:
return result
for attr in cls.__attrs__.values():
if attr.name in result:
attr.accessor.set(output, result[attr.name]) | python | def deserialize(cls, value, output=None, **kwargs):
"""Deserialize the HAL structure into the output value.
:param value: Dict of already loaded json which will be deserialized by schema attributes.
:param output: If present, the output object will be updated instead of returning the deserialized data.
:returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is
deserialized value from value dict.
:raises: ValidationError.
"""
errors = []
result = {}
for attr in cls.__attrs__.values():
try:
result[attr.name] = attr.deserialize(value, **kwargs)
except NotImplementedError:
# Links don't support deserialization
continue
except ValueError as e:
errors.append(exceptions.ValidationError(e, attr.name))
except exceptions.ValidationError as e:
e.attr = attr.name
errors.append(e)
except (KeyError, AttributeError):
if attr.required:
errors.append(exceptions.ValidationError("Missing attribute.", attr.name))
if errors:
raise exceptions.ValidationError(errors)
if output is None:
return result
for attr in cls.__attrs__.values():
if attr.name in result:
attr.accessor.set(output, result[attr.name]) | [
"def",
"deserialize",
"(",
"cls",
",",
"value",
",",
"output",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"result",
"=",
"{",
"}",
"for",
"attr",
"in",
"cls",
".",
"__attrs__",
".",
"values",
"(",
")",
":",
"try",
... | Deserialize the HAL structure into the output value.
:param value: Dict of already loaded json which will be deserialized by schema attributes.
:param output: If present, the output object will be updated instead of returning the deserialized data.
:returns: Dict of deserialized value for attributes. Where key is name of schema's attribute and value is
deserialized value from value dict.
:raises: ValidationError. | [
"Deserialize",
"the",
"HAL",
"structure",
"into",
"the",
"output",
"value",
"."
] | 2dec0a67c506d02d1f51915fa7163f59764a0bde | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/schema.py#L416-L450 | train | 47,545 |
dhondta/tinyscript | tinyscript/helpers/types.py | neg_int | def neg_int(i):
""" Simple negative integer validation. """
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i > 0:
raise Exception()
except:
raise ValueError("Not a negative integer")
return i | python | def neg_int(i):
""" Simple negative integer validation. """
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i > 0:
raise Exception()
except:
raise ValueError("Not a negative integer")
return i | [
"def",
"neg_int",
"(",
"i",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"i",
",",
"string_types",
")",
":",
"i",
"=",
"int",
"(",
"i",
")",
"if",
"not",
"isinstance",
"(",
"i",
",",
"int",
")",
"or",
"i",
">",
"0",
":",
"raise",
"Exception",... | Simple negative integer validation. | [
"Simple",
"negative",
"integer",
"validation",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L21-L30 | train | 47,546 |
dhondta/tinyscript | tinyscript/helpers/types.py | pos_int | def pos_int(i):
""" Simple positive integer validation. """
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i < 0:
raise Exception()
except:
raise ValueError("Not a positive integer")
return i | python | def pos_int(i):
""" Simple positive integer validation. """
try:
if isinstance(i, string_types):
i = int(i)
if not isinstance(i, int) or i < 0:
raise Exception()
except:
raise ValueError("Not a positive integer")
return i | [
"def",
"pos_int",
"(",
"i",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"i",
",",
"string_types",
")",
":",
"i",
"=",
"int",
"(",
"i",
")",
"if",
"not",
"isinstance",
"(",
"i",
",",
"int",
")",
"or",
"i",
"<",
"0",
":",
"raise",
"Exception",... | Simple positive integer validation. | [
"Simple",
"positive",
"integer",
"validation",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L34-L43 | train | 47,547 |
dhondta/tinyscript | tinyscript/helpers/types.py | ints | def ints(l, ifilter=lambda x: x, idescr=None):
""" Parses a comma-separated list of ints. """
if isinstance(l, string_types):
if l[0] == '[' and l[-1] == ']':
l = l[1:-1]
l = list(map(lambda x: x.strip(), l.split(',')))
try:
l = list(map(ifilter, list(map(int, l))))
except:
raise ValueError("Bad list of {}integers"
.format("" if idescr is None else idescr + " "))
return l | python | def ints(l, ifilter=lambda x: x, idescr=None):
""" Parses a comma-separated list of ints. """
if isinstance(l, string_types):
if l[0] == '[' and l[-1] == ']':
l = l[1:-1]
l = list(map(lambda x: x.strip(), l.split(',')))
try:
l = list(map(ifilter, list(map(int, l))))
except:
raise ValueError("Bad list of {}integers"
.format("" if idescr is None else idescr + " "))
return l | [
"def",
"ints",
"(",
"l",
",",
"ifilter",
"=",
"lambda",
"x",
":",
"x",
",",
"idescr",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"l",
",",
"string_types",
")",
":",
"if",
"l",
"[",
"0",
"]",
"==",
"'['",
"and",
"l",
"[",
"-",
"1",
"]",
... | Parses a comma-separated list of ints. | [
"Parses",
"a",
"comma",
"-",
"separated",
"list",
"of",
"ints",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L47-L58 | train | 47,548 |
dhondta/tinyscript | tinyscript/helpers/types.py | ip_address_list | def ip_address_list(ips):
""" IP address range validation and expansion. """
# first, try it as a single IP address
try:
return ip_address(ips)
except ValueError:
pass
# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
return list(ipaddress.ip_network(u(ips)).hosts()) | python | def ip_address_list(ips):
""" IP address range validation and expansion. """
# first, try it as a single IP address
try:
return ip_address(ips)
except ValueError:
pass
# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
return list(ipaddress.ip_network(u(ips)).hosts()) | [
"def",
"ip_address_list",
"(",
"ips",
")",
":",
"# first, try it as a single IP address",
"try",
":",
"return",
"ip_address",
"(",
"ips",
")",
"except",
"ValueError",
":",
"pass",
"# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it",
"return",
"list",
... | IP address range validation and expansion. | [
"IP",
"address",
"range",
"validation",
"and",
"expansion",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L72-L80 | train | 47,549 |
dhondta/tinyscript | tinyscript/helpers/types.py | port_number | def port_number(port):
""" Port number validation. """
try:
port = int(port)
except ValueError:
raise ValueError("Bad port number")
if not 0 <= port < 2 ** 16:
raise ValueError("Bad port number")
return port | python | def port_number(port):
""" Port number validation. """
try:
port = int(port)
except ValueError:
raise ValueError("Bad port number")
if not 0 <= port < 2 ** 16:
raise ValueError("Bad port number")
return port | [
"def",
"port_number",
"(",
"port",
")",
":",
"try",
":",
"port",
"=",
"int",
"(",
"port",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Bad port number\"",
")",
"if",
"not",
"0",
"<=",
"port",
"<",
"2",
"**",
"16",
":",
"raise",
"V... | Port number validation. | [
"Port",
"number",
"validation",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L94-L102 | train | 47,550 |
dhondta/tinyscript | tinyscript/helpers/types.py | port_number_range | def port_number_range(prange):
""" Port number range validation and expansion. """
# first, try it as a normal port number
try:
return port_number(prange)
except ValueError:
pass
# then, consider it as a range with the format "x-y" and expand it
try:
bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups()))
if bounds[0] > bounds[1]:
raise AttributeError()
except (AttributeError, TypeError):
raise ValueError("Bad port number range")
return list(range(bounds[0], bounds[1] + 1)) | python | def port_number_range(prange):
""" Port number range validation and expansion. """
# first, try it as a normal port number
try:
return port_number(prange)
except ValueError:
pass
# then, consider it as a range with the format "x-y" and expand it
try:
bounds = list(map(int, re.match(r'^(\d+)\-(\d+)$', prange).groups()))
if bounds[0] > bounds[1]:
raise AttributeError()
except (AttributeError, TypeError):
raise ValueError("Bad port number range")
return list(range(bounds[0], bounds[1] + 1)) | [
"def",
"port_number_range",
"(",
"prange",
")",
":",
"# first, try it as a normal port number",
"try",
":",
"return",
"port_number",
"(",
"prange",
")",
"except",
"ValueError",
":",
"pass",
"# then, consider it as a range with the format \"x-y\" and expand it",
"try",
":",
... | Port number range validation and expansion. | [
"Port",
"number",
"range",
"validation",
"and",
"expansion",
"."
] | 624a0718db698899e7bc3ba6ac694baed251e81d | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/types.py#L105-L119 | train | 47,551 |
d0ugal/python-rfxcom | rfxcom/protocol/base.py | BasePacket.parse_header_part | def parse_header_part(self, data):
"""Extracts and converts the RFX common header part of all valid
packets to a plain dictionary. RFX header part is the 4 bytes prior
the sensor vendor specific data part.
The RFX common header part contains respectively:
- packet length
- packet type
- packet sub-type
- sequence number
:param data: bytearray of received data
:type data: bytearray
"""
packet_length = data[0]
packet_type = data[1]
packet_subtype = data[2]
sequence_number = data[3]
return {
'packet_length': packet_length,
'packet_type': packet_type,
'packet_type_name': self.PACKET_TYPES.get(packet_type),
'packet_subtype': packet_subtype,
'packet_subtype_name': self.PACKET_SUBTYPES.get(packet_subtype),
'sequence_number': sequence_number
} | python | def parse_header_part(self, data):
"""Extracts and converts the RFX common header part of all valid
packets to a plain dictionary. RFX header part is the 4 bytes prior
the sensor vendor specific data part.
The RFX common header part contains respectively:
- packet length
- packet type
- packet sub-type
- sequence number
:param data: bytearray of received data
:type data: bytearray
"""
packet_length = data[0]
packet_type = data[1]
packet_subtype = data[2]
sequence_number = data[3]
return {
'packet_length': packet_length,
'packet_type': packet_type,
'packet_type_name': self.PACKET_TYPES.get(packet_type),
'packet_subtype': packet_subtype,
'packet_subtype_name': self.PACKET_SUBTYPES.get(packet_subtype),
'sequence_number': sequence_number
} | [
"def",
"parse_header_part",
"(",
"self",
",",
"data",
")",
":",
"packet_length",
"=",
"data",
"[",
"0",
"]",
"packet_type",
"=",
"data",
"[",
"1",
"]",
"packet_subtype",
"=",
"data",
"[",
"2",
"]",
"sequence_number",
"=",
"data",
"[",
"3",
"]",
"return... | Extracts and converts the RFX common header part of all valid
packets to a plain dictionary. RFX header part is the 4 bytes prior
the sensor vendor specific data part.
The RFX common header part contains respectively:
- packet length
- packet type
- packet sub-type
- sequence number
:param data: bytearray of received data
:type data: bytearray | [
"Extracts",
"and",
"converts",
"the",
"RFX",
"common",
"header",
"part",
"of",
"all",
"valid",
"packets",
"to",
"a",
"plain",
"dictionary",
".",
"RFX",
"header",
"part",
"is",
"the",
"4",
"bytes",
"prior",
"the",
"sensor",
"vendor",
"specific",
"data",
"pa... | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L58-L84 | train | 47,552 |
d0ugal/python-rfxcom | rfxcom/protocol/base.py | BasePacket.load | def load(self, data):
"""This is the entrance method for all data which is used to store the
raw data and start parsing the data.
:param data: The raw untouched bytearray as recieved by the RFXtrx
:type data: bytearray
:return: The parsed data represented in a dictionary
:rtype: dict
"""
self.loaded_at = datetime.utcnow()
self.raw = data
self.data = self.parse(data)
return self.data | python | def load(self, data):
"""This is the entrance method for all data which is used to store the
raw data and start parsing the data.
:param data: The raw untouched bytearray as recieved by the RFXtrx
:type data: bytearray
:return: The parsed data represented in a dictionary
:rtype: dict
"""
self.loaded_at = datetime.utcnow()
self.raw = data
self.data = self.parse(data)
return self.data | [
"def",
"load",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"loaded_at",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"raw",
"=",
"data",
"self",
".",
"data",
"=",
"self",
".",
"parse",
"(",
"data",
")",
"return",
"self",
".",
"data... | This is the entrance method for all data which is used to store the
raw data and start parsing the data.
:param data: The raw untouched bytearray as recieved by the RFXtrx
:type data: bytearray
:return: The parsed data represented in a dictionary
:rtype: dict | [
"This",
"is",
"the",
"entrance",
"method",
"for",
"all",
"data",
"which",
"is",
"used",
"to",
"store",
"the",
"raw",
"data",
"and",
"start",
"parsing",
"the",
"data",
"."
] | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L86-L99 | train | 47,553 |
d0ugal/python-rfxcom | rfxcom/protocol/base.py | BasePacketHandler.validate_packet | def validate_packet(self, data):
"""Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of defined PACKET_TYPES for this class.
- The third byte is in the set of this class defined PACKET_SUBTYPES.
If one or more of these conditions isn't met then we have a packet that
isn't valid or at least isn't understood by this handler.
:param data: bytearray to be verified
:type data: bytearray
:raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the
number of bytes in the packet doesn't match the expected length.
:raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet
type is unknown to this packet handler
:raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the
packet sub type is unknown to this packet handler
:return: true is returned if validation passes.
:rtype: boolean
"""
# Validate length.
# The first byte in the packet should be equal to the number of
# remaining bytes (i.e. length excluding the first byte).
expected_length = data[0] + 1
if len(data) != expected_length:
raise InvalidPacketLength(
"Expected packet length to be %s bytes but it was %s bytes"
% (expected_length, len(data))
)
# Validate minimal length.
# The packet contains at least the RFX header:
# packet_length (1 byte) + packet_type (1 byte)
# + packet_subtype (1 byte) + sequence_number (1 byte)
if expected_length < 4:
raise MalformedPacket(
"Expected packet length to be larger than 4 bytes but \
it was %s bytes"
% (len(data))
)
# Validate Packet Type.
# This specifies the family of devices.
# Check it is one of the supported packet types
packet_type = data[1]
if self.PACKET_TYPES and packet_type not in self.PACKET_TYPES:
types = ",".join("0x{:02x}".format(pt) for pt in self.PACKET_TYPES)
raise UnknownPacketType(
"Expected packet type to be one of [%s] but recieved %s"
% (types, packet_type)
)
# Validate Packet Subtype.
# This specifies the sub-family of devices.
# Check it is one of the supported packet subtypes for current type
sub_type = data[2]
if self.PACKET_SUBTYPES and sub_type not in self.PACKET_SUBTYPES:
types = \
",".join("0x{:02x}".format(pt) for pt in self.PACKET_SUBTYPES)
raise UnknownPacketSubtype(
"Expected packet type to be one of [%s] but recieved %s"
% (types, sub_type))
return True | python | def validate_packet(self, data):
"""Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of defined PACKET_TYPES for this class.
- The third byte is in the set of this class defined PACKET_SUBTYPES.
If one or more of these conditions isn't met then we have a packet that
isn't valid or at least isn't understood by this handler.
:param data: bytearray to be verified
:type data: bytearray
:raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the
number of bytes in the packet doesn't match the expected length.
:raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet
type is unknown to this packet handler
:raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the
packet sub type is unknown to this packet handler
:return: true is returned if validation passes.
:rtype: boolean
"""
# Validate length.
# The first byte in the packet should be equal to the number of
# remaining bytes (i.e. length excluding the first byte).
expected_length = data[0] + 1
if len(data) != expected_length:
raise InvalidPacketLength(
"Expected packet length to be %s bytes but it was %s bytes"
% (expected_length, len(data))
)
# Validate minimal length.
# The packet contains at least the RFX header:
# packet_length (1 byte) + packet_type (1 byte)
# + packet_subtype (1 byte) + sequence_number (1 byte)
if expected_length < 4:
raise MalformedPacket(
"Expected packet length to be larger than 4 bytes but \
it was %s bytes"
% (len(data))
)
# Validate Packet Type.
# This specifies the family of devices.
# Check it is one of the supported packet types
packet_type = data[1]
if self.PACKET_TYPES and packet_type not in self.PACKET_TYPES:
types = ",".join("0x{:02x}".format(pt) for pt in self.PACKET_TYPES)
raise UnknownPacketType(
"Expected packet type to be one of [%s] but recieved %s"
% (types, packet_type)
)
# Validate Packet Subtype.
# This specifies the sub-family of devices.
# Check it is one of the supported packet subtypes for current type
sub_type = data[2]
if self.PACKET_SUBTYPES and sub_type not in self.PACKET_SUBTYPES:
types = \
",".join("0x{:02x}".format(pt) for pt in self.PACKET_SUBTYPES)
raise UnknownPacketSubtype(
"Expected packet type to be one of [%s] but recieved %s"
% (types, sub_type))
return True | [
"def",
"validate_packet",
"(",
"self",
",",
"data",
")",
":",
"# Validate length.",
"# The first byte in the packet should be equal to the number of",
"# remaining bytes (i.e. length excluding the first byte).",
"expected_length",
"=",
"data",
"[",
"0",
"]",
"+",
"1",
"if",
"... | Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of defined PACKET_TYPES for this class.
- The third byte is in the set of this class defined PACKET_SUBTYPES.
If one or more of these conditions isn't met then we have a packet that
isn't valid or at least isn't understood by this handler.
:param data: bytearray to be verified
:type data: bytearray
:raises: :py:class:`rfxcom.exceptions.InvalidPacketLength`: If the
number of bytes in the packet doesn't match the expected length.
:raises: :py:class:`rfxcom.exceptions.UnknownPacketType`: If the packet
type is unknown to this packet handler
:raises: :py:class:`rfxcom.exceptions.UnknownPacketSubtype`: If the
packet sub type is unknown to this packet handler
:return: true is returned if validation passes.
:rtype: boolean | [
"Validate",
"a",
"packet",
"against",
"this",
"packet",
"handler",
"and",
"determine",
"if",
"it",
"meets",
"the",
"requirements",
".",
"This",
"is",
"done",
"by",
"checking",
"the",
"following",
"conditions",
"are",
"true",
"."
] | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/base.py#L122-L198 | train | 47,554 |
toumorokoshi/transmute-core | transmute_core/object_serializers/schematics_serializer.py | _enforce_instance | def _enforce_instance(model_or_class):
"""
It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor.
"""
if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType):
return model_or_class()
return model_or_class | python | def _enforce_instance(model_or_class):
"""
It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor.
"""
if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType):
return model_or_class()
return model_or_class | [
"def",
"_enforce_instance",
"(",
"model_or_class",
")",
":",
"if",
"isinstance",
"(",
"model_or_class",
",",
"type",
")",
"and",
"issubclass",
"(",
"model_or_class",
",",
"BaseType",
")",
":",
"return",
"model_or_class",
"(",
")",
"return",
"model_or_class"
] | It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor. | [
"It",
"s",
"a",
"common",
"mistake",
"to",
"not",
"initialize",
"a",
"schematics",
"class",
".",
"We",
"should",
"handle",
"that",
"by",
"just",
"calling",
"the",
"default",
"constructor",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/schematics_serializer.py#L177-L185 | train | 47,555 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/ipynb.py | render | def render(file):
"""Generate the result HTML."""
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources | python | def render(file):
"""Generate the result HTML."""
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources | [
"def",
"render",
"(",
"file",
")",
":",
"fp",
"=",
"file",
".",
"open",
"(",
")",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"fp",
".",
"close",
"(",
")",
"notebook",
"=",
"nbformat",
".",
"reads",
"(",
"content",
".",
"decode",
"(",
"'utf-8'",... | Generate the result HTML. | [
"Generate",
"the",
"result",
"HTML",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/ipynb.py#L18-L29 | train | 47,556 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/ipynb.py | preview | def preview(file):
"""Render the IPython Notebook."""
body, resources = render(file)
default_ipython_style = resources['inlining']['css'][1]
return render_template(
'invenio_previewer/ipynb.html',
file=file,
content=body,
style=default_ipython_style
) | python | def preview(file):
"""Render the IPython Notebook."""
body, resources = render(file)
default_ipython_style = resources['inlining']['css'][1]
return render_template(
'invenio_previewer/ipynb.html',
file=file,
content=body,
style=default_ipython_style
) | [
"def",
"preview",
"(",
"file",
")",
":",
"body",
",",
"resources",
"=",
"render",
"(",
"file",
")",
"default_ipython_style",
"=",
"resources",
"[",
"'inlining'",
"]",
"[",
"'css'",
"]",
"[",
"1",
"]",
"return",
"render_template",
"(",
"'invenio_previewer/ipy... | Render the IPython Notebook. | [
"Render",
"the",
"IPython",
"Notebook",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/ipynb.py#L37-L46 | train | 47,557 |
toumorokoshi/transmute-core | example.py | transmute_route | def transmute_route(app, fn, context=default_context):
"""
this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application.
"""
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
"""
the route being attached is a great place to start building up a
swagger spec. the SwaggerSpec object handles creating the
swagger spec from transmute routes for you.
almost all web frameworks provide some app-specific context
that one can add values to. It's recommended to attach
and retrieve the swagger spec from there.
"""
if not hasattr(app, SWAGGER_ATTR_NAME):
setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app.route(r, methods=transmute_func.methods)(handler) | python | def transmute_route(app, fn, context=default_context):
"""
this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application.
"""
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
"""
the route being attached is a great place to start building up a
swagger spec. the SwaggerSpec object handles creating the
swagger spec from transmute routes for you.
almost all web frameworks provide some app-specific context
that one can add values to. It's recommended to attach
and retrieve the swagger spec from there.
"""
if not hasattr(app, SWAGGER_ATTR_NAME):
setattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app.route(r, methods=transmute_func.methods)(handler) | [
"def",
"transmute_route",
"(",
"app",
",",
"fn",
",",
"context",
"=",
"default_context",
")",
":",
"transmute_func",
"=",
"TransmuteFunction",
"(",
"fn",
")",
"routes",
",",
"handler",
"=",
"create_routes_and_handler",
"(",
"transmute_func",
",",
"context",
")",... | this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application. | [
"this",
"is",
"the",
"main",
"interface",
"to",
"transmute",
".",
"It",
"will",
"handle",
"adding",
"converting",
"the",
"python",
"function",
"into",
"the",
"a",
"flask",
"-",
"compatible",
"route",
"and",
"adding",
"it",
"to",
"the",
"application",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L27-L49 | train | 47,558 |
toumorokoshi/transmute-core | example.py | create_routes_and_handler | def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
"""
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args, kwargs = ParamExtractorFlask().extract_params(
context, transmute_func, request.content_type
)
result = transmute_func(*args, **kwargs)
except Exception as e:
exc = e
"""
attaching the traceack is done for you in Python 3, but
in Python 2 the __traceback__ must be
attached to the object manually.
"""
exc.__traceback__ = sys.exc_info()[2]
"""
transmute_func.process_result handles converting
the response from the function into the response body,
the status code that should be returned, and the
response content-type.
"""
response = transmute_func.process_result(
context, result, exc, request.content_type
)
return Response(
response["body"],
status=response["code"],
mimetype=response["content-type"],
headers=response["headers"]
)
return (
_convert_paths_to_flask(transmute_func.paths),
handler
) | python | def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
"""
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args, kwargs = ParamExtractorFlask().extract_params(
context, transmute_func, request.content_type
)
result = transmute_func(*args, **kwargs)
except Exception as e:
exc = e
"""
attaching the traceack is done for you in Python 3, but
in Python 2 the __traceback__ must be
attached to the object manually.
"""
exc.__traceback__ = sys.exc_info()[2]
"""
transmute_func.process_result handles converting
the response from the function into the response body,
the status code that should be returned, and the
response content-type.
"""
response = transmute_func.process_result(
context, result, exc, request.content_type
)
return Response(
response["body"],
status=response["code"],
mimetype=response["content-type"],
headers=response["headers"]
)
return (
_convert_paths_to_flask(transmute_func.paths),
handler
) | [
"def",
"create_routes_and_handler",
"(",
"transmute_func",
",",
"context",
")",
":",
"@",
"wraps",
"(",
"transmute_func",
".",
"raw_func",
")",
"def",
"handler",
"(",
")",
":",
"exc",
",",
"result",
"=",
"None",
",",
"None",
"try",
":",
"args",
",",
"kwa... | return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to. | [
"return",
"back",
"a",
"handler",
"that",
"is",
"the",
"api",
"generated",
"from",
"the",
"transmute_func",
"and",
"a",
"list",
"of",
"routes",
"it",
"should",
"be",
"mounted",
"to",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L52-L92 | train | 47,559 |
toumorokoshi/transmute-core | example.py | add_swagger | def add_swagger(app, json_route, html_route, **kwargs):
"""
add a swagger html page, and a swagger.json generated
from the routes added to the app.
"""
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = json.dumps(spec).encode("UTF-8")
@app.route(json_route)
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can be requested at swagger.io
headers={"Access-Control-Allow-Origin": "*"},
content_type="application/json",
)
# add the statics
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_PATH, json_route
).encode("utf-8")
@app.route(html_route)
def swagger_ui():
return Response(swagger_body, content_type="text/html")
# the blueprint work is the easiest way to integrate a static
# directory into flask.
blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,
static_folder=static_root)
app.register_blueprint(blueprint) | python | def add_swagger(app, json_route, html_route, **kwargs):
"""
add a swagger html page, and a swagger.json generated
from the routes added to the app.
"""
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = json.dumps(spec).encode("UTF-8")
@app.route(json_route)
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can be requested at swagger.io
headers={"Access-Control-Allow-Origin": "*"},
content_type="application/json",
)
# add the statics
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_PATH, json_route
).encode("utf-8")
@app.route(html_route)
def swagger_ui():
return Response(swagger_body, content_type="text/html")
# the blueprint work is the easiest way to integrate a static
# directory into flask.
blueprint = Blueprint('swagger', __name__, static_url_path=STATIC_PATH,
static_folder=static_root)
app.register_blueprint(blueprint) | [
"def",
"add_swagger",
"(",
"app",
",",
"json_route",
",",
"html_route",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"getattr",
"(",
"app",
",",
"SWAGGER_ATTR_NAME",
")",
"if",
"spec",
":",
"spec",
"=",
"spec",
".",
"swagger_definition",
"(",
"*",
"... | add a swagger html page, and a swagger.json generated
from the routes added to the app. | [
"add",
"a",
"swagger",
"html",
"page",
"and",
"a",
"swagger",
".",
"json",
"generated",
"from",
"the",
"routes",
"added",
"to",
"the",
"app",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/example.py#L155-L190 | train | 47,560 |
d0ugal/python-rfxcom | rfxcom/protocol/status.py | Status._log_enabled_protocols | def _log_enabled_protocols(self, flags, protocols):
"""Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zipped together to create the mapping.
Then return a tuple of two lists containing the names of the enabled
and disabled protocols.
:param character: A list of single character strings of 1's and 0's
:type character: list
:param protocols: A list of protocol names.
:type protocols: list
:return: Tuple containing two lists which contain n strings.
:rtype: tuple
"""
enabled, disabled = [], []
for procol, flag in sorted(zip(protocols, flags)):
if flag == '1':
enabled.append(procol)
status = 'Enabled'
else:
disabled.append(procol)
status = 'Disabled'
message = "{0:21}: {1}".format(procol, status)
self.log.info(message)
return enabled, disabled | python | def _log_enabled_protocols(self, flags, protocols):
"""Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zipped together to create the mapping.
Then return a tuple of two lists containing the names of the enabled
and disabled protocols.
:param character: A list of single character strings of 1's and 0's
:type character: list
:param protocols: A list of protocol names.
:type protocols: list
:return: Tuple containing two lists which contain n strings.
:rtype: tuple
"""
enabled, disabled = [], []
for procol, flag in sorted(zip(protocols, flags)):
if flag == '1':
enabled.append(procol)
status = 'Enabled'
else:
disabled.append(procol)
status = 'Disabled'
message = "{0:21}: {1}".format(procol, status)
self.log.info(message)
return enabled, disabled | [
"def",
"_log_enabled_protocols",
"(",
"self",
",",
"flags",
",",
"protocols",
")",
":",
"enabled",
",",
"disabled",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"procol",
",",
"flag",
"in",
"sorted",
"(",
"zip",
"(",
"protocols",
",",
"flags",
")",
")",
":",... | Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zipped together to create the mapping.
Then return a tuple of two lists containing the names of the enabled
and disabled protocols.
:param character: A list of single character strings of 1's and 0's
:type character: list
:param protocols: A list of protocol names.
:type protocols: list
:return: Tuple containing two lists which contain n strings.
:rtype: tuple | [
"Given",
"a",
"list",
"of",
"single",
"character",
"strings",
"of",
"1",
"s",
"and",
"0",
"s",
"and",
"a",
"list",
"of",
"protocol",
"names",
".",
"Log",
"the",
"status",
"of",
"each",
"protocol",
"where",
"1",
"is",
"enabled",
"and",
"0",
"is",
"dis... | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/status.py#L98-L130 | train | 47,561 |
d0ugal/python-rfxcom | rfxcom/protocol/status.py | Status.parse | def parse(self, data):
"""Parse a 13 byte packet in the Status format.
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
packet_length = data[0]
packet_type = data[1]
sub_type = data[2]
sequence_number = data[3]
command_type = data[4]
transceiver_type = data[5]
transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5])
firmware_version = data[6]
flags = self._int_to_binary_list(data[7])
flags.extend(self._int_to_binary_list(data[8]))
flags.extend(self._int_to_binary_list(data[9]))
enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS)
return {
'packet_length': packet_length,
'packet_type': packet_type,
'packet_type_name': self.PACKET_TYPES.get(packet_type),
'sequence_number': sequence_number,
'sub_type': sub_type,
'sub_type_name': self.PACKET_SUBTYPES.get(sub_type),
'command_type': command_type,
'transceiver_type': transceiver_type,
'transceiver_type_text': transceiver_type_text,
'firmware_version': firmware_version,
'enabled_protocols': enabled,
'disabled_protocols': disabled,
} | python | def parse(self, data):
"""Parse a 13 byte packet in the Status format.
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
packet_length = data[0]
packet_type = data[1]
sub_type = data[2]
sequence_number = data[3]
command_type = data[4]
transceiver_type = data[5]
transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5])
firmware_version = data[6]
flags = self._int_to_binary_list(data[7])
flags.extend(self._int_to_binary_list(data[8]))
flags.extend(self._int_to_binary_list(data[9]))
enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS)
return {
'packet_length': packet_length,
'packet_type': packet_type,
'packet_type_name': self.PACKET_TYPES.get(packet_type),
'sequence_number': sequence_number,
'sub_type': sub_type,
'sub_type_name': self.PACKET_SUBTYPES.get(sub_type),
'command_type': command_type,
'transceiver_type': transceiver_type,
'transceiver_type_text': transceiver_type_text,
'firmware_version': firmware_version,
'enabled_protocols': enabled,
'disabled_protocols': disabled,
} | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"packet_length",
"=",
"data",
"[",
"0",
"]",
"packet_type",
"=",
"data",
"[",
"1",
"]",
"sub_type",
"=",
"data",
"[",
"2",
"]",
"sequence_number",
"... | Parse a 13 byte packet in the Status format.
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict | [
"Parse",
"a",
"13",
"byte",
"packet",
"in",
"the",
"Status",
"format",
"."
] | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/status.py#L144-L184 | train | 47,562 |
toumorokoshi/transmute-core | transmute_core/swagger/template.py | _capture_variable | def _capture_variable(iterator, parameters):
"""
return the replacement string.
this assumes the preceeding {{ has already been
popped off.
"""
key = ""
next_c = next(iterator)
while next_c != "}":
key += next_c
next_c = next(iterator)
# remove the final "}"
next(iterator)
return parameters[key] | python | def _capture_variable(iterator, parameters):
"""
return the replacement string.
this assumes the preceeding {{ has already been
popped off.
"""
key = ""
next_c = next(iterator)
while next_c != "}":
key += next_c
next_c = next(iterator)
# remove the final "}"
next(iterator)
return parameters[key] | [
"def",
"_capture_variable",
"(",
"iterator",
",",
"parameters",
")",
":",
"key",
"=",
"\"\"",
"next_c",
"=",
"next",
"(",
"iterator",
")",
"while",
"next_c",
"!=",
"\"}\"",
":",
"key",
"+=",
"next_c",
"next_c",
"=",
"next",
"(",
"iterator",
")",
"# remov... | return the replacement string.
this assumes the preceeding {{ has already been
popped off. | [
"return",
"the",
"replacement",
"string",
".",
"this",
"assumes",
"the",
"preceeding",
"{{",
"has",
"already",
"been",
"popped",
"off",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/template.py#L30-L43 | train | 47,563 |
tehmaze/ansi | ansi/colour/rgb.py | rgb_distance | def rgb_distance(rgb1, rgb2):
'''
Calculate the distance between two RGB sequences.
'''
return sum(map(lambda c: (c[0] - c[1]) ** 2,
zip(rgb1, rgb2))) | python | def rgb_distance(rgb1, rgb2):
'''
Calculate the distance between two RGB sequences.
'''
return sum(map(lambda c: (c[0] - c[1]) ** 2,
zip(rgb1, rgb2))) | [
"def",
"rgb_distance",
"(",
"rgb1",
",",
"rgb2",
")",
":",
"return",
"sum",
"(",
"map",
"(",
"lambda",
"c",
":",
"(",
"c",
"[",
"0",
"]",
"-",
"c",
"[",
"1",
"]",
")",
"**",
"2",
",",
"zip",
"(",
"rgb1",
",",
"rgb2",
")",
")",
")"
] | Calculate the distance between two RGB sequences. | [
"Calculate",
"the",
"distance",
"between",
"two",
"RGB",
"sequences",
"."
] | 7d3d23bcbb5ae02b614111d94c2b4798c064073e | https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L15-L20 | train | 47,564 |
tehmaze/ansi | ansi/colour/rgb.py | rgb_reduce | def rgb_reduce(r, g, b, mode=8):
'''
Convert an RGB colour to 8 or 16 colour ANSI graphics.
'''
colours = ANSI_COLOURS[:mode]
matches = [(rgb_distance(c, map(int, [r, g, b])), i)
for i, c in enumerate(colours)]
matches.sort()
return sequence('m')(str(30 + matches[0][1])) | python | def rgb_reduce(r, g, b, mode=8):
'''
Convert an RGB colour to 8 or 16 colour ANSI graphics.
'''
colours = ANSI_COLOURS[:mode]
matches = [(rgb_distance(c, map(int, [r, g, b])), i)
for i, c in enumerate(colours)]
matches.sort()
return sequence('m')(str(30 + matches[0][1])) | [
"def",
"rgb_reduce",
"(",
"r",
",",
"g",
",",
"b",
",",
"mode",
"=",
"8",
")",
":",
"colours",
"=",
"ANSI_COLOURS",
"[",
":",
"mode",
"]",
"matches",
"=",
"[",
"(",
"rgb_distance",
"(",
"c",
",",
"map",
"(",
"int",
",",
"[",
"r",
",",
"g",
",... | Convert an RGB colour to 8 or 16 colour ANSI graphics. | [
"Convert",
"an",
"RGB",
"colour",
"to",
"8",
"or",
"16",
"colour",
"ANSI",
"graphics",
"."
] | 7d3d23bcbb5ae02b614111d94c2b4798c064073e | https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L22-L30 | train | 47,565 |
tehmaze/ansi | ansi/colour/rgb.py | rgb256 | def rgb256(r, g, b):
'''
Convert an RGB colour to 256 colour ANSI graphics.
'''
grey = False
poss = True
step = 2.5
while poss: # As long as the colour could be grey scale
if r < step or g < step or b < step:
grey = r < step and g < step and b < step
poss = False
step += 42.5
if grey:
colour = 232 + int(float(sum([r, g, b]) / 33.0))
else:
colour = sum([16] + [int (6 * float(val) / 256) * mod
for val, mod in ((r, 36), (g, 6), (b, 1))])
return sequence('m', fields=3)(38, 5, colour) | python | def rgb256(r, g, b):
'''
Convert an RGB colour to 256 colour ANSI graphics.
'''
grey = False
poss = True
step = 2.5
while poss: # As long as the colour could be grey scale
if r < step or g < step or b < step:
grey = r < step and g < step and b < step
poss = False
step += 42.5
if grey:
colour = 232 + int(float(sum([r, g, b]) / 33.0))
else:
colour = sum([16] + [int (6 * float(val) / 256) * mod
for val, mod in ((r, 36), (g, 6), (b, 1))])
return sequence('m', fields=3)(38, 5, colour) | [
"def",
"rgb256",
"(",
"r",
",",
"g",
",",
"b",
")",
":",
"grey",
"=",
"False",
"poss",
"=",
"True",
"step",
"=",
"2.5",
"while",
"poss",
":",
"# As long as the colour could be grey scale",
"if",
"r",
"<",
"step",
"or",
"g",
"<",
"step",
"or",
"b",
"<... | Convert an RGB colour to 256 colour ANSI graphics. | [
"Convert",
"an",
"RGB",
"colour",
"to",
"256",
"colour",
"ANSI",
"graphics",
"."
] | 7d3d23bcbb5ae02b614111d94c2b4798c064073e | https://github.com/tehmaze/ansi/blob/7d3d23bcbb5ae02b614111d94c2b4798c064073e/ansi/colour/rgb.py#L44-L65 | train | 47,566 |
inveniosoftware/invenio-previewer | invenio_previewer/api.py | PreviewFile.uri | def uri(self):
"""Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``.
"""
return url_for(
'.{0}_files'.format(self.pid.pid_type),
pid_value=self.pid.pid_value,
filename=self.file.key) | python | def uri(self):
"""Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``.
"""
return url_for(
'.{0}_files'.format(self.pid.pid_type),
pid_value=self.pid.pid_value,
filename=self.file.key) | [
"def",
"uri",
"(",
"self",
")",
":",
"return",
"url_for",
"(",
"'.{0}_files'",
".",
"format",
"(",
"self",
".",
"pid",
".",
"pid_type",
")",
",",
"pid_value",
"=",
"self",
".",
"pid",
".",
"pid_value",
",",
"filename",
"=",
"self",
".",
"file",
".",
... | Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``. | [
"Get",
"file",
"download",
"link",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/api.py#L46-L57 | train | 47,567 |
inveniosoftware/invenio-previewer | invenio_previewer/api.py | PreviewFile.has_extensions | def has_extensions(self, *exts):
"""Check if file has one of the extensions."""
file_ext = splitext(self.filename)[1]
file_ext = file_ext.lower()
for e in exts:
if file_ext == e:
return True
return False | python | def has_extensions(self, *exts):
"""Check if file has one of the extensions."""
file_ext = splitext(self.filename)[1]
file_ext = file_ext.lower()
for e in exts:
if file_ext == e:
return True
return False | [
"def",
"has_extensions",
"(",
"self",
",",
"*",
"exts",
")",
":",
"file_ext",
"=",
"splitext",
"(",
"self",
".",
"filename",
")",
"[",
"1",
"]",
"file_ext",
"=",
"file_ext",
".",
"lower",
"(",
")",
"for",
"e",
"in",
"exts",
":",
"if",
"file_ext",
"... | Check if file has one of the extensions. | [
"Check",
"if",
"file",
"has",
"one",
"of",
"the",
"extensions",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/api.py#L63-L71 | train | 47,568 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/json_prismjs.py | render | def render(file):
"""Pretty print the JSON file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
json_data = json.loads(file_content, object_pairs_hook=OrderedDict)
return json.dumps(json_data, indent=4, separators=(',', ': ')) | python | def render(file):
"""Pretty print the JSON file for rendering."""
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
file_content = fp.read().decode(encoding)
json_data = json.loads(file_content, object_pairs_hook=OrderedDict)
return json.dumps(json_data, indent=4, separators=(',', ': ')) | [
"def",
"render",
"(",
"file",
")",
":",
"with",
"file",
".",
"open",
"(",
")",
"as",
"fp",
":",
"encoding",
"=",
"detect_encoding",
"(",
"fp",
",",
"default",
"=",
"'utf-8'",
")",
"file_content",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"("... | Pretty print the JSON file for rendering. | [
"Pretty",
"print",
"the",
"JSON",
"file",
"for",
"rendering",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/json_prismjs.py#L23-L29 | train | 47,569 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/json_prismjs.py | validate_json | def validate_json(file):
"""Validate a JSON file."""
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
json.loads(fp.read().decode('utf-8'))
return True
except:
return False | python | def validate_json(file):
"""Validate a JSON file."""
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
json.loads(fp.read().decode('utf-8'))
return True
except:
return False | [
"def",
"validate_json",
"(",
"file",
")",
":",
"max_file_size",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'PREVIEWER_MAX_FILE_SIZE_BYTES'",
",",
"1",
"*",
"1024",
"*",
"1024",
")",
"if",
"file",
".",
"size",
">",
"max_file_size",
":",
"return",
... | Validate a JSON file. | [
"Validate",
"a",
"JSON",
"file",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/json_prismjs.py#L32-L44 | train | 47,570 |
LCAV/pylocus | pylocus/edm_completion.py | optspace | def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False):
"""Complete and denoise EDM using OptSpace algorithm.
Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is
X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter, tol: see opt_space module for description.
:return: Completed matrix.
"""
from .opt_space import opt_space
N = edm_missing.shape[0]
X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter,
tol=tol, print_out=print_out)
edm_complete = X.dot(S.dot(Y.T))
edm_complete[range(N), range(N)] = 0.0
return edm_complete | python | def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False):
"""Complete and denoise EDM using OptSpace algorithm.
Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is
X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter, tol: see opt_space module for description.
:return: Completed matrix.
"""
from .opt_space import opt_space
N = edm_missing.shape[0]
X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter,
tol=tol, print_out=print_out)
edm_complete = X.dot(S.dot(Y.T))
edm_complete[range(N), range(N)] = 0.0
return edm_complete | [
"def",
"optspace",
"(",
"edm_missing",
",",
"rank",
",",
"niter",
"=",
"500",
",",
"tol",
"=",
"1e-6",
",",
"print_out",
"=",
"False",
")",
":",
"from",
".",
"opt_space",
"import",
"opt_space",
"N",
"=",
"edm_missing",
".",
"shape",
"[",
"0",
"]",
"X... | Complete and denoise EDM using OptSpace algorithm.
Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is
X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter, tol: see opt_space module for description.
:return: Completed matrix. | [
"Complete",
"and",
"denoise",
"EDM",
"using",
"OptSpace",
"algorithm",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L9-L27 | train | 47,571 |
LCAV/pylocus | pylocus/edm_completion.py | rank_alternation | def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None):
"""Complete and denoise EDM using rank alternation.
Iteratively impose rank and strucutre to complete marix entries
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter: maximum number of iterations.
:param edm: if given, the relative EDM error is tracked.
:return: Completed matrix and array of errors (empty if no true edm is given).
The matrix is of the correct structure, but might not have the right measured entries.
"""
from pylocus.basics import low_rank_approximation
errs = []
N = edm_missing.shape[0]
edm_complete = edm_missing.copy()
edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0])
for i in range(niter):
# impose matrix rank
edm_complete = low_rank_approximation(edm_complete, rank)
# impose known entries
edm_complete[edm_missing > 0] = edm_missing[edm_missing > 0]
# impose matrix structure
edm_complete[range(N), range(N)] = 0.0
edm_complete[edm_complete < 0] = 0.0
edm_complete = 0.5 * (edm_complete + edm_complete.T)
if edm_true is not None:
err = np.linalg.norm(edm_complete - edm_true)
errs.append(err)
return edm_complete, errs | python | def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None):
"""Complete and denoise EDM using rank alternation.
Iteratively impose rank and strucutre to complete marix entries
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter: maximum number of iterations.
:param edm: if given, the relative EDM error is tracked.
:return: Completed matrix and array of errors (empty if no true edm is given).
The matrix is of the correct structure, but might not have the right measured entries.
"""
from pylocus.basics import low_rank_approximation
errs = []
N = edm_missing.shape[0]
edm_complete = edm_missing.copy()
edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0])
for i in range(niter):
# impose matrix rank
edm_complete = low_rank_approximation(edm_complete, rank)
# impose known entries
edm_complete[edm_missing > 0] = edm_missing[edm_missing > 0]
# impose matrix structure
edm_complete[range(N), range(N)] = 0.0
edm_complete[edm_complete < 0] = 0.0
edm_complete = 0.5 * (edm_complete + edm_complete.T)
if edm_true is not None:
err = np.linalg.norm(edm_complete - edm_true)
errs.append(err)
return edm_complete, errs | [
"def",
"rank_alternation",
"(",
"edm_missing",
",",
"rank",
",",
"niter",
"=",
"50",
",",
"print_out",
"=",
"False",
",",
"edm_true",
"=",
"None",
")",
":",
"from",
"pylocus",
".",
"basics",
"import",
"low_rank_approximation",
"errs",
"=",
"[",
"]",
"N",
... | Complete and denoise EDM using rank alternation.
Iteratively impose rank and strucutre to complete marix entries
:param edm_missing: EDM with 0 where no measurement was taken.
:param rank: expected rank of complete EDM.
:param niter: maximum number of iterations.
:param edm: if given, the relative EDM error is tracked.
:return: Completed matrix and array of errors (empty if no true edm is given).
The matrix is of the correct structure, but might not have the right measured entries. | [
"Complete",
"and",
"denoise",
"EDM",
"using",
"rank",
"alternation",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L30-L64 | train | 47,572 |
LCAV/pylocus | pylocus/edm_completion.py | completion_acd | def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3):
""" Complete an denoise EDM using alternating decent.
The idea here is to simply run reconstruct_acd for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps.
"""
from .algorithms import reconstruct_acd
Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps)
return get_edm(Xhat) | python | def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3):
""" Complete an denoise EDM using alternating decent.
The idea here is to simply run reconstruct_acd for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps.
"""
from .algorithms import reconstruct_acd
Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps)
return get_edm(Xhat) | [
"def",
"completion_acd",
"(",
"edm",
",",
"X0",
",",
"W",
"=",
"None",
",",
"tol",
"=",
"1e-6",
",",
"sweeps",
"=",
"3",
")",
":",
"from",
".",
"algorithms",
"import",
"reconstruct_acd",
"Xhat",
",",
"costs",
"=",
"reconstruct_acd",
"(",
"edm",
",",
... | Complete an denoise EDM using alternating decent.
The idea here is to simply run reconstruct_acd for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps. | [
"Complete",
"an",
"denoise",
"EDM",
"using",
"alternating",
"decent",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L144-L159 | train | 47,573 |
LCAV/pylocus | pylocus/edm_completion.py | completion_dwmds | def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100):
""" Complete an denoise EDM using dwMDS.
The idea here is to simply run reconstruct_dwmds for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps.
"""
from .algorithms import reconstruct_dwmds
Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps)
return get_edm(Xhat) | python | def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100):
""" Complete an denoise EDM using dwMDS.
The idea here is to simply run reconstruct_dwmds for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps.
"""
from .algorithms import reconstruct_dwmds
Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps)
return get_edm(Xhat) | [
"def",
"completion_dwmds",
"(",
"edm",
",",
"X0",
",",
"W",
"=",
"None",
",",
"tol",
"=",
"1e-10",
",",
"sweeps",
"=",
"100",
")",
":",
"from",
".",
"algorithms",
"import",
"reconstruct_dwmds",
"Xhat",
",",
"costs",
"=",
"reconstruct_dwmds",
"(",
"edm",
... | Complete an denoise EDM using dwMDS.
The idea here is to simply run reconstruct_dwmds for a few iterations,
yieding a position estimate, which can in turn be used
to get a completed and denoised edm.
:param edm: noisy matrix (NxN)
:param X0: starting points (Nxd)
:param W: optional weight matrix.
:param tol: Stopping criterion of iterative algorithm.
:param sweeps: Maximum number of sweeps. | [
"Complete",
"an",
"denoise",
"EDM",
"using",
"dwMDS",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/edm_completion.py#L162-L177 | train | 47,574 |
toumorokoshi/transmute-core | transmute_core/frameworks/tornado/url.py | url_spec | def url_spec(transmute_path, handler, *args, **kwargs):
"""
convert the transmute_path
to a tornado compatible regex,
and return a tornado url object.
"""
p = _to_tornado_pattern(transmute_path)
for m in METHODS:
method = getattr(handler, m)
if hasattr(method, "transmute_func"):
method.transmute_func.paths.add(transmute_path)
return tornado.web.URLSpec(
p, handler,
*args, **kwargs
) | python | def url_spec(transmute_path, handler, *args, **kwargs):
"""
convert the transmute_path
to a tornado compatible regex,
and return a tornado url object.
"""
p = _to_tornado_pattern(transmute_path)
for m in METHODS:
method = getattr(handler, m)
if hasattr(method, "transmute_func"):
method.transmute_func.paths.add(transmute_path)
return tornado.web.URLSpec(
p, handler,
*args, **kwargs
) | [
"def",
"url_spec",
"(",
"transmute_path",
",",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"p",
"=",
"_to_tornado_pattern",
"(",
"transmute_path",
")",
"for",
"m",
"in",
"METHODS",
":",
"method",
"=",
"getattr",
"(",
"handler",
",",
... | convert the transmute_path
to a tornado compatible regex,
and return a tornado url object. | [
"convert",
"the",
"transmute_path",
"to",
"a",
"tornado",
"compatible",
"regex",
"and",
"return",
"a",
"tornado",
"url",
"object",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/tornado/url.py#L6-L20 | train | 47,575 |
LCAV/pylocus | pylocus/point_set.py | AngleSet.get_orientation | def get_orientation(k, i, j):
from pylocus.basics_angles import from_0_to_2pi
"""calculate angles theta_ik and theta_jk theta produce point Pk.
Should give the same as get_absolute_angle! """
theta_ij = own.abs_angles[i, j]
theta_ji = own.abs_angles[j, i]
# complicated
xi = own.points[i, 0]
xj = own.points[j, 0]
yi = own.points[i, 1]
yj = own.points[j, 1]
w = np.array([yi - yj, xj - xi])
test = np.dot(own.points[k, :] - own.points[i, :], w) > 0
# more elegant
theta_ik = truth.abs_angles[i, k]
diff = from_0_to_2pi(theta_ik - theta_ij)
test2 = (diff > 0 and diff < pi)
assert (test == test2), "diff: %r, scalar prodcut: %r" % (diff, np.dot(
own.points[k, :] - own.points[i, :], w))
thetai_jk = truth.get_theta(i, j, k)
thetaj_ik = truth.get_theta(j, i, k)
if test:
theta_ik = theta_ij + thetai_jk
theta_jk = theta_ji - thetaj_ik
else:
theta_ik = theta_ij - thetai_jk
theta_jk = theta_ji + thetaj_ik
theta_ik = from_0_to_2pi(theta_ik)
theta_jk = from_0_to_2pi(theta_jk)
return theta_ik, theta_jk | python | def get_orientation(k, i, j):
from pylocus.basics_angles import from_0_to_2pi
"""calculate angles theta_ik and theta_jk theta produce point Pk.
Should give the same as get_absolute_angle! """
theta_ij = own.abs_angles[i, j]
theta_ji = own.abs_angles[j, i]
# complicated
xi = own.points[i, 0]
xj = own.points[j, 0]
yi = own.points[i, 1]
yj = own.points[j, 1]
w = np.array([yi - yj, xj - xi])
test = np.dot(own.points[k, :] - own.points[i, :], w) > 0
# more elegant
theta_ik = truth.abs_angles[i, k]
diff = from_0_to_2pi(theta_ik - theta_ij)
test2 = (diff > 0 and diff < pi)
assert (test == test2), "diff: %r, scalar prodcut: %r" % (diff, np.dot(
own.points[k, :] - own.points[i, :], w))
thetai_jk = truth.get_theta(i, j, k)
thetaj_ik = truth.get_theta(j, i, k)
if test:
theta_ik = theta_ij + thetai_jk
theta_jk = theta_ji - thetaj_ik
else:
theta_ik = theta_ij - thetai_jk
theta_jk = theta_ji + thetaj_ik
theta_ik = from_0_to_2pi(theta_ik)
theta_jk = from_0_to_2pi(theta_jk)
return theta_ik, theta_jk | [
"def",
"get_orientation",
"(",
"k",
",",
"i",
",",
"j",
")",
":",
"from",
"pylocus",
".",
"basics_angles",
"import",
"from_0_to_2pi",
"theta_ij",
"=",
"own",
".",
"abs_angles",
"[",
"i",
",",
"j",
"]",
"theta_ji",
"=",
"own",
".",
"abs_angles",
"[",
"j... | calculate angles theta_ik and theta_jk theta produce point Pk.
Should give the same as get_absolute_angle! | [
"calculate",
"angles",
"theta_ik",
"and",
"theta_jk",
"theta",
"produce",
"point",
"Pk",
".",
"Should",
"give",
"the",
"same",
"as",
"get_absolute_angle!"
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L306-L338 | train | 47,576 |
LCAV/pylocus | pylocus/point_set.py | AngleSet.get_G | def get_G(self, k, add_noise=True):
""" get G matrix from angles. """
G = np.ones((self.N - 1, self.N - 1))
if (add_noise):
noise = pi * 0.1 * np.random.rand(
(self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1))
other_indices = np.delete(range(self.N), k)
for idx, i in enumerate(other_indices):
for jdx, j in enumerate(other_indices):
if (add_noise and
i != j): # do not add noise on diagonal elements.
thetak_ij = self.get_inner_angle(k,
(i, j)) + noise[idx, jdx]
else:
thetak_ij = self.get_inner_angle(k, (i, j))
G[idx, jdx] = cos(thetak_ij)
G[jdx, idx] = cos(thetak_ij)
return G | python | def get_G(self, k, add_noise=True):
""" get G matrix from angles. """
G = np.ones((self.N - 1, self.N - 1))
if (add_noise):
noise = pi * 0.1 * np.random.rand(
(self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1))
other_indices = np.delete(range(self.N), k)
for idx, i in enumerate(other_indices):
for jdx, j in enumerate(other_indices):
if (add_noise and
i != j): # do not add noise on diagonal elements.
thetak_ij = self.get_inner_angle(k,
(i, j)) + noise[idx, jdx]
else:
thetak_ij = self.get_inner_angle(k, (i, j))
G[idx, jdx] = cos(thetak_ij)
G[jdx, idx] = cos(thetak_ij)
return G | [
"def",
"get_G",
"(",
"self",
",",
"k",
",",
"add_noise",
"=",
"True",
")",
":",
"G",
"=",
"np",
".",
"ones",
"(",
"(",
"self",
".",
"N",
"-",
"1",
",",
"self",
".",
"N",
"-",
"1",
")",
")",
"if",
"(",
"add_noise",
")",
":",
"noise",
"=",
... | get G matrix from angles. | [
"get",
"G",
"matrix",
"from",
"angles",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L423-L440 | train | 47,577 |
LCAV/pylocus | pylocus/point_set.py | HeterogenousSet.get_KE_constraints | def get_KE_constraints(self):
"""Get linear constraints on KE matrix.
"""
C2 = np.eye(self.m)
C2 = C2[:self.m - 2, :]
to_be_deleted = []
for idx_vij_1 in range(self.m - 2):
idx_vij_2 = idx_vij_1 + 1
C2[idx_vij_1, idx_vij_2] = -1
i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0]
i2 = np.where(self.C[idx_vij_2, :] == 1)[0][0]
j = np.where(self.C[idx_vij_1, :] == -1)[0][0]
if i1 == i2:
i = i1
k = np.where(self.C[idx_vij_2, :] == -1)[0][0]
i_indices = self.C[:, j] == 1
j_indices = self.C[:, k] == -1
idx_vij_3 = np.where(np.bitwise_and(
i_indices, j_indices))[0][0]
#print('v{}{}, v{}{}, v{}{}\n{} {} {}'.format(j,i,k,i,k,j,idx_vij_1,idx_vij_2,idx_vij_3))
C2[idx_vij_1, idx_vij_3] = 1
else:
#print('v{}{}, v{}{} not considered.'.format(j,i1,j,i2))
to_be_deleted.append(idx_vij_1)
C2 = np.delete(C2, to_be_deleted, axis=0)
b = np.zeros((C2.shape[0], 1))
return C2, b | python | def get_KE_constraints(self):
"""Get linear constraints on KE matrix.
"""
C2 = np.eye(self.m)
C2 = C2[:self.m - 2, :]
to_be_deleted = []
for idx_vij_1 in range(self.m - 2):
idx_vij_2 = idx_vij_1 + 1
C2[idx_vij_1, idx_vij_2] = -1
i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0]
i2 = np.where(self.C[idx_vij_2, :] == 1)[0][0]
j = np.where(self.C[idx_vij_1, :] == -1)[0][0]
if i1 == i2:
i = i1
k = np.where(self.C[idx_vij_2, :] == -1)[0][0]
i_indices = self.C[:, j] == 1
j_indices = self.C[:, k] == -1
idx_vij_3 = np.where(np.bitwise_and(
i_indices, j_indices))[0][0]
#print('v{}{}, v{}{}, v{}{}\n{} {} {}'.format(j,i,k,i,k,j,idx_vij_1,idx_vij_2,idx_vij_3))
C2[idx_vij_1, idx_vij_3] = 1
else:
#print('v{}{}, v{}{} not considered.'.format(j,i1,j,i2))
to_be_deleted.append(idx_vij_1)
C2 = np.delete(C2, to_be_deleted, axis=0)
b = np.zeros((C2.shape[0], 1))
return C2, b | [
"def",
"get_KE_constraints",
"(",
"self",
")",
":",
"C2",
"=",
"np",
".",
"eye",
"(",
"self",
".",
"m",
")",
"C2",
"=",
"C2",
"[",
":",
"self",
".",
"m",
"-",
"2",
",",
":",
"]",
"to_be_deleted",
"=",
"[",
"]",
"for",
"idx_vij_1",
"in",
"range"... | Get linear constraints on KE matrix. | [
"Get",
"linear",
"constraints",
"on",
"KE",
"matrix",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/point_set.py#L666-L692 | train | 47,578 |
d0ugal/python-rfxcom | rfxcom/protocol/elec.py | Elec._bytes_to_uint_48 | def _bytes_to_uint_48(self, bytes_):
"""Converts an array of 6 bytes to a 48bit integer.
:param data: bytearray to be converted to a 48bit integer
:type data: bytearray
:return: the integer
:rtype: int
"""
return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 32)) +
(bytes_[2] * pow(2, 24)) + (bytes_[3] << 16) +
(bytes_[4] << 8) + bytes_[4]) | python | def _bytes_to_uint_48(self, bytes_):
"""Converts an array of 6 bytes to a 48bit integer.
:param data: bytearray to be converted to a 48bit integer
:type data: bytearray
:return: the integer
:rtype: int
"""
return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 32)) +
(bytes_[2] * pow(2, 24)) + (bytes_[3] << 16) +
(bytes_[4] << 8) + bytes_[4]) | [
"def",
"_bytes_to_uint_48",
"(",
"self",
",",
"bytes_",
")",
":",
"return",
"(",
"(",
"bytes_",
"[",
"0",
"]",
"*",
"pow",
"(",
"2",
",",
"40",
")",
")",
"+",
"(",
"bytes_",
"[",
"1",
"]",
"*",
"pow",
"(",
"2",
",",
"32",
")",
")",
"+",
"("... | Converts an array of 6 bytes to a 48bit integer.
:param data: bytearray to be converted to a 48bit integer
:type data: bytearray
:return: the integer
:rtype: int | [
"Converts",
"an",
"array",
"of",
"6",
"bytes",
"to",
"a",
"48bit",
"integer",
"."
] | 2eb87f85e5f5a04d00f32f25e0f010edfefbde0d | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/elec.py#L64-L75 | train | 47,579 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/csv_dthreejs.py | validate_csv | def validate_csv(file):
"""Return dialect information about given csv file."""
try:
# Detect encoding and dialect
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
sample = fp.read(
current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024))
delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter
is_valid = True
except Exception as e:
current_app.logger.debug(
'File {0} is not valid CSV: {1}'.format(file.uri, e))
encoding = ''
delimiter = ''
is_valid = False
return {
'delimiter': delimiter,
'encoding': encoding,
'is_valid': is_valid
} | python | def validate_csv(file):
"""Return dialect information about given csv file."""
try:
# Detect encoding and dialect
with file.open() as fp:
encoding = detect_encoding(fp, default='utf-8')
sample = fp.read(
current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024))
delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter
is_valid = True
except Exception as e:
current_app.logger.debug(
'File {0} is not valid CSV: {1}'.format(file.uri, e))
encoding = ''
delimiter = ''
is_valid = False
return {
'delimiter': delimiter,
'encoding': encoding,
'is_valid': is_valid
} | [
"def",
"validate_csv",
"(",
"file",
")",
":",
"try",
":",
"# Detect encoding and dialect",
"with",
"file",
".",
"open",
"(",
")",
"as",
"fp",
":",
"encoding",
"=",
"detect_encoding",
"(",
"fp",
",",
"default",
"=",
"'utf-8'",
")",
"sample",
"=",
"fp",
".... | Return dialect information about given csv file. | [
"Return",
"dialect",
"information",
"about",
"given",
"csv",
"file",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/csv_dthreejs.py#L23-L44 | train | 47,580 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/zip.py | make_tree | def make_tree(file):
"""Create tree structure from ZIP archive."""
max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000)
tree = {'type': 'folder', 'id': -1, 'children': {}}
try:
with file.open() as fp:
zf = zipfile.ZipFile(fp)
# Detect filenames encoding.
sample = ' '.join(zf.namelist()[:max_files_count])
if not isinstance(sample, binary_type):
sample = sample.encode('utf-16be')
encoding = chardet.detect(sample).get('encoding', 'utf-8')
for i, info in enumerate(zf.infolist()):
if i > max_files_count:
raise BufferError('Too many files inside the ZIP file.')
comps = info.filename.split(os.sep)
node = tree
for c in comps:
if not isinstance(c, text_type):
c = c.decode(encoding)
if c not in node['children']:
if c == '':
node['type'] = 'folder'
continue
node['children'][c] = {
'name': c,
'type': 'item',
'id': 'item{0}'.format(i),
'children': {}
}
node = node['children'][c]
node['size'] = info.file_size
except BufferError:
return tree, True, None
except (zipfile.LargeZipFile):
return tree, False, 'Zipfile is too large to be previewed.'
except Exception as e:
current_app.logger.warning(str(e), exc_info=True)
return tree, False, 'Zipfile is not previewable.'
return tree, False, None | python | def make_tree(file):
"""Create tree structure from ZIP archive."""
max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000)
tree = {'type': 'folder', 'id': -1, 'children': {}}
try:
with file.open() as fp:
zf = zipfile.ZipFile(fp)
# Detect filenames encoding.
sample = ' '.join(zf.namelist()[:max_files_count])
if not isinstance(sample, binary_type):
sample = sample.encode('utf-16be')
encoding = chardet.detect(sample).get('encoding', 'utf-8')
for i, info in enumerate(zf.infolist()):
if i > max_files_count:
raise BufferError('Too many files inside the ZIP file.')
comps = info.filename.split(os.sep)
node = tree
for c in comps:
if not isinstance(c, text_type):
c = c.decode(encoding)
if c not in node['children']:
if c == '':
node['type'] = 'folder'
continue
node['children'][c] = {
'name': c,
'type': 'item',
'id': 'item{0}'.format(i),
'children': {}
}
node = node['children'][c]
node['size'] = info.file_size
except BufferError:
return tree, True, None
except (zipfile.LargeZipFile):
return tree, False, 'Zipfile is too large to be previewed.'
except Exception as e:
current_app.logger.warning(str(e), exc_info=True)
return tree, False, 'Zipfile is not previewable.'
return tree, False, None | [
"def",
"make_tree",
"(",
"file",
")",
":",
"max_files_count",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'PREVIEWER_ZIP_MAX_FILES'",
",",
"1000",
")",
"tree",
"=",
"{",
"'type'",
":",
"'folder'",
",",
"'id'",
":",
"-",
"1",
",",
"'children'",
"... | Create tree structure from ZIP archive. | [
"Create",
"tree",
"structure",
"from",
"ZIP",
"archive",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L26-L67 | train | 47,581 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/zip.py | children_to_list | def children_to_list(node):
"""Organize children structure."""
if node['type'] == 'item' and len(node['children']) == 0:
del node['children']
else:
node['type'] = 'folder'
node['children'] = list(node['children'].values())
node['children'].sort(key=lambda x: x['name'])
node['children'] = map(children_to_list, node['children'])
return node | python | def children_to_list(node):
"""Organize children structure."""
if node['type'] == 'item' and len(node['children']) == 0:
del node['children']
else:
node['type'] = 'folder'
node['children'] = list(node['children'].values())
node['children'].sort(key=lambda x: x['name'])
node['children'] = map(children_to_list, node['children'])
return node | [
"def",
"children_to_list",
"(",
"node",
")",
":",
"if",
"node",
"[",
"'type'",
"]",
"==",
"'item'",
"and",
"len",
"(",
"node",
"[",
"'children'",
"]",
")",
"==",
"0",
":",
"del",
"node",
"[",
"'children'",
"]",
"else",
":",
"node",
"[",
"'type'",
"... | Organize children structure. | [
"Organize",
"children",
"structure",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L70-L79 | train | 47,582 |
inveniosoftware/invenio-previewer | invenio_previewer/extensions/zip.py | preview | def preview(file):
"""Return appropriate template and pass the file and an embed flag."""
tree, limit_reached, error = make_tree(file)
list = children_to_list(tree)['children']
return render_template(
"invenio_previewer/zip.html",
file=file,
tree=list,
limit_reached=limit_reached,
error=error,
js_bundles=current_previewer.js_bundles + ['previewer_fullscreen_js'],
css_bundles=current_previewer.css_bundles,
) | python | def preview(file):
"""Return appropriate template and pass the file and an embed flag."""
tree, limit_reached, error = make_tree(file)
list = children_to_list(tree)['children']
return render_template(
"invenio_previewer/zip.html",
file=file,
tree=list,
limit_reached=limit_reached,
error=error,
js_bundles=current_previewer.js_bundles + ['previewer_fullscreen_js'],
css_bundles=current_previewer.css_bundles,
) | [
"def",
"preview",
"(",
"file",
")",
":",
"tree",
",",
"limit_reached",
",",
"error",
"=",
"make_tree",
"(",
"file",
")",
"list",
"=",
"children_to_list",
"(",
"tree",
")",
"[",
"'children'",
"]",
"return",
"render_template",
"(",
"\"invenio_previewer/zip.html\... | Return appropriate template and pass the file and an embed flag. | [
"Return",
"appropriate",
"template",
"and",
"pass",
"the",
"file",
"and",
"an",
"embed",
"flag",
"."
] | 558fd22e0f29cc8cd7a6999abd4febcf6b248c49 | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/zip.py#L87-L99 | train | 47,583 |
LCAV/pylocus | pylocus/simulation.py | create_mask | def create_mask(N, method='all', nmissing=0):
""" Create weight mask according to method.
:param N: Dimension of square weight matrix.
:param method: Method to use (default: 'all').
- none: no missing entries (only diagonal is set to 0 for dwMDS)
- first: only randomly delete measurements to first point (zeros in first row/column of matrix)
- all: randomly delete measurements in whole matrix
:param nmissing: Number of deleted measurements, used by methods 'first' and 'all'
:return: Binary weight mask.
:rtype: numpy.ndarray
"""
weights = np.ones((N, N))
weights[range(N), range(N)] = 0
if method == 'none':
return weights
# create indices object to choose from
elif method == 'all':
all_indices = np.triu_indices(N, 1)
elif method == 'first':
all_indices = [np.zeros(N - 1).astype(np.int),
np.arange(1, N).astype(np.int)]
ntotal = len(all_indices[0])
# randomly choose from indices and set to 0
choice = np.random.choice(ntotal, nmissing, replace=False)
chosen = [all_indices[0][choice], all_indices[1][choice]]
weights[chosen] = 0
weights[chosen[1], chosen[0]] = 0
return weights | python | def create_mask(N, method='all', nmissing=0):
""" Create weight mask according to method.
:param N: Dimension of square weight matrix.
:param method: Method to use (default: 'all').
- none: no missing entries (only diagonal is set to 0 for dwMDS)
- first: only randomly delete measurements to first point (zeros in first row/column of matrix)
- all: randomly delete measurements in whole matrix
:param nmissing: Number of deleted measurements, used by methods 'first' and 'all'
:return: Binary weight mask.
:rtype: numpy.ndarray
"""
weights = np.ones((N, N))
weights[range(N), range(N)] = 0
if method == 'none':
return weights
# create indices object to choose from
elif method == 'all':
all_indices = np.triu_indices(N, 1)
elif method == 'first':
all_indices = [np.zeros(N - 1).astype(np.int),
np.arange(1, N).astype(np.int)]
ntotal = len(all_indices[0])
# randomly choose from indices and set to 0
choice = np.random.choice(ntotal, nmissing, replace=False)
chosen = [all_indices[0][choice], all_indices[1][choice]]
weights[chosen] = 0
weights[chosen[1], chosen[0]] = 0
return weights | [
"def",
"create_mask",
"(",
"N",
",",
"method",
"=",
"'all'",
",",
"nmissing",
"=",
"0",
")",
":",
"weights",
"=",
"np",
".",
"ones",
"(",
"(",
"N",
",",
"N",
")",
")",
"weights",
"[",
"range",
"(",
"N",
")",
",",
"range",
"(",
"N",
")",
"]",
... | Create weight mask according to method.
:param N: Dimension of square weight matrix.
:param method: Method to use (default: 'all').
- none: no missing entries (only diagonal is set to 0 for dwMDS)
- first: only randomly delete measurements to first point (zeros in first row/column of matrix)
- all: randomly delete measurements in whole matrix
:param nmissing: Number of deleted measurements, used by methods 'first' and 'all'
:return: Binary weight mask.
:rtype: numpy.ndarray | [
"Create",
"weight",
"mask",
"according",
"to",
"method",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/simulation.py#L67-L99 | train | 47,584 |
toumorokoshi/transmute-core | transmute_core/decorators.py | describe | def describe(**kwargs):
""" describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)
:param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET.
:param list(str) query_parameters: the names of arguments that
should be query parameters. By default, all arguments are query_or path parameters for a GET request.
:param body_parameters: the names of arguments that should be body parameters.
By default, all arguments are either body or path parameters for a non-GET request.
in the case of a single string, the whole body is validated against a single object.
:type body_parameters: List[str] or str
:param list(str) header_parameters: the arguments that should be passed into the header.
:param list(str) path_parameters: the arguments that are specified by the path. By default, arguments
that are found in the path are used first before the query_parameters and body_parameters.
:param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name.
this will appear in the swagger documentation.
"""
# if we have a single method, make it a list.
if isinstance(kwargs.get("paths"), string_type):
kwargs["paths"] = [kwargs["paths"]]
if isinstance(kwargs.get("methods"), string_type):
kwargs["methods"] = [kwargs["methods"]]
attrs = TransmuteAttributes(**kwargs)
def decorator(f):
if hasattr(f, "transmute"):
f.transmute = f.transmute | attrs
else:
f.transmute = attrs
return f
return decorator | python | def describe(**kwargs):
""" describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)
:param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET.
:param list(str) query_parameters: the names of arguments that
should be query parameters. By default, all arguments are query_or path parameters for a GET request.
:param body_parameters: the names of arguments that should be body parameters.
By default, all arguments are either body or path parameters for a non-GET request.
in the case of a single string, the whole body is validated against a single object.
:type body_parameters: List[str] or str
:param list(str) header_parameters: the arguments that should be passed into the header.
:param list(str) path_parameters: the arguments that are specified by the path. By default, arguments
that are found in the path are used first before the query_parameters and body_parameters.
:param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name.
this will appear in the swagger documentation.
"""
# if we have a single method, make it a list.
if isinstance(kwargs.get("paths"), string_type):
kwargs["paths"] = [kwargs["paths"]]
if isinstance(kwargs.get("methods"), string_type):
kwargs["methods"] = [kwargs["methods"]]
attrs = TransmuteAttributes(**kwargs)
def decorator(f):
if hasattr(f, "transmute"):
f.transmute = f.transmute | attrs
else:
f.transmute = attrs
return f
return decorator | [
"def",
"describe",
"(",
"*",
"*",
"kwargs",
")",
":",
"# if we have a single method, make it a list.",
"if",
"isinstance",
"(",
"kwargs",
".",
"get",
"(",
"\"paths\"",
")",
",",
"string_type",
")",
":",
"kwargs",
"[",
"\"paths\"",
"]",
"=",
"[",
"kwargs",
"[... | describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)
:param list(str) methods: the methods this function should respond to. if non is set, transmute defaults to a GET.
:param list(str) query_parameters: the names of arguments that
should be query parameters. By default, all arguments are query_or path parameters for a GET request.
:param body_parameters: the names of arguments that should be body parameters.
By default, all arguments are either body or path parameters for a non-GET request.
in the case of a single string, the whole body is validated against a single object.
:type body_parameters: List[str] or str
:param list(str) header_parameters: the arguments that should be passed into the header.
:param list(str) path_parameters: the arguments that are specified by the path. By default, arguments
that are found in the path are used first before the query_parameters and body_parameters.
:param list(str) parameter_descriptions: descriptions for each parameter, keyed by attribute name.
this will appear in the swagger documentation. | [
"describe",
"is",
"a",
"decorator",
"to",
"customize",
"the",
"rest",
"API",
"that",
"transmute",
"generates",
"such",
"as",
"choosing",
"certain",
"arguments",
"to",
"be",
"query",
"parameters",
"or",
"body",
"parameters",
"or",
"a",
"different",
"method",
".... | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/decorators.py#L5-L47 | train | 47,585 |
LCAV/pylocus | pylocus/basics_angles.py | rmse_2pi | def rmse_2pi(x, xhat):
''' Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.'''
real_diff = from_0_to_pi(x - xhat)
np.square(real_diff, out=real_diff)
sum_ = np.sum(real_diff)
return sqrt(sum_ / len(x)) | python | def rmse_2pi(x, xhat):
''' Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.'''
real_diff = from_0_to_pi(x - xhat)
np.square(real_diff, out=real_diff)
sum_ = np.sum(real_diff)
return sqrt(sum_ / len(x)) | [
"def",
"rmse_2pi",
"(",
"x",
",",
"xhat",
")",
":",
"real_diff",
"=",
"from_0_to_pi",
"(",
"x",
"-",
"xhat",
")",
"np",
".",
"square",
"(",
"real_diff",
",",
"out",
"=",
"real_diff",
")",
"sum_",
"=",
"np",
".",
"sum",
"(",
"real_diff",
")",
"retur... | Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi. | [
"Calcualte",
"rmse",
"between",
"vector",
"or",
"matrix",
"x",
"and",
"xhat",
"ignoring",
"mod",
"of",
"2pi",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics_angles.py#L68-L73 | train | 47,586 |
toumorokoshi/transmute-core | transmute_core/contenttype_serializers/serializer_set.py | SerializerSet.keys | def keys(self):
"""
return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported.
"""
return_value = []
for s in self.serializers:
return_value += s.content_type
return return_value | python | def keys(self):
"""
return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported.
"""
return_value = []
for s in self.serializers:
return_value += s.content_type
return return_value | [
"def",
"keys",
"(",
"self",
")",
":",
"return_value",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"serializers",
":",
"return_value",
"+=",
"s",
".",
"content_type",
"return",
"return_value"
] | return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported. | [
"return",
"a",
"list",
"of",
"the",
"content",
"types",
"this",
"set",
"supports",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/contenttype_serializers/serializer_set.py#L41-L52 | train | 47,587 |
toumorokoshi/transmute-core | transmute_core/function/parameters.py | _extract_path_parameters_from_paths | def _extract_path_parameters_from_paths(paths):
"""
from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised.
"""
params = set()
for path in paths:
parts = PART_REGEX.split(path)
for p in parts:
match = PARAM_REGEX.match(p)
if match:
params.add(match.group("name"))
return params | python | def _extract_path_parameters_from_paths(paths):
"""
from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised.
"""
params = set()
for path in paths:
parts = PART_REGEX.split(path)
for p in parts:
match = PARAM_REGEX.match(p)
if match:
params.add(match.group("name"))
return params | [
"def",
"_extract_path_parameters_from_paths",
"(",
"paths",
")",
":",
"params",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"parts",
"=",
"PART_REGEX",
".",
"split",
"(",
"path",
")",
"for",
"p",
"in",
"parts",
":",
"match",
"=",
"PARAM_REGE... | from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised. | [
"from",
"a",
"list",
"of",
"paths",
"return",
"back",
"a",
"list",
"of",
"the",
"arguments",
"present",
"in",
"those",
"paths",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/parameters.py#L84-L99 | train | 47,588 |
toumorokoshi/transmute-core | transmute_core/http_parameters/swagger.py | _build_body_schema | def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.description
required = True
else:
if len(body_parameters) == 0:
return None
required = set()
body_properties = {}
for name, param in body_parameters.items():
arginfo = param.arginfo
body_properties[name] = serializer.to_json_schema(arginfo.type)
body_properties[name]["description"] = param.description
if arginfo.default is NoDefault:
required.add(name)
schema = {
"type": "object",
"required": list(required),
"properties": body_properties,
}
required = len(required) > 0
return BodyParameter(
{
"name": "body",
"description": description,
"required": required,
"schema": schema,
}
) | python | def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.description
required = True
else:
if len(body_parameters) == 0:
return None
required = set()
body_properties = {}
for name, param in body_parameters.items():
arginfo = param.arginfo
body_properties[name] = serializer.to_json_schema(arginfo.type)
body_properties[name]["description"] = param.description
if arginfo.default is NoDefault:
required.add(name)
schema = {
"type": "object",
"required": list(required),
"properties": body_properties,
}
required = len(required) > 0
return BodyParameter(
{
"name": "body",
"description": description,
"required": required,
"schema": schema,
}
) | [
"def",
"_build_body_schema",
"(",
"serializer",
",",
"body_parameters",
")",
":",
"description",
"=",
"\"\"",
"if",
"isinstance",
"(",
"body_parameters",
",",
"Param",
")",
":",
"schema",
"=",
"serializer",
".",
"to_json_schema",
"(",
"body_parameters",
".",
"ar... | body is built differently, since it's a single argument no matter what. | [
"body",
"is",
"built",
"differently",
"since",
"it",
"s",
"a",
"single",
"argument",
"no",
"matter",
"what",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/http_parameters/swagger.py#L46-L77 | train | 47,589 |
LCAV/pylocus | pylocus/algorithms.py | procrustes | def procrustes(anchors, X, scale=True, print_out=False):
""" Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor.
"""
def centralize(X):
n = X.shape[0]
ones = np.ones((n, 1))
return X - np.multiply(1 / n * np.dot(ones.T, X), ones)
m = anchors.shape[0]
N, d = X.shape
assert m >= d, 'Have to give at least d anchor nodes.'
X_m = X[N - m:, :]
ones = np.ones((m, 1))
mux = 1 / m * np.dot(ones.T, X_m)
muy = 1 / m * np.dot(ones.T, anchors)
sigmax = 1 / m * np.linalg.norm(X_m - mux)**2
sigmaxy = 1 / m * np.dot((anchors - muy).T, X_m - mux)
try:
U, D, VT = np.linalg.svd(sigmaxy)
except np.LinAlgError:
print('strange things are happening...')
print(sigmaxy)
print(np.linalg.matrix_rank(sigmaxy))
#this doesn't work and doesn't seem to be necessary! (why?)
# S = np.eye(D.shape[0])
# if (np.linalg.det(U)*np.linalg.det(VT.T) < 0):
# print('switching')
# S[-1,-1] = -1.0
# else:
# print('not switching')
# c = np.trace(np.dot(np.diag(D),S))/sigmax
# R = np.dot(U, np.dot(S,VT))
if (scale):
c = np.trace(np.diag(D)) / sigmax
else:
c = np.trace(np.diag(D)) / sigmax
if (print_out):
print('Optimal scale would be: {}. Setting it to 1 now.'.format(c))
c = 1.0
R = np.dot(U, VT)
t = muy.T - c * np.dot(R, mux.T)
X_transformed = (c * np.dot(R, (X - mux).T) + muy.T).T
return X_transformed, R, t, c | python | def procrustes(anchors, X, scale=True, print_out=False):
""" Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor.
"""
def centralize(X):
n = X.shape[0]
ones = np.ones((n, 1))
return X - np.multiply(1 / n * np.dot(ones.T, X), ones)
m = anchors.shape[0]
N, d = X.shape
assert m >= d, 'Have to give at least d anchor nodes.'
X_m = X[N - m:, :]
ones = np.ones((m, 1))
mux = 1 / m * np.dot(ones.T, X_m)
muy = 1 / m * np.dot(ones.T, anchors)
sigmax = 1 / m * np.linalg.norm(X_m - mux)**2
sigmaxy = 1 / m * np.dot((anchors - muy).T, X_m - mux)
try:
U, D, VT = np.linalg.svd(sigmaxy)
except np.LinAlgError:
print('strange things are happening...')
print(sigmaxy)
print(np.linalg.matrix_rank(sigmaxy))
#this doesn't work and doesn't seem to be necessary! (why?)
# S = np.eye(D.shape[0])
# if (np.linalg.det(U)*np.linalg.det(VT.T) < 0):
# print('switching')
# S[-1,-1] = -1.0
# else:
# print('not switching')
# c = np.trace(np.dot(np.diag(D),S))/sigmax
# R = np.dot(U, np.dot(S,VT))
if (scale):
c = np.trace(np.diag(D)) / sigmax
else:
c = np.trace(np.diag(D)) / sigmax
if (print_out):
print('Optimal scale would be: {}. Setting it to 1 now.'.format(c))
c = 1.0
R = np.dot(U, VT)
t = muy.T - c * np.dot(R, mux.T)
X_transformed = (c * np.dot(R, (X - mux).T) + muy.T).T
return X_transformed, R, t, c | [
"def",
"procrustes",
"(",
"anchors",
",",
"X",
",",
"scale",
"=",
"True",
",",
"print_out",
"=",
"False",
")",
":",
"def",
"centralize",
"(",
"X",
")",
":",
"n",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"ones",
"=",
"np",
".",
"ones",
"(",
"(",
... | Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor. | [
"Fit",
"X",
"to",
"anchors",
"by",
"applying",
"optimal",
"translation",
"rotation",
"and",
"reflection",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L61-L112 | train | 47,590 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_cdm | def reconstruct_cdm(dm, absolute_angles, all_points, W=None):
""" Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
"""
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V
from pylocus.mds import signedMDS
N = all_points.shape[0]
V = get_V(absolute_angles, dm)
dmx = dmi_from_V(V, 0)
dmy = dmi_from_V(V, 1)
sdmx = sdm_from_dmi(dmx, N)
sdmy = sdm_from_dmi(dmy, N)
points_x = signedMDS(sdmx, W)
points_y = signedMDS(sdmy, W)
Xhat = np.c_[points_x, points_y]
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | python | def reconstruct_cdm(dm, absolute_angles, all_points, W=None):
""" Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
"""
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V
from pylocus.mds import signedMDS
N = all_points.shape[0]
V = get_V(absolute_angles, dm)
dmx = dmi_from_V(V, 0)
dmy = dmi_from_V(V, 1)
sdmx = sdm_from_dmi(dmx, N)
sdmy = sdm_from_dmi(dmy, N)
points_x = signedMDS(sdmx, W)
points_y = signedMDS(sdmy, W)
Xhat = np.c_[points_x, points_y]
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | [
"def",
"reconstruct_cdm",
"(",
"dm",
",",
"absolute_angles",
",",
"all_points",
",",
"W",
"=",
"None",
")",
":",
"from",
"pylocus",
".",
"point_set",
"import",
"dmi_from_V",
",",
"sdm_from_dmi",
",",
"get_V",
"from",
"pylocus",
".",
"mds",
"import",
"signedM... | Reconstruct point set from angle and distance measurements, using coordinate difference matrices. | [
"Reconstruct",
"point",
"set",
"from",
"angle",
"and",
"distance",
"measurements",
"using",
"coordinate",
"difference",
"matrices",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L146-L167 | train | 47,591 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_mds | def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1):
""" Reconstruct point set using MDS and matrix completion algorithms.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
if mask is not None:
edm_missing = np.multiply(edm, mask)
if completion == 'optspace':
from .edm_completion import optspace
edm_complete = optspace(edm_missing, d + 2)
elif completion == 'alternate':
from .edm_completion import rank_alternation
edm_complete, errs = rank_alternation(
edm_missing, d + 2, print_out=False, edm_true=edm)
else:
raise NameError('Unknown completion method {}'.format(completion))
if (print_out):
err = np.linalg.norm(edm_complete - edm)**2 / \
np.linalg.norm(edm)**2
print('{}: relative error:{}'.format(completion, err))
edm = edm_complete
Xhat = MDS(edm, d, method, False).T
Y, R, t, c = procrustes(all_points[n:], Xhat, True)
#Y, R, t, c = procrustes(all_points, Xhat, True)
return Y | python | def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1):
""" Reconstruct point set using MDS and matrix completion algorithms.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
if mask is not None:
edm_missing = np.multiply(edm, mask)
if completion == 'optspace':
from .edm_completion import optspace
edm_complete = optspace(edm_missing, d + 2)
elif completion == 'alternate':
from .edm_completion import rank_alternation
edm_complete, errs = rank_alternation(
edm_missing, d + 2, print_out=False, edm_true=edm)
else:
raise NameError('Unknown completion method {}'.format(completion))
if (print_out):
err = np.linalg.norm(edm_complete - edm)**2 / \
np.linalg.norm(edm)**2
print('{}: relative error:{}'.format(completion, err))
edm = edm_complete
Xhat = MDS(edm, d, method, False).T
Y, R, t, c = procrustes(all_points[n:], Xhat, True)
#Y, R, t, c = procrustes(all_points, Xhat, True)
return Y | [
"def",
"reconstruct_mds",
"(",
"edm",
",",
"all_points",
",",
"completion",
"=",
"'optspace'",
",",
"mask",
"=",
"None",
",",
"method",
"=",
"'geometric'",
",",
"print_out",
"=",
"False",
",",
"n",
"=",
"1",
")",
":",
"from",
".",
"point_set",
"import",
... | Reconstruct point set using MDS and matrix completion algorithms. | [
"Reconstruct",
"point",
"set",
"using",
"MDS",
"and",
"matrix",
"completion",
"algorithms",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L170-L196 | train | 47,592 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_sdp | def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs):
""" Reconstruct point set using semi-definite rank relaxation.
"""
from .edm_completion import semidefinite_relaxation
edm_complete = semidefinite_relaxation(
edm, lamda=lamda, W=W, print_out=print_out, **kwargs)
Xhat = reconstruct_mds(edm_complete, all_points, method='geometric')
return Xhat, edm_complete | python | def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs):
""" Reconstruct point set using semi-definite rank relaxation.
"""
from .edm_completion import semidefinite_relaxation
edm_complete = semidefinite_relaxation(
edm, lamda=lamda, W=W, print_out=print_out, **kwargs)
Xhat = reconstruct_mds(edm_complete, all_points, method='geometric')
return Xhat, edm_complete | [
"def",
"reconstruct_sdp",
"(",
"edm",
",",
"all_points",
",",
"W",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"lamda",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"edm_completion",
"import",
"semidefinite_relaxation",
"edm_complete",
... | Reconstruct point set using semi-definite rank relaxation. | [
"Reconstruct",
"point",
"set",
"using",
"semi",
"-",
"definite",
"rank",
"relaxation",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L199-L206 | train | 47,593 |
LCAV/pylocus | pylocus/lateration.py | get_lateration_parameters | def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r2 = np.delete(edm[index, :], indices)
w = np.delete(W[index, :], indices)
# set w to zero where measurements are invalid
if np.isnan(r2).any():
nan_measurements = np.where(np.isnan(r2))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
if np.isnan(w).any():
nan_measurements = np.where(np.isnan(w))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
# delete anchors where weight is zero to avoid ill-conditioning
missing_anchors = np.where(w == 0.0)[0]
w = np.asarray(np.delete(w, missing_anchors))
r2 = np.asarray(np.delete(r2, missing_anchors))
w.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
r2.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
anchors = np.delete(anchors, missing_anchors, axis=0)
assert w.shape[0] == anchors.shape[0]
assert np.isnan(w).any() == False
assert np.isnan(r2).any() == False
return anchors, w, r2 | python | def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r2 = np.delete(edm[index, :], indices)
w = np.delete(W[index, :], indices)
# set w to zero where measurements are invalid
if np.isnan(r2).any():
nan_measurements = np.where(np.isnan(r2))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
if np.isnan(w).any():
nan_measurements = np.where(np.isnan(w))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
# delete anchors where weight is zero to avoid ill-conditioning
missing_anchors = np.where(w == 0.0)[0]
w = np.asarray(np.delete(w, missing_anchors))
r2 = np.asarray(np.delete(r2, missing_anchors))
w.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
r2.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
anchors = np.delete(anchors, missing_anchors, axis=0)
assert w.shape[0] == anchors.shape[0]
assert np.isnan(w).any() == False
assert np.isnan(r2).any() == False
return anchors, w, r2 | [
"def",
"get_lateration_parameters",
"(",
"all_points",
",",
"indices",
",",
"index",
",",
"edm",
",",
"W",
"=",
"None",
")",
":",
"if",
"W",
"is",
"None",
":",
"W",
"=",
"np",
".",
"ones",
"(",
"edm",
".",
"shape",
")",
"# delete points that are not cons... | Get parameters relevant for lateration from full all_points, edm and W. | [
"Get",
"parameters",
"relevant",
"for",
"lateration",
"from",
"full",
"all_points",
"edm",
"and",
"W",
"."
] | c56a38c251d8a435caf4641a8ae6027ecba2c8c6 | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L11-L42 | train | 47,594 |
toumorokoshi/transmute-core | transmute_core/attributes/__init__.py | TransmuteAttributes._join_parameters | def _join_parameters(base, nxt):
""" join parameters from the lhs to the rhs, if compatible. """
if nxt is None:
return base
if isinstance(base, set) and isinstance(nxt, set):
return base | nxt
else:
return nxt | python | def _join_parameters(base, nxt):
""" join parameters from the lhs to the rhs, if compatible. """
if nxt is None:
return base
if isinstance(base, set) and isinstance(nxt, set):
return base | nxt
else:
return nxt | [
"def",
"_join_parameters",
"(",
"base",
",",
"nxt",
")",
":",
"if",
"nxt",
"is",
"None",
":",
"return",
"base",
"if",
"isinstance",
"(",
"base",
",",
"set",
")",
"and",
"isinstance",
"(",
"nxt",
",",
"set",
")",
":",
"return",
"base",
"|",
"nxt",
"... | join parameters from the lhs to the rhs, if compatible. | [
"join",
"parameters",
"from",
"the",
"lhs",
"to",
"the",
"rhs",
"if",
"compatible",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/attributes/__init__.py#L99-L106 | train | 47,595 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction.get_swagger_operation | def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": Response(
{
"description": "invalid input received",
"schema": Schema(
{
"title": "FailureObject",
"type": "object",
"properties": {
"success": {"type": "boolean"},
"result": {"type": "string"},
},
"required": ["success", "result"],
}
),
}
)
}
for code, details in self.response_types.items():
responses[str(code)] = details.swagger_definition(context)
return Operation(
{
"summary": self.summary,
"description": self.description,
"consumes": consumes,
"produces": produces,
"parameters": parameters,
"responses": responses,
"operationId": self.raw_func.__name__,
"tags": self.tags,
}
) | python | def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": Response(
{
"description": "invalid input received",
"schema": Schema(
{
"title": "FailureObject",
"type": "object",
"properties": {
"success": {"type": "boolean"},
"result": {"type": "string"},
},
"required": ["success", "result"],
}
),
}
)
}
for code, details in self.response_types.items():
responses[str(code)] = details.swagger_definition(context)
return Operation(
{
"summary": self.summary,
"description": self.description,
"consumes": consumes,
"produces": produces,
"parameters": parameters,
"responses": responses,
"operationId": self.raw_func.__name__,
"tags": self.tags,
}
) | [
"def",
"get_swagger_operation",
"(",
"self",
",",
"context",
"=",
"default_context",
")",
":",
"consumes",
"=",
"produces",
"=",
"context",
".",
"contenttype_serializers",
".",
"keys",
"(",
")",
"parameters",
"=",
"get_swagger_parameters",
"(",
"self",
".",
"par... | get the swagger_schema operation representation. | [
"get",
"the",
"swagger_schema",
"operation",
"representation",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L89-L128 | train | 47,596 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction.process_result | def process_result(self, context, result_body, exc, content_type):
"""
given an result body and an exception object,
return the appropriate result object,
or raise an exception.
"""
return process_result(self, context, result_body, exc, content_type) | python | def process_result(self, context, result_body, exc, content_type):
"""
given an result body and an exception object,
return the appropriate result object,
or raise an exception.
"""
return process_result(self, context, result_body, exc, content_type) | [
"def",
"process_result",
"(",
"self",
",",
"context",
",",
"result_body",
",",
"exc",
",",
"content_type",
")",
":",
"return",
"process_result",
"(",
"self",
",",
"context",
",",
"result_body",
",",
"exc",
",",
"content_type",
")"
] | given an result body and an exception object,
return the appropriate result object,
or raise an exception. | [
"given",
"an",
"result",
"body",
"and",
"an",
"exception",
"object",
"return",
"the",
"appropriate",
"result",
"object",
"or",
"raise",
"an",
"exception",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L130-L136 | train | 47,597 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction._parse_response_types | def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.response_types.copy()
if return_type or len(response_types) == 0:
response_types[attrs.success_code] = ResponseType(
type=return_type,
type_description=type_description,
description="success",
)
return response_types | python | def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.response_types.copy()
if return_type or len(response_types) == 0:
response_types[attrs.success_code] = ResponseType(
type=return_type,
type_description=type_description,
description="success",
)
return response_types | [
"def",
"_parse_response_types",
"(",
"argspec",
",",
"attrs",
")",
":",
"return_type",
"=",
"argspec",
".",
"annotations",
".",
"get",
"(",
"\"return\"",
")",
"or",
"None",
"type_description",
"=",
"attrs",
".",
"parameter_descriptions",
".",
"get",
"(",
"\"re... | from the given parameters, return back the response type dictionaries. | [
"from",
"the",
"given",
"parameters",
"return",
"back",
"the",
"response",
"type",
"dictionaries",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L152-L165 | train | 47,598 |
toumorokoshi/transmute-core | transmute_core/swagger/__init__.py | generate_swagger_html | def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
) | python | def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
) | [
"def",
"generate_swagger_html",
"(",
"swagger_static_root",
",",
"swagger_json_url",
")",
":",
"tmpl",
"=",
"_get_template",
"(",
"\"swagger.html\"",
")",
"return",
"tmpl",
".",
"render",
"(",
"swagger_root",
"=",
"swagger_static_root",
",",
"swagger_json_url",
"=",
... | given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values. | [
"given",
"a",
"root",
"directory",
"for",
"the",
"swagger",
"statics",
"and",
"a",
"swagger",
"json",
"path",
"return",
"back",
"a",
"swagger",
"html",
"designed",
"to",
"use",
"those",
"values",
"."
] | a2c26625d5d8bab37e00038f9d615a26167fc7f4 | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L10-L19 | train | 47,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.