repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
modlinltd/django-advanced-filters | advanced_filters/admin.py | AdminAdvancedFiltersMixin.changelist_view | python | def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(Admin... | Add advanced_filters form to changelist context | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/admin.py#L93-L102 | [
"def adv_filters_handle(self, request, extra_context={}):\n data = request.POST if request.POST.get(\n 'action') == 'advanced_filters' else None\n adv_filters_form = self.advanced_filter_form(\n data=data, model_admin=self, extra_form=True)\n extra_context.update({\n 'original_change_l... | class AdminAdvancedFiltersMixin(object):
""" Generic AdvancedFilters mixin """
advanced_change_list_template = "admin/advanced_filters.html"
advanced_filter_form = AdvancedFilterForm
def __init__(self, *args, **kwargs):
super(AdminAdvancedFiltersMixin, self).__init__(*args, **kwargs)
if... |
modlinltd/django-advanced-filters | advanced_filters/models.py | UserLookupManager.filter_by_user | python | def filter_by_user(self, user):
return self.filter(Q(users=user) | Q(groups__in=user.groups.all())) | All filters that should be displayed to a user (by users/group) | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L10-L13 | null | class UserLookupManager(models.Manager):
|
modlinltd/django-advanced-filters | advanced_filters/models.py | AdvancedFilter.query | python | def query(self):
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query) | De-serialize, decode and return an ORM query stored in b64_query. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L39-L46 | [
"def dumps(self, obj):\n if not isinstance(obj, Q):\n raise SerializationError\n string = json.dumps(self.serialize(obj), default=dt2ts)\n if self.b64_enabled:\n return base64.b64encode(six.b(string)).decode(\"utf-8\")\n return string\n",
"def loads(self, string, raw=False):\n if self... | class AdvancedFilter(models.Model):
class Meta:
verbose_name = _('Advanced Filter')
verbose_name_plural = _('Advanced Filters')
title = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('Title'))
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
... |
modlinltd/django-advanced-filters | advanced_filters/models.py | AdvancedFilter.query | python | def query(self, value):
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value) | Serialize an ORM query, Base-64 encode it and set it to
the b64_query field | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/models.py#L49-L57 | [
"def dumps(self, obj):\n if not isinstance(obj, Q):\n raise SerializationError\n string = json.dumps(self.serialize(obj), default=dt2ts)\n if self.b64_enabled:\n return base64.b64encode(six.b(string)).decode(\"utf-8\")\n return string\n",
"def loads(self, string, raw=False):\n if self... | class AdvancedFilter(models.Model):
class Meta:
verbose_name = _('Advanced Filter')
verbose_name_plural = _('Advanced Filters')
title = models.CharField(max_length=255, null=False, blank=False, verbose_name=_('Title'))
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
... |
modlinltd/django-advanced-filters | advanced_filters/q_serializer.py | QSerializer.serialize | python | def serialize(self, q):
children = []
for child in q.children:
if isinstance(child, Q):
children.append(self.serialize(child))
else:
children.append(child)
serialized = q.__dict__
serialized['children'] = children
return ser... | Serialize a Q object into a (possibly nested) dict. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/q_serializer.py#L55-L67 | [
"def serialize(self, q):\n \"\"\"\n Serialize a Q object into a (possibly nested) dict.\n \"\"\"\n children = []\n for child in q.children:\n if isinstance(child, Q):\n children.append(self.serialize(child))\n else:\n children.append(child)\n serialized = q.__di... | class QSerializer(object):
"""
A Q object serializer base class. Pass base64=True when initializing
to Base-64 encode/decode the returned/passed string.
By default the class provides loads/dumps methods that wrap around
json serialization, but they may be easily overwritten to serialize
into ot... |
modlinltd/django-advanced-filters | advanced_filters/q_serializer.py | QSerializer.deserialize | python | def deserialize(self, d):
children = []
for child in d.pop('children'):
if isinstance(child, dict):
children.append(self.deserialize(child))
else:
children.append(self.prepare_value(child))
query = Q()
query.children = children
... | De-serialize a Q object from a (possibly nested) dict. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/q_serializer.py#L69-L85 | [
"def prepare_value(self, qtuple):\n if self._is_range(qtuple):\n qtuple[1][0] = qtuple[1][0] or min_ts\n qtuple[1][1] = qtuple[1][1] or max_ts\n qtuple[1] = (datetime.fromtimestamp(qtuple[1][0]),\n datetime.fromtimestamp(qtuple[1][1]))\n return qtuple\n",
"def deseri... | class QSerializer(object):
"""
A Q object serializer base class. Pass base64=True when initializing
to Base-64 encode/decode the returned/passed string.
By default the class provides loads/dumps methods that wrap around
json serialization, but they may be easily overwritten to serialize
into ot... |
modlinltd/django-advanced-filters | advanced_filters/q_serializer.py | QSerializer.get_field_values_list | python | def get_field_values_list(self, d):
fields = []
children = d.get('children', [])
for child in children:
if isinstance(child, dict):
fields.extend(self.get_field_values_list(child))
else:
f = {'field': child[0], 'value': child[1]}
... | Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',
'value_to': 'optional_range_val2',
... | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/q_serializer.py#L87-L117 | [
"def _is_range(qtuple):\n return qtuple[0].endswith(\"__range\") and len(qtuple[1]) == 2\n",
"def get_field_values_list(self, d):\n \"\"\"\n Iterate over a (possibly nested) dict, and return a list\n of all children queries, as a dict of the following structure:\n {\n 'field': 'some_field__i... | class QSerializer(object):
"""
A Q object serializer base class. Pass base64=True when initializing
to Base-64 encode/decode the returned/passed string.
By default the class provides loads/dumps methods that wrap around
json serialization, but they may be easily overwritten to serialize
into ot... |
modlinltd/django-advanced-filters | advanced_filters/form_helpers.py | VaryingTypeCharField.to_python | python | def to_python(self, value):
res = super(VaryingTypeCharField, self).to_python(value)
split_res = res.split(self._default_separator)
if not res or len(split_res) < 2:
return res.strip()
# create a regex string out of the list of choices passed, i.e: (a|b)
res = r"({pa... | Split a string value by separator (default to ",") into a
list; then, returns a regex pattern string that ORs the values
in the resulting list.
>>> field = VaryingTypeCharField()
>>> assert field.to_python('') == ''
>>> assert field.to_python('test') == 'test'
>>> assert... | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/form_helpers.py#L20-L40 | null | class VaryingTypeCharField(forms.CharField):
"""
This CharField subclass returns a regex OR patterns from a
comma separated list value.
"""
_default_separator = ","
|
modlinltd/django-advanced-filters | advanced_filters/form_helpers.py | CleanWhiteSpacesMixin.clean | python | def clean(self):
cleaned_data = super(CleanWhiteSpacesMixin, self).clean()
for k in self.cleaned_data:
if isinstance(self.cleaned_data[k], six.string_types):
cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
self.cleaned_data[k] or '... | >>> import django.forms
>>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
... some_field = django.forms.CharField()
>>>
>>> form = MyForm({'some_field': ' a weird value '})
>>> assert form.is_valid()
>>> assert form.cleaned_data == {'some_field': 'a weird... | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/form_helpers.py#L48-L63 | null | class CleanWhiteSpacesMixin(object):
"""
This mixin, when added to any form subclass, adds a clean method which
strips repeating spaces in and around each string value of "clean_data".
"""
|
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm._build_field_choices | python | def _build_field_choices(self, fields):
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES | Iterate over passed model fields tuple and update initial choices. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L77-L84 | null | class AdvancedFilterQueryForm(CleanWhiteSpacesMixin, forms.Form):
""" Build the query from field, operator and value """
OPERATORS = (
("iexact", _("Equals")),
("icontains", _("Contains")),
("iregex", _("One of")),
("range", _("DateTime Range")),
("isnull", _("Is NULL")),... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm._build_query_dict | python | def _build_query_dict(self, formdata=None):
if self.is_valid() and formdata is None:
formdata = self.cleaned_data
key = "{field}__{operator}".format(**formdata)
if formdata['operator'] == "isnull":
return {key: None}
elif formdata['operator'] == "istrue":
... | Take submitted data from form and create a query dict to be
used in a Q object (or filter) | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L86-L100 | null | class AdvancedFilterQueryForm(CleanWhiteSpacesMixin, forms.Form):
""" Build the query from field, operator and value """
OPERATORS = (
("iexact", _("Equals")),
("icontains", _("Contains")),
("iregex", _("One of")),
("range", _("DateTime Range")),
("isnull", _("Is NULL")),... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm._parse_query_dict | python | def _parse_query_dict(query_data, model):
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if... | Take a list of query field dict and return data for form initialization | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L103-L149 | null | class AdvancedFilterQueryForm(CleanWhiteSpacesMixin, forms.Form):
""" Build the query from field, operator and value """
OPERATORS = (
("iexact", _("Equals")),
("icontains", _("Contains")),
("iregex", _("One of")),
("range", _("DateTime Range")),
("isnull", _("Is NULL")),... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm.set_range_value | python | def set_range_value(self, data):
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto) | Validates date range by parsing into 2 datetime objects and
validating them both. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L151-L161 | null | class AdvancedFilterQueryForm(CleanWhiteSpacesMixin, forms.Form):
""" Build the query from field, operator and value """
OPERATORS = (
("iexact", _("Equals")),
("icontains", _("Contains")),
("iregex", _("One of")),
("range", _("DateTime Range")),
("isnull", _("Is NULL")),... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterQueryForm.make_query | python | def make_query(self, *args, **kwargs):
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**quer... | Returns a Q object from the submitted form | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L171-L179 | [
"def _build_query_dict(self, formdata=None):\n \"\"\"\n Take submitted data from form and create a query dict to be\n used in a Q object (or filter)\n \"\"\"\n if self.is_valid() and formdata is None:\n formdata = self.cleaned_data\n key = \"{field}__{operator}\".format(**formdata)\n if ... | class AdvancedFilterQueryForm(CleanWhiteSpacesMixin, forms.Form):
""" Build the query from field, operator and value """
OPERATORS = (
("iexact", _("Equals")),
("icontains", _("Contains")),
("iregex", _("One of")),
("range", _("DateTime Range")),
("isnull", _("Is NULL")),... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterForm.get_fields_from_model | python | def get_fields_from_model(self, model, fields):
model_fields = {}
for field in fields:
if isinstance(field, tuple) and len(field) == 2:
field, verbose_name = field[0], field[1]
else:
try:
model_field = get_fi... | Iterate over given <field> names (in "orm query" notation) and find
the actual field given the initial <model>.
If <field> is a tuple of the format ('field_name', 'Verbose name'),
overwrite the field's verbose name with the given name for display
purposes. | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L245-L267 | null | class AdvancedFilterForm(CleanWhiteSpacesMixin, forms.ModelForm):
""" Form to save/edit advanced filter forms """
class Meta:
model = AdvancedFilter
fields = ('title',)
class Media:
required_js = [
'admin/js/%sjquery.min.js' % ('vendor/jquery/' if USE_VENDOR_DIR else '')... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterForm.generate_query | python | def generate_query(self):
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
... | Reduces multiple queries into a single usable query | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L322-L338 | null | class AdvancedFilterForm(CleanWhiteSpacesMixin, forms.ModelForm):
""" Form to save/edit advanced filter forms """
class Meta:
model = AdvancedFilter
fields = ('title',)
class Media:
required_js = [
'admin/js/%sjquery.min.js' % ('vendor/jquery/' if USE_VENDOR_DIR else '')... |
modlinltd/django-advanced-filters | advanced_filters/forms.py | AdvancedFilterForm.initialize_form | python | def initialize_form(self, instance, model, data=None, extra=None):
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse... | Takes a "finalized" query and generate it's form data | train | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/forms.py#L340-L356 | [
"def _parse_query_dict(query_data, model):\n \"\"\"\n Take a list of query field dict and return data for form initialization\n \"\"\"\n operator = 'iexact'\n if query_data['field'] == '_OR':\n query_data['operator'] = operator\n return query_data\n\n parts = query_data['field'].spli... | class AdvancedFilterForm(CleanWhiteSpacesMixin, forms.ModelForm):
""" Form to save/edit advanced filter forms """
class Meta:
model = AdvancedFilter
fields = ('title',)
class Media:
required_js = [
'admin/js/%sjquery.min.js' % ('vendor/jquery/' if USE_VENDOR_DIR else '')... |
jrspruitt/ubi_reader | ubireader/ubi_io.py | ubi_file.read_block | python | def read_block(self, block):
self.seek(block.file_offset)
return self._fhandle.read(block.size) | Read complete PEB data from file.
Argument:
Obj:block -- Block data is desired for. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi_io.py#L149-L156 | [
"def seek(self, offset):\n self._fhandle.seek(offset)\n"
] | class ubi_file(object):
"""UBI image file object
Arguments:
Str:path -- Path to file to parse
Int:block_size -- Erase block size of NAND in bytes.
Int:start_offset -- (optional) Where to start looking in the file for
UBI data.
Int:end_offset -- (optional) Whe... |
jrspruitt/ubi_reader | ubireader/ubi_io.py | ubi_file.read_block_data | python | def read_block_data(self, block):
self.seek(block.file_offset + block.ec_hdr.data_offset)
buf = self._fhandle.read(block.size - block.ec_hdr.data_offset - block.vid_hdr.data_pad)
return buf | Read LEB data from file
Argument:
Obj:block -- Block data is desired for. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi_io.py#L159-L167 | [
"def seek(self, offset):\n self._fhandle.seek(offset)\n"
] | class ubi_file(object):
"""UBI image file object
Arguments:
Str:path -- Path to file to parse
Int:block_size -- Erase block size of NAND in bytes.
Int:start_offset -- (optional) Where to start looking in the file for
UBI data.
Int:end_offset -- (optional) Whe... |
jrspruitt/ubi_reader | ubireader/ubi/block/__init__.py | extract_blocks | python | def extract_blocks(ubi):
blocks = {}
ubi.file.seek(ubi.file.start_offset)
peb_count = 0
cur_offset = 0
bad_blocks = []
# range instead of xrange, as xrange breaks > 4GB end_offset.
for i in range(ubi.file.start_offset, ubi.file.end_offset, ubi.file.block_size):
try:
buf... | Get a list of UBI block objects from file
Arguments:.
Obj:ubi -- UBI object.
Returns:
Dict -- Of block objects keyed by PEB number. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/__init__.py#L105-L162 | [
"def error(obj, level, message):\n if settings.error_action is 'exit':\n print('{} {}: {}'.format(obj.__name__, level, message))\n if settings.fatal_traceback:\n traceback.print_exc()\n sys.exit(1)\n\n else:\n if level.lower() == 'warn':\n print('{} {}: {}'.fo... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_image_seq | python | def by_image_seq(blocks, image_seq):
return list(filter(lambda block: blocks[block].ec_hdr.image_seq == image_seq, blocks)) | Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L20-L30 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_leb | python | def by_leb(blocks):
"""Sort blocks by Logical Erase Block number.
Arguments:
List:blocks -- List of block objects to sort.
Returns:
List -- Indexes of blocks sorted by LEB.
"""
slist_len = len(blocks)
slist = ['x'] * slist_len
for block in blocks:
if ... | Sort blocks by Logical Erase Block number.
Arguments:
List:blocks -- List of block objects to sort.
Returns:
List -- Indexes of blocks sorted by LEB. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L32-L52 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_vol_id | python | def by_vol_id(blocks, slist=None):
vol_blocks = {}
# sort block by volume
# not reliable with multiple partitions (fifo)
for i in blocks:
if slist and i not in slist:
continue
elif not blocks[i].is_valid:
continue
if blocks[i].vid_hdr.vol_id not in vol... | Sort blocks by volume id
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Return:
Dict -- blocks grouped in lists with dict key as volume id. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L55-L82 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/sort.py | by_type | python | def by_type(blocks, slist=None):
layout = []
data = []
int_vol = []
unknown = []
for i in blocks:
if slist and i not in slist:
continue
if blocks[i].is_vtbl and blocks[i].is_valid:
layout.append(i)
elif blocks[i].is_internal_vol and blocks[i].i... | Sort blocks into layout, internal volume, data or unknown
Arguments:
Obj:blocks -- List of block objects.
List:slist -- (optional) List of block indexes.
Returns:
List:layout -- List of block indexes of blocks containing the
volume table records.
List:data -- List o... | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/sort.py#L84-L123 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubifs/output.py | extract_files | python | def extract_files(ubifs, out_path, perms=False):
try:
inodes = {}
bad_blocks = []
walk.index(ubifs, ubifs.master_node.root_lnum, ubifs.master_node.root_offs, inodes, bad_blocks)
if len(inodes) < 2:
raise Exception('No inodes found')
for dent in inodes[1]['dent'... | Extract UBIFS contents to_path/
Arguments:
Obj:ubifs -- UBIFS object.
Str:out_path -- Path to extract contents to. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/output.py#L30-L53 | [
"def index(ubifs, lnum, offset, inodes={}, bad_blocks=[]):\n \"\"\"Walk the index gathering Inode, Dir Entry, and File nodes.\n\n Arguments:\n Obj:ubifs -- UBIFS object.\n Int:lnum -- Logical erase block number.\n Int:offset -- Offset in logical erase block.\n Dict:inodes -- Dict of ino/... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubifs
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | get_newest | python | def get_newest(blocks, layout_blocks):
layout_temp = list(layout_blocks)
for i in range(0, len(layout_temp)):
for k in range(0, len(layout_blocks)):
if blocks[layout_temp[i]].ec_hdr.image_seq != blocks[layout_blocks[k]].ec_hdr.image_seq:
continue
if blocks[layou... | Filter out old layout blocks from list
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Newest layout blocks in list | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L23-L47 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | group_pairs | python | def group_pairs(blocks, layout_blocks_list):
image_dict={}
for block_id in layout_blocks_list:
image_seq=blocks[block_id].ec_hdr.image_seq
if image_seq not in image_dict:
image_dict[image_seq]=[block_id]
else:
image_dict[image_seq].append(block_id)
log(group... | Sort a list of layout blocks into pairs
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Layout block pair indexes grouped in a list | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L50-L71 | [
"def log(obj, message):\n if settings.logging_on or settings.logging_on_verbose:\n print('{} {}'.format(obj.__name__, message))\n"
] | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/block/layout.py | associate_blocks | python | def associate_blocks(blocks, layout_pairs, start_peb_num):
seq_blocks = []
for layout_pair in layout_pairs:
seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)
layout_pair.append(seq_blocks)
return layout_pairs | Group block indexes with appropriate layout pairs
Arguments:
List:blocks -- List of block objects
List:layout_pairs -- List of grouped layout blocks
Int:start_peb_num -- Number of the PEB to start from.
Returns:
List -- Layout block pairs grouped with associated block ranges. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/block/layout.py#L74-L91 | [
"def by_image_seq(blocks, image_seq):\n \"\"\"Filter blocks to return only those associated with the provided image_seq number.\n\n Argument:\n List:blocks -- List of block objects to sort.\n Int:image_seq -- image_seq number found in ec_hdr.\n\n Returns:\n List -- List of block in... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubi/volume.py | get_volumes | python | def get_volumes(blocks, layout_info):
volumes = {}
vol_blocks_lists = sort.by_vol_id(blocks, layout_info[2])
for vol_rec in blocks[layout_info[0]].vtbl_recs:
vol_name = vol_rec.name.strip(b'\x00').decode('utf-8')
if vol_rec.rec_index not in vol_blocks_lists:
vol_blocks_lists[vo... | Get a list of UBI volume objects from list of blocks
Arguments:
List:blocks -- List of layout block objects
List:layout_info -- Layout info (indexes of layout blocks and
associated data blocks.)
Returns:
Dict -- Of Volume objects by volume name... | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubi/volume.py#L98-L120 | [
"def by_vol_id(blocks, slist=None):\n \"\"\"Sort blocks by volume id\n\n Arguments:\n Obj:blocks -- List of block objects.\n List:slist -- (optional) List of block indexes.\n\n Return:\n Dict -- blocks grouped in lists with dict key as volume id.\n \"\"\"\n\n vol_blocks = {}\n\n # sor... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubi
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundatio... |
jrspruitt/ubi_reader | ubireader/ubifs/misc.py | parse_key | python | def parse_key(key):
hkey, lkey = struct.unpack('<II',key[0:UBIFS_SK_LEN])
ino_num = hkey & UBIFS_S_KEY_HASH_MASK
key_type = lkey >> UBIFS_S_KEY_BLOCK_BITS
khash = lkey
#if key_type < UBIFS_KEY_TYPES_CNT:
return {'type':key_type, 'ino_num':ino_num, 'khash': khash} | Parse node key
Arguments:
Str:key -- Hex string literal of node key.
Returns:
Int:key_type -- Type of key, data, ino, dent, etc.
Int:ino_num -- Inode number.
Int:khash -- Key hash. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/misc.py#L31-L48 | null | #!/usr/bin/env python
#############################################################
# ubi_reader/ubifs
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
jrspruitt/ubi_reader | ubireader/ubifs/misc.py | decompress | python | def decompress(ctype, unc_len, data):
if ctype == UBIFS_COMPR_LZO:
try:
return lzo.decompress(b''.join((b'\xf0', struct.pack('>I', unc_len), data)))
except Exception as e:
error(decompress, 'Warn', 'LZO Error: %s' % e)
elif ctype == UBIFS_COMPR_ZLIB:
try:
... | Decompress data.
Arguments:
Int:ctype -- Compression type LZO, ZLIB (*currently unused*).
Int:unc_len -- Uncompressed data lenth.
Str:data -- Data to be uncompessed.
Returns:
Uncompressed Data. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/misc.py#L51-L73 | [
"def error(obj, level, message):\n if settings.error_action is 'exit':\n print('{} {}: {}'.format(obj.__name__, level, message))\n if settings.fatal_traceback:\n traceback.print_exc()\n sys.exit(1)\n\n else:\n if level.lower() == 'warn':\n print('{} {}: {}'.fo... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubifs
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
jrspruitt/ubi_reader | ubireader/ubifs/walk.py | index | python | def index(ubifs, lnum, offset, inodes={}, bad_blocks=[]):
try:
if len(bad_blocks):
if lnum in bad_blocks:
return
ubifs.file.seek((ubifs.leb_size * lnum) + offset)
buf = ubifs.file.read(UBIFS_COMMON_HDR_SZ)
chdr = nodes.common_hdr(buf)
log(index , ... | Walk the index gathering Inode, Dir Entry, and File nodes.
Arguments:
Obj:ubifs -- UBIFS object.
Int:lnum -- Logical erase block number.
Int:offset -- Offset in logical erase block.
Dict:inodes -- Dict of ino/dent/file nodes keyed to inode number.
Returns:
Dict:inodes -- Dict of... | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/ubifs/walk.py#L25-L151 | [
"def index(ubifs, lnum, offset, inodes={}, bad_blocks=[]):\n \"\"\"Walk the index gathering Inode, Dir Entry, and File nodes.\n\n Arguments:\n Obj:ubifs -- UBIFS object.\n Int:lnum -- Logical erase block number.\n Int:offset -- Offset in logical erase block.\n Dict:inodes -- Dict of ino/... | #!/usr/bin/env python
#############################################################
# ubi_reader/ubifs
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat... |
jrspruitt/ubi_reader | ubireader/utils.py | guess_leb_size | python | def guess_leb_size(path):
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
block_size = None
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBIFS_NODE_MAGIC, buf):
start = m.start()
chdr = ... | Get LEB size from superblock
Arguments:
Str:path -- Path to file.
Returns:
Int -- LEB size.
Searches file for superblock and retrieves leb size. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/utils.py#L86-L127 | null | #!/usr/bin/env python
#############################################################
# ubi_reader
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, e... |
jrspruitt/ubi_reader | ubireader/utils.py | guess_peb_size | python | def guess_peb_size(path):
file_offset = 0
offsets = []
f = open(path, 'rb')
f.seek(0,2)
file_size = f.tell()+1
f.seek(0)
for _ in range(0, file_size, FILE_CHUNK_SZ):
buf = f.read(FILE_CHUNK_SZ)
for m in re.finditer(UBI_EC_HDR_MAGIC, buf):
start = m.start()
... | Determine the most likely block size
Arguments:
Str:path -- Path to file.
Returns:
Int -- PEB size.
Searches file for Magic Number, picks most
common length between them. | train | https://github.com/jrspruitt/ubi_reader/blob/7079dd380c1c9896bced30d6d34e8780b9181597/ubireader/utils.py#L131-L186 | null | #!/usr/bin/env python
#############################################################
# ubi_reader
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, e... |
edx/event-tracking | eventtracking/backends/mongodb.py | MongoBackend._create_indexes | python | def _create_indexes(self):
# WARNING: The collection will be locked during the index
# creation. If the collection has a large number of
# documents in it, the operation can take a long time.
# TODO: The creation of indexes can be moved to a Django
# management command or equiva... | Ensures the proper fields are indexed | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/mongodb.py#L75-L85 | null | class MongoBackend(object):
"""Class for a MongoDB event tracker Backend"""
def __init__(self, **kwargs):
"""
Connect to a MongoDB.
:Parameters:
- `host`: hostname
- `port`: port
- `user`: collection username
- `password`: collection user passwo... |
edx/event-tracking | eventtracking/backends/mongodb.py | MongoBackend.send | python | def send(self, event):
try:
self.collection.insert(event, manipulate=False)
except (PyMongoError, BSONError):
# The event will be lost in case of a connection error or any error
# that occurs when trying to insert the event into Mongo.
# pymongo will re-co... | Insert the event in to the Mongo collection | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/mongodb.py#L87-L97 | null | class MongoBackend(object):
"""Class for a MongoDB event tracker Backend"""
def __init__(self, **kwargs):
"""
Connect to a MongoDB.
:Parameters:
- `host`: hostname
- `port`: port
- `user`: collection username
- `password`: collection user passwo... |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.create_backends_from_settings | python | def create_backends_from_settings(self):
config = getattr(settings, DJANGO_BACKEND_SETTING_NAME, {})
backends = self.instantiate_objects(config)
return backends | Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
... | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L31-L57 | [
"def instantiate_objects(self, node):\n \"\"\"\n Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated\n\n Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the\n special \"ENGINE\" key whic... | class DjangoTracker(Tracker):
"""
A `eventtracking.tracker.Tracker` that constructs its backends from
Django settings.
"""
def __init__(self):
backends = self.create_backends_from_settings()
processors = self.create_processors_from_settings()
super(DjangoTracker, self).__ini... |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.instantiate_objects | python | def instantiate_objects(self, node):
result = node
if isinstance(node, dict):
if 'ENGINE' in node:
result = self.instantiate_from_dict(node)
else:
result = {}
for key, value in six.iteritems(node):
result[key] = ... | Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated
Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the
special "ENGINE" key which indicates that a class of that type should be instanti... | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L59-L116 | [
"def instantiate_objects(self, node):\n \"\"\"\n Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated\n\n Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the\n special \"ENGINE\" key whic... | class DjangoTracker(Tracker):
"""
A `eventtracking.tracker.Tracker` that constructs its backends from
Django settings.
"""
def __init__(self):
backends = self.create_backends_from_settings()
processors = self.create_processors_from_settings()
super(DjangoTracker, self).__ini... |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.instantiate_from_dict | python | def instantiate_from_dict(self, values):
name = values['ENGINE']
options = values.get('OPTIONS', {})
# Parse the name
parts = name.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
# Get the class
try:
module = import_modu... | Constructs an object given a dictionary containing an "ENGINE" key
which contains the full module path to the class, and an "OPTIONS"
key which contains a dictionary that will be passed in to the
constructor as keyword args. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L118-L143 | [
"def instantiate_objects(self, node):\n \"\"\"\n Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated\n\n Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the\n special \"ENGINE\" key whic... | class DjangoTracker(Tracker):
"""
A `eventtracking.tracker.Tracker` that constructs its backends from
Django settings.
"""
def __init__(self):
backends = self.create_backends_from_settings()
processors = self.create_processors_from_settings()
super(DjangoTracker, self).__ini... |
edx/event-tracking | eventtracking/django/__init__.py | DjangoTracker.create_processors_from_settings | python | def create_processors_from_settings(self):
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors | Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and
point to a list of backend engine configurations.
Example::
EVENT_TRACKING_PROCESSORS = [
{
'ENGINE': 'some.arbitrary.Processor'
},
{
... | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/django/__init__.py#L145-L168 | [
"def instantiate_objects(self, node):\n \"\"\"\n Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated\n\n Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the\n special \"ENGINE\" key whic... | class DjangoTracker(Tracker):
"""
A `eventtracking.tracker.Tracker` that constructs its backends from
Django settings.
"""
def __init__(self):
backends = self.create_backends_from_settings()
processors = self.create_processors_from_settings()
super(DjangoTracker, self).__ini... |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.register_backend | python | def register_backend(self, name, backend):
if not hasattr(backend, 'send') or not callable(backend.send):
raise ValueError('Backend %s does not have a callable "send" method.' % backend.__class__.__name__)
else:
self.backends[name] = backend | Register a new backend that will be called for each processed event.
Note that backends are called in the order that they are registered. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L55-L64 | null | class RoutingBackend(object):
"""
Route events to the appropriate backends.
A routing backend has two types of components:
1) Processors - These are run sequentially, processing the output of the previous processor. If you had three
processors [a, b, c], the output of the processing step would... |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.register_processor | python | def register_processor(self, processor):
if not callable(processor):
raise ValueError('Processor %s is not callable.' % processor.__class__.__name__)
else:
self.processors.append(processor) | Register a new processor.
Note that processors are called in the order that they are registered. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L66-L75 | null | class RoutingBackend(object):
"""
Route events to the appropriate backends.
A routing backend has two types of components:
1) Processors - These are run sequentially, processing the output of the previous processor. If you had three
processors [a, b, c], the output of the processing step would... |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.send | python | def send(self, event):
try:
processed_event = self.process_event(event)
except EventEmissionExit:
return
else:
self.send_to_backends(processed_event) | Process the event using all registered processors and send it to all registered backends.
Logs and swallows all `Exception`. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L77-L88 | [
"def process_event(self, event):\n \"\"\"\n\n Executes all event processors on the event in order.\n\n `event` is a nested dictionary that represents the event.\n\n Logs and swallows all `Exception` except `EventEmissionExit` which is re-raised if it is raised by a processor.\n\n Returns the modified... | class RoutingBackend(object):
"""
Route events to the appropriate backends.
A routing backend has two types of components:
1) Processors - These are run sequentially, processing the output of the previous processor. If you had three
processors [a, b, c], the output of the processing step would... |
edx/event-tracking | eventtracking/backends/routing.py | RoutingBackend.send_to_backends | python | def send_to_backends(self, event):
for name, backend in six.iteritems(self.backends):
try:
backend.send(event)
except Exception: # pylint: disable=broad-except
LOG.exception(
'Unable to send event to backend: %s', name
... | Sends the event to all registered backends.
Logs and swallows all `Exception`. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/routing.py#L121-L134 | null | class RoutingBackend(object):
"""
Route events to the appropriate backends.
A routing backend has two types of components:
1) Processors - These are run sequentially, processing the output of the previous processor. If you had three
processors [a, b, c], the output of the processing step would... |
edx/event-tracking | eventtracking/tracker.py | Tracker.emit | python | def emit(self, name=None, data=None):
event = {
'name': name or UNKNOWN_EVENT_TYPE,
'timestamp': datetime.now(UTC),
'data': data or {},
'context': self.resolve_context()
}
self.routing_backend.send(event) | Emit an event annotated with the UTC time when this function was called.
`name` is a unique identification string for an event that has
already been registered.
`data` is a dictionary mapping field names to the value to include in the event.
Note that all values provided must be... | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L65-L82 | [
"def resolve_context(self):\n \"\"\"\n Create a new dictionary that corresponds to the union of all of the\n contexts that have been entered but not exited at this point.\n \"\"\"\n merged = dict()\n for context in self.located_context.values():\n merged.update(context)\n return merged\n... | class Tracker(object):
"""
Track application events. Holds references to a set of backends that will
be used to persist any events that are emitted.
"""
def __init__(self, backends=None, context_locator=None, processors=None):
self.routing_backend = RoutingBackend(backends=backends, process... |
edx/event-tracking | eventtracking/tracker.py | Tracker.resolve_context | python | def resolve_context(self):
merged = dict()
for context in self.located_context.values():
merged.update(context)
return merged | Create a new dictionary that corresponds to the union of all of the
contexts that have been entered but not exited at this point. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L84-L92 | null | class Tracker(object):
"""
Track application events. Holds references to a set of backends that will
be used to persist any events that are emitted.
"""
def __init__(self, backends=None, context_locator=None, processors=None):
self.routing_backend = RoutingBackend(backends=backends, process... |
edx/event-tracking | eventtracking/tracker.py | Tracker.context | python | def context(self, name, ctx):
self.enter_context(name, ctx)
try:
yield
finally:
self.exit_context(name) | Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/tracker.py#L111-L121 | [
"def enter_context(self, name, ctx):\n \"\"\"\n Enter a named context. Any events emitted after calling this\n method will contain all of the key-value pairs included in `ctx`\n unless overridden by a context that is entered after this call.\n \"\"\"\n self.located_context[name] = ctx\n",
"def ... | class Tracker(object):
"""
Track application events. Holds references to a set of backends that will
be used to persist any events that are emitted.
"""
def __init__(self, backends=None, context_locator=None, processors=None):
self.routing_backend = RoutingBackend(backends=backends, process... |
edx/event-tracking | eventtracking/backends/segment.py | SegmentBackend.send | python | def send(self, event):
if analytics is None:
return
context = event.get('context', {})
user_id = context.get('user_id')
name = event.get('name')
if name is None or user_id is None:
return
segment_context = {}
ga_client_id = context.get('... | Use the segment.com python API to send the event to segment.com | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/segment.py#L50-L100 | null | class SegmentBackend(object):
"""
Send events to segment.com
It is assumed that other code elsewhere initializes the segment.com API and makes calls to analytics.identify.
Requires all emitted events to have the following structure (at a minimum)::
{
'name': 'something',
... |
edx/event-tracking | eventtracking/locator.py | ThreadLocalContextLocator.get | python | def get(self):
if not self.thread_local_data:
self.thread_local_data = threading.local()
if not hasattr(self.thread_local_data, 'context'):
self.thread_local_data.context = OrderedDict()
return self.thread_local_data.context | Return a reference to a thread-specific context | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/locator.py#L47-L55 | null | class ThreadLocalContextLocator(object):
"""
Returns a different context depending on the thread that the locator
was called from. Thus, contexts can be isolated from one another
on thread boundaries.
Note that this makes use of `threading.local(),` which is typically
monkey-patched by altern... |
edx/event-tracking | eventtracking/backends/logger.py | LoggerBackend.send | python | def send(self, event):
event_str = json.dumps(event, cls=DateTimeJSONEncoder)
# TODO: do something smarter than simply dropping the event on
# the floor.
if self.max_event_size is None or len(event_str) <= self.max_event_size:
self.log(event_str) | Send the event to the standard python logger | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/logger.py#L35-L42 | null | class LoggerBackend(object):
"""
Event tracker backend that uses a python logger.
Events are logged to the INFO level as JSON strings.
"""
def __init__(self, **kwargs):
"""
Event tracker backend that uses a python logger.
`name` is an identifier for the logger, which shoul... |
edx/event-tracking | eventtracking/backends/logger.py | DateTimeJSONEncoder.default | python | def default(self, obj): # lint-amnesty, pylint: disable=arguments-differ, method-hidden
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj) # pylint: disable=no-value-for-parameter
else:
... | Serialize datetime and date objects of iso format.
datatime objects are converted to UTC. | train | https://github.com/edx/event-tracking/blob/8f993560545061d77f11615f5e3865b3916d5ea9/eventtracking/backends/logger.py#L48-L66 | null | class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
|
rochacbruno/python-pagseguro | examples/flask/flask_seguro/__init__.py | create_app | python | def create_app(config_name):
app = Flask(__name__)
app.config.from_object(CONFIG[config_name])
BOOTSTRAP.init_app(app)
# call controllers
from flask_seguro.controllers.main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app | Factory Function | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/__init__.py#L9-L20 | null | """ Application Skeleton """
from flask import Flask
from flask_bootstrap import Bootstrap
from config import CONFIG
BOOTSTRAP = Bootstrap()
|
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.build_checkout_params | python | def build_checkout_params(self, **kwargs):
params = kwargs or {}
if self.sender:
params['senderName'] = self.sender.get('name')
params['senderAreaCode'] = self.sender.get('area_code')
params['senderPhone'] = self.sender.get('phone')
params['senderEmail'] =... | build a dict with params | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L55-L164 | [
"def is_valid_email(value):\n user_regex = re.compile(\n r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$\"\n r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013'\n r\"\"\"\\014\\016-\\177])*\"$)\"\"\", re.IGNORECASE)\n domain_regex = re.comp... | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.build_pre_approval_payment_params | python | def build_pre_approval_payment_params(self, **kwargs):
params = kwargs or {}
params['reference'] = self.reference
params['preApprovalCode'] = self.code
for i, item in enumerate(self.items, 1):
params['itemId%s' % i] = item.get('id')
params['itemDescription%s' %... | build a dict with params | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L166-L183 | [
"def clean_none_params(self):\n self.data = \\\n {k: v for k, v in self.data.items() if v or isinstance(v, bool)}\n"
] | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.get | python | def get(self, url):
return requests.get(url, params=self.data, headers=self.config.HEADERS) | do a get transaction | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L209-L211 | null | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.post | python | def post(self, url):
return requests.post(url, data=self.data, headers=self.config.HEADERS) | do a post request | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L213-L215 | null | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.checkout | python | def checkout(self, transparent=False, **kwargs):
self.data['currency'] = self.config.CURRENCY
self.build_checkout_params(**kwargs)
if transparent:
response = self.post(url=self.config.TRANSPARENT_CHECKOUT_URL)
else:
response = self.post(url=self.config.CHECKOUT_UR... | create a pagseguro checkout | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L217-L225 | [
"def build_checkout_params(self, **kwargs):\n \"\"\" build a dict with params \"\"\"\n params = kwargs or {}\n if self.sender:\n params['senderName'] = self.sender.get('name')\n params['senderAreaCode'] = self.sender.get('area_code')\n params['senderPhone'] = self.sender.get('phone')\n... | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.check_notification | python | def check_notification(self, code):
response = self.get(url=self.config.NOTIFICATION_URL % code)
return PagSeguroNotificationResponse(response.content, self.config) | check a notification by its code | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L232-L235 | [
"def get(self, url):\n \"\"\" do a get transaction \"\"\"\n return requests.get(url, params=self.data, headers=self.config.HEADERS)\n"
] | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.check_pre_approval_notification | python | def check_pre_approval_notification(self, code):
response = self.get(
url=self.config.PRE_APPROVAL_NOTIFICATION_URL % code)
return PagSeguroPreApprovalNotificationResponse(
response.content, self.config) | check a notification by its code | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L237-L242 | [
"def get(self, url):\n \"\"\" do a get transaction \"\"\"\n return requests.get(url, params=self.data, headers=self.config.HEADERS)\n"
] | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.pre_approval_ask_payment | python | def pre_approval_ask_payment(self, **kwargs):
self.build_pre_approval_payment_params(**kwargs)
response = self.post(url=self.config.PRE_APPROVAL_PAYMENT_URL)
return PagSeguroPreApprovalPayment(response.content, self.config) | ask form a subscribe payment | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L244-L248 | [
"def build_pre_approval_payment_params(self, **kwargs):\n \"\"\" build a dict with params \"\"\"\n\n params = kwargs or {}\n\n params['reference'] = self.reference\n params['preApprovalCode'] = self.code\n\n for i, item in enumerate(self.items, 1):\n params['itemId%s' % i] = item.get('id')\n ... | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.pre_approval_cancel | python | def pre_approval_cancel(self, code):
response = self.get(url=self.config.PRE_APPROVAL_CANCEL_URL % code)
return PagSeguroPreApprovalCancel(response.content, self.config) | cancel a subscribe | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L250-L253 | [
"def get(self, url):\n \"\"\" do a get transaction \"\"\"\n return requests.get(url, params=self.data, headers=self.config.HEADERS)\n"
] | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.check_transaction | python | def check_transaction(self, code):
response = self.get(url=self.config.TRANSACTION_URL % code)
return PagSeguroNotificationResponse(response.content, self.config) | check a transaction by its code | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L255-L258 | [
"def get(self, url):\n \"\"\" do a get transaction \"\"\"\n return requests.get(url, params=self.data, headers=self.config.HEADERS)\n"
] | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.query_transactions | python | def query_transactions(self, initial_date, final_date,
page=None,
max_results=None):
last_page = False
results = []
while last_page is False:
search_result = self._consume_query_transactions(
initial_date, final_da... | query transaction by date range | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L260-L277 | [
"def _consume_query_transactions(self, initial_date, final_date,\n page=None,\n max_results=None):\n querystring = {\n 'initialDate': initial_date.strftime('%Y-%m-%dT%H:%M'),\n 'finalDate': final_date.strftime('%Y-%m-%dT%H:%M'),\n ... | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | pagseguro/__init__.py | PagSeguro.query_pre_approvals | python | def query_pre_approvals(self, initial_date, final_date, page=None,
max_results=None):
last_page = False
results = []
while last_page is False:
search_result = self._consume_query_pre_approvals(
initial_date, final_date, page, max_results)
... | query pre-approvals by date range | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/pagseguro/__init__.py#L293-L309 | [
"def _consume_query_pre_approvals(self, initial_date, final_date, page=None,\n max_results=None):\n querystring = {\n 'initialDate': initial_date.strftime('%Y-%m-%dT%H:%M'),\n 'finalDate': final_date.strftime('%Y-%m-%dT%H:%M'),\n 'page': page,\n 'maxPag... | class PagSeguro(object):
""" Pag Seguro V2 wrapper """
PAC = 1
SEDEX = 2
NONE = 3
def __init__(self, email, token, data=None, config=None):
config = config or {}
if not type(config) == dict:
raise Exception('Malformed config dict param')
self.config = Config(*... |
rochacbruno/python-pagseguro | examples/flask/flask_seguro/controllers/main/__init__.py | add_to_cart | python | def add_to_cart(item_id):
cart = Cart(session['cart'])
if cart.change_item(item_id, 'add'):
session['cart'] = cart.to_dict()
return list_products() | Cart with Product | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/controllers/main/__init__.py#L44-L49 | null | # -*- coding: utf-8 -*-
""" Main Controllers """
from flask import session
from flask import jsonify
from flask import request
from flask import redirect
from flask import render_template
from flask import current_app as app
from pagseguro import PagSeguro
from flask_seguro.products import Products
from flask_seguro.c... |
rochacbruno/python-pagseguro | examples/flask/flask_seguro/cart.py | Cart.to_dict | python | def to_dict(self):
return {
"total": self.total,
"subtotal": self.subtotal,
"items": self.items,
"extra_amount": self.extra_amount
} | Attribute values to dict | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/cart.py#L24-L32 | null | class Cart(object):
""" The classe is responsable for cart in webpage """
def __init__(self, cart_dict=None):
""" Initializing class """
cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
... |
rochacbruno/python-pagseguro | examples/flask/flask_seguro/cart.py | Cart.change_item | python | def change_item(self, item_id, operation):
product = Products().get_one(item_id)
if product:
if operation == 'add':
self.items.append(product)
elif operation == 'remove':
cart_p = [x for x in self.items if x['id'] == product['id']]
... | Remove items in cart | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/cart.py#L34-L47 | [
"def update(self):\n \"\"\" Remove items in cart \"\"\"\n\n subtotal = float(0)\n total = float(0)\n for product in self.items:\n subtotal += float(product[\"price\"])\n if subtotal > 0:\n total = subtotal + self.extra_amount\n self.subtotal = subtotal\n self.total = total\n"
] | class Cart(object):
""" The classe is responsable for cart in webpage """
def __init__(self, cart_dict=None):
""" Initializing class """
cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
... |
rochacbruno/python-pagseguro | examples/flask/flask_seguro/cart.py | Cart.update | python | def update(self):
subtotal = float(0)
total = float(0)
for product in self.items:
subtotal += float(product["price"])
if subtotal > 0:
total = subtotal + self.extra_amount
self.subtotal = subtotal
self.total = total | Remove items in cart | train | https://github.com/rochacbruno/python-pagseguro/blob/18a9ca3301783cb323e838574b59f9ddffa9a593/examples/flask/flask_seguro/cart.py#L49-L59 | null | class Cart(object):
""" The classe is responsable for cart in webpage """
def __init__(self, cart_dict=None):
""" Initializing class """
cart_dict = cart_dict or {}
if cart_dict == {}:
self.total = 0
self.subtotal = 0
self.items = []
else:
... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/viewlets.py | ViewletView.getViewletByName | python | def getViewletByName(self, name):
views = registration.getViews(IBrowserRequest)
for v in views:
if v.provided == IViewlet:
# Note that we might have conflicting BrowserView with the same
# name, thus we need to check for provided
if v.name =... | Viewlets allow through-the-web customizations.
Through-the-web customization magic is managed by five.customerize.
We need to think of this when looking up viewlets.
@return: Viewlet registration object | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/viewlets.py#L162-L181 | null | class ViewletView(BrowserView):
"""Expose arbitrary viewlets to traversing by name.
Example how to render plone.logo viewlet in arbitrary template code point::
<div tal:content="context/@@viewlets/plone.logo" />
https://docs.plone.org/develop/plone/views/viewlets.html#rendering-viewlet-by-name
... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/viewlets.py | ViewletView.setupViewletByName | python | def setupViewletByName(self, name):
context = aq_inner(self.context)
request = self.request
# Perform viewlet regisration look-up
# from adapters registry
reg = self.getViewletByName(name)
if reg is None:
return None
# factory method is responsible f... | Constructs a viewlet instance by its name.
Viewlet update() and render() method are not called.
@return: Viewlet instance of None if viewlet with name does not exist | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/viewlets.py#L183-L213 | null | class ViewletView(BrowserView):
"""Expose arbitrary viewlets to traversing by name.
Example how to render plone.logo viewlet in arbitrary template code point::
<div tal:content="context/@@viewlets/plone.logo" />
https://docs.plone.org/develop/plone/views/viewlets.html#rendering-viewlet-by-name
... |
senaite/senaite.lims | src/senaite/lims/setuphandlers.py | setup_handler | python | def setup_handler(context):
if context.readDataFile('senaite.lims.txt') is None:
return
logger.info("SENAITE setup handler [BEGIN]")
portal = context.getSite() # noqa
# Custom setup handlers
setup_html_filter(portal)
logger.info("SENAITE setup handler [DONE]") | Generic setup handler | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/setuphandlers.py#L30-L43 | [
"def setup_html_filter(portal):\n \"\"\"Setup HTML filtering for resultsinterpretations\n \"\"\"\n logger.info(\"*** Setup HTML Filter ***\")\n # bypass the broken API from portal_transforms\n adapter = IFilterSchema(portal)\n style_whitelist = adapter.style_whitelist\n for style in ALLOWED_STY... | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/setuphandlers.py | setup_html_filter | python | def setup_html_filter(portal):
logger.info("*** Setup HTML Filter ***")
# bypass the broken API from portal_transforms
adapter = IFilterSchema(portal)
style_whitelist = adapter.style_whitelist
for style in ALLOWED_STYLES:
logger.info("Allow style '{}'".format(style))
if style not in ... | Setup HTML filtering for resultsinterpretations | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/setuphandlers.py#L46-L57 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/setuphandlers.py | pre_install | python | def pre_install(portal_setup):
logger.info("SENAITE LIMS pre-install handler [BEGIN]")
# https://docs.plone.org/develop/addons/components/genericsetup.html#custom-installer-code-setuphandlers-py
profile_id = "profile-senaite.lims:default"
context = portal_setup._getImportContext(profile_id)
portal ... | Runs berfore the first import step of the *default* profile
This handler is registered as a *pre_handler* in the generic setup profile
:param portal_setup: SetupTool | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/setuphandlers.py#L60-L79 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/upgrades/handlers.py | to_1000 | python | def to_1000(portal_setup):
logger.info("Run all import steps from SENAITE LIMS ...")
context = portal_setup._getImportContext(PROFILE_ID)
portal = context.getSite()
setup_html_filter(portal)
portal_setup.runAllImportStepsFromProfile(PROFILE_ID)
logger.info("Run all import steps from SENAITE LIM... | Initial version to 1000
:param portal_setup: The portal_setup tool | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/upgrades/handlers.py#L27-L38 | [
"def setup_html_filter(portal):\n \"\"\"Setup HTML filtering for resultsinterpretations\n \"\"\"\n logger.info(\"*** Setup HTML Filter ***\")\n # bypass the broken API from portal_transforms\n adapter = IFilterSchema(portal)\n style_whitelist = adapter.style_whitelist\n for style in ALLOWED_STY... | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | spotlight_search_route | python | def spotlight_search_route(context, request):
catalogs = [
CATALOG_ANALYSIS_REQUEST_LISTING,
"portal_catalog",
"bika_setup_catalog",
"bika_catalog",
"bika_catalog_worksheet_listing"
]
search_results = []
for catalog in catalogs:
search_results.extend(sear... | The spotlight search route | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L31-L52 | [
"def search(query=None, catalog=None):\n \"\"\"Search\n \"\"\"\n if query is None:\n query = make_query(catalog)\n if query is None:\n return []\n return api.search(query, catalog=catalog)\n"
] | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | get_brain_info | python | def get_brain_info(brain):
icon = api.get_icon(brain)
# avoid 404 errors with these guys
if "document_icon.gif" in icon:
icon = ""
id = api.get_id(brain)
url = api.get_url(brain)
title = api.get_title(brain)
description = api.get_description(brain)
parent = api.get_parent(brain)... | Extract the brain info | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L55-L80 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | search | python | def search(query=None, catalog=None):
if query is None:
query = make_query(catalog)
if query is None:
return []
return api.search(query, catalog=catalog) | Search | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L83-L90 | [
"def make_query(catalog):\n \"\"\"A function to prepare a query\n \"\"\"\n query = {}\n request = api.get_request()\n index = get_search_index_for(catalog)\n limit = request.form.get(\"limit\")\n\n q = request.form.get(\"q\")\n if len(q) > 0:\n query[index] = q + \"*\"\n else:\n ... | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | get_search_index_for | python | def get_search_index_for(catalog):
searchable_text_index = "SearchableText"
listing_searchable_text_index = "listing_searchable_text"
if catalog == CATALOG_ANALYSIS_REQUEST_LISTING:
tool = api.get_tool(catalog)
indexes = tool.indexes()
if listing_searchable_text_index in indexes:
... | Returns the search index to query | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L94-L106 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/spotlight/jsonapi.py | make_query | python | def make_query(catalog):
query = {}
request = api.get_request()
index = get_search_index_for(catalog)
limit = request.form.get("limit")
q = request.form.get("q")
if len(q) > 0:
query[index] = q + "*"
else:
return None
portal_type = request.form.get("portal_type")
if... | A function to prepare a query | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/spotlight/jsonapi.py#L109-L132 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/views.py | icon_cache_key | python | def icon_cache_key(method, self, brain_or_object):
url = api.get_url(brain_or_object)
modified = api.get_modification_date(brain_or_object).millis()
key = "{}?modified={}".format(url, modified)
logger.debug("Generated Cache Key: {}".format(key))
return key | Generates a cache key for the icon lookup
Includes the virtual URL to handle multiple HTTP/HTTPS domains
Example: http://senaite.local/clients?modified=1512033263370 | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/views.py#L33-L43 | null | # -*- coding: utf-8 -*-
#
# This file is part of SENAITE.LIMS.
#
# SENAITE.LIMS is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, bu... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/views.py | BootstrapView.get_icon_for | python | def get_icon_for(self, brain_or_object):
portal_types = api.get_tool("portal_types")
fti = portal_types.getTypeInfo(api.get_portal_type(brain_or_object))
icon = fti.getIcon()
if not icon:
return ""
# Always try to get the big icon for high-res displays
icon_bi... | Get the navigation portlet icon for the brain or object
The cache key ensures that the lookup is done only once per domain name | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/views.py#L60-L81 | null | class BootstrapView(BrowserView):
"""Twitter Bootstrap helper view for SENAITE LIMS
"""
implements(IBootstrapView)
def __init__(self, context, request):
super(BrowserView, self).__init__(context, request)
@cache(icon_cache_key)
def getViewportValues(self, view=None):
"""Deter... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/views.py | BootstrapView.getViewportValues | python | def getViewportValues(self, view=None):
values = {
'width': 'device-width',
'initial-scale': '1.0',
}
return ','.join('%s=%s' % (k, v) for k, v in values.items()) | Determine the value of the viewport meta-tag | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/views.py#L83-L91 | null | class BootstrapView(BrowserView):
"""Twitter Bootstrap helper view for SENAITE LIMS
"""
implements(IBootstrapView)
def __init__(self, context, request):
super(BrowserView, self).__init__(context, request)
@cache(icon_cache_key)
def get_icon_for(self, brain_or_object):
"""Get th... |
senaite/senaite.lims | src/senaite/lims/browser/bootstrap/views.py | BootstrapView.getColumnsClasses | python | def getColumnsClasses(self, view=None):
plone_view = getMultiAdapter(
(self.context, self.request), name=u'plone')
portal_state = getMultiAdapter(
(self.context, self.request), name=u'plone_portal_state')
sl = plone_view.have_portlets('plone.leftcolumn', view=view)
... | Determine whether a column should be shown. The left column is
called plone.leftcolumn; the right column is called
plone.rightcolumn. | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/bootstrap/views.py#L93-L142 | null | class BootstrapView(BrowserView):
"""Twitter Bootstrap helper view for SENAITE LIMS
"""
implements(IBootstrapView)
def __init__(self, context, request):
super(BrowserView, self).__init__(context, request)
@cache(icon_cache_key)
def get_icon_for(self, brain_or_object):
"""Get th... |
senaite/senaite.lims | src/senaite/lims/browser/controlpanel/views/setupview.py | SetupView.get_icon_url | python | def get_icon_url(self, brain):
icon_url = api.get_icon(brain, html_tag=False)
url, icon = icon_url.rsplit("/", 1)
relative_url = url.lstrip(self.portal.absolute_url())
name, ext = os.path.splitext(icon)
# big icons endwith _big
if not name.endswith("_big"):
i... | Returns the (big) icon URL for the given catalog brain | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/controlpanel/views/setupview.py#L63-L81 | null | class SetupView(BrowserView):
"""SENAITE LIMS Setup View
"""
template = ViewPageTemplateFile("templates/setupview.pt")
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
self.request.set("disable_border", 1)
retur... |
senaite/senaite.lims | src/senaite/lims/browser/controlpanel/views/setupview.py | SetupView.setupitems | python | def setupitems(self):
query = {
"path": {
"query": api.get_path(self.setup),
"depth": 1,
},
}
items = api.search(query, "portal_catalog")
# filter out items
items = filter(lambda item: not item.exclude_from_nav, items)
... | Lookup available setup items
:returns: catalog brains | train | https://github.com/senaite/senaite.lims/blob/3c7fc7b462321fb354c478c19b5c20f3014fa398/src/senaite/lims/browser/controlpanel/views/setupview.py#L83-L104 | null | class SetupView(BrowserView):
"""SENAITE LIMS Setup View
"""
template = ViewPageTemplateFile("templates/setupview.pt")
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
self.request.set("disable_border", 1)
retur... |
ppb/pursuedpybear | ppb/engine.py | GameEngine.on_start_scene | python | def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]):
self.pause_scene()
self.start_scene(event.new_scene, event.kwargs) | Start a new scene. The current scene pauses. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L143-L148 | [
"def pause_scene(self):\n # Empty the queue before changing scenes.\n self.flush_events()\n self.signal(events.ScenePaused())\n self.publish()\n",
"def start_scene(self, scene, kwargs):\n if isinstance(scene, type):\n scene = scene(self, **(kwargs or {}))\n self.scenes.append(scene)\n ... | class GameEngine(Engine, EventMixin, LoggingMixin):
def __init__(self, first_scene: Type, *,
systems=(Renderer, Updater, PygameEventPoller),
scene_kwargs=None, **kwargs):
super(GameEngine, self).__init__()
# Engine Configuration
self.first_scene = first_s... |
ppb/pursuedpybear | ppb/engine.py | GameEngine.on_stop_scene | python | def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]):
self.stop_scene()
if self.current_scene is not None:
signal(events.SceneContinued())
else:
signal(events.Quit()) | Stop a running scene. If there's a scene on the stack, it resumes. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L150-L158 | [
"def stop_scene(self):\n # Empty the queue before changing scenes.\n self.flush_events()\n self.signal(events.SceneStopped())\n self.publish()\n self.scenes.pop()\n"
] | class GameEngine(Engine, EventMixin, LoggingMixin):
def __init__(self, first_scene: Type, *,
systems=(Renderer, Updater, PygameEventPoller),
scene_kwargs=None, **kwargs):
super(GameEngine, self).__init__()
# Engine Configuration
self.first_scene = first_s... |
ppb/pursuedpybear | ppb/engine.py | GameEngine.on_replace_scene | python | def on_replace_scene(self, event: events.ReplaceScene, signal):
self.stop_scene()
self.start_scene(event.new_scene, event.kwargs) | Replace the running scene with a new one. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L160-L165 | [
"def stop_scene(self):\n # Empty the queue before changing scenes.\n self.flush_events()\n self.signal(events.SceneStopped())\n self.publish()\n self.scenes.pop()\n",
"def start_scene(self, scene, kwargs):\n if isinstance(scene, type):\n scene = scene(self, **(kwargs or {}))\n self.sce... | class GameEngine(Engine, EventMixin, LoggingMixin):
def __init__(self, first_scene: Type, *,
systems=(Renderer, Updater, PygameEventPoller),
scene_kwargs=None, **kwargs):
super(GameEngine, self).__init__()
# Engine Configuration
self.first_scene = first_s... |
ppb/pursuedpybear | ppb/engine.py | GameEngine.register | python | def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]):
if not isinstance(event_type, type) and event_type is not ...:
raise TypeError(f"{type(self)}.register requires event_type to be a type.")
if not callable(callback):
raise TypeError(f"{type(self)... | Register a callback to be applied to an event at time of publishing.
Primarily to be used by subsystems.
The callback will receive the event. Your code should modify the event
in place. It does not need to return it.
:param event_type: The class of an event.
:param callback: A... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L189-L206 | null | class GameEngine(Engine, EventMixin, LoggingMixin):
def __init__(self, first_scene: Type, *,
systems=(Renderer, Updater, PygameEventPoller),
scene_kwargs=None, **kwargs):
super(GameEngine, self).__init__()
# Engine Configuration
self.first_scene = first_s... |
ppb/pursuedpybear | ppb/utils.py | _build_index | python | def _build_index():
global _module_file_index
_module_file_index = {
mod.__file__: mod.__name__
for mod in sys.modules.values()
if hasattr(mod, '__file__') and hasattr(mod, '__name__')
} | Rebuild _module_file_index from sys.modules | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/utils.py#L11-L20 | null | import logging
import sys
__all__ = 'LoggingMixin',
# Dictionary mapping file names -> module names
_module_file_index = {}
def _get_module(file_name):
"""
Find the module name for the given file name, or raise KeyError if it's
not a loaded module.
"""
if file_name not in _module_file_index:
... |
ppb/pursuedpybear | ppb/utils.py | LoggingMixin.logger | python | def logger(self):
# This is internal/CPython only/etc
# It's also astonishingly faster than alternatives.
frame = sys._getframe(1)
file_name = frame.f_code.co_filename
module_name = _get_module(file_name)
return logging.getLogger(module_name) | The logger for this class. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/utils.py#L40-L50 | [
"def _get_module(file_name):\n \"\"\"\n Find the module name for the given file name, or raise KeyError if it's\n not a loaded module.\n \"\"\"\n if file_name not in _module_file_index:\n _build_index()\n return _module_file_index[file_name]\n"
] | class LoggingMixin:
"""
A simple mixin to provide a `logger` attribute to instances, based on their
module.
"""
@property
|
ppb/pursuedpybear | ppb/features/animation.py | Animation.pause | python | def pause(self):
if not self._pause_level:
self._paused_time = self._clock() + self._offset
self._paused_frame = self.current_frame
self._pause_level += 1 | Pause the animation. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/features/animation.py#L72-L79 | [
"def _clock(self):\n return type(self).clock()\n"
] | class Animation:
"""
An "image" that actually rotates through numbered files at the specified rate.
"""
# Override this to change the clock used for frames.
clock = time.monotonic
def __init__(self, filename, frames_per_second):
"""
:param str filename: A path containing a ``{2.... |
ppb/pursuedpybear | ppb/features/animation.py | Animation.unpause | python | def unpause(self):
self._pause_level -= 1
if not self._pause_level:
self._offset = self._paused_time - self._clock() | Unpause the animation. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/features/animation.py#L81-L87 | [
"def _clock(self):\n return type(self).clock()\n"
] | class Animation:
"""
An "image" that actually rotates through numbered files at the specified rate.
"""
# Override this to change the clock used for frames.
clock = time.monotonic
def __init__(self, filename, frames_per_second):
"""
:param str filename: A path containing a ``{2.... |
ppb/pursuedpybear | ppb/features/animation.py | Animation.current_frame | python | def current_frame(self):
if not self._pause_level:
return (
int((self._clock() + self._offset) * self.frames_per_second)
% len(self._frames)
)
else:
return self._paused_frame | Compute the number of the current frame (0-indexed) | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/features/animation.py#L99-L109 | [
"def _clock(self):\n return type(self).clock()\n"
] | class Animation:
"""
An "image" that actually rotates through numbered files at the specified rate.
"""
# Override this to change the clock used for frames.
clock = time.monotonic
def __init__(self, filename, frames_per_second):
"""
:param str filename: A path containing a ``{2.... |
ppb/pursuedpybear | ppb/__init__.py | run | python | def run(setup: Callable[[BaseScene], None]=None, *, log_level=logging.WARNING,
starting_scene=BaseScene):
logging.basicConfig(level=log_level)
kwargs = {
"resolution": (800, 600),
"scene_kwargs": {
"set_up": setup,
}
}
with GameEngine(starting_scene, **kwarg... | Run a small game.
The resolution will 800 pixels wide by 600 pixels tall.
setup is a callable that accepts a scene and returns None.
log_level let's you set the expected log level. Consider logging.DEBUG if
something is behaving oddly.
starting_scene let's you change the scene used by the engine... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/__init__.py#L10-L34 | null | import logging
from typing import Callable
from ppb.vector import Vector
from ppb.engine import GameEngine
from ppb.scenes import BaseScene
from ppb.sprites import BaseSprite
|
ppb/pursuedpybear | ppb/scenes.py | GameObjectCollection.add | python | def add(self, game_object: Hashable, tags: Iterable[Hashable]=()) -> None:
if isinstance(tags, (str, bytes)):
raise TypeError("You passed a string instead of an iterable, this probably isn't what you intended.\n\nTry making it a tuple.")
self.all.add(game_object)
for kind in type(ga... | Add a game_object to the container.
game_object: Any Hashable object. The item to be added.
tags: An iterable of Hashable objects. Values that can be used to
retrieve a group containing the game_object.
Examples:
container.add(MyObject())
container.add(My... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L35-L55 | null | class GameObjectCollection(Collection):
"""A container for game objects."""
def __init__(self):
self.all = set()
self.kinds = defaultdict(set)
self.tags = defaultdict(set)
def __contains__(self, item: Hashable) -> bool:
return item in self.all
def __iter__(self) -> Ite... |
ppb/pursuedpybear | ppb/scenes.py | GameObjectCollection.get | python | def get(self, *, kind: Type=None, tag: Hashable=None, **_) -> Iterator:
if kind is None and tag is None:
raise TypeError("get() takes at least one keyword-only argument. 'kind' or 'tag'.")
kinds = self.all
tags = self.all
if kind is not None:
kinds = self.kinds[ki... | Get an iterator of objects by kind or tag.
kind: Any type. Pass to get a subset of contained items with the given
type.
tag: Any Hashable object. Pass to get a subset of contained items with
the given tag.
Pass both kind and tag to get objects that are both that type... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L57-L84 | null | class GameObjectCollection(Collection):
"""A container for game objects."""
def __init__(self):
self.all = set()
self.kinds = defaultdict(set)
self.tags = defaultdict(set)
def __contains__(self, item: Hashable) -> bool:
return item in self.all
def __iter__(self) -> Ite... |
ppb/pursuedpybear | ppb/scenes.py | GameObjectCollection.remove | python | def remove(self, game_object: Hashable) -> None:
self.all.remove(game_object)
for kind in type(game_object).mro():
self.kinds[kind].remove(game_object)
for s in self.tags.values():
s.discard(game_object) | Remove the given object from the container.
game_object: A hashable contained by container.
Example:
container.remove(myObject) | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L86-L99 | null | class GameObjectCollection(Collection):
"""A container for game objects."""
def __init__(self):
self.all = set()
self.kinds = defaultdict(set)
self.tags = defaultdict(set)
def __contains__(self, item: Hashable) -> bool:
return item in self.all
def __iter__(self) -> Ite... |
ppb/pursuedpybear | ppb/scenes.py | BaseScene.change | python | def change(self) -> Tuple[bool, dict]:
next = self.next
self.next = None
if self.next or not self.running:
message = "The Scene.change interface is deprecated. Use the events commands instead."
warn(message, DeprecationWarning)
return self.running, {"scene_class"... | Default case, override in subclass as necessary. | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L144-L154 | null | class BaseScene(Scene, EventMixin):
# Background color, in RGB, each channel is 0-255
background_color: Sequence[int] = (0, 0, 100)
container_class: Type = GameObjectCollection
def __init__(self, engine, *,
set_up: Callable=None, pixel_ratio: Number=64,
... |
ppb/pursuedpybear | ppb/scenes.py | BaseScene.add | python | def add(self, game_object: Hashable, tags: Iterable=())-> None:
self.game_objects.add(game_object, tags) | Add a game_object to the scene.
game_object: Any GameObject object. The item to be added.
tags: An iterable of Hashable objects. Values that can be used to
retrieve a group containing the game_object.
Examples:
scene.add(MyGameObject())
scene.add(MyGameOb... | train | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/scenes.py#L156-L169 | null | class BaseScene(Scene, EventMixin):
# Background color, in RGB, each channel is 0-255
background_color: Sequence[int] = (0, 0, 100)
container_class: Type = GameObjectCollection
def __init__(self, engine, *,
set_up: Callable=None, pixel_ratio: Number=64,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.