Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def visit_importfrom(self, node):
'''triggered when a from statement is seen'''
module_filename = node.root().file
if fnmatch.fnmatch(module_filename, '__init__.py*') and \
not fnmatch.fnmatch(module_filename, 'test_*.py*'):
... | [] |
Please provide a description of the function:def _check_blacklisted_module(self, node, mod_path):
'''check if the module is blacklisted'''
for mod_name in self.blacklisted_modules:
if mod_path == mod_name or mod_path.startswith(mod_name + '.'):
names = []
for ... | [] |
Please provide a description of the function:def visit_import(self, node):
'''triggered when an import statement is seen'''
if self.process_module:
# Store salt imported modules
for module, import_as in node.names:
if not module.startswith('salt'):
... | [] |
Please provide a description of the function:def visit_importfrom(self, node):
'''triggered when a from statement is seen'''
if self.process_module:
if not node.modname.startswith('salt'):
return
# Store salt imported modules
for module, import_as in n... | [] |
Please provide a description of the function:def register(linter):
'''
Register the transformation functions.
'''
try:
MANAGER.register_transform(nodes.Class, rootlogger_transform)
except AttributeError:
MANAGER.register_transform(nodes.ClassDef, rootlogger_transform) | [] |
Please provide a description of the function:def register(linter):
'''
required method to auto register this checker
'''
if HAS_PEP8 is False:
return
linter.register_checker(PEP8Indentation(linter))
linter.register_checker(PEP8Whitespace(linter))
linter.register_checker(PEP8BlankLin... | [] |
Please provide a description of the function:def process_module(self, node):
'''
process a module
the module's content is accessible via node.file_stream object
'''
nodepaths = []
if not isinstance(node.path, list):
nodepaths = [node.path]
else:
... | [] |
Please provide a description of the function:def process_module(self, node):
'''
process a module
'''
if not HAS_PYQVER:
return
minimum_version = tuple([int(x) for x in self.config.minimum_python_version.split('.')])
with open(node.path, 'r') as rfh:
... | [] |
Please provide a description of the function:def get_xblock_settings(self, default=None):
settings_service = self.runtime.service(self, "settings")
if settings_service:
return settings_service.get_settings_bucket(self, default=default)
return default | [
"\n Gets XBlock-specific settigns for current XBlock\n\n Returns default if settings service is not available.\n\n Parameters:\n default - default value to be used in two cases:\n * No settings service is available\n * As a `default` paramete... |
Please provide a description of the function:def get_theme(self):
xblock_settings = self.get_xblock_settings(default={})
if xblock_settings and self.theme_key in xblock_settings:
return xblock_settings[self.theme_key]
return self.default_theme_config | [
"\n Gets theme settings from settings service. Falls back to default (LMS) theme\n if settings service is not available, xblock theme settings are not set or does\n contain mentoring theme settings.\n "
] |
Please provide a description of the function:def include_theme_files(self, fragment):
theme = self.get_theme()
if not theme or 'package' not in theme:
return
theme_package, theme_files = theme.get('package', None), theme.get('locations', [])
resource_loader = Resour... | [
"\n Gets theme configuration and renders theme css into fragment\n "
] |
Please provide a description of the function:def load_unicode(self, resource_path):
resource_content = pkg_resources.resource_string(self.module_name, resource_path)
return resource_content.decode('utf-8') | [
"\n Gets the content of a resource\n "
] |
Please provide a description of the function:def render_django_template(self, template_path, context=None, i18n_service=None):
context = context or {}
context['_i18n_service'] = i18n_service
libraries = {
'i18n': 'xblockutils.templatetags.i18n',
}
# For djan... | [
"\n Evaluate a django template by resource path, applying the provided context.\n "
] |
Please provide a description of the function:def render_mako_template(self, template_path, context=None):
context = context or {}
template_str = self.load_unicode(template_path)
lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])
temp... | [
"\n Evaluate a mako template by resource path, applying the provided context\n "
] |
Please provide a description of the function:def render_template(self, template_path, context=None):
warnings.warn(
"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template"
)
return self.render_django_template(template_path, cont... | [
"\n This function has been deprecated. It calls render_django_template to support backwards compatibility.\n "
] |
Please provide a description of the function:def render_js_template(self, template_path, element_id, context=None):
context = context or {}
return u"<script type='text/template' id='{}'>\n{}\n</script>".format(
element_id,
self.render_template(template_path, context)
... | [
"\n Render a js template.\n "
] |
Please provide a description of the function:def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False):
base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__))
scenario_dir = os.path.join(base_dir, relative_scenario_dir)
scenarios ... | [
"\n Returns an array of (title, xmlcontent) from files contained in a specified directory,\n formatted as expected for the return value of the workbench_scenarios() method.\n\n If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).\n "
] |
Please provide a description of the function:def merge_translation(self, context):
language = get_language()
i18n_service = context.get('_i18n_service', None)
if i18n_service:
# Cache the original translation object to reduce overhead
if language not in self._tra... | [
"\n Context wrapper which modifies the given language's translation catalog using the i18n service, if found.\n "
] |
Please provide a description of the function:def render(self, context):
with self.merge_translation(context):
django_translated = self.do_translate.render(context)
return django_translated | [
"\n Renders the translated text using the XBlock i18n service, if available.\n "
] |
Please provide a description of the function:def studio_view(self, context):
fragment = Fragment()
context = {'fields': []}
# Build a list of all the fields that can be edited:
for field_name in self.editable_fields:
field = self.fields[field_name]
assert... | [
"\n Render a form for editing this XBlock\n "
] |
Please provide a description of the function:def _make_field_info(self, field_name, field):
supported_field_types = (
(Integer, 'integer'),
(Float, 'float'),
(Boolean, 'boolean'),
(String, 'string'),
(List, 'list'),
(DateTime, 'dat... | [
"\n Create the information that the template needs to render a form field for this field.\n ",
" Dummy ugettext method that doesn't do anything "
] |
Please provide a description of the function:def submit_studio_edits(self, data, suffix=''):
values = {} # dict of new field values we are updating
to_reset = [] # list of field names to delete from this XBlock
for field_name in self.editable_fields:
field = self.fields[fi... | [
"\n AJAX handler for studio_view() Save button\n "
] |
Please provide a description of the function:def validate(self):
validation = super(StudioEditableXBlockMixin, self).validate()
self.validate_field_data(validation, self)
return validation | [
"\n Validates the state of this XBlock.\n\n Subclasses should override validate_field_data() to validate fields and override this\n only for validation not related to this block's field values.\n "
] |
Please provide a description of the function:def render_children(self, context, fragment, can_reorder=True, can_add=False):
contents = []
child_context = {'reorderable_items': set()}
if context:
child_context.update(context)
for child_id in self.children:
... | [
"\n Renders the children of the module with HTML appropriate for Studio. If can_reorder is\n True, then the children will be rendered to support drag and drop.\n "
] |
Please provide a description of the function:def author_view(self, context):
root_xblock = context.get('root_xblock')
if root_xblock and root_xblock.location == self.location:
# User has clicked the "View" link. Show an editable preview of this block's children
return s... | [
"\n Display a the studio editor when the user has clicked \"View\" to see the container view,\n otherwise just show the normal 'author_preview_view' or 'student_view' preview.\n "
] |
Please provide a description of the function:def author_edit_view(self, context):
fragment = Fragment()
self.render_children(context, fragment, can_reorder=True, can_add=False)
return fragment | [
"\n Child blocks can override this to control the view shown to authors in Studio when\n editing this block's children.\n "
] |
Please provide a description of the function:def preview_view(self, context):
view_to_render = 'author_view' if hasattr(self, 'author_view') else 'student_view'
renderer = getattr(self, view_to_render)
return renderer(context) | [
"\n Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.\n Default implementation uses author_view if available, otherwise falls back to student_view\n Child classes can override this method to control their presentation in preview context\n ... |
Please provide a description of the function:def get_nested_blocks_spec(self):
return [
block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec)
for block_spec in self.allowed_nested_blocks
] | [
"\n Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface\n "
] |
Please provide a description of the function:def author_edit_view(self, context):
fragment = Fragment()
if 'wrap_children' in context:
fragment.add_content(context['wrap_children']['head'])
self.render_children(context, fragment, can_reorder=True, can_add=False)
i... | [
"\n View for adding/editing nested blocks\n "
] |
Please provide a description of the function:def author_preview_view(self, context):
children_contents = []
fragment = Fragment()
for child_id in self.children:
child = self.runtime.get_block(child_id)
child_fragment = self._render_child_fragment(child, context,... | [
"\n View for previewing contents in studio.\n "
] |
Please provide a description of the function:def _render_child_fragment(self, child, context, view='student_view'):
try:
child_fragment = child.render(view, context)
except NoSuchViewError:
if child.scope_ids.block_type == 'html' and getattr(self.runtime, 'is_author_mode... | [
"\n Helper method to overcome html block rendering quirks\n "
] |
Please provide a description of the function:def package_data(pkg, root_list):
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, root)):
for fname in files:
data.append(os.path.relpath(os.path.join(dirname, fname), pkg))
return {pkg... | [
"Generic function to find package_data for `pkg` under `root`."
] |
Please provide a description of the function:def load_requirements(*requirements_paths):
requirements = set()
for path in requirements_paths:
requirements.update(
line.split('#')[0].strip() for line in open(path).readlines()
if is_requirement(line.strip())
)
retu... | [
"\n Load all requirements from the specified requirements files.\n Returns a list of requirement strings.\n "
] |
Please provide a description of the function:def is_requirement(line):
return not (
line == '' or
line.startswith('-r') or
line.startswith('#') or
line.startswith('-e') or
line.startswith('git+')
) | [
"\n Return True if the requirement line is a package requirement;\n that is, it is not blank, a comment, a URL, or an included file.\n "
] |
Please provide a description of the function:def publish_event(self, data, suffix=''):
try:
event_type = data.pop('event_type')
except KeyError:
return {'result': 'error', 'message': 'Missing event_type in JSON data'}
return self.publish_event_from_dict(event_ty... | [
"\n AJAX handler to allow client-side code to publish a server-side event\n "
] |
Please provide a description of the function:def publish_event_from_dict(self, event_type, data):
for key, value in self.additional_publish_event_data.items():
if key in data:
return {'result': 'error', 'message': 'Key should not be in publish_event data: {}'.format(key)}
... | [
"\n Combine 'data' with self.additional_publish_event_data and publish an event\n "
] |
Please provide a description of the function:def child_isinstance(block, child_id, block_class_or_mixin):
def_id = block.runtime.id_reader.get_definition_id(child_id)
type_name = block.runtime.id_reader.get_block_type(def_id)
child_class = block.runtime.load_block_type(type_name)
return issubclass(... | [
"\n Efficiently check if a child of an XBlock is an instance of the given class.\n\n Arguments:\n block -- the parent (or ancestor) of the child block in question\n child_id -- the usage key of the child block we are wondering about\n block_class_or_mixin -- We return true if block's child indentifie... |
Please provide a description of the function:def attr(self, *args, **kwargs):
kwargs.update({k: bool for k in args})
for key, value in kwargs.items():
if key == "klass":
self.attrs["klass"].update(value.split())
elif key == "style":
if isi... | [
"Add an attribute to the element"
] |
Please provide a description of the function:def remove_attr(self, attr):
self._stable = False
self.attrs.pop(attr, None)
return self | [
"Removes an attribute."
] |
Please provide a description of the function:def render_attrs(self):
ret = []
for k, v in self.attrs.items():
if v:
if v is bool:
ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k))
else:
fnc = self._FORMAT_ATTRS.... | [
"Renders the tag's attributes using the formats and performing special attributes name substitution."
] |
Please provide a description of the function:def toggle_class(self, csscl):
self._stable = False
action = ("add", "remove")[self.has_class(csscl)]
return getattr(self.attrs["klass"], action)(csscl) | [
"Same as jQuery's toggleClass function. It toggles the css class on this element."
] |
Please provide a description of the function:def add_class(self, cssclass):
if self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | [
"Adds a css class to this element."
] |
Please provide a description of the function:def remove_class(self, cssclass):
if not self.has_class(cssclass):
return self
return self.toggle_class(cssclass) | [
"Removes the given class from this element."
] |
Please provide a description of the function:def css(self, *props, **kwprops):
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, p... | [
"Adds css properties to this element."
] |
Please provide a description of the function:def show(self, display=None):
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self | [
"Removes the display style attribute.\n If a display type is provided "
] |
Please provide a description of the function:def toggle(self):
self._stable = False
return self.show() if self.attrs["style"]["display"] == "none" else self.hide() | [
"Same as jQuery's toggle, toggles the display attribute of this element."
] |
Please provide a description of the function:def text(self):
texts = []
for child in self.childs:
if isinstance(child, Tag):
texts.append(child.text())
elif isinstance(child, Content):
texts.append(child.render())
else:
... | [
"Renders the contents inside this element, without html tags."
] |
Please provide a description of the function:def render(self, *args, **kwargs):
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop("pretty", False)
if pretty and self._stable != "pretty":
self._stab... | [
"Renders the element and all his childrens."
] |
Please provide a description of the function:def _make_tempy_tag(self, tag, attrs, void):
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknown_tag_maker, self.unknown_tag_maker.Void][void]
tempy_tag_cls = unknow_m... | [
"Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to\n create a custom tag."
] |
Please provide a description of the function:def from_string(self, html_string):
self._html_parser._reset().feed(html_string)
return self._html_parser.result | [
"Parses an html string and returns a list of Tempy trees."
] |
Please provide a description of the function:def dump(self, tempy_tree_list, filename, pretty=False):
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
... | [
"Dumps a Tempy object to a python file"
] |
Please provide a description of the function:def _filter_classes(cls_list, cls_type):
for cls in cls_list:
if isinstance(cls, type) and issubclass(cls, cls_type):
if cls_type == TempyPlace and cls._base_place:
pass
else:
yield cls | [
"Filters a list of classes and yields TempyREPR subclasses"
] |
Please provide a description of the function:def _evaluate_tempyREPR(self, child, repr_cls):
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR have the same name of the container
score += 1
elif repr_cls.__name__ == self.root.__cl... | [
"Assign a score ito a TempyRepr class.\n The scores depends on the current scope and position of the object in which the TempyREPR is found."
] |
Please provide a description of the function:def _search_for_view(self, obj):
evaluator = partial(self._evaluate_tempyREPR, obj)
sorted_reprs = sorted(
_filter_classes(obj.__class__.__dict__.values(), TempyREPR),
key=evaluator,
reverse=True,
)
... | [
"Searches for TempyREPR class declarations in the child's class.\n If at least one TempyREPR is found, it uses the best one to make a Tempy object.\n Otherwise the original object is returned.\n "
] |
Please provide a description of the function:def set_charset(self, charset):
self.head.charset.attr(charset=charset)
return self | [
"Changes the <meta> charset tag (default charset in init is UTF-8)."
] |
Please provide a description of the function:def set_description(self, description):
self.head.description.attr(content=description)
return self | [
"Changes the <meta> description tag."
] |
Please provide a description of the function:def set_keywords(self, keywords):
self.head.keywords.attr(content=", ".join(keywords))
return self | [
"Changes the <meta> keywords tag."
] |
Please provide a description of the function:def set_title(self, title):
self.head.title.attr(content=title)
return self | [
"Changes the <meta> title tag."
] |
Please provide a description of the function:def populate(self, data, resize_x=True, normalize=True):
if data is None:
raise WidgetDataError(
self,
"Parameter data should be non-None, to empty the table use TempyTable.clear() or "
"pass an emp... | [
"Adds/Replace data in the table.\n data: an iterable of iterables in the form [[col1, col2, col3], [col1, col2, col3]]\n resize_x: if True, changes the x-size of the table according to the given data.\n If False and data have dimensions different from the existing table structure a WidgetDa... |
Please provide a description of the function:def add_row(self, row_data, resize_x=True):
if not resize_x:
self._check_row_size(row_data)
self.body(Tr()(Td()(cell) for cell in row_data))
return self | [
"Adds a row at the end of the table"
] |
Please provide a description of the function:def pop_row(self, idr=None, tags=False):
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row] | [
"Pops a row, default the last"
] |
Please provide a description of the function:def pop_cell(self, idy=None, idx=None, tags=False):
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.childs[0] | [
"Pops a cell, default the last of the last row"
] |
Please provide a description of the function:def make_caption(self, caption):
if not hasattr(self, "caption"):
self(caption=Caption())
return self.caption.empty()(caption) | [
"Adds/Substitutes the table's caption."
] |
Please provide a description of the function:def make_scope(self, col_scope_list=None, row_scope_list=None):
if col_scope_list is not None and len(col_scope_list) > 0:
self.apply_scope(col_scope_list, "col")
if row_scope_list is not None and len(row_scope_list) > 0:
sel... | [
"Makes scopes and converts Td to Th for given arguments\n which represent lists of tuples (row_index, col_index)"
] |
Please provide a description of the function:def populate(self, struct):
if struct is None:
# Maybe raise? Empty the list?
return self
if isinstance(struct, (list, set, tuple)):
struct = dict(zip_longest(struct, [None]))
if not isinstance(struct, di... | [
"Generates the list tree.\n struct: if a list/set/tuple is given, a flat list is generated\n <*l><li>v1</li><li>v2</li>...</*l>\n If the list type is 'Dl' a flat list without definitions is generated\n <*l><dt>v1</dt><dt>v2</dt>...</*l>\n\n If the given struct is a dict, key conta... |
Please provide a description of the function:def render(self, *args, **kwargs):
return self.doctype.render() + super().render(*args, **kwargs) | [
"Override so each html page served have a doctype"
] |
Please provide a description of the function:def render(self, *args, **kwargs):
if not self.childs and "href" in self.attrs:
return self.clone()(self.attrs["href"]).render(*args, **kwargs)
return super().render(*args, **kwargs) | [
"Override of the rendering so that if the link have no text in it, the href is used inside the <a> tag"
] |
Please provide a description of the function:def _find_content(self, cont_name):
try:
a = self.content_data[cont_name]
return a
except KeyError:
if self.parent:
return self.parent._find_content(cont_name)
else:
# Fa... | [
"Search for a content_name in the content data, if not found the parent is searched."
] |
Please provide a description of the function:def _get_non_tempy_contents(self):
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing | [
"Returns rendered Contents and non-DOMElement stuff inside this Tag."
] |
Please provide a description of the function:def siblings(self):
return list(filter(lambda x: id(x) != id(self), self.parent.childs)) | [
"Returns all the siblings of this element as a list."
] |
Please provide a description of the function:def slice(self, start=None, end=None, step=None):
return self.childs[start:end:step] | [
"Slice of this element's childs as childs[start:end:step]"
] |
Please provide a description of the function:def bft(self):
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs) | [
" Generator that returns each element of the tree in Breadth-first order"
] |
Please provide a description of the function:def dfs_preorder(self, reverse=False):
stack = deque()
stack.append(self)
while stack:
node = stack.pop()
yield node
if hasattr(node, "childs"):
if reverse:
stack.extend(... | [
"Generator that returns each element of the tree in Preorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left."
] |
Please provide a description of the function:def dfs_inorder(self, reverse=False):
stack = deque()
visited = set()
visited.add(self)
if reverse:
stack.append(self.childs[0])
stack.append(self)
stack.extend(self.childs[1:])
else:
... | [
"Generator that returns each element of the tree in Inorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left."
] |
Please provide a description of the function:def dfs_postorder(self, reverse=False):
stack = deque()
stack.append(self)
visited = set()
while stack:
node = stack.pop()
if node in visited:
yield node
else:
visite... | [
"Generator that returns each element of the tree in Postorder order.\n Keyword arguments:\n reverse -- if true, the search is done from right to left."
] |
Please provide a description of the function:def content_receiver(reverse=False):
def _receiver(func):
@wraps(func)
def wrapped(inst, *tags, **kwtags):
verse = (1, -1)[int(reverse)]
kwtags = kwtags.items()
i = 0
fo... | [
"Decorator for content adding methods.\n Takes args and kwargs and calls the decorated method one time for each argument provided.\n The reverse parameter should be used for prepending (relative to self) methods.\n "
] |
Please provide a description of the function:def _insert(self, dom_group, idx=None, prepend=False, name=None):
if idx and idx < 0:
idx = 0
if prepend:
idx = 0
else:
idx = idx if idx is not None else len(self.childs)
if dom_group is not None:
... | [
"Inserts a DOMGroup inside this element.\n If provided at the given index, if prepend at the start of the childs list, by default at the end.\n If the child is a DOMElement, correctly links the child.\n If the DOMGroup have a name, an attribute containing the child is created in this instance.\... |
Please provide a description of the function:def after(self, i, sibling, name=None):
self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
return self | [
"Adds siblings after the current tag."
] |
Please provide a description of the function:def prepend(self, _, child, name=None):
self._insert(child, prepend=True, name=name)
return self | [
"Adds childs to this tag, starting from the first position."
] |
Please provide a description of the function:def append(self, _, child, name=None):
self._insert(child, name=name)
return self | [
"Adds childs to this tag, after the current existing childs."
] |
Please provide a description of the function:def wrap(self, other):
if other.childs:
raise TagError(self, "Wrapping in a non empty Tag is forbidden.")
if self.parent:
self.before(other)
self.parent.pop(self._own_index)
other.append(self)
retur... | [
"Wraps this element inside another empty tag."
] |
Please provide a description of the function:def wrap_many(self, *args, strict=False):
for arg in args:
is_elem = arg and isinstance(arg, DOMElement)
is_elem_iter = (
not is_elem and arg and isinstance(arg, Iterable) and isinstance(iter(arg).__next__(), DOMEleme... | [
"Wraps different copies of this element inside all empty tags\n listed in params or param's (non-empty) iterators.\n\n Returns list of copies of this element wrapped inside args\n or None if not succeeded, in the same order and same structure,\n i.e. args = (Div(), (Div())) -> value = (A... |
Please provide a description of the function:def replace_with(self, other):
self.after(other)
self.parent.pop(self._own_index)
return other | [
"Replace this element with the given DOMElement."
] |
Please provide a description of the function:def remove(self):
if self._own_index is not None and self.parent:
self.parent.pop(self._own_index)
return self | [
"Detach this element from his father."
] |
Please provide a description of the function:def _detach_childs(self, idx_from=None, idx_to=None):
idx_from = idx_from or 0
idx_to = idx_to or len(self.childs)
removed = self.childs[idx_from:idx_to]
for child in removed:
if issubclass(child.__class__, DOMElement):
... | [
"Moves all the childs to a new father"
] |
Please provide a description of the function:def move(self, new_father, idx=None, prepend=None, name=None):
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self | [
"Moves this element from his father to the given one."
] |
Please provide a description of the function:def pop(self, arg=None):
self._stable = False
if arg is None:
arg = len(self.childs) - 1
if isinstance(arg, int):
try:
result = self.childs.pop(arg)
except IndexError:
raise ... | [
"Removes the child at given position or by name (or name iterator).\n if no argument is given removes the last."
] |
Please provide a description of the function:def data(self, key=None, **kwargs):
self.content_data.update(kwargs)
if key:
return self.content_data[key]
if not kwargs:
return self.content_data
return self | [
"Adds or retrieve extra data to this element, this data will not be rendered.\n Every tag have a _data attribute (dict), if key is given _data[key] is returned.\n Kwargs are used to udpate this Tag's _data."
] |
Please provide a description of the function:def inject(self, contents=None, **kwargs):
if contents and not isinstance(contents, dict):
raise WrongContentError(self, contents, "contents should be a dict")
self._stable = False
if not contents:
contents = {}
... | [
"\n Adds content data in this element. This will be used in the rendering of this element's childs.\n Multiple injections on the same key will override the content (dict.update behavior).\n "
] |
Please provide a description of the function:def send(self, message):
url = '{0}message'.format(self.remote)
data = self._wrap_post_data(content=message)
res = requests.post(url, data=data, timeout=self.timeout)
if res.status_code == requests.codes.ok:
res_data = jso... | [
"\n 发送基本文字消息\n\n :param message: (必填|str) - 需要发送的文本消息\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n "
] |
Please provide a description of the function:def delay_send(self, content, time, title='', remind=DEFAULT_REMIND_TIME):
url = '{0}delay_message'.format(self.remote)
if isinstance(time, (datetime.datetime, datetime.date)):
time = time.strftime('%Y-%m-%d %H:%M:%S')
if isinstan... | [
"\n 发送延时消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param time: (必填|str|datetime) - 发送消息的开始时间,支持 datetime.date、datetime.datetime 格式或者如 '2017-05-21 10:00:00' 的字符串\n :param title: (选填|str) - 需要发送的消息标题\n :param remind: (选填|int|datetime.timedelta) - 消息提醒时移,默认 1 小时,即早于 time 值 1 小时发送... |
Please provide a description of the function:def periodic_send(self, content, interval, title=''):
url = '{0}periodic_message'.format(self.remote)
if isinstance(interval, datetime.timedelta):
interval = int(interval.total_seconds())
if not isinstance(interval, int):
... | [
"\n 发送周期消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param interval: (必填|int|datetime.timedelta) - 发送消息间隔时间,支持 datetime.timedelta 或 integer 表示的秒数\n :param title: (选填|str) - 需要发送的消息标题\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n "
] |
Please provide a description of the function:def send_to(self, content, search):
url = '{0}send_to_message'.format(self.remote)
if isinstance(search, dict):
search = json.dumps(search)
elif isinstance(search, list):
search = reduce(lambda x, y: '{0} {1}'.format(x... | [
"\n 向指定好友发送消息\n\n :param content: (必填|str) - 需要发送的消息内容\n :param search: (必填|str|dict|list)-搜索对象,同 wxpy.chats.search 使用方法一样。例如,可以使用字符串进行搜索好友或群,或指定具体属性搜索,如 puid=xxx 的字典\n :return: * status:发送状态,True 发送成,False 发送失败\n * message:发送失败详情\n "
] |
Please provide a description of the function:def _read_config_list():
with codecs.open('conf.ini', 'w+', encoding='utf-8') as f1:
conf_list = [conf for conf in f1.read().split('\n') if conf != '']
return conf_list | [
"\n 配置列表读取\n "
] |
Please provide a description of the function:def write_config(name, value):
name = name.lower()
new = True
conf_list = _read_config_list()
for i, conf in enumerate(conf_list):
if conf.startswith(name):
conf_list[i] = '{0}={1}'.format(name, value)
new = False
... | [
"\n 配置写入\n "
] |
Please provide a description of the function:def read_config(name):
name = name.lower()
conf_list = _read_config_list()
for conf in conf_list:
if conf.startswith(name):
return conf.split('=')[1].split('#')[0].strip()
return None | [
"\n 配置读取\n "
] |
Please provide a description of the function:def init_receivers(self, receivers):
if not receivers:
self.default_receiver = self.bot.file_helper
return True
if isinstance(receivers, list):
self.default_receiver = receivers[0]
for receiver in recei... | [
"\n 初始化 receivers\n "
] |
Please provide a description of the function:def send_msg(self, msg):
for receiver in msg.receivers:
current_receiver = self.receivers.get(receiver, self.default_receiver)
current_receiver.send_msg(msg) | [
"\n wxpy 发送文本消息的基本封装,这里会进行消息 receiver 识别分发\n "
] |
Please provide a description of the function:def render_message(self):
message = None
if self.title:
message = '标题:{0}'.format(self.title)
if self.message_time:
message = '{0}\n时间:{1}'.format(message, self.time)
if message:
message = '{0}\n内容:... | [
"\n 渲染消息\n\n :return: 渲染后的消息\n "
] |
Please provide a description of the function:def generate_run_info():
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(glb.run_info.create_time())
memory_usage = glb.run_info.memory_info().rss
msg = '[当前时间] {now:%H:%M:%S}\n[运行时间] {uptime}\n[内存占用] {memory}\n[发送消息] {messages}'.format(
... | [
"\n 获取当前运行状态\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.