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 visit_arguments(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as argument list."""
args = node.args dflts = node.defaults vararg = node.vararg kwargs = node.kwonlyargs kwdflts = node.kw_defaults kwarg = node.kwarg self.compact = True n_args_without_dflt = len(args) - len(dflts) args_src = (arg.arg for arg in args[:n_args_without...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Lambda(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as lambda expression."""
with self.op_man(node): src = f"lambda {self.visit(node.args)}: {self.visit(node.body)}" return self.wrap_expr(src, dfltChaining)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_IfExp(self, node: AST, dfltChaining: bool = True) -> str:
with self.op_man(node): src = " if ".join((self.visit(node.body, dfltChaining=False), " else ".join((self.visit(node.test), self.visit(node.orelse))))) return self.wrap_expr(src, dfltChaining)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Attribute(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as attribute access."""
return '.'.join((self.visit(node.value), node.attr))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Slice(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as slice."""
elems = [self.visit(node.lower), self.visit(node.upper)] if node.step is not None: elems.append(self.visit(node.step)) return ':'.join(elems)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_ExtSlice(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as extended slice."""
return ', '.join((self.visit(dim) for dim in node.dims))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_comprehension(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as comprehension."""
target = node.target try: elts = target.elts # we have a tuple of names except AttributeError: names = self.visit(target) else: names = ', '.join(self.visit(elt) for elt in elts) src = f"for {names} in {self.visit(node.iter)}" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as list comprehension."""
return f"[{self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}]"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_SetComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as set comprehension."""
return f"{{{self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_DictComp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as dict comprehension."""
return f"{{{self.visit(node.key)}: {self.visit(node.value)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)}}}"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_GeneratorExp(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as generator expression."""
return f"({self.visit(node.elt)} " \ f"{' '.join(self.visit(gen) for gen in node.generators)})"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visible_line_width(self, position = Point): """Return the visible width of the text in line buffer up to position."""
extra_char_width = len([ None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD]) return len(self[:position].quoted_text()) + self[:position].line_buffer.count(u"\t")*7 + extra_char_width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run CleanUp."""
import fnmatch import shutil import glob matches = [] matches.extend(glob.glob('./*.pyc')) matches.extend(glob.glob('./*.pyd')) matches.extend(glob.glob('./*.pyo')) matches.extend(glob.glob('./*.so')) dirs = [] dirs.extend(glob.glob('./__p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run git add and commit with message if provided."""
if os.system('git add .'): sys.exit(1) if self.message is not None: os.system('git commit -a -m "' + self.message + '"') else: os.system('git commit -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 uri(self, value): """Set new uri value in record. It will not change the location of the underlying file! """
jsonpointer.set_pointer(self.record, self.pointer, 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 open(self, mode='r', **kwargs): """Open file ``uri`` under the pointer."""
_fs, filename = opener.parse(self.uri) return _fs.open(filename, mode=mode, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, dst, **kwargs): """Move file to a new destination and update ``uri``."""
_fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) movefile(_fs, filename, _fs_dst, filename_dst, **kwargs) self.uri = dst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setcontents(self, source, **kwargs): """Create a new file from a string or file-like object."""
if isinstance(source, six.string_types): _file = opener.open(source, 'rb') else: _file = source # signals.document_before_content_set.send(self) data = _file.read() _fs, filename = opener.parse(self.uri) _fs.setcontents(filename, data, **kwargs)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, force=False): """Remove file reference from record. If force is True it removes the file from filesystem """
if force: _fs, filename = opener.parse(self.uri) _fs.remove(filename) self.uri = 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 tobytes( self, root=None, encoding='UTF-8', doctype=None, canonicalized=True, xml_declaration=True, pretty_print=True, with_comments=True, ): """re...
if root is None: root = self.root if canonicalized == True: return self.canonicalized_bytes(root) else: return etree.tostring( root, encoding=encoding or self.info.encoding, doctype=doctype or self.info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tostring(self, root=None, doctype=None, pretty_print=True): """return the content of the XML document as a unicode string"""
if root is None: root = self.root return etree.tounicode( root, doctype=doctype or self.info.doctype, pretty_print=pretty_print )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def digest(self, **args): """calculate a digest based on the hash of the XML content"""
return String(XML.canonicalized_string(self.root)).digest(**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 element(self, tag_path, test=None, **attributes): """given a tag in xpath form and optional attributes, find the element in self.root or return a new one.""...
xpath = tag_path tests = ["@%s='%s'" % (k, attributes[k]) for k in attributes] if test is not None: tests.insert(0, test) if len(tests) > 0: xpath += "[%s]" % ' and '.join(tests) e = self.find(self.root, xpath) if e is None: 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 namespace(self, elem=None): """return the URL, if any, for the doc root or elem, if given."""
if elem is None: elem = self.root return XML.tag_namespace(elem.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 tag_namespace(cls, tag): """return the namespace for a given tag, or '' if no namespace given"""
md = re.match("^(?:\{([^\}]*)\})", tag) if md is not None: return md.group(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 tag_name(cls, tag): """return the name of the tag, with the namespace removed"""
while isinstance(tag, etree._Element): tag = tag.tag return tag.split('}')[-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 element_map( self, tags=None, xpath="//*", exclude_attribs=[], include_attribs=[], attrib_vals=False, hierarchy=False, minimize=False, ): """return...
if tags is None: tags = Dict() for elem in self.root.xpath(xpath): if elem.tag not in tags.keys(): tags[elem.tag] = Dict(**{'parents': [], 'children': [], 'attributes': Dict()}) for a in [ a for a in elem.attrib...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_key_tag(Class, key, namespaces=None): """convert a dict key into an element or attribute name"""
namespaces = namespaces or Class.NS ns = Class.tag_namespace(key) tag = Class.tag_name(key) if ns is None and ':' in key: prefix, tag = key.split(':') if prefix in namespaces.keys(): ns = namespaces[prefix] if ns is not 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 replace_with_contents(c, elem): "removes an element and leaves its contents in its place. Namespaces supported." parent = elem.getparent() index = parent.index(elem) children = elem.getchildren() previous = elem.getprevious() # text if index == 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 remove_range(cls, elem, end_elem, delete_end=True): """delete everything from elem to end_elem, including elem. if delete_end==True, also including end_ele...
while elem is not None and elem != end_elem and end_elem not in elem.xpath("descendant::*"): parent = elem.getparent() nxt = elem.getnext() parent.remove(elem) if DEBUG == True: print(etree.tounicode(elem)) elem = nxt 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 wrap_content(cls, container, wrapper): "wrap the content of container element with wrapper element" wrapper.text = (container.text or '') + (wrapper.text or '') container.text = '' for ch in container: wrapper.append(ch) container.insert(0, wrapper) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_contiguous(C, node, xpath, namespaces=None): """Within a given node, merge elements that are next to each other if they have the same tag and attrib...
new_node = deepcopy(node) elems = XML.xpath(new_node, xpath, namespaces=namespaces) elems.reverse() for elem in elems: nxt = elem.getnext() if elem.attrib == {}: XML.replace_with_contents(elem) elif ( elem.tail...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unnest(c, elem, ignore_whitespace=False): """unnest the element from its parent within doc. MUTABLE CHANGES"""
parent = elem.getparent() gparent = parent.getparent() index = parent.index(elem) # put everything up to elem into a new parent element right before the current parent preparent = etree.Element(parent.tag) preparent.text, parent.text = (parent.text or ''), '' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interior_nesting(cls, elem1, xpath, namespaces=None): """for elem1 containing elements at xpath, embed elem1 inside each of those elements, and then remove...
for elem2 in elem1.xpath(xpath, namespaces=namespaces): child_elem1 = etree.Element(elem1.tag) for k in elem1.attrib: child_elem1.set(k, elem1.get(k)) child_elem1.text, elem2.text = elem2.text, '' for ch in elem2.getchildren(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fragment_nesting(cls, elem1, tag2, namespaces=None): """for elem1 containing elements with tag2, fragment elem1 into elems that are adjacent to and nested...
elems2 = elem1.xpath("child::%s" % tag2, namespaces=namespaces) while len(elems2) > 0: elem2 = elems2[0] parent2 = elem2.getparent() index2 = parent2.index(elem2) # all of elem2 has a new tag1 element embedded inside of it child_elem1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def communityvisibilitystate(self): """Return the Visibility State of the Users Profile"""
if self._communityvisibilitystate == None: return None elif self._communityvisibilitystate in self.VisibilityState: return self.VisibilityState[self._communityvisibilitystate] else: #Invalid State 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 personastate(self): """Return the Persona State of the Users Profile"""
if self._personastate == None: return None elif self._personastate in self.PersonaState: return self.PersonaState[self._personastate] else: #Invalid State 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 mcus(): """MCU list."""
ls = [] for h in hwpack_names(): for b in board_names(h): ls += [mcu(b, h)] ls = sorted(list(set(ls))) return ls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logpath2dt(filepath): """ given a dataflashlog in the format produced by Mission Planner, return a datetime which says when the file was downloaded from the ...
return datetime.datetime.strptime(re.match(r'.*/(.*) .*$',filepath).groups()[0],'%Y-%m-%d %H-%M')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def url(self): '''url of the item Notes ----- if remote-adderes was given, then that is used as the base ''' path = '/web/itemdetails.html?id={}'.format(self.id) return self.connector.get_url(path, attach_api_key=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def update(self, fields=''): '''reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post : ''' path = 'Users/{{UserId}}/Items/{}'.format(self.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def send(self): '''send data that was changed to emby |coro| This should be used after using any of the setter. Not necessarily immediately, but soon after. See Also -------- post: same thing update : refresh : Returns ------- aiohttp.ClientResponse or N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_lib(lib_name): """remove library. :param lib_name: library name (e.g. 'PS2Keyboard') :rtype: None """
targ_dlib = libraries_dir() / lib_name log.debug('remove %s', targ_dlib) targ_dlib.rmtree()
<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_holidays(self, filename): """ Read holidays from an iCalendar-format file. """
cal = Calendar.from_ical(open(filename, 'rb').read()) holidays = [] for component in cal.walk('VEVENT'): start = component.decoded('DTSTART') try: end = component.decoded('DTEND') except KeyError: # RFC allows DTEND to be missing if isinstance(start, datetime): # For DATETIME instances...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_hours(self, office=None, when=None): """ Finds if it is business hours in the given office. :param office: Office ID to look up, or None to check if...
if when == None: when = datetime.now(tz=utc) if office == None: for office in self.offices.itervalues(): if office.in_hours(when): return True return False else: # check specific office return self.offices[office].in_hours(when)
<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_logging(namespace): """ setup global logging """
loglevel = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, }.get(namespace.verbosity, logging.DEBUG) if namespace.verbosity > 1: logformat = '%(levelname)s csvpandas %(lineno)s %(message)s' else: logformat = 'csvpandas %(messa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_subcommands(parser, subcommands, argv): """ Setup all sub-commands """
subparsers = parser.add_subparsers(dest='subparser_name') # add help sub-command parser_help = subparsers.add_parser( 'help', help='Detailed help for actions using `help <action>`') parser_help.add_argument('action', nargs=1) # add all other subcommands modules = [ name for _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def opener(mode='r'): """Factory for creating file objects Keyword Arguments: - mode -- A string indicating how the file is to be opened. Accepts the same values...
def open_file(f): if f is sys.stdout or f is sys.stdin: return f elif f == '-': return sys.stdin if 'r' in mode else sys.stdout elif f.endswith('.bz2'): return bz2.BZ2File(f, mode) elif f.endswith('.gz'): return gzip.open(f, mode) ...
<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(self, id, no_summary=False): """ List details for a specific tenant id """
resp = self.client.accounts.get(id) if no_summary: return self.display(resp) results = [] # Get a list of all volumes for this tenant id client = LunrClient(self.get_admin(), debug=self.debug) volumes = client.volumes.list(account_id=resp['id']) #vol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, id): """ Create a new tenant id """
resp = self.client.accounts.create(id=id) self.display(resp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, id): """ Delete an tenant id """
resp = self.client.accounts.delete(id) self.display(resp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Main method for debug purposes."""
parser = argparse.ArgumentParser() group_tcp = parser.add_argument_group('TCP') group_tcp.add_argument('--tcp', dest='mode', action='store_const', const=PROP_MODE_TCP, help="Set tcp mode") group_tcp.add_argument('--host', dest='hostname', help="Specify hostname", default='') group_tcp.add_argument(...
<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_connection(self): """Open a connection to the easyfire unit."""
if (self._mode == PROP_MODE_SERIAL): self._serial = serial.Serial(self._serial_device, self._serial_speed) elif (self._mode == PROP_MODE_TCP): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._ip, self._port)) elif (...
<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_connection(self): """Close the connection to the easyfire unit."""
if (self._mode == PROP_MODE_SERIAL): self._serial.close() elif (self._mode == PROP_MODE_TCP): self._socket.close() elif (self._mode == PROP_MODE_FILE): self._file.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_to_checksum(self, checksum, value): """Add a byte to the checksum."""
checksum = self._byte_rot_left(checksum, 1) checksum = checksum + value if (checksum > 255): checksum = checksum - 255 self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(value)) return checksum
<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_byte(self): """Read a byte from input."""
to_return = "" if (self._mode == PROP_MODE_SERIAL): to_return = self._serial.read(1) elif (self._mode == PROP_MODE_TCP): to_return = self._socket.recv(1) elif (self._mode == PROP_MODE_FILE): to_return = struct.pack("B", int(self._file.readline())) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_temp(byte_1, byte_2): """Decode a signed short temperature as two bytes to a single number."""
temp = (byte_1 << 8) + byte_2 if (temp > 32767): temp = temp - 65536 temp = temp / 10 return temp
<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_packet(self): """Read a packet from the input."""
status = STATUS_WAITING mode = 0 checksum = 0 checksum_calculated = 0 length = 0 version = 0 i = 0 cnt = 0 packet = bytearray(0) while (status != STATUS_PACKET_DONE): read = self._read_ord_byte() if (status != 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 _decode_sense_packet(self, version, packet): """Decode a sense packet into the list of sensors."""
data = self._sense_packet_to_data(packet) offset = 4 i = 0 datalen = len(data) - offset - 6 temp_count = int(datalen / 2) temp = [] for i in range(temp_count): temp_index = i * 2 + offset temp.append(self._decode_temp(data[temp_index],...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_ctrl_packet(self, version, packet): """Decode a control packet into the list of sensors."""
for i in range(5): input_bit = packet[i] self._debug(PROP_LOGLEVEL_DEBUG, "Byte " + str(i) + ": " + str((input_bit >> 7) & 1) + str((input_bit >> 6) & 1) + str((input_bit >> 5) & 1) + str((input_bit >> 4) & 1) + str((input_bit >> 3) & 1) + str((input_bit >> 2) & 1) + str((input_bit >> ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Main thread that reads from input and populates the sensors."""
while (self._run_thread): (mode, version, packet) = self._read_packet() if (mode == PROP_PACKET_SENSE): self._decode_sense_packet(version, packet) elif (mode == PROP_PACKET_CTRL): self._decode_ctrl_packet(version, packet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_thread(self): """Run the main thread."""
self._run_thread = True self._thread.setDaemon(True) self._thread.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unused(self, _dict): """ Remove empty parameters from the dict """
for key, value in _dict.items(): if value is None: del _dict[key] return _dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def required(self, method, _dict, require): """ Ensure the required items are in the dictionary """
for key in require: if key not in _dict: raise LunrError("'%s' is required argument for method '%s'" % (key, method))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allowed(self, method, _dict, allow): """ Only these items are allowed in the dictionary """
for key in _dict.keys(): if key not in allow: raise LunrError("'%s' is not an argument for method '%s'" % (key, method))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_event_name(name): """Returns the python module and obj given an event name """
try: app, event = name.split('.') return '{}.{}'.format(app, EVENTS_MODULE_NAME), event except ValueError: raise InvalidEventNameError( (u'The name "{}" is invalid. ' u'Make sure you are using the "app.KlassName" format' ).format(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 find_event(name): """Actually import the event represented by name Raises the `EventNotFoundError` if it's not possible to find the event class refered by `n...
try: module, klass = parse_event_name(name) return getattr(import_module(module), klass) except (ImportError, AttributeError): raise EventNotFoundError( ('Event "{}" not found. ' 'Make sure you have a class called "{}" inside the "{}" ' 'module.'.fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup_handlers(event=None): """Remove handlers of a given `event`. If no event is informed, wipe out all events registered. Be careful!! This function is i...
if event: if event in HANDLER_REGISTRY: del HANDLER_REGISTRY[event] if event in EXTERNAL_HANDLER_REGISTRY: del EXTERNAL_HANDLER_REGISTRY[event] else: HANDLER_REGISTRY.clear() EXTERNAL_HANDLER_REGISTRY.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_handlers(event_name, registry=HANDLER_REGISTRY): """Small helper to find all handlers associated to a given event If the event can't be found, an empty ...
handlers = [] # event_name can be a BaseEvent or the string representation if isinstance(event_name, basestring): matched_events = [event for event in registry.keys() if fnmatch.fnmatchcase(event_name, event)] for matched_event in matched_events: handlers.extend(reg...
<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_default_values(data): """Return all default values that an event should have"""
request = data.get('request') result = {} result['__datetime__'] = datetime.now() result['__ip_address__'] = request and get_ip(request) or '0.0.0.0' return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_data_values(data): """Remove special values that log function can take There are some special values, like "request" that the `log()` function can tak...
banned = ('request',) return {key: val for key, val in data.items() if not key in banned}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_event_modules(): """Import all events declared for all currently installed apps This function walks through the list of installed apps and tries to im...
for installed_app in getsetting('INSTALLED_APPS'): module_name = u'{}.{}'.format(installed_app, EVENTS_MODULE_NAME) try: import_module(module_name) except ImportError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_expired_accounts(): """ Check of expired accounts. """
ACTIVATED = RegistrationProfile.ACTIVATED expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) to_delete = [] print "Processing %s registration profiles..." % str(RegistrationProfile.objects.all().count()) for profile in RegistrationProfile.objects.all(): # if re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate(self, request, activation_key): """ Override default activation process. This will activate the user even if its passed its expiration date. """
if SHA1_RE.search(activation_key): try: profile = RegistrationProfile.objects.get(activation_key=activation_key) except RegistrationProfile.DoesNotExist: return False user = profile.user user.is_active = 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(self, request, **kwargs): """ Create and immediately log in a new user. Only require a email to register, username is generated automatically and a ...
if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) email = kwargs['email'] # Generate random password password = User.objects.make_random_password() # Generate username based off...
<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_activation_email(self, user, profile, password, site): """ Custom send email method to supplied the activation link and new generated password. """
ctx_dict = { 'password': password, 'site': site, 'activation_key': profile.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS} subject = render_to_string( 'registration/email/emails/passw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_registration_redirect(self, request, user): """ After registration, redirect to the home page or supplied "next" query string or hidden field value. """
next_url = "/registration/register/complete/" if "next" in request.GET or "next" in request.POST: next_url = request.GET.get("next", None) or request.POST.get("next", None) or "/" return (next_url, (), {})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ Returns the next batch for the batched sequence or `None`, if this batch is already the last batch. :rtype: :class:`Batch` instance or `None`...
if self.start + self.size > self.total_size: result = None else: result = Batch(self.start + self.size, self.size, self.total_size) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def previous(self): """ Returns the previous batch for the batched sequence or `None`, if this batch is already the first batch. :rtype: :class:`Batch` instance ...
if self.start - self.size < 0: result = None else: result = Batch(self.start - self.size, self.size, self.total_size) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last(self): """ Returns the last batch for the batched sequence. :rtype: :class:`Batch` instance. """
start = max(self.number - 1, 0) * self.size return Batch(start, self.size, self.total_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 number(self): """ Returns the number of batches the batched sequence contains. :rtype: integer. """
return int(math.ceil(self.total_size / float(self.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 watermark(url, args=''): """ Returns the URL to a watermarked copy of the image specified. """
# initialize some variables args = args.split(',') params = dict( name=args.pop(0), opacity=0.5, tile=False, scale=1.0, greyscale=False, rotation=0, position=None, quality=QUALITY, obscure=OBSCURE_ORIGINAL, random_position_onc...
<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_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT): """Makes a filesystem path from the specified URL path"""
if url_path.startswith(settings.MEDIA_URL): url_path = url_path[len(settings.MEDIA_URL):] # strip media root url return os.path.normpath(os.path.join(basedir, url2pathname(url_path)))
<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_filename(self, mark, **kwargs): """Comes up with a good filename for the watermarked image"""
kwargs = kwargs.copy() kwargs['opacity'] = int(kwargs['opacity'] * 100) kwargs['st_mtime'] = kwargs['fstat'].st_mtime kwargs['st_size'] = kwargs['fstat'].st_size params = [ '%(original_basename)s', 'wm', 'w%(watermark)i', 'o%(op...
<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_url_path(self, basedir, original_basename, ext, name, obscure=True): """Determines an appropriate watermark path"""
try: hash = hashlib.sha1(smart_str(name)).hexdigest() except TypeError: hash = hashlib.sha1(smart_str(name).encode('utf-8')).hexdigest() # figure out where the watermark would be saved on the filesystem if obscure is True: logger.debug('Obscuring or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_watermark(self, target, mark, fpath, quality=QUALITY, **kwargs): """Create the watermarked image on the filesystem"""
im = utils.watermark(target, mark, **kwargs) im.save(fpath, quality=quality) return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _val(var, is_percent=False): """ Tries to determine the appropriate value of a particular variable that is passed in. If the value is supposed to be a percen...
try: if is_percent: var = float(int(var.strip('%')) / 100.0) else: var = int(var) except ValueError: raise ValueError('invalid watermark parameter: ' + var) return var
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce_opacity(img, opacity): """ Returns an image with reduced opacity. """
assert opacity >= 0 and opacity <= 1 if img.mode != 'RGBA': img = img.convert('RGBA') else: img = img.copy() alpha = img.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) img.putalpha(alpha) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_scale(scale, img, mark): """ Scales an image using a specified ratio, 'F' or 'R'. If `scale` is 'F', the image is scaled to be as big as possible t...
if scale: try: scale = float(scale) except (ValueError, TypeError): pass if isinstance(scale, six.string_types) and scale.upper() == 'F': # scale watermark to full, but preserve the aspect ratio scale = min( float(img.size[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 determine_rotation(rotation, mark): """ Determines the number of degrees to rotate the watermark image. """
if isinstance(rotation, six.string_types) and rotation.lower() == 'r': rotation = random.randint(0, 359) else: rotation = _int(rotation) return rotation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def watermark(img, mark, position=(0, 0), opacity=1, scale=1.0, tile=False, greyscale=False, rotation=0, return_name=False, **kwargs): """Adds a watermark to an ...
if opacity < 1: mark = reduce_opacity(mark, opacity) if not isinstance(scale, tuple): scale = determine_scale(scale, img, mark) mark = mark.resize(scale, resample=Image.ANTIALIAS) if greyscale and mark.mode != 'LA': mark = mark.convert('LA') rotation = determine_rotatio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parsed_file(config_file): """Parse an ini-style config file."""
parser = ConfigParser(allow_no_value=True) parser.readfp(config_file) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commands(config, names): """Return the list of commands to run."""
commands = {cmd: Command(**dict((minus_to_underscore(k), v) for k, v in config.items(cmd))) for cmd in config.sections() if cmd != 'packages'} try: return tuple(commands[x] for x in names) except KeyError as e: raise Runtim...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def project_path(*names): """Path to a file in the project."""
return os.path.join(os.path.dirname(__file__), *names)
<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_osa_commit(repo, ref, rpc_product=None): """Get the OSA sha referenced by an RPCO Repo."""
osa_differ.checkout(repo, ref) functions_path = os.path.join(repo.working_tree_dir, 'scripts/functions.sh') release_path = os.path.join(repo.working_tree_dir, 'playbooks/vars/rpc-release.yml') if os.path.exists(release_path): w...
<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_report(report, args, old_commit, new_commit): """Publish the RST report based on the user request."""
# Print the report to stdout unless the user specified --quiet. output = "" if not args.quiet and not args.gist and not args.file: return report if args.gist: gist_url = post_gist(report, old_commit, new_commit) output += "\nReport posted to GitHub Gist: {0}".format(gist_url) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_rpc_differ(): """The script starts here."""
args = parse_arguments() # Set up DEBUG logging if needed if args.debug: log.setLevel(logging.DEBUG) elif args.verbose: log.setLevel(logging.INFO) # Create the storage directory if it doesn't exist already. try: storage_directory = osa_differ.prepare_storage_dir(args.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 main(raw_args=None): """Console script entry point."""
parser = argparse.ArgumentParser( description="poor man's integration testing") parser.add_argument( 'cmds', metavar='cmd', default=['test'], nargs='*', help='Run command(s) defined in the configuration file. Each command ' 'is run on each package before proceeding with the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, list): """ Removes a list from the site. """
xml = SP.DeleteList(SP.listName(list.id)) self.opener.post_soap(LIST_WEBSERVICE, xml, soapaction='http://schemas.microsoft.com/sharepoint/soap/DeleteList') self.all_lists.remove(list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, name, description='', template=100): """ Creates a new list in the site. """
try: template = int(template) except ValueError: template = LIST_TEMPLATES[template] if name in self: raise ValueError("List already exists: '{0}".format(name)) if uuid_re.match(name): raise ValueError("Cannot create a list with a UUID as ...