text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_name(self, name, style_type = None): """Find style by it's descriptive name. :Returns: Returns found style of type :class:`ooxml.doc.Style`. """
for st in self.styles.values(): if st: if st.name == name: return st if style_type and not st: st = self.styles.get(self.default_styles[style_type], None) return st
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_id(self, style_id, style_type = None): """Find style by it's unique identifier :Returns: Returns found style of type :class:`ooxml.doc.Style`. """
for st in self.styles.values(): if st: if st.style_id == style_id: return st if style_type: return self.styles.get(self.default_styles[style_type], None) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_affinity(affinity=None): """Get or set the CPU affinity set for the current process. This will affect all future threads spawned by this process. It ...
if affinity is not None: affinity = CPUSet(affinity) if not affinity.issubset(system_affinity()): raise ValueError("unknown cpus: %s" % affinity) return system_affinity()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire(self,blocking=True,timeout=None): """Attempt to acquire this lock. If the optional argument "blocking" is True and "timeout" is None, this methods bl...
if timeout is None: return self.__lock.acquire(blocking) else: # Simulated timeout using progressively longer sleeps. # This is the same timeout scheme used in the stdlib Condition # class. If there's lots of contention on the lock then there's ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_thread(cls,thread): """Convert a vanilla thread object into an instance of this class. This method "upgrades" a vanilla thread object to an instance of ...
new_classes = [] for new_cls in cls.__mro__: if new_cls not in thread.__class__.__mro__: new_classes.append(new_cls) if isinstance(thread,cls): pass elif issubclass(cls,thread.__class__): thread.__class__ = cls else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire(self,blocking=True,timeout=None,shared=False): """Acquire the lock in shared or exclusive mode."""
with self._lock: if shared: self._acquire_shared(blocking,timeout) else: self._acquire_exclusive(blocking,timeout) assert not (self.is_shared and self.is_exclusive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_font_size(document, style): """Get font size defined for this style. It will try to get font size from it's parent style if it is not defined by origina...
font_size = style.get_font_size() if font_size == -1: if style.based_on: based_on = document.styles.get_by_id(style.based_on) if based_on: return _get_font_size(document, based_on) return font_size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_numbering(document, numid, ilvl): """Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error....
try: abs_num = document.numbering[numid] return document.abstruct_numbering[abs_num][ilvl]['numFmt'] except: return 'bullet'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_parent(root): """Returns root element for a list. :Args: root (Element): lxml element of current location :Returns: lxml element representing list """
elem = root while True: elem = elem.getparent() if elem.tag in ['ul', 'ol']: return elem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_list(ctx, root): """Close already opened list if needed. This will try to see if it is needed to close already opened list. :Args: - ctx (:class:`Conte...
try: n = len(ctx.in_list) if n <= 0: return root elem = root while n > 0: while True: if elem.tag in ['ul', 'ol', 'td']: elem = elem.getparent() break elem = elem....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_list(ctx, document, par, root, elem): """Open list if it is needed and place current element as first member of a list. :Args: - ctx (:class:`Context`):...
_ls = None if par.ilvl != ctx.ilvl or par.numid != ctx.numid: # start if ctx.ilvl is not None and (par.ilvl > ctx.ilvl): fmt = _get_numbering(document, par.numid, par.ilvl) if par.ilvl > 0: # get last <li> in <ul> # could be nicer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_break(ctx, document, elem, root): "Serialize break element." if elem.break_type == u'textWrapping': _div = etree.SubElement(root, 'br') else: _div = etree.SubElement(root, 'span') if ctx.options['embed_styles']: _div.set('style', 'page-break-after: always;'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_math(ctx, document, elem, root): """Serialize math element. Math objects are not supported at the moment. This is wht we only show error message. "...
_div = etree.SubElement(root, 'span') if ctx.options['embed_styles']: _div.set('style', 'border: 1px solid red') _div.text = 'We do not support Math blocks at the moment.' fire_hooks(ctx, document, elem, _div, ctx.get_hook('math')) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_link(ctx, document, elem, root): """Serilaze link element. This works only for external links at the moment. """
_a = etree.SubElement(root, 'a') for el in elem.elements: _ser = ctx.get_serializer(el) if _ser: _td = _ser(ctx, document, el, _a) else: if isinstance(el, doc.Text): children = list(_a) if len(children) == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_image(ctx, document, elem, root): """Serialize image element. This is not abstract enough. """
_img = etree.SubElement(root, 'img') # make path configurable if elem.rid in document.relationships[ctx.options['relationship']]: img_src = document.relationships[ctx.options['relationship']][elem.rid].get('target', '') img_name, img_extension = os.path.splitext(img_src) _img.set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire_hooks(ctx, document, elem, element, hooks): """Fire hooks on newly created element. For each newly created element we will try to find defined hooks and...
if not hooks: return for hook in hooks: hook(ctx, document, elem, element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_style(node): """Tells us if node element has defined styling. :Args: - node (:class:`ooxml.doc.Element`): Element :Returns: True or False """
elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps'] return any([True for elem in elements if elem in node.rpr])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_style_css(ctx, node, embed=True, fontsize=-1): """Returns as string defined CSS for this node. Defined CSS can be different if it is embeded or no. When ...
style = [] if not node: return if fontsize in [-1, 2]: if 'sz' in node.rpr: size = int(node.rpr['sz']) / 2 if ctx.options['embed_fontsize']: if ctx.options['scale_to_size']: multiplier = size-ctx.options['scale_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_styles(document, style): """Returns list of styles on which specified style is based on. :Args: - document (:class:`ooxml.doc.Document`): Document o...
classes = [] while True: classes.insert(0, get_style_name(style)) if style.based_on: style = document.styles.get_by_id(style.based_on) else: break return classes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_css_classes(document, style): """Returns CSS classes for this style. This function will check all the styles specified style is based on and return their...
lst = [st.lower() for st in get_all_styles(document, style)[-1:]] + \ ['{}-fontsize'.format(st.lower()) for st in get_all_styles(document, style)[-1:]] return ' '.join(lst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_symbol(ctx, document, el, root): "Serialize special symbols." span = etree.SubElement(root, 'span') span.text = el.value() fire_hooks(ctx, document, el, span, ctx.get_hook('symbol')) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_footnote(ctx, document, el, root): "Serializes footnotes." footnote_num = el.rid if el.rid not in ctx.footnote_list: ctx.footnote_id += 1 ctx.footnote_list[el.rid] = ctx.footnote_id footnote_num = ctx.footnote_list[el.rid] note = etree.SubElement(root, 'sup') li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_comment(ctx, document, el, root): "Serializes comment." # Check if option is turned on if el.comment_type == 'end': ctx.opened_comments.remove(el.cid) else: if el.comment_type != 'reference': ctx.opened_comments.append(el.cid) if ctx.options['comment_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_endnote(ctx, document, el, root): "Serializes endnotes." footnote_num = el.rid if el.rid not in ctx.endnote_list: ctx.endnote_id += 1 ctx.endnote_list[el.rid] = ctx.endnote_id footnote_num = ctx.endnote_list[el.rid] note = etree.SubElement(root, 'sup') link = et...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize_smarttag(ctx, document, el, root): "Serializes smarttag." if ctx.options['smarttag_span']: _span = etree.SubElement(root, 'span', {'class': 'smarttag', 'data-smarttag-element': el.element}) else: _span = root for elem in el.elements: _ser = ctx.get_serializer(elem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_table(ctx, document, table, root): """Serializes table element. """
# What we should check really is why do we pass None as root element # There is a good chance some content is missing after the import if root is None: return root if ctx.ilvl != None: root = close_list(ctx, root) ctx.ilvl, ctx.numid = None, None _table = etree.SubElemen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_textbox(ctx, document, txtbox, root): """Serialize textbox element."""
_div = etree.SubElement(root, 'div') _div.set('class', 'textbox') for elem in txtbox.elements: _ser = ctx.get_serializer(elem) if _ser: _ser(ctx, document, elem, _div) fire_hooks(ctx, document, txtbox, _div, ctx.get_hook('textbox')) return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_elements(document, elements, options=None): """Serialize list of elements into HTML string. :Args: - document (:class:`ooxml.doc.Document`): Docum...
ctx = Context(document, options) tree_root = root = etree.Element('div') for elem in elements: _ser = ctx.get_serializer(elem) if _ser: root = _ser(ctx, document, elem, root) # TODO: # - create footnotes now return etree.tostring(tree_root, pretty_print=ctx....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_header(self, elem, font_size, node, style=None): """Used for checking if specific element is a header or not. :Returns: True or False """
# This logic has been disabled for now. Mark this as header if it has # been marked during the parsing or mark. # if hasattr(elem, 'possible_header'): # if elem.possible_header: # return True # if not style: # return Fals...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_header(self, elem, style, node): """Returns HTML tag representing specific header for this element. :Returns: String representation of HTML tag. """
font_size = style if hasattr(elem, 'possible_header'): if elem.possible_header: return 'h1' if not style: return 'h6' if hasattr(style, 'style_id'): font_size = _get_font_size(self.doc, style) try: if font_size i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_serializer(self, node): """Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns referen...
return self.options['serializers'].get(type(node), None) if type(node) in self.options['serializers']: return self.options['serializers'][type(node)] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def priority(self,priority): """Set the priority for all threads in this group. If setting priority fails on any thread, the priority of all threads is restored ...
with self.__lock: old_priorities = {} try: for thread in self.__threads: old_priorities[thread] = thread.priority thread.priority = priority except Exception: for (thread,old_priority) in old_priorities....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def affinity(self,affinity): """Set the affinity for all threads in this group. If setting affinity fails on any thread, the affinity of all threads is restored ...
with self.__lock: old_affinities = {} try: for thread in self.__threads: old_affinities[thread] = thread.affinity thread.affinity = affinity except Exception: for (thread,old_affinity) in old_affinities....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(self,timeout=None): """Join all threads in this group. If the optional "timeout" argument is given, give up after that many seconds. This method returns...
if timeout is None: for thread in self.__threads: thread.join() else: deadline = _time() + timeout for thread in self.__threads: delay = deadline - _time() if delay <= 0: return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_length(elem): """Returns length of the content in this element. Return value is not correct but it is **good enough***. """
if not elem: return 0 value = elem.value() try: value = len(value) except: value = 0 try: for a in elem.elements: value += len(a.value()) except: pass return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reset(self): "Resets the values." self.zf = zipfile.ZipFile(self.file_name, 'r') self._doc = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_rrule(count=None, interval=None, bysecond=None, byminute=None, byhour=None, byweekno=None, bymonthday=None, byyearday=None, bymonth=None, until=None, by...
result = {} if count is not None: result['COUNT'] = count if interval is not None: result['INTERVAL'] = interval if bysecond is not None: result['BYSECOND'] = bysecond if byminute is not None: result['BYMINUTE'] = byminute if byhour is not None: resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_rrule_from_recurrences_rrule(rule): """ Build rrule dictionary for vRecur class from a django_recurrences rrule. django_recurrences is a popular implem...
from recurrence import serialize line = serialize(rule) if line.startswith('RRULE:'): line = line[6:] return build_rrule_from_text(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_rrule_from_dateutil_rrule(rule): """ Build rrule dictionary for vRecur class from a dateutil rrule. Dateutils rrule is a popular implementation of rrul...
lines = str(rule).splitlines() for line in lines: if line.startswith('DTSTART:'): continue if line.startswith('RRULE:'): line = line[6:] return build_rrule_from_text(line)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, outfile, encoding): u""" Writes the feed to the specified file in the specified encoding. """
cal = Calendar() cal.add('version', '2.0') cal.add('calscale', 'GREGORIAN') for ifield, efield in FEED_FIELD_MAP: val = self.feed.get(ifield) if val is not None: cal.add(efield, val) self.write_items(cal) to_ical = getattr(cal, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_items(self, calendar): """ Write all events to the calendar """
for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_FIELD_MAP: val = item.get(ifield) if val is not None: event.add(efield, val) calendar.add_component(event)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _textlist(self, _addtail=False): '''Returns a list of text strings contained within an element and its sub-elements. Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook). ''' result = [] if (not _addtail) and (self.text is not None): result.append(self.text) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reindent(s, indent, reformat=True): """ Remove the existing indentation from each line of a chunk of text, s, and then prefix each line with a new indent st...
s = textwrap.dedent(s) s = s.split('\n') s = [x.rstrip() for x in s] while s and (not s[0]): s = s[1:] while s and (not s[-1]): s = s[:-1] if reformat: s = '\n'.join(s) s = textwrap.wrap(s, initial_indent=indent, subsequent_indent=indent) else: s = [i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_docstr(element, indent='', wrap=None): """ Generate a Python docstr for a given element in the AMQP XML spec file. The element could be a class or m...
result = [] txt = element.text and element.text.rstrip() if txt: result.append(_reindent(txt, indent)) result.append(indent) for d in element.findall('doc') + element.findall('rule'): docval = ''.join(d.textlist()).rstrip() if not docval: continue r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_module(spec, out): """ Given an AMQP spec parsed into an xml.etree.ElemenTree, and a file-like 'out' object to write to, generate the skeleton of a ...
# # HACK THE SPEC so that 'access' is handled by 'channel' instead of 'connection' # for amqp_class in spec.findall('class'): if amqp_class.attrib['name'] == 'access': amqp_class.attrib['handler'] = 'channel' # # Build up some helper dictionaries # for domain in spe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_method_frame(self, channel, payload): """ Process Method frames """
method_sig = unpack('>HH', payload[:4]) args = AMQPReader(payload[4:]) if method_sig in _CONTENT_METHODS: # # Save what we've got so far and wait for the content-header # self.partial_messages[channel] = _PartialMessage(method_sig, args) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _alert(self, args): """ This method allows the server to send a non-fatal warning to the client. This is used for methods that are normally asynchronous and ...
reply_code = args.read_short() reply_text = args.read_shortstr() details = args.read_table() self.alerts.put((reply_code, reply_text, details))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def access_request(self, realm, exclusive=False, passive=False, active=False, write=False, read=False): """ request an access ticket This method requests an acce...
args = AMQPWriter() args.write_shortstr(realm) args.write_bit(exclusive) args.write_bit(passive) args.write_bit(active) args.write_bit(write) args.write_bit(read) self._send_method((30, 10), args) return self.wait(allowed_methods=[ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, internal=False, nowait=False, arguments=None, ticket=None): """ declar...
if arguments is None: arguments = {} args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(exchange) args.write_shortstr(type) args.write_bit(passiv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exchange_delete(self, exchange, if_unused=False, nowait=False, ticket=None): """ delete an exchange This method deletes an exchange. When an exchange is dele...
args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(exchange) args.write_bit(if_unused) args.write_bit(nowait) self._send_method((40, 20), args) if no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_bind(self, queue, exchange, routing_key='', nowait=False, arguments=None, ticket=None): """ bind queue to an exchange This method binds a queue to an e...
if arguments is None: arguments = {} args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(queue) args.write_shortstr(exchange) args.write_shortstr(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _queue_declare_ok(self, args): """ confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automa...
queue = args.read_shortstr() message_count = args.read_long() consumer_count = args.read_long() return queue, message_count, consumer_count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, ticket=None): """ start a queue co...
args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(queue) args.write_shortstr(consumer_tag) args.write_bit(no_local) args.write_bit(no_ack) args.write...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _basic_deliver(self, args, msg): """ notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronou...
consumer_tag = args.read_shortstr() delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() msg.delivery_info = { 'channel': self, 'consumer_tag': consumer_tag, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_get(self, queue='', no_ack=False, ticket=None): """ direct access to a queue This method provides a direct access to the messages in a queue using a sy...
args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(queue) args.write_bit(no_ack) self._send_method((60, 70), args) return self.wait(allowed_methods=[ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False, ticket=None): """ publish a message This method publishes a message t...
args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(exchange) args.write_shortstr(routing_key) args.write_bit(mandatory) args.write_bit(immediate) sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _basic_return(self, args, msg): """ return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or...
reply_code = args.read_short() reply_text = args.read_shortstr() exchange = args.read_shortstr() routing_key = args.read_shortstr() self.returned_messages.put( (reply_code, reply_text, exchange, routing_key, msg) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wait_method(self, channel_id, allowed_methods): """ Wait for a method from the server destined for a particular channel. """
# # Check the channel's deferred methods # method_queue = self.channels[channel_id].method_queue for queued_method in method_queue: method_sig = queued_method[0] if (allowed_methods is None) \ or (method_sig in allowed_methods) \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def channel(self, channel_id=None): """ Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist. """
if channel_id in self.channels: return self.channels[channel_id] return Channel(self, channel_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _close(self, args): """ request a connection close This method indicates that the sender wants to close the connection. This may be due to internal condition...
reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._x_close_ok() raise AMQPConnectionException(reply_code, reply_text, (class_id, method_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _x_open(self, virtual_host, capabilities='', insist=False): """ open connection to virtual host This method opens a connection to a virtual host, which is a ...
args = AMQPWriter() args.write_shortstr(virtual_host) args.write_shortstr(capabilities) args.write_bit(insist) self._send_method((10, 40), args) return self.wait(allowed_methods=[ (10, 41), # Connection.open_ok (10, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _open_ok(self, args): """ signal that the connection is ready This method signals to the client that the connection is ready for use. PARAMETERS: known_hosts...
self.known_hosts = args.read_shortstr() AMQP_LOGGER.debug('Open OK! known_hosts [%s]' % self.known_hosts) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _redirect(self, args): """ asks the client to use a different server This method redirects the client to another server, based on the requested virtual host ...
host = args.read_shortstr() self.known_hosts = args.read_shortstr() AMQP_LOGGER.debug('Redirected to [%s], known_hosts [%s]' % (host, self.known_hosts)) return host
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start(self, args): """ start connection negotiation This method starts the connection negotiation process by telling the client the protocol version that th...
self.version_major = args.read_octet() self.version_minor = args.read_octet() self.server_properties = args.read_table() self.mechanisms = args.read_longstr().split(' ') self.locales = args.read_longstr().split(' ') AMQP_LOGGER.debug('Start from server, version: %d.%d, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _x_start_ok(self, client_properties, mechanism, response, locale): """ select security mechanism and locale This method selects a SASL security mechanism. AS...
args = AMQPWriter() args.write_table(client_properties) args.write_shortstr(mechanism) args.write_longstr(response) args.write_shortstr(locale) self._send_method((10, 11), args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tune(self, args): """ propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accep...
self.channel_max = args.read_short() or self.channel_max self.frame_max = args.read_long() or self.frame_max self.method_writer.frame_max = self.frame_max self.heartbeat = args.read_short() self._x_tune_ok(self.channel_max, self.frame_max, 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_method(self, method_sig, args=bytes(), content=None): """ Send a method for our channel. """
if isinstance(args, AMQPWriter): args = args.getvalue() self.connection.method_writer.write_method(self.channel_id, method_sig, args, content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_frame(self): """ Read an AMQP frame. """
frame_type, channel, size = unpack('>BHI', self._read(7)) payload = self._read(size) ch = ord(self._read(1)) if ch == 206: # '\xce' return frame_type, channel, payload else: raise Exception('Framing Error, received 0x%02x while expecting 0xce' % ch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_frame(self, frame_type, channel, payload): """ Write out an AMQP frame. """
size = len(payload) self._write(pack('>BHI%dsB' % size, frame_type, channel, size, payload, 0xce))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_transport(self): """ Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version. """
if HAVE_PY26_SSL: if hasattr(self, 'sslopts'): self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts) else: self.sslobj = ssl.wrap_socket(self.sock) self.sslobj.do_handshake() else: self.sslobj = socket.ssl(self.sock)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_bit(self, b): """ Write a boolean value. """
if b: b = 1 else: b = 0 shift = self.bitcount % 8 if shift == 0: self.bits.append(0) self.bits[-1] |= (b << shift) self.bitcount += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_unexpected_error(e): # pragma: no cover """Catch-all error handler Unexpected errors will be handled by this function. """
sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(name, description, bucket, timeout, memory, stages, requirements, function, runtime, config_file, **kwargs): """Generate a configuration file."""
if os.path.exists(config_file): raise RuntimeError('Please delete the old version {} if you want to ' 'reconfigure your project.'.format(config_file)) module, app = function.split(':') if not name: name = module.replace('_', '-') if not re.match('^[a-zA-Z][-a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_lambda_handler(config, output='.slam/handler.py'): """Generate a handler.py file for the lambda function start up."""
# Determine what the start up code is. The default is to just run the # function, but it can be overriden by a plugin such as wsgi for a more # elaborated way to run the function. run_function = _run_lambda_function for name, plugin in plugins.items(): if name in config and hasattr(plugin, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(rebuild_deps, config_file): """Build lambda package."""
config = _load_config(config_file) print("Building lambda package...") package = _build(config, rebuild_deps=rebuild_deps) print("{} has been built successfully.".format(package))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file): """Deploy the project to the development stage."""
config = _load_config(config_file) if stage is None: stage = config['devstage'] s3 = boto3.client('s3') cfn = boto3.client('cloudformation') region = _get_aws_region() # obtain previous deployment if it exists previous_deployment = None try: previous_deployment = cfn.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(version, stage, config_file): """Publish a version of the project to a stage."""
config = _load_config(config_file) cfn = boto3.client('cloudformation') if version is None: version = config['devstage'] elif version not in config['stage_environments'].keys() and \ not version.isdigit(): raise ValueError('Invalid version. Use a stage name or a numeric ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke(stage, async, dry_run, config_file, args): """Invoke the lambda function."""
config = _load_config(config_file) if stage is None: stage = config['devstage'] cfn = boto3.client('cloudformation') lmb = boto3.client('lambda') try: stack = cfn.describe_stacks(StackName=config['name'])['Stacks'][0] except botocore.exceptions.ClientError: raise Runti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template(config_file): """Print the default Cloudformation deployment template."""
config = _load_config(config_file) print(get_cfn_template(config, pretty=True))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_plugins(): """find any installed plugins and register them."""
if pkg_resources: # pragma: no cover for ep in pkg_resources.iter_entry_points('slam_plugins'): plugin = ep.load() # add any init options to the main init command if hasattr(plugin, 'init') and hasattr(plugin.init, '_arguments'): for arg in plugin.init....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def synchronise_device_state(self, device_state, authentication_headers): """ Synchronizing the component states with AVS Components state must be synchronised w...
payload = { 'context': device_state, 'event': { 'header': { 'namespace': 'System', 'name': 'SynchronizeState', 'messageId': '' }, 'payload': {} } } mu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_audio_file( self, audio_file, device_state, authentication_headers, dialog_request_id, distance_profile, audio_format ): """ Send audio to AVS The file-...
payload = { 'context': device_state, 'event': { 'header': { 'namespace': 'SpeechRecognizer', 'name': 'Recognize', 'messageId': self.generate_message_id(), 'dialogRequestId': dialog_request_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_api_token(self): """ Retrieve the access token from AVS. This function is memoized, so the value returned by the function will be remembered and ret...
payload = self.oauth2_manager.get_access_token_params( refresh_token=self.refresh_token ) response = requests.post( self.oauth2_manager.access_token_url, json=payload ) response.raise_for_status() response_json = json.loads(response.text) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def webpack_template_tag(path_to_config): """ A template tag that will output a webpack bundle. Usage: {% load webpack %} {% webpack 'path/to/webpack.config.js' ...
# TODO: allow selection of entries # Django's template system silently fails on some exceptions try: return webpack(path_to_config) except (AttributeError, ValueError) as e: raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_key(key, *args, **kwargs): """ if arguments are given, adds a hash of the args to the key. """
if not args and not kwargs: return key items = sorted(kwargs.items()) hashable_args = (args, tuple(items)) args_key = hashlib.md5(pickle.dumps(hashable_args)).hexdigest() return "%s/args:%s" % (key, args_key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(logdir='log'): """ Set up dual logging to console and to logfile. When this function is called, it first creates the given directory. It then creates a...
# Create the root logger. logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Validate the given directory. logdir = os.path.normpath(logdir) # Create a folder for the logfiles. if not os.path.exists(logdir): os.makedirs(logdir) # Construct the logfile name. t ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_versions() -> FileVersionResult: """ Search specific project files and extract versions to check. :return: A FileVersionResult object for reporting. """
version_counter = Counter() versions_match = False version_str = None versions_discovered = OrderedDict() for version_obj in version_objects: discovered = version_obj.get_version() versions_discovered[version_obj.key_name] = discovered version_counter.update([discovered]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def supportedChars(*tests): """ Takes any number of strings, and returns the first one the terminal encoding supports. If none are supported it returns '?' the l...
for test in tests: try: test.encode(sys.stdout.encoding) return test except UnicodeEncodeError: pass return '?' * len(tests[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def app_templates_dirs(self): """ Build a cached dict with settings.INSTALLED_APPS as keys and the 'templates' directory of each application as values. """
app_templates_dirs = OrderedDict() for app_config in apps.get_app_configs(): templates_dir = os.path.join( getattr(app_config, 'path', '/'), 'templates') if os.path.isdir(templates_dir): templates_dir = upath(templates_dir) app_tem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_contents(self, origin): """ Try to load the origin. """
try: path = self.get_app_template_path( origin.app_name, origin.template_name) with io.open(path, encoding=self.engine.file_charset) as fp: return fp.read() except KeyError: raise TemplateDoesNotExist(origin) except IOError as ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_template_source(self, *ka): """ Backward compatible method for Django < 2.0. """
template_name = ka[0] for origin in self.get_template_sources(template_name): try: return self.get_contents(origin), origin.name except TemplateDoesNotExist: pass raise TemplateDoesNotExist(template_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateImage(image, angle): """ rotates a 2d array to a multiple of 90 deg. 0 = default 1 = 90 deg. cw 2 = 180 deg. 3 = 90 deg. ccw """
image = [list(row) for row in image] for n in range(angle % 4): image = list(zip(*image[::-1])) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlaps(self, canvas, exclude=[]): """ Returns True if sprite is touching any other sprite. """
try: exclude = list(exclude) except TypeError: exclude = [exclude] exclude.append(self) for selfY, row in enumerate(self.image.image()): for selfX, pixel in enumerate(row): canvasPixelOn = canvas.testPixel( (selfX ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onEdge(self, canvas): """ Returns a list of the sides of the sprite which are touching the edge of the canvas. 0 = Bottom 1 = Left 2 = Top 3 = Right """
sides = [] if int(self.position[0]) <= 0: sides.append(1) if (int(self.position[0]) + self.image.width) >= canvas.width: sides.append(3) if int(self.position[1]) <= 0: sides.append(2) if (int(self.position[1]) + self.image.height) >= canvas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remote_property(name, get_command, set_command, field_name, doc=None): """Property decorator that facilitates writing properties for values from a remote dev...
def getter(self): try: return getattr(self, name) except AttributeError: value = getattr(self.sendCommand(get_command()), field_name) setattr(self, name, value) return value def setter(self, value): setattr(self, name, value) sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendCommand(self, command): """Sends a Command object to the MCP2210 and returns its response. Arguments: A commands.Command instance Returns: A commands.Res...
command_data = [ord(x) for x in buffer(command)] self.hid.write(command_data) response_data = ''.join(chr(x) for x in self.hid.read(64)) response = command.RESPONSE.from_buffer_copy(response_data) if response.status != 0: raise CommandException(response.status) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer(self, data): """Transfers data over SPI. Arguments: data: The data to transfer. Returns: The data returned by the SPI device. """
settings = self.transfer_settings settings.spi_tx_size = len(data) self.transfer_settings = settings response = '' for i in range(0, len(data), 60): response += self.sendCommand(commands.SPITransferCommand(data[i:i + 60])).data time.sleep(0.01) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_json_response(self, context_dict, status=200): """ Limited serialization for shipping plain data. Do not use for models or other complex or custom obj...
json_context = json.dumps( context_dict, cls=DjangoJSONEncoder, **self.get_json_dumps_kwargs() ).encode(u'utf-8') return HttpResponse( json_context, content_type=self.get_content_type(), status=status )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_valid(self, form): """ If the request is ajax, save the form and return a json response. Otherwise return super as expected. """
self.object = form.save(commit=False) self.pre_save() self.object.save() if hasattr(form, 'save_m2m'): form.save_m2m() self.post_save() if self.request.is_ajax(): return self.render_json_response(self.get_success_result()) return HttpResp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_invalid(self, form): """ We have errors in the form. If ajax, return them as json. Otherwise, proceed as normal. """
if self.request.is_ajax(): return self.render_json_response(self.get_error_result(form)) return super(AjaxFormMixin, self).form_invalid(form)