_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q275900
|
missing_categories
|
test
|
def missing_categories(context):
''' Adds the categories that the user does not currently have. '''
user = user_for_context(context)
categories_available = set(CategoryController.available_categories(user))
|
python
|
{
"resource": ""
}
|
q275901
|
available_credit
|
test
|
def available_credit(context):
''' Calculates the sum of unclaimed credit from this user's credit notes.
Returns:
Decimal: the sum of the values of unclaimed credit notes for the
current user.
'''
notes = commerce.CreditNote.unclaimed().filter(
|
python
|
{
"resource": ""
}
|
q275902
|
sold_out_and_unregistered
|
test
|
def sold_out_and_unregistered(context):
''' If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
pertinent question for people who already have a ticket).
'''
user = user_for_context(context)
if hasattr(user, "attendee") and user.attendee.completed_registration:
# This user has completed registration, and so we don't need to answer
# whether they have sold out yet.
# TODO: what if a user has got to the review phase?
|
python
|
{
"resource": ""
}
|
q275903
|
guided_registration
|
test
|
def guided_registration(request, page_number=None):
''' Goes through the registration process in order, making sure user sees
all valid categories.
The user must be logged in to see this view.
Parameter:
page_number:
1) Profile form (and e-mail address?)
2) Ticket type
3) Remaining products
4) Mark registration as complete
Returns:
render: Renders ``registrasion/guided_registration.html``,
with the following data::
{
"current_step": int(), # The current step in the
# registration
"sections": sections, # A list of
# GuidedRegistrationSections
"title": str(), # The title of the page
"total_steps": int(), # The total number of steps
}
'''
PAGE_PROFILE = 1
PAGE_TICKET = 2
PAGE_PRODUCTS = 3
PAGE_PRODUCTS_MAX = 4
TOTAL_PAGES = 4
ticket_category = inventory.Category.objects.get(
id=settings.TICKET_PRODUCT_CATEGORY
)
cart = CartController.for_user(request.user)
attendee = people.Attendee.get_instance(request.user)
# This guided registration process is only for people who have
# not completed registration (and has confusing behaviour if you go
# back to it.)
if attendee.completed_registration:
return redirect(review)
# Calculate the current maximum page number for this user.
has_profile = hasattr(attendee, "attendeeprofilebase")
if not has_profile:
# If there's no profile, they have to go to the profile page.
max_page = PAGE_PROFILE
redirect_page = PAGE_PROFILE
else:
# We have a profile.
# Do they have a ticket?
products = inventory.Product.objects.filter(
productitem__cart=cart.cart
)
products = products.filter(category=ticket_category)
if products.count() == 0:
# If no ticket, they can only see the profile or ticket page.
max_page = PAGE_TICKET
redirect_page = PAGE_TICKET
else:
# If there's a ticket, they should *see* the general products page#
# but be able to go to the overflow page if needs be.
max_page = PAGE_PRODUCTS_MAX
redirect_page = PAGE_PRODUCTS
if page_number is None or int(page_number) > max_page:
return redirect("guided_registration", redirect_page)
page_number = int(page_number)
next_step = redirect("guided_registration", page_number + 1)
with BatchController.batch(request.user):
# This view doesn't work if the conference has sold out.
available = ProductController.available_products(
request.user, category=ticket_category
|
python
|
{
"resource": ""
}
|
q275904
|
edit_profile
|
test
|
def edit_profile(request):
''' View for editing an attendee's profile
The user must be logged in to edit their profile.
Returns:
redirect or render:
In the case of a ``POST`` request, it'll redirect to ``dashboard``,
or otherwise, it will render ``registrasion/profile_form.html``
with data::
{
"form": form, # Instance of ATTENDEE_PROFILE_FORM.
|
python
|
{
"resource": ""
}
|
q275905
|
_handle_profile
|
test
|
def _handle_profile(request, prefix):
''' Returns a profile form instance, and a boolean which is true if the
form was handled. '''
attendee = people.Attendee.get_instance(request.user)
try:
profile = attendee.attendeeprofilebase
profile = people.AttendeeProfileBase.objects.get_subclass(
pk=profile.id,
)
except ObjectDoesNotExist:
profile = None
# Load a pre-entered name from the speaker's profile,
# if they have one.
try:
speaker_profile = request.user.speaker_profile
speaker_name = speaker_profile.name
except ObjectDoesNotExist:
speaker_name = None
name_field = ProfileForm.Meta.model.name_field()
initial = {}
|
python
|
{
"resource": ""
}
|
q275906
|
product_category
|
test
|
def product_category(request, category_id):
''' Form for selecting products from an individual product category.
Arguments:
category_id (castable to int): The id of the category to display.
Returns:
redirect or render:
If the form has been sucessfully submitted, redirect to
``dashboard``. Otherwise, render
``registrasion/product_category.html`` with data::
{
"category": category, # An inventory.Category for
# category_id
"discounts": discounts, # A list of
# DiscountAndQuantity
"form": products_form, # A form for selecting
# products
"voucher_form": voucher_form, # A form for entering a
# voucher code
}
'''
PRODUCTS_FORM_PREFIX = "products"
VOUCHERS_FORM_PREFIX = "vouchers"
# Handle the voucher
|
python
|
{
"resource": ""
}
|
q275907
|
_handle_products
|
test
|
def _handle_products(request, category, products, prefix):
''' Handles a products list form in the given request. Returns the
form instance, the discounts applicable to this form, and whether the
contents were handled. '''
current_cart = CartController.for_user(request.user)
ProductsForm = forms.ProductsForm(category, products)
# Create initial data for each of products in category
items = commerce.ProductItem.objects.filter(
product__in=products,
cart=current_cart.cart,
).select_related("product")
quantities = []
seen = set()
for item in items:
quantities.append((item.product, item.quantity))
seen.add(item.product)
zeros = set(products) - seen
for product in zeros:
quantities.append((product, 0))
products_form = ProductsForm(
request.POST or None,
product_quantities=quantities,
prefix=prefix,
)
if request.method == "POST" and products_form.is_valid():
if products_form.has_changed():
_set_quantities_from_products_form(products_form, current_cart)
# If category is required, the user must have at least one
# in an active+valid cart
if category.required:
carts = commerce.Cart.objects.filter(user=request.user)
|
python
|
{
"resource": ""
}
|
q275908
|
_handle_voucher
|
test
|
def _handle_voucher(request, prefix):
''' Handles a voucher form in the given request. Returns the voucher
form instance, and whether the voucher code was handled. '''
voucher_form = forms.VoucherForm(request.POST or None, prefix=prefix)
current_cart = CartController.for_user(request.user)
if (voucher_form.is_valid() and
voucher_form.cleaned_data["voucher"].strip()):
voucher = voucher_form.cleaned_data["voucher"]
voucher = inventory.Voucher.normalise_code(voucher)
if len(current_cart.cart.vouchers.filter(code=voucher)) > 0:
# This voucher has already been applied to this cart.
# Do not
|
python
|
{
"resource": ""
}
|
q275909
|
checkout
|
test
|
def checkout(request, user_id=None):
''' Runs the checkout process for the current cart.
If the query string contains ``fix_errors=true``, Registrasion will attempt
to fix errors preventing the system from checking out, including by
cancelling expired discounts and vouchers, and removing any unavailable
products.
Arguments:
user_id (castable to int):
If the requesting user is staff, then the user ID can be used to
run checkout for another user.
Returns:
render or redirect:
If the invoice is generated successfully, or there's already a
valid invoice for the current cart, redirect to ``invoice``.
If there are errors when generating the invoice, render
``registrasion/checkout_errors.html`` with the following data::
{
"error_list", [str, ...] # The errors to display.
}
'''
if user_id is not None:
|
python
|
{
"resource": ""
}
|
q275910
|
invoice_access
|
test
|
def invoice_access(request, access_code):
''' Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's a paid invoice, show the most recent one, otherwise
- Show the most recent invoid of all
Arguments:
access_code (castable to int): The access code for the user whose
invoice you want to see.
Returns:
redirect:
Redirect to the selected invoice for that user.
Raises:
Http404: If the user has no invoices.
'''
invoices = commerce.Invoice.objects.filter(
|
python
|
{
"resource": ""
}
|
q275911
|
invoice
|
test
|
def invoice(request, invoice_id, access_code=None):
''' Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoice_id for the invoice you want
to view.
access_code (Optional[str]): The access code for the user who owns
this invoice.
Returns:
|
python
|
{
"resource": ""
}
|
q275912
|
manual_payment
|
test
|
def manual_payment(request, invoice_id):
''' Allows staff to make manual payments or refunds on an invoice.
This form requires a login, and the logged in user needs to be staff.
Arguments:
invoice_id (castable to int): The invoice ID to be paid
Returns:
render:
Renders ``registrasion/manual_payment.html`` with the following
data::
{
"invoice": models.commerce.Invoice(),
"form": form, # A form that saves
|
python
|
{
"resource": ""
}
|
q275913
|
refund
|
test
|
def refund(request, invoice_id):
''' Marks an invoice as refunded and requests a credit note for the
full amount paid against the invoice.
This view requires a login, and the logged in user must be staff.
Arguments:
invoice_id (castable to int): The ID of the
|
python
|
{
"resource": ""
}
|
q275914
|
credit_note
|
test
|
def credit_note(request, note_id, access_code=None):
''' Displays a credit note.
If ``request`` is a ``POST`` request, forms for applying or refunding
a credit note will be processed.
This view requires a login, and the logged in user must be staff.
Arguments:
note_id (castable to int): The ID of the credit note to view.
Returns:
render or redirect:
If the "apply to invoice" form is correctly processed, redirect to
that invoice, otherwise, render ``registration/credit_note.html``
with the following data::
{
"credit_note": models.commerce.CreditNote(),
"apply_form": form, # A form for applying credit note
# to an invoice.
"refund_form": form, # A form for applying a *manual*
# refund of the credit note.
"cancellation_fee_form" : form, # A form for generating an
# invoice with a
# cancellation fee
}
'''
note_id = int(note_id)
current_note = CreditNoteController.for_id_or_404(note_id)
apply_form = forms.ApplyCreditNoteForm(
current_note.credit_note.invoice.user,
request.POST or None,
prefix="apply_note"
)
refund_form = forms.ManualCreditNoteRefundForm(
request.POST or None,
prefix="refund_note"
)
cancellation_fee_form = forms.CancellationFeeForm(
request.POST or None,
prefix="cancellation_fee"
)
if request.POST and apply_form.is_valid():
inv_id = apply_form.cleaned_data["invoice"]
invoice = commerce.Invoice.objects.get(pk=inv_id)
|
python
|
{
"resource": ""
}
|
q275915
|
amend_registration
|
test
|
def amend_registration(request, user_id):
''' Allows staff to amend a user's current registration cart, and etc etc.
'''
user = User.objects.get(id=int(user_id))
current_cart = CartController.for_user(user)
items = commerce.ProductItem.objects.filter(
cart=current_cart.cart,
).select_related("product")
initial = [{"product": i.product, "quantity": i.quantity} for i in items]
StaffProductsFormSet = forms.staff_products_formset_factory(user)
formset = StaffProductsFormSet(
request.POST or None,
initial=initial,
prefix="products",
)
for item, form in zip(items, formset):
queryset = inventory.Product.objects.filter(id=item.product.id)
form.fields["product"].queryset = queryset
voucher_form = forms.VoucherForm(
request.POST or None,
prefix="voucher",
)
if request.POST and formset.is_valid():
pq = [
|
python
|
{
"resource": ""
}
|
q275916
|
extend_reservation
|
test
|
def extend_reservation(request, user_id, days=7):
''' Allows staff to extend the reservation on a given user's cart.
'''
|
python
|
{
"resource": ""
}
|
q275917
|
invoice_mailout
|
test
|
def invoice_mailout(request):
''' Allows staff to send emails to users based on their invoice status. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoiceEmailForm(
request.POST or None,
category=category,
product=product,
status=status,
)
emails = []
if form.is_valid():
emails = []
for invoice in form.cleaned_data["invoice"]:
# datatuple = (subject, message, from_email, recipient_list)
from_email = form.cleaned_data["from_email"]
subject = form.cleaned_data["subject"]
body = Template(form.cleaned_data["body"]).render(
Context({
"invoice": invoice,
"user": invoice.user,
})
)
|
python
|
{
"resource": ""
}
|
q275918
|
badges
|
test
|
def badges(request):
''' Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoicesWithProductAndStatusForm(
request.POST or None,
category=category,
product=product,
status=status,
)
if form.is_valid():
response = HttpResponse()
response["Content-Type"] = "application.zip"
response["Content-Disposition"] = 'attachment; filename="badges.zip"'
z =
|
python
|
{
"resource": ""
}
|
q275919
|
render_badge
|
test
|
def render_badge(user):
''' Renders a single user's badge. '''
data = {
"user": user,
}
|
python
|
{
"resource": ""
}
|
q275920
|
DiscountController.available_discounts
|
test
|
def available_discounts(cls, user, categories, products):
''' Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. '''
filtered_clauses = cls._filtered_clauses(user)
# clauses that match provided categories
categories = set(categories)
# clauses that match provided products
products = set(products)
# clauses that match categories for provided products
product_categories = set(product.category for product in products)
# (Not relevant: clauses that match products in provided categories)
all_categories = categories | product_categories
filtered_clauses = (
clause for clause in filtered_clauses
if hasattr(clause, 'product') and clause.product in products or
hasattr(clause, 'category') and clause.category in all_categories
)
discounts = []
# Markers so that we don't need to evaluate given conditions
# more than once
accepted_discounts = set()
failed_discounts = set()
for clause in filtered_clauses:
discount = clause.discount
cond = ConditionController.for_condition(discount)
|
python
|
{
"resource": ""
}
|
q275921
|
DiscountController._annotate_with_past_uses
|
test
|
def _annotate_with_past_uses(cls, queryset, user):
''' Annotates the queryset with a usage count for that discount claus
by the given user. '''
if queryset.model == conditions.DiscountForCategory:
matches = (
Q(category=F('discount__discountitem__product__category'))
)
elif queryset.model == conditions.DiscountForProduct:
matches = (
Q(product=F('discount__discountitem__product'))
)
in_carts = (
Q(discount__discountitem__cart__user=user) &
Q(discount__discountitem__cart__status=commerce.Cart.STATUS_PAID)
|
python
|
{
"resource": ""
}
|
q275922
|
ProductController.available_products
|
test
|
def available_products(cls, user, category=None, products=None):
''' Returns a list of all of the products that are available per
flag conditions from the given categories. '''
if category is None and products is None:
raise ValueError("You must provide products or a category")
if category is not None:
all_products = inventory.Product.objects.filter(category=category)
all_products = all_products.select_related("category")
else:
all_products = []
if products is not None:
all_products = set(itertools.chain(all_products, products))
category_remainders = CategoryController.user_remainders(user)
product_remainders = ProductController.user_remainders(user)
passed_limits = set(
|
python
|
{
"resource": ""
}
|
q275923
|
CreditNoteController.apply_to_invoice
|
test
|
def apply_to_invoice(self, invoice):
''' Applies the total value of this credit note to the specified
invoice. If this credit note overpays the invoice, a new credit note
containing the residual value will be created.
Raises ValidationError if the given invoice is not allowed to be
paid.
'''
# Local import to fix import cycles. Can we do better?
from .invoice import InvoiceController
inv = InvoiceController(invoice)
inv.validate_allowed_to_pay()
# Apply payment to invoice
|
python
|
{
"resource": ""
}
|
q275924
|
CreditNoteController.cancellation_fee
|
test
|
def cancellation_fee(self, percentage):
''' Generates an invoice with a cancellation fee, and applies
credit to the invoice.
percentage (Decimal): The percentage of the credit note to turn into
a cancellation fee. Must be 0 <= percentage <= 100.
'''
# Local import to fix import cycles. Can we do better?
|
python
|
{
"resource": ""
}
|
q275925
|
generate_access_code
|
test
|
def generate_access_code():
''' Generates an access code for users' payments as well as their
fulfilment code for check-in.
The access code will 4 characters long, which allows for 1,500,625
unique codes, which really should be enough for anyone. '''
length = 6
# all upper-case letters + digits 1-9 (no 0 vs O confusion)
|
python
|
{
"resource": ""
}
|
q275926
|
lazy
|
test
|
def lazy(function, *args, **kwargs):
''' Produces a callable so that functions can be lazily evaluated in
templates.
Arguments:
function (callable): The function to call at evaluation time.
args: Positional arguments, passed directly to ``function``.
|
python
|
{
"resource": ""
}
|
q275927
|
get_object_from_name
|
test
|
def get_object_from_name(name):
''' Returns the named object.
Arguments:
name (str): A string of form `package.subpackage.etc.module.property`.
This function will import `package.subpackage.etc.module` and
return `property` from that module.
'''
dot = name.rindex(".")
|
python
|
{
"resource": ""
}
|
q275928
|
InvoiceController.for_cart
|
test
|
def for_cart(cls, cart):
''' Returns an invoice object for a given cart at its current revision.
If such an invoice does not exist, the cart is validated, and if valid,
an invoice is generated.'''
cart.refresh_from_db()
try:
invoice = commerce.Invoice.objects.exclude(
status=commerce.Invoice.STATUS_VOID,
).get(
cart=cart,
cart_revision=cart.revision,
|
python
|
{
"resource": ""
}
|
q275929
|
InvoiceController.manual_invoice
|
test
|
def manual_invoice(cls, user, due_delta, description_price_pairs):
''' Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
due.
description_price_pairs ([(str, long or Decimal), ...]): A list of
pairs. Each pair consists of the description for
|
python
|
{
"resource": ""
}
|
q275930
|
InvoiceController._generate_from_cart
|
test
|
def _generate_from_cart(cls, cart):
''' Generates an invoice for the given cart. '''
cart.refresh_from_db()
# Generate the line items from the cart.
product_items = commerce.ProductItem.objects.filter(cart=cart)
product_items = product_items.select_related(
"product",
"product__category",
)
product_items = product_items.order_by(
"product__category__order", "product__order"
)
if len(product_items) == 0:
raise ValidationError("Your cart is empty.")
discount_items = commerce.DiscountItem.objects.filter(cart=cart)
discount_items = discount_items.select_related(
"discount",
"product",
"product__category",
)
def format_product(product):
return "%s - %s" % (product.category.name, product.name)
def format_discount(discount, product):
description = discount.description
return "%s (%s)" % (description, format_product(product))
line_items = []
for item in product_items:
product = item.product
line_item = commerce.LineItem(
|
python
|
{
"resource": ""
}
|
q275931
|
InvoiceController._apply_credit_notes
|
test
|
def _apply_credit_notes(cls, invoice):
''' Applies the user's credit notes to the given invoice on creation.
'''
# We only automatically apply credit notes if this is the *only*
# unpaid invoice for this user.
invoices = commerce.Invoice.objects.filter(
user=invoice.user,
status=commerce.Invoice.STATUS_UNPAID,
)
if invoices.count() > 1:
return
notes = commerce.CreditNote.unclaimed().filter(
invoice__user=invoice.user
|
python
|
{
"resource": ""
}
|
q275932
|
InvoiceController.can_view
|
test
|
def can_view(self, user=None, access_code=None):
''' Returns true if the accessing user is allowed to view this invoice,
or if the given access code matches this invoice's user's access code.
'''
if user == self.invoice.user:
|
python
|
{
"resource": ""
}
|
q275933
|
InvoiceController._refresh
|
test
|
def _refresh(self):
''' Refreshes the underlying invoice and cart objects. '''
self.invoice.refresh_from_db()
|
python
|
{
"resource": ""
}
|
q275934
|
InvoiceController.validate_allowed_to_pay
|
test
|
def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
return
|
python
|
{
"resource": ""
}
|
q275935
|
InvoiceController.update_status
|
test
|
def update_status(self):
''' Updates the status of this invoice based upon the total
payments.'''
old_status = self.invoice.status
total_paid = self.invoice.total_payments()
num_payments = commerce.PaymentBase.objects.filter(
invoice=self.invoice,
).count()
remainder = self.invoice.value - total_paid
if old_status == commerce.Invoice.STATUS_UNPAID:
# Invoice had an amount owing
if remainder <= 0:
# Invoice no longer has amount owing
self._mark_paid()
elif total_paid == 0 and num_payments > 0:
# Invoice has multiple payments totalling zero
self._mark_void()
elif old_status == commerce.Invoice.STATUS_PAID:
if remainder > 0:
# Invoice went from having a remainder of zero or less
# to having a positive remainder -- must be a refund
self._mark_refunded()
elif old_status == commerce.Invoice.STATUS_REFUNDED:
# Should not ever change from
|
python
|
{
"resource": ""
}
|
q275936
|
InvoiceController._mark_paid
|
test
|
def _mark_paid(self):
''' Marks the invoice as paid, and updates the attached cart if
necessary. '''
cart = self.invoice.cart
if cart:
cart.status = commerce.Cart.STATUS_PAID
|
python
|
{
"resource": ""
}
|
q275937
|
InvoiceController._invoice_matches_cart
|
test
|
def _invoice_matches_cart(self):
''' Returns true if there is no cart, or if the revision of this
invoice matches the current revision
|
python
|
{
"resource": ""
}
|
q275938
|
InvoiceController.update_validity
|
test
|
def update_validity(self):
''' Voids this invoice if the attached cart is no longer valid because
the cart revision has changed, or the reservations have expired. '''
is_valid = self._invoice_matches_cart()
cart = self.invoice.cart
if self.invoice.is_unpaid and is_valid and cart:
try:
CartController(cart).validate_cart()
except ValidationError:
is_valid = False
|
python
|
{
"resource": ""
}
|
q275939
|
InvoiceController.void
|
test
|
def void(self):
''' Voids the invoice if it is valid to do so. '''
if self.invoice.total_payments() > 0:
raise ValidationError("Invoices with payments must be refunded.")
elif self.invoice.is_refunded:
|
python
|
{
"resource": ""
}
|
q275940
|
InvoiceController.refund
|
test
|
def refund(self):
''' Refunds the invoice by generating a CreditNote for the value of
all of the payments against the cart.
The invoice is marked as refunded, and the underlying cart is marked
as released.
'''
if self.invoice.is_void:
raise ValidationError("Void invoices cannot be refunded")
#
|
python
|
{
"resource": ""
}
|
q275941
|
InvoiceController.email
|
test
|
def email(cls, invoice, kind):
''' Sends out an e-mail notifying the user about something to do
with that invoice. '''
context = {
"invoice":
|
python
|
{
"resource": ""
}
|
q275942
|
GenData.update
|
test
|
def update(self, data):
"""Update the object with new data."""
fields = [
'id',
'status',
'type',
'persistence',
'date_start',
'date_finish',
'date_created',
'date_modified',
'checksum',
'processor_name',
'input',
'input_schema',
'output',
'output_schema',
'static',
'static_schema',
'var',
'var_template',
]
self.annotation = {}
|
python
|
{
"resource": ""
}
|
q275943
|
GenData._flatten_field
|
test
|
def _flatten_field(self, field, schema, path):
"""Reduce dicts of dicts to dot separated keys."""
flat = {}
for field_schema, fields, path in iterate_schema(field, schema, path):
name = field_schema['name']
typ = field_schema['type']
|
python
|
{
"resource": ""
}
|
q275944
|
GenData.print_downloads
|
test
|
def print_downloads(self):
"""Print file fields to standard output."""
for path, ann in self.annotation.items():
|
python
|
{
"resource": ""
}
|
q275945
|
GenData.download
|
test
|
def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
if field not in self.annotation:
raise ValueError("Download field {}
|
python
|
{
"resource": ""
}
|
q275946
|
Genesis.project_data
|
test
|
def project_data(self, project):
"""Return a list of Data objects for given project.
:param project: ObjectId or slug of Genesis project
:type project: string
:rtype: list of Data objects
"""
projobjects = self.cache['project_objects']
objects = self.cache['objects']
project_id = str(project)
if not re.match('^[0-9a-fA-F]{24}$', project_id):
# project_id is a slug
projects = self.api.case.get(url_slug=project_id)['objects']
if len(projects) != 1:
raise ValueError(msg='Attribute project not a slug or ObjectId: {}'.format(project_id))
project_id = str(projects[0]['id'])
if project_id not in projobjects:
projobjects[project_id] = []
data = self.api.data.get(case_ids__contains=project_id)['objects']
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
objects[_id].update(d)
else:
# Insert new object
objects[_id] = GenData(d, self)
projobjects[project_id].append(objects[_id])
# Hydrate reference fields
for d in projobjects[project_id]:
while True:
ref_annotation = {}
remove_annotation = []
for path, ann in d.annotation.items():
|
python
|
{
"resource": ""
}
|
q275947
|
Genesis.processors
|
test
|
def processors(self, processor_name=None):
"""Return a list of Processor objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:rtype: list of Processor objects
"""
if processor_name:
|
python
|
{
"resource": ""
}
|
q275948
|
Genesis.print_processor_inputs
|
test
|
def print_processor_inputs(self, processor_name):
"""Print processor input fields and types.
:param processor_name: Processor object name
:type processor_name: string
"""
p = self.processors(processor_name=processor_name)
|
python
|
{
"resource": ""
}
|
q275949
|
Genesis.rundata
|
test
|
def rundata(self, strjson):
"""POST JSON data object to server"""
|
python
|
{
"resource": ""
}
|
q275950
|
Genesis.upload
|
test
|
def upload(self, project_id, processor_name, **fields):
"""Upload files and data objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:param processor_name: Processor object name
:type processor_name: string
:param fields: Processor field-value pairs
:type fields: args
:rtype: HTTP Response object
"""
p = self.processors(processor_name=processor_name)
if len(p) == 1:
p = p[0]
else:
Exception('Invalid processor name {}'.format(processor_name))
for field_name, field_val in fields.items():
if field_name not in p['input_schema']:
|
python
|
{
"resource": ""
}
|
q275951
|
Genesis._upload_file
|
test
|
def _upload_file(self, fn):
"""Upload a single file on the platform.
File is uploaded in chunks of 1,024 bytes.
:param fn: File path
:type fn: string
"""
size = os.path.getsize(fn)
counter = 0
base_name = os.path.basename(fn)
session_id = str(uuid.uuid4())
with open(fn, 'rb') as f:
while True:
response = None
chunk = f.read(CHUNK_SIZE)
if not chunk:
break
for i in range(5):
content_range = 'bytes {}-{}/{}'.format(counter * CHUNK_SIZE,
counter * CHUNK_SIZE + len(chunk) - 1, size)
if i > 0 and response is not None:
print("Chunk upload failed (error {}): repeating {}"
.format(response.status_code, content_range))
response = requests.post(urlparse.urljoin(self.url, 'upload/'),
auth=self.auth,
data=chunk,
headers={
'Content-Disposition': 'attachment; filename="{}"'.format(base_name),
|
python
|
{
"resource": ""
}
|
q275952
|
Genesis.download
|
test
|
def download(self, data_objects, field):
"""Download files of data objects.
:param data_objects: Data object ids
:type data_objects: list of UUID strings
:param field: Download field name
:type field: string
:rtype: generator of requests.Response objects
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
for o in data_objects:
o = str(o)
if re.match('^[0-9a-fA-F]{24}$', o) is None:
raise ValueError("Invalid object id {}".format(o))
if o not in self.cache['objects']:
self.cache['objects'][o] = GenData(self.api.data(o).get(), self)
|
python
|
{
"resource": ""
}
|
q275953
|
get_subclasses
|
test
|
def get_subclasses(c):
"""Gets the subclasses of a class."""
subclasses =
|
python
|
{
"resource": ""
}
|
q275954
|
Action.get_repo_and_project
|
test
|
def get_repo_and_project(self):
"""Returns repository and project."""
app = self.app
# Get repo
repo = app.data.apply('github-repo', app.args.github_repo,
app.prompt_repo,
on_load=app.github.get_repo,
on_save=lambda r: r.id
)
assert repo, "repository not found."
# Get project
project = app.data.apply('asana-project', app.args.asana_project,
app.prompt_project,
on_load=app.asana.projects.find_by_id,
on_save=lambda p: p['id']
)
assert project, "project not found."
|
python
|
{
"resource": ""
}
|
q275955
|
get_variant_phenotypes_with_suggested_changes
|
test
|
def get_variant_phenotypes_with_suggested_changes(variant_id_list):
'''for each variant, yields evidence and associated phenotypes, both current and suggested'''
variants = civic.get_variants_by_ids(variant_id_list)
evidence = list()
for variant in variants:
evidence.extend(variant.evidence)
for e in evidence:
suggested_changes_url = f'https://civicdb.org/api/evidence_items/{e.id}/suggested_changes'
resp = requests.get(suggested_changes_url)
resp.raise_for_status()
suggested_changes = dict()
for suggested_change in resp.json():
pheno_changes = suggested_change['suggested_changes'].get('phenotype_ids', None)
if pheno_changes
|
python
|
{
"resource": ""
}
|
q275956
|
get_variant_phenotypes_with_suggested_changes_merged
|
test
|
def get_variant_phenotypes_with_suggested_changes_merged(variant_id_list):
'''for each variant, yields evidence and merged phenotype from applying suggested changes to current'''
for evidence, phenotype_status in get_variant_phenotypes_with_suggested_changes(variant_id_list):
final = phenotype_status['current']
for rid in sorted(phenotype_status['suggested_changes']):
changes
|
python
|
{
"resource": ""
}
|
q275957
|
search_variants_by_coordinates
|
test
|
def search_variants_by_coordinates(coordinate_query, search_mode='any'):
"""
Search the cache for variants matching provided coordinates using the corresponding search mode.
:param coordinate_query: A civic CoordinateQuery object
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:return: Returns a list of variant hashes matching the coordinates and search_mode
"""
get_all_variants()
ct = COORDINATE_TABLE
start_idx = COORDINATE_TABLE_START
stop_idx = COORDINATE_TABLE_STOP
chr_idx = COORDINATE_TABLE_CHR
start = int(coordinate_query.start)
stop = int(coordinate_query.stop)
chromosome = str(coordinate_query.chr)
# overlapping = (start <= ct.stop) & (stop >= ct.start)
left_idx = chr_idx.searchsorted(chromosome)
right_idx = chr_idx.searchsorted(chromosome, side='right')
chr_ct_idx = chr_idx[left_idx:right_idx].index
right_idx = start_idx.searchsorted(stop, side='right')
start_ct_idx = start_idx[:right_idx].index
|
python
|
{
"resource": ""
}
|
q275958
|
bulk_search_variants_by_coordinates
|
test
|
def bulk_search_variants_by_coordinates(sorted_queries, search_mode='any'):
"""
An interator to search the cache for variants matching the set of sorted coordinates and yield
matches corresponding to the search mode.
:param sorted_queries: A list of civic CoordinateQuery objects, sorted by coordinate.
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:yield: Yields (query, match) tuples for each identified match
"""
def is_sorted(prev_q, current_q):
if prev_q['chr'] < current_q['chr']:
return True
if prev_q['chr'] > current_q['chr']:
return False
if prev_q['start'] < current_q['start']:
return True
if prev_q['start'] > current_q['start']:
return False
if prev_q['stop'] < current_q['stop']:
return True
if prev_q['stop'] > current_q['stop']:
return False
return True
ct_pointer = 0
query_pointer = 0
last_query_pointer = -1
match_start = None
ct = MODULE.COORDINATE_TABLE
matches = defaultdict(list)
Match = namedtuple('Match', ct.columns)
while query_pointer < len(sorted_queries) and ct_pointer < len(ct):
if last_query_pointer != query_pointer:
q = sorted_queries[query_pointer]
if match_start is not None:
ct_pointer = match_start
|
python
|
{
"resource": ""
}
|
q275959
|
CivicRecord.update
|
test
|
def update(self, allow_partial=True, force=False, **kwargs):
"""Updates record and returns True if record is complete after update, else False."""
if kwargs:
self.__init__(partial=allow_partial, force=force, **kwargs)
return not self._partial
if not force and CACHE.get(hash(self)):
cached = CACHE[hash(self)]
for field in self._SIMPLE_FIELDS | self._COMPLEX_FIELDS:
v = getattr(cached, field)
setattr(self, field, v)
|
python
|
{
"resource": ""
}
|
q275960
|
ToolApp.uniqify
|
test
|
def uniqify(cls, seq):
"""Returns a unique list of seq"""
seen = set()
seen_add = seen.add
|
python
|
{
"resource": ""
}
|
q275961
|
ToolApp.authenticate
|
test
|
def authenticate(self):
"""Connects to Github and Asana and authenticates via OAuth."""
if self.oauth:
return False
# Save asana.
self.settings.apply('api-asana', self.args.asana_api,
"enter asana api key")
# Save github.com
self.settings.apply('api-github', self.args.github_api,
"enter github.com token")
logging.debug("authenticating asana api.")
|
python
|
{
"resource": ""
}
|
q275962
|
ToolApp._list_select
|
test
|
def _list_select(cls, lst, prompt, offset=0):
"""Given a list of values and names, accepts the index value or name."""
inp = raw_input("select %s: " % prompt)
assert inp, "value required."
try:
|
python
|
{
"resource": ""
}
|
q275963
|
ToolApp.get_saved_issue_data
|
test
|
def get_saved_issue_data(self, issue, namespace='open'):
"""Returns issue data from local data.
Args:
issue:
`int`. Github issue number.
namespace:
`str`. Namespace for storing this issue.
"""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
|
python
|
{
"resource": ""
}
|
q275964
|
ToolApp.move_saved_issue_data
|
test
|
def move_saved_issue_data(self, issue, ns, other_ns):
"""Moves an issue_data from one namespace to another."""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
issue_data_key = self._issue_data_key(ns)
other_issue_data_key = self._issue_data_key(other_ns)
issue_data = self.data.get(issue_data_key,
|
python
|
{
"resource": ""
}
|
q275965
|
ToolApp.get_saved_task_data
|
test
|
def get_saved_task_data(self, task):
"""Returns task data from local data.
Args:
task:
`int`. Asana task number.
"""
if isinstance(task, int):
task_number = str(task)
elif isinstance(task, basestring):
task_number = task
else:
|
python
|
{
"resource": ""
}
|
q275966
|
ToolApp.get_asana_task
|
test
|
def get_asana_task(self, asana_task_id):
"""Retrieves a task from asana."""
try:
return self.asana.tasks.find_by_id(asana_task_id)
except
|
python
|
{
"resource": ""
}
|
q275967
|
JSONData.save
|
test
|
def save(self):
"""Save data."""
with open(self.filename, 'wb') as file:
self.prune()
self.data['version'] = self.version
|
python
|
{
"resource": ""
}
|
q275968
|
JSONData.apply
|
test
|
def apply(self, key, value, prompt=None,
on_load=lambda a: a, on_save=lambda a: a):
"""Applies a setting value to a key, if the value is not `None`.
Returns without prompting if either of the following:
* `value` is not `None`
* already present in the dictionary
Args:
prompt:
May either be a string to prompt via `raw_input` or a
method (callable) that returns the value.
on_load:
lambda. Value is passed through here after loaded.
on_save:
lambda. Value is saved as this value.
"""
# Reset value if flag exists without value
if value == '':
value = None
if key and self.data.has_key(key): del self.data[key]
# If value is explicitly set from args.
if value is not None:
value = on_load(value)
|
python
|
{
"resource": ""
}
|
q275969
|
transport_task
|
test
|
def transport_task(func):
"""Decorator for retrying tasks with special cases."""
def wrapped_func(*args, **kwargs):
tries = 0
while True:
try:
try:
return func(*args, **kwargs)
except (asana_errors.InvalidRequestError,
asana_errors.NotFoundError), exc:
logging.warn("warning: invalid request: %r", exc)
except asana_errors.ForbiddenError, exc:
logging.warn("forbidden error: %r", exc)
except asana_errors.NotFoundError, exc:
|
python
|
{
"resource": ""
}
|
q275970
|
flush
|
test
|
def flush(callback=None):
"""Waits until queue is empty."""
while True:
if shutdown_event.is_set():
return
if callable(callback):
callback()
try:
|
python
|
{
"resource": ""
}
|
q275971
|
task_create
|
test
|
def task_create(asana_workspace_id, name, notes, assignee, projects,
completed, **kwargs):
"""Creates a task"""
put("task_create",
asana_workspace_id=asana_workspace_id,
name=name,
|
python
|
{
"resource": ""
}
|
q275972
|
format_task_numbers_with_links
|
test
|
def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
|
python
|
{
"resource": ""
}
|
q275973
|
TransportWorker.create_missing_task
|
test
|
def create_missing_task(self,
asana_workspace_id,
name,
assignee,
projects,
completed,
issue_number,
issue_html_url,
issue_state,
issue_body,
tasks,
labels,
label_tag_map):
"""Creates a missing task."""
task = self.asana.tasks.create_in_workspace(
asana_workspace_id,
{
'name': name,
|
python
|
{
"resource": ""
}
|
q275974
|
GenProject.data_types
|
test
|
def data_types(self):
"""Return a list of data types."""
data =
|
python
|
{
"resource": ""
}
|
q275975
|
ekm_log
|
test
|
def ekm_log(logstr, priority=3):
""" Send string to module level log
Args:
logstr (str): string to print.
priority (int): priority, supports 3 (default) and 4 (special).
"""
if priority <= ekmmeters_log_level:
dt = datetime.datetime
stamp
|
python
|
{
"resource": ""
}
|
q275976
|
SerialPort.initPort
|
test
|
def initPort(self):
""" Required initialization call, wraps pyserial constructor. """
try:
self.m_ser = serial.Serial(port=self.m_ttyport,
baudrate=self.m_baudrate,
timeout=0,
parity=serial.PARITY_EVEN,
|
python
|
{
"resource": ""
}
|
q275977
|
SerialPort.setPollingValues
|
test
|
def setPollingValues(self, max_waits, wait_sleep):
""" Optional polling loop control
Args:
max_waits (int): waits
wait_sleep (int): ms per wait
|
python
|
{
"resource": ""
}
|
q275978
|
MeterDB.combineAB
|
test
|
def combineAB(self):
""" Use the serial block definitions in V3 and V4 to create one field list. """
v4definition_meter = V4Meter()
v4definition_meter.makeAB()
defv4 = v4definition_meter.getReadBuffer()
v3definition_meter = V3Meter()
v3definition_meter.makeReturnFormat()
defv3 = v3definition_meter.getReadBuffer()
for fld in defv3:
if fld not in self.m_all_fields:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC"
|
python
|
{
"resource": ""
}
|
q275979
|
SqliteMeterDB.renderJsonReadsSince
|
test
|
def renderJsonReadsSince(self, timestamp, meter):
""" Simple since Time_Stamp query returned as JSON records.
Args:
timestamp (int): Epoch time in seconds.
meter (str): 12 character meter address to query
Returns:
str: JSON rendered read records.
"""
result = ""
try:
connection = sqlite3.connect(self.m_connection_string)
connection.row_factory = self.dict_factory
select_cursor = connection.cursor()
select_cursor.execute("select * from Meter_Reads where " + Field.Time_Stamp +
|
python
|
{
"resource": ""
}
|
q275980
|
Meter.setContext
|
test
|
def setContext(self, context_str):
""" Set context string for serial command. Private setter.
Args:
context_str (str): Command specific string.
"""
if (len(self.m_context) == 0) and (len(context_str) >= 7):
|
python
|
{
"resource": ""
}
|
q275981
|
Meter.calcPF
|
test
|
def calcPF(pf):
""" Simple wrap to calc legacy PF value
Args:
pf: meter power factor reading
Returns:
int: legacy push pf
"""
pf_y = pf[:1]
pf_x = pf[1:]
|
python
|
{
"resource": ""
}
|
q275982
|
Meter.setMaxDemandPeriod
|
test
|
def setMaxDemandPeriod(self, period, password="00000000"):
""" Serial call to set max demand period.
Args:
period (int): : as int.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMaxDemandPeriod")
try:
if period < 1 or period > 3:
self.writeCmdMsg("Correct parameter: 1 = 15 minute, 2 = 30 minute, 3 = hour")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_str = "015731023030353028" + binascii.hexlify(str(period)).zfill(2) + "2903"
req_str
|
python
|
{
"resource": ""
}
|
q275983
|
Meter.setMeterPassword
|
test
|
def setMeterPassword(self, new_pwd, pwd="00000000"):
""" Serial Call to set meter password. USE WITH CAUTION.
Args:
new_pwd (str): 8 digit numeric password to set
pwd (str): Old 8 digit numeric password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMeterPassword")
try:
if len(new_pwd) != 8 or len(pwd) != 8:
self.writeCmdMsg("Passwords must be exactly eight characters.")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Pre command read failed: check serial line.")
else:
if not self.serialCmdPwdAuth(pwd):
self.writeCmdMsg("Password failure")
else:
req_pwd = binascii.hexlify(new_pwd.zfill(8))
req_str =
|
python
|
{
"resource": ""
}
|
q275984
|
Meter.unpackStruct
|
test
|
def unpackStruct(self, data, def_buf):
""" Wrapper for struct.unpack with SerialBlock buffer definitionns.
Args:
data (str): Implicit cast bytes to str, serial port return.
def_buf (SerialBlock): Block object holding field lengths.
Returns:
tuple: parsed result of struct.unpack() with field
|
python
|
{
"resource": ""
}
|
q275985
|
Meter.convertData
|
test
|
def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):
""" Move data from raw tuple into scaled and conveted values.
Args:
contents (tuple): Breakout of passed block from unpackStruct().
def_buf (): Read buffer destination.
kwh_scale (int): :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`
Returns:
bool: True on completion.
"""
log_str = ""
count = 0
# getting scale does not require a full read. It does require that the
# reads have the scale value in the first block read. This requirement
# is filled by default in V3 and V4 requests
if kwh_scale == ScaleKWH.EmptyScale:
scale_offset = int(def_buf.keys().index(Field.kWh_Scale))
self.m_kwh_precision = kwh_scale = int(contents[scale_offset])
for fld in def_buf:
if def_buf[fld][MeterData.CalculatedFlag]:
count += 1
continue
if len(contents) == 0:
count += 1
continue
try: # scrub up messes on a field by field basis
raw_data = contents[count]
fld_type = def_buf[fld][MeterData.TypeValue]
fld_scale = def_buf[fld][MeterData.ScaleValue]
if fld_type == FieldType.Float:
float_data = float(str(raw_data))
divisor = 1
if fld_scale == ScaleType.KWH:
divisor = 1
if kwh_scale == ScaleKWH.Scale10:
divisor =
|
python
|
{
"resource": ""
}
|
q275986
|
Meter.jsonRender
|
test
|
def jsonRender(self, def_buf):
""" Translate the passed serial block into string only JSON.
Args:
def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object.
Returns:
str: JSON rendering of meter record.
"""
try:
ret_dict = SerialBlock()
ret_dict[Field.Meter_Address] = self.getMeterAddress()
for fld in def_buf:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld
|
python
|
{
"resource": ""
}
|
q275987
|
Meter.crcMeterRead
|
test
|
def crcMeterRead(self, raw_read, def_buf):
""" Internal read CRC wrapper.
Args:
raw_read (str): Bytes with implicit string cast from serial read
def_buf (SerialBlock): Populated read buffer.
Returns:
bool: True if passed CRC equals calculated CRC.
"""
try:
if len(raw_read) == 0:
ekm_log("(" + self.m_context + ") Empty return read.")
return False
sent_crc = self.calc_crc16(raw_read[1:-2])
logstr = "(" + self.m_context + ")CRC sent = " + str(def_buf["crc16"][MeterData.StringValue])
logstr += " CRC calc = " + sent_crc
ekm_log(logstr)
if int(def_buf["crc16"][MeterData.StringValue], 16) == int(sent_crc, 16):
return True
# A cross simple test lines on a USB serial adapter, these occur every
# 1000 to 2000 reads, and they show up here as a bad unpack or
# a bad crc type call. In either case, we suppress them a log will
# become quite large. ekmcrc errors come through as type errors.
# Failures of int type conversion in 16 bit conversion occur as value
# errors.
except struct.error:
ekm_log(str(sys.exc_info()))
|
python
|
{
"resource": ""
}
|
q275988
|
Meter.splitEkmDate
|
test
|
def splitEkmDate(dateint):
"""Break out a date from Omnimeter read.
Note a corrupt date will raise an exception when you
convert it to int to hand to this method.
Args:
dateint (int): Omnimeter datetime as int.
Returns:
tuple: Named tuple which breaks out as followws:
========== =====================
yy Last 2 digits of year
mm Month 1-12
dd Day 1-31
weekday Zero based weekday
hh Hour 0-23
minutes Minutes 0-59
ss Seconds 0-59
========== =====================
"""
date_str = str(dateint)
dt = namedtuple('EkmDate', ['yy', 'mm', 'dd', 'weekday', 'hh', 'minutes', 'ss'])
if
|
python
|
{
"resource": ""
}
|
q275989
|
Meter.getMonthsBuffer
|
test
|
def getMonthsBuffer(self, direction):
""" Get the months tariff SerialBlock for meter.
Args:
direction (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
SerialBlock: Requested months tariffs buffer.
|
python
|
{
"resource": ""
}
|
q275990
|
Meter.setCTRatio
|
test
|
def setCTRatio(self, new_ct, password="00000000"):
""" Serial call to set CT ratio for attached inductive pickup.
Args:
new_ct (int): A :class:`~ekmmeters.CTRatio` value, a legal amperage setting.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
ret = False
self.setContext("setCTRatio")
try:
self.clearCmdMsg()
if ((new_ct != CTRatio.Amps_100) and (new_ct != CTRatio.Amps_200) and
(new_ct != CTRatio.Amps_400) and (new_ct != CTRatio.Amps_600) and
(new_ct != CTRatio.Amps_800) and (new_ct != CTRatio.Amps_1000) and
(new_ct != CTRatio.Amps_1200) and (new_ct != CTRatio.Amps_1500) and
(new_ct != CTRatio.Amps_2000) and (new_ct != CTRatio.Amps_3000) and
|
python
|
{
"resource": ""
}
|
q275991
|
Meter.assignSchedule
|
test
|
def assignSchedule(self, schedule, period, hour, minute, tariff):
""" Assign one schedule tariff period to meter bufffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
hour (int): Hour from 0-23.
minute (int): Minute from 0-59.
tariff (int): Rate value.
Returns:
bool: True on completed assignment.
"""
if ((schedule not in range(Extents.Schedules)) or
(period not in range(Extents.Tariffs)) or
(hour < 0) or (hour > 23) or (minute < 0) or
(minute > 59) or (tariff < 0)):
ekm_log("Out of bounds in Schedule_" + str(schedule + 1))
return False
period += 1
idx_min = "Min_" + str(period)
idx_hour = "Hour_" + str(period)
idx_rate = "Tariff_" + str(period)
|
python
|
{
"resource": ""
}
|
q275992
|
Meter.assignSeasonSchedule
|
test
|
def assignSeasonSchedule(self, season, month, day, schedule):
""" Define a single season and assign a schedule
Args:
season (int): A :class:`~ekmmeters.Seasons` value or in range(Extent.Seasons).
month (int): Month 1-12.
day (int): Day 1-31.
schedule (int): A :class:`~ekmmeters.LCDItems` value or in range(Extent.Schedules).
Returns:
bool: True on completion and ACK.
"""
season += 1
schedule += 1
if ((season < 1) or (season > Extents.Seasons) or (schedule < 1) or
(schedule > Extents.Schedules) or (month > 12) or (month < 0) or
(day < 0) or (day > 31)):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) +
" schedule " + str(schedule) + " season " + str(season))
return False
idx_mon = "Season_" + str(season) + "_Start_Day"
idx_day = "Season_" + str(season) + "_Start_Month"
idx_schedule = "Season_" + str(season) + "_Schedule"
|
python
|
{
"resource": ""
}
|
q275993
|
Meter.setSeasonSchedules
|
test
|
def setSeasonSchedules(self, cmd_dict=None, password="00000000"):
""" Serial command to set seasons table.
If no dictionary is passed, the meter object buffer is used.
Args:
cmd_dict (dict): Optional dictionary of season schedules.
password (str): Optional password
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setSeasonSchedules")
if not cmd_dict:
cmd_dict = self.m_seasons_sched_params
try:
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_table = ""
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Schedule"]).zfill(2))
|
python
|
{
"resource": ""
}
|
q275994
|
Meter.assignHolidayDate
|
test
|
def assignHolidayDate(self, holiday, month, day):
""" Set a singe holiday day and month in object buffer.
There is no class style enum for holidays.
Args:
holiday (int): 0-19 or range(Extents.Holidays).
month (int): Month 1-12.
day (int): Day 1-31
Returns:
bool: True on completion.
"""
holiday += 1
if (month > 12) or (month < 0) or (day > 31) or (day < 0) or (holiday < 1) or (holiday > Extents.Holidays):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) + " holiday " + str(holiday))
return False
day_str = "Holiday_" + str(holiday) + "_Day"
|
python
|
{
"resource": ""
}
|
q275995
|
Meter.readSchedules
|
test
|
def readSchedules(self, tableset):
""" Serial call to read schedule tariffs buffer
Args:
tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.
Returns:
bool: True on completion and ACK.
"""
self.setContext("readSchedules")
try:
req_table = binascii.hexlify(str(tableset).zfill(1))
req_str = "01523102303037" + req_table + "282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
return_crc = self.calc_crc16(raw_ret[1:-2])
if tableset == ReadSchedules.Schedules_1_To_4:
unpacked_read = self.unpackStruct(raw_ret, self.m_schd_1_to_4)
self.convertData(unpacked_read, self.m_schd_1_to_4, self.m_kwh_precision)
if str(return_crc) == str(self.m_schd_1_to_4["crc16"][MeterData.StringValue]):
ekm_log("Schedules 1 to 4 CRC success (06 return")
self.setContext("")
|
python
|
{
"resource": ""
}
|
q275996
|
Meter.extractSchedule
|
test
|
def extractSchedule(self, schedule, period):
""" Read a single schedule tariff from meter object buffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extent.Schedules).
tariff (int): A :class:`~ekmmeters.Tariffs` value or in range(Extent.Tariffs).
Returns:
bool: True on completion.
"""
ret = namedtuple("ret", ["Hour", "Min", "Tariff", "Period", "Schedule"])
work_table = self.m_schd_1_to_4
if Schedules.Schedule_5 <= schedule <= Schedules.Schedule_6:
work_table = self.m_schd_5_to_6
period += 1
schedule += 1
ret.Period = str(period)
ret.Schedule = str(schedule)
if (schedule < 1) or (schedule > Extents.Schedules) or (period < 0) or (period > Extents.Periods):
ekm_log("Out of bounds: tariff " + str(period) + " for schedule " + str(schedule))
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
idxhr = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Hour"
idxmin = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Min"
idxrate = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Tariff"
if idxhr not in work_table:
|
python
|
{
"resource": ""
}
|
q275997
|
Meter.readMonthTariffs
|
test
|
def readMonthTariffs(self, months_type):
""" Serial call to read month tariffs block into meter object buffer.
Args:
months_type (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
bool: True on completion.
"""
self.setContext("readMonthTariffs")
try:
req_type = binascii.hexlify(str(months_type).zfill(1))
req_str = "01523102303031" + req_type + "282903"
work_table = self.m_mons
if months_type == ReadMonths.kWhReverse:
work_table = self.m_rev_mons
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret =
|
python
|
{
"resource": ""
}
|
q275998
|
Meter.extractMonthTariff
|
test
|
def extractMonthTariff(self, month):
""" Extract the tariff for a single month from the meter object buffer.
Args:
month (int): A :class:`~ekmmeters.Months` value or range(Extents.Months).
Returns:
tuple: The eight tariff period totals for month. The return tuple breaks out as follows:
================= ======================================
kWh_Tariff_1 kWh for tariff period 1 over month.
kWh_Tariff_2 kWh for tariff period 2 over month
kWh_Tariff_3 kWh for tariff period 3 over month
kWh_Tariff_4 kWh for tariff period 4 over month
kWh_Tot Total kWh over requested month
Rev_kWh_Tariff_1 Rev kWh for tariff period 1 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 2 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 3 over month
Rev_kWh_Tariff_4 Rev kWh for tariff period 4 over month
Rev_kWh_Tot Total Rev kWh over requested month
================= ======================================
"""
ret = namedtuple("ret", ["Month", Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3,
Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1,
Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3,
Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])
month += 1
ret.Month = str(month)
if (month < 1) or (month > Extents.Months):
|
python
|
{
"resource": ""
}
|
q275999
|
Meter.readHolidayDates
|
test
|
def readHolidayDates(self):
""" Serial call to read holiday dates into meter object buffer.
Returns:
bool: True on completion.
"""
self.setContext("readHolidayDates")
try:
req_str = "0152310230304230282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
unpacked_read = self.unpackStruct(raw_ret, self.m_hldy)
self.convertData(unpacked_read, self.m_hldy, self.m_kwh_precision)
return_crc =
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.