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 loads(inputStr): """Takes a string and converts it into an internal hypercat object, with some checking"""
inCat = json.loads(inputStr) assert CATALOGUE_TYPE in _values(inCat[CATALOGUE_METADATA], ISCONTENTTYPE_RELATION) # Manually copy mandatory fields, to check that they are they, and exclude other garbage desc = _values(inCat[CATALOGUE_METADATA], DESCRIPTION_RELATION)[0] # TODO: We are ASSUMING just one ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rels(self): """Returns a LIST of all the metadata relations"""
r = [] for i in self.metadata: r = r + i[REL] return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prettyprint(self): """Return hypercat formatted prettily"""
return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tailf( filepath, lastn=0, timeout=60, stopon=None, encoding="utf8", delay=0.1 ): """provide a `tail -f` like function :param filepath: file to tail -f, absol...
if not os.path.isfile(filepath): raise ShCmdError("[{0}] not exists".format(filepath)) if consts.TIMEOUT_MAX > timeout: timeout = consts.TIMEOUT_DEFAULT delay = delay if consts.DELAY_MAX > delay > 0 else consts.DELAY_DEFAULT if isinstance(stopon, types.FunctionType) is 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 _execfile(filename, globals, locals=None): """ Python 3 implementation of execfile. """
mode = 'rb' # Python 2.6 compile requires LF for newlines, so use deprecated # Universal newlines support. if sys.version_info < (2, 7): mode += 'U' with open(filename, mode) as stream: script = stream.read() if locals is None: locals = globals code = compile(script...
<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(self, value=None): """Send a single value to this element for processing"""
if self.chain_fork: return self._send_fork(value) return self._send_flat(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 read_interfaces(path: str) -> Interfaces: """Reads an Interfaces JSON file at the given path and returns it as a dictionary."""
with open(path, encoding='utf-8') as f: return json.load(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiple(layer: int, limit: int) -> Set[str]: """Returns a set of strings to be used as Slots with Pabianas default Clock. Args: layer: The layer in the h...
return {str(x).zfill(2) for x in [2**x for x in range(limit)] if x % 2**(layer - 1) == 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 print_change(self, symbol, typ, changes=None, document=None, **kwargs): """Print out a change"""
values = ", ".join("{0}={1}".format(key, val) for key, val in sorted(kwargs.items())) print("{0} {1}({2})".format(symbol, typ, values)) if changes: for change in changes: print("\n".join("\t{0}".format(line) for line in change.split('\n'))) elif document: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change(self, symbol, typ, **kwargs): """Print out a change and then do the change if not doing a dry run"""
self.print_change(symbol, typ, **kwargs) if not self.dry_run: try: yield except: raise else: self.amazon.changes = 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 urlopen(url, timeout=20, redirects=None): """A minimal urlopen replacement hack that supports timeouts for http. Note that this supports GET only."""
scheme, host, path, params, query, frag = urlparse(url) if not scheme in ('http', 'https'): return urllib.urlopen(url) if params: path = '%s;%s' % (path, params) if query: path = '%s?%s' % (path, query) if frag: path = '%s#%s' % (path, frag) if scheme == 'https': # If ssl 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 SOAPUriToVersion(self, uri): """Return the SOAP version related to an envelope uri."""
value = self._soap_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WSDLUriToVersion(self, uri): """Return the WSDL version related to a WSDL namespace uri."""
value = self._wsdl_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isElement(self, node, name, nsuri=None): """Return true if the given node is an element with the given name and optional namespace uri."""
if node.nodeType != node.ELEMENT_NODE: return 0 return node.localName == name and \ (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElement(self, node, name, nsuri=None, default=join): """Return the first child of node with a matching name and namespace uri, or the default if one is pr...
nsmatch = self.nsUriMatch ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if ((child.localName == name or name is None) and (nsuri is None or nsmatch(child.namespaceURI, nsuri)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementById(self, node, id, default=join): """Return the first child of node matching an id reference."""
attrget = self.getAttr ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if attrget(child, 'id') == id: return child if default is not join: return default raise KeyError,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElements(self, node, name, nsuri=None): """Return a sequence of the child elements of the given node that match the given name and optional namespace uri....
nsmatch = self.nsUriMatch result = [] ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if ((child.localName == name or name is None) and ( (nsuri is None) or nsmatch(child.namespaceURI, nsur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasAttr(self, node, name, nsuri=None): """Return true if element has attribute with the given name and optional nsuri. If nsuri is not specified, returns tru...
if nsuri is None: if node.hasAttribute(name): return True return False return node.hasAttributeNS(nsuri, 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 getAttr(self, node, name, nsuri=None, default=join): """Return the value of the attribute named 'name' with the optional nsuri, or the default if one is spec...
if nsuri is None: result = node._attrs.get(name, None) if result is None: for item in node._attrsNS.keys(): if item[1] == name: result = node._attrsNS[item] break else: result = node....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAttrs(self, node): """Return a Collection of all attributes """
attrs = {} for k,v in node._attrs.items(): attrs[k] = v.value return attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementText(self, node, preserve_ws=None): """Return the text value of an xml element node. Leading and trailing whitespace is stripped from the value unl...
result = [] for child in node.childNodes: nodetype = child.nodeType if nodetype == child.TEXT_NODE or \ nodetype == child.CDATA_SECTION_NODE: result.append(child.nodeValue) value = join(result, '') if preserve_ws is 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 findNamespaceURI(self, prefix, node): """Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix) DOCUMENT_NODE = node.DOCUMENT_NODE ELEMENT_NODE = node.ELEMENT_NODE while 1: if node is None: raise DOMException('Value for prefix %s not found.' % prefix) if node.nodeType != ELEMENT_NODE: node = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findTargetNS(self, node): """Return the defined target namespace uri for the given node."""
attrget = self.getAttr attrkey = (self.NS_XMLNS, 'xmlns') DOCUMENT_NODE = node.DOCUMENT_NODE ELEMENT_NODE = node.ELEMENT_NODE while 1: if node.nodeType != ELEMENT_NODE: node = node.parentNode continue result = attrget(node,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nsUriMatch(self, value, wanted, strict=0, tt=type(())): """Return a true value if two namespace uri values match."""
if value == wanted or (type(wanted) is tt) and value in wanted: return 1 if not strict and value is not None: wanted = type(wanted) is tt and wanted or (wanted,) value = value[-1:] != '/' and value or value[:-1] for item in wanted: if item...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createDocument(self, nsuri, qname, doctype=None): """Create a new writable DOM document object."""
impl = xml.dom.minidom.getDOMImplementation() return impl.createDocument(nsuri, qname, doctype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadFromURL(self, url): """Load an xml file from a URL and return a DOM document."""
if isfile(url) is True: file = open(url, 'r') else: file = urlopen(url) try: result = self.loadDocument(file) except Exception, ex: file.close() raise ParseError(('Failed to load document %s' %url,) + ex.args) els...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getUniquePrefix(self): '''I guess we need to resolve all potential prefixes because when the current node is attached it copies the namespaces into the parent node. ''' while 1: self._indx += 1 prefix = 'ns%d' %self._indx try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def createDocument(self, namespaceURI, localName, doctype=None): '''If specified must be a SOAP envelope, else may contruct an empty document. ''' prefix = self._soap_env_prefix if namespaceURI == self.reserved_ns[prefix]: qualifiedName = '%s:%s' %(prefix,localName) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def face_and_energy_detector(image_path, detect_faces=True): """ Finds faces and energy in an image """
source = Image.open(image_path) work_width = 800 if source.mode != 'RGB' or source.bits != 8: source24 = source.convert('RGB') else: source24 = source.copy() grayscaleRMY = source24.convert('L', (0.5, 0.419, 0.081, 0)) w = min(grayscaleRMY.size[0], work_width) h = w * grays...
<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_crop_size(crop_w, crop_h, image_w, image_h): """ Determines the correct scale size for the image when img w == crop w and img h > crop h Use these dimens...
scale1 = float(crop_w) / float(image_w) scale2 = float(crop_h) / float(image_h) scale1_w = crop_w # int(round(img_w * scale1)) scale1_h = int(round(image_h * scale1)) scale2_w = int(round(image_w * scale2)) scale2_h = crop_h # int(round(img_h * scale2)) if scale1_h > crop_h: # scale1_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 calc_subrange(range_max, sub_amount, weight): """ return the start and stop points that are sub_amount distance apart and contain weight, without going outsi...
if weight > range_max or sub_amount > range_max: raise ValueError("sub_amount and weight must be less than range_max. range_max %s, sub_amount %s, weight %s" % (range_max, sub_amount, weight)) half_amount = sub_amount / 2 bottom = weight - half_amount top = bottom + sub_amount if top <= ran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smart_crop(crop_w, crop_h, image_path): """ Return the scaled image size and crop rectangle """
cropping = face_and_energy_detector(image_path) img = Image.open(image_path) w, h = img.size scaled_size = get_crop_size(crop_w, crop_h, *img.size) gravity_x = int(round(scaled_size[0] * cropping.gravity[0])) gravity_y = int(round(scaled_size[1] * cropping.gravity[1])) if scaled_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 expiration_time(self): """ Returns the time until this access attempt is forgotten. """
logging_forgotten_time = configuration.behavior.login_forgotten_seconds if logging_forgotten_time <= 0: return None now = timezone.now() delta = now - self.modified time_remaining = logging_forgotten_time - delta.seconds return time_remaining
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bling(self, target, sender): "will print yo" if target.startswith("#"): self.message(target, "%s: yo" % sender) else: self.message(sender, "yo")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def repeat(self, target, sender, **kwargs): "will repeat whatever yo say" if target.startswith("#"): self.message(target, kwargs["msg"]) else: self.message(sender, kwargs["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 stopword(self, target, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message only applies to channel messages """
if target.startswith("#"): self.message(target, args[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 compare_dicts(dict1, dict2): """ Checks if dict1 equals dict2 """
for k, v in dict2.items(): if v != dict1[k]: return False return 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 getItalianAccentedVocal(vocal, acc_type="g"): """ It returns given vocal with grave or acute accent """
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'}, 'e': {'g': u'\xe8', 'a': u'\xe9'}, 'i': {'g': u'\xec', 'a': u'\xed'}, 'o': {'g': u'\xf2', 'a': u'\xf3'}, 'u': {'g': u'\xf9', 'a': u'\xfa'}} return vocals[vocal][acc_type]
<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_certificate(self, certificate_name): ''' a method to retrieve the details about a server certificate :param certificate_name: string with name of server certificate :return: dictionary with certificate details ''' title = '%s.read_certificate' % self.__cla...
<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_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """
return self.term.color(color_code) + message + self.term.normal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """files that will be add to tar file later should be tuple, list or generator that returns strings """
ios_names = [info.name for info in self._ios_to_add.keys()] return set(self.files_to_add + ios_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 add_fileobj(self, fname, fcontent): """add file like object, it will be add to tar file later :param fname: name in tar file :param fcontent: content. bytes,...
tar_info = tarfile.TarInfo(fname) if isinstance(fcontent, io.BytesIO): tar_info.size = len(fcontent.getvalue()) elif isinstance(fcontent, io.StringIO): tar_info.size = len(fcontent.getvalue()) fcontent = io.BytesIO(fcontent.getvalue().encode("utf8")) ...
<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(self): """generate tar file ..Usage:: """
if self._tar_buffer.tell(): self._tar_buffer.seek(0, 0) yield self._tar_buffer.read() for fname in self._files_to_add: last = self._tar_buffer.tell() self._tar_obj.add(fname) self._tar_buffer.seek(last, os.SEEK_SET) data = self._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 tar(self): """tar in bytes format"""
if not self.generated: for data in self.generate(): pass return self._tar_buffer.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Starts the mongodb connection. Must be called before anything else will work. """
self.client = MongoClient(self.mongo_uri) self.db = self.client[self.db_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(self, collection, query): """ Search a collection for the query provided. Just a raw interface to mongo to do any query you want. Args: collection: The ...
obj = getattr(self.db, collection) result = obj.find(query) 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 find_all(self, collection): """ Search a collection for all available items. Args: collection: The db collection. See main class documentation. Returns: List...
obj = getattr(self.db, collection) result = obj.find() 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 find_one(self, collection, query): """ Search a collection for the query provided and return one result. Just a raw interface to mongo to do any query you wa...
obj = getattr(self.db, collection) result = obj.find_one(query) 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 find_distinct(self, collection, key): """ Search a collection for the distinct key values provided. Args: collection: The db collection. See main class docum...
obj = getattr(self.db, collection) result = obj.distinct(key) 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 add_embedded_campaign(self, id, collection, campaign, confidence, analyst, date, description): """ Adds an embedded campaign to the TLO. Args: id: the CRITs ...
if type(id) is not ObjectId: id = ObjectId(id) # TODO: Make sure the object does not already have the campaign # Return if it does. Add it if it doesn't obj = getattr(self.db, collection) result = obj.find({'_id': id, 'campaign.name': campaign}) if result.cou...
<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_bucket_list_item(self, id, collection, item): """ Removes an item from the bucket list Args: id: the CRITs object id of the TLO collection: The db col...
if type(id) is not ObjectId: id = ObjectId(id) obj = getattr(self.db, collection) result = obj.update( {'_id': id}, {'$pull': {'bucket_list': item}} ) 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 get_campaign_name_list(self): """ Returns a list of all valid campaign names Returns: List of strings containing all valid campaign names """
campaigns = self.find('campaigns', {}) campaign_names = [] for campaign in campaigns: if 'name' in campaign: campaign_names.append(campaign['name']) return campaign_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 deserialize(self): """ Invoke the RFC 7159 spec compliant parser :return: the parsed & vetted request body """
super(Deserializer, self).deserialize() try: return json.loads(self.req.get_body()) except TypeError: link = 'tools.ietf.org/html/rfc7159' self.fail('Typically, this error is due to a missing JSON ' 'payload in your request when one wa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quantize_without_scipy(self, image): """" This function can be used if no scipy is availabe. It's 7 times slower though. """
w, h = image.size px = np.asarray(image).copy() memo = {} for j in range(w): for i in range(h): key = (px[i, j, 0], px[i, j, 1], px[i, j, 2]) try: val = memo[key] except KeyError: val = 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 get_installed_extjs_apps(): """ Get all installed extjs apps. :return: List of ``(appdir, module, appname)``. """
installed_apps = [] checked = set() for app in settings.INSTALLED_APPS: if not app.startswith('django.') and not app in checked: checked.add(app) try: installed_apps.append(get_appinfo(app)) except LookupError, e: pass return 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 createJsbConfig(self): """ Create JSB config file using ``sencha create jsb``. :return: The created jsb3 config as a string. """
tempdir = mkdtemp() tempfile = join(tempdir, 'app.jsb3') cmd = ['sencha', 'create', 'jsb', '-a', self.url, '-p', tempfile] log.debug('Running: %s', ' '.join(cmd)) call(cmd) jsb3 = open(tempfile).read() rmtree(tempdir) return jsb3
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanJsbConfig(self, jsbconfig): """ Clean up the JSB config. """
config = json.loads(jsbconfig) self._cleanJsbAllClassesSection(config) self._cleanJsbAppAllSection(config) return json.dumps(config, indent=4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildFromJsbString(self, jsb, nocompressjs=False): """ Build from the given config file using ``sencha build``. :param jsb: The JSB config as a string. :para...
tempconffile = 'temp-app.jsb3' cmd = ['sencha', 'build', '-p', tempconffile, '-d', self.outdir] if nocompressjs: cmd.append('--nocompress') open(tempconffile, 'w').write(jsb) log.info('Running: %s', ' '.join(cmd)) try: call(cmd) finally: ...
<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_actions(self, request, view): """ For generic class based views we return information about the fields that are accepted for 'PUT' and 'POST' metho...
actions = {} for method in {'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) try: # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def music_search(self, entitiy_type, query, **kwargs): """ Search the music database Where ``entitiy_type`` is a comma separated list of: ``song`` songs ``album`...
return self.make_request('music', entitiy_type, query, 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 amg_video_search(self, entitiy_type, query, **kwargs): """ Search the Movies and TV database Where ``entitiy_type`` is a comma separated list of: ``movie`` M...
return self.make_request('amgvideo', entitiy_type, query, 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 video_search(self, entitiy_type, query, **kwargs): """ Search the TV schedule database Where ``entitiy_type`` is a comma separated list of: ``movie`` Movie `...
return self.make_request('video', entitiy_type, query, 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 structureOutput(fileUrl, fileName, searchFiles, format=True, space=40): """Formats the output of a list of packages"""
#First, remove the filename if format: splitUrls = fileUrl[1:].split('/') fileUrl = "" for splitUrl in splitUrls: # This is a gimmicky fix to make formatting consistent # Cemetech doesn't have /pub/ at the front of it's repo paths # Also, Omnimaga has a /files/ we need to get rid of similarly # Thi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Counts the number of ticalc.org files containing some s...
fileData = {} nameData = {} #Search the index if searchFiles: fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension) else: nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString) #Now search the other index if searchFiles: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchHierarchy(self, fparent): """Core function to search directory structure for child files and folders of a parent"""
data = [] returnData = [] parentslashes = fparent.count('/') filecount = 0 foldercount = 0 #open files for folder searching try: dirFile = open(self.dirIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.dirIndex) return #search for folders for fldr ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Core function to search the indexes and return data"""
data = [] nameData = {} fileData = {} #Search the name index if searchFiles: fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension, searchFiles) else: nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString) #Now search the f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""): """Search the files index using the...
try: fileFile = open(fileIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return None, None count = 1 for line in fileFile: count += 1 try: if nameData[count] != None: #category argument if category in line: fileData[coun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False): """Search the names index ...
nameData = {} try: nameFile = open(nameIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return None count = 1 for line in nameFile: count += 1 if searchString.lower() in line.lower(): #Extension argument if extension in 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 select_parser(self, request, parsers): """ Given a list of parsers and a media type, return the appropriate parser to handle the incoming request. """
for parser in parsers: if media_type_matches(parser.media_type, request.content_type): return parser 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 filter_renderers(self, renderers, format): """ If there is a '.json' style format suffix, filter the renderers so that we only negotiation against those that...
renderers = [renderer for renderer in renderers if renderer.format == format] if not renderers: raise Http404 return renderers
<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_accept_list(self, request): """ Given the incoming request, return a tokenised list of media type strings. """
header = request.META.get('HTTP_ACCEPT', '*/*') return [token.strip() for token in header.split(',')]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unit_pos_to_spot(unit_pos) -> ParkingSpot: """ Translates a unit position to a known parking spot Args: unit_pos: unit position as Vec2 Returns: ParkingSpot o...
min_ = 50 res = None for airport in parkings: for spot in parkings[airport]: # type: ignore spot_pos = parkings[airport][spot] # type: ignore dist = math.hypot(unit_pos[0] - spot_pos[0], unit_pos[1] - spot_pos[1]) if dist < min_: min_ = dist # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect(self): """ Select the best suited data of all available in the subclasses. In each subclass, the functions alphabetical order should correspond to th...
class_functions = [] for key in self.__class__.__dict__.keys(): func = self.__class__.__dict__[key] if (inspect.isfunction(func)): class_functions.append(func) functions = sorted(class_functions, key=lambda func: func.__name__) for function in fu...
<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(self): """ Initialize a new password db store """
self.y = {"version": int(time.time())} recipient_email = raw_input("Enter Email ID: ") self.import_key(emailid=recipient_email) self.encrypt(emailid_list=[recipient_email])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_users(self): """ Get user list from the encrypted passdb file """
crypt = self._decrypt_file() self.logger.info(crypt.stderr) raw_userlist = crypt.stderr.split('\n') userlist = list() for index, line in enumerate(raw_userlist): if 'gpg: encrypted' in line: m = re.search('ID (\w+)', line) keyid = m.g...
<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_user(self, recipient_email): """ Add user to encryption """
self.import_key(emailid=recipient_email) emailid_list = self.list_user_emails() self.y = self.decrypt() emailid_list.append(recipient_email) self.encrypt(emailid_list=emailid_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 delete_user(self, recipient_email): """ Remove user from encryption """
emailid_list = self.list_user_emails() if recipient_email not in emailid_list: raise Exception("User {0} not present!".format(recipient_email)) else: emailid_list.remove(recipient_email) self.y = self.decrypt() self.encrypt(emailid_list=emailid_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 parse_meta(filename, data): """ Parse `data` to EPublication. Args: filename (str): Used to choose right parser based at suffix. data (str): Content of the...
if "." not in filename: raise MetaParsingException( "Can't recognize type of your metadata ('%s')!" % filename ) suffix = filename.rsplit(".", 1)[1].lower() if suffix not in SUPPORTED_FILES: raise MetaParsingException("Can't parse file of type '%s'!" % suffix) fp ...
<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_instance(page_to_consume): """Return an instance of ConsumeModel."""
global _instances if isinstance(page_to_consume, basestring): uri = page_to_consume page_to_consume = consumepage.get_instance(uri) elif isinstance(page_to_consume, consumepage.ConsumePage): uri = page_to_consume.uri else: raise TypeError( "get_instance() exp...
<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_dict(self): """Return a dictionary of the object primed for dumping."""
data = self.data_dict.copy() data.update({ "class": self.classification, "tags": self.tags, "key_value_data": self.key_value_dict, "crumbs": self.crumb_list if len(self.crumb_list) > 0 else None, "media": [ mediafile.filename ...
<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, redirect_uri=None): """Create a new Device object. Devices tie Users and Applications together. For your Application to access and act on ...
data = dict(name=name) if redirect_uri: data['redirect_uri'] = redirect_uri auth_request_resource = self.resource.create(data) return (auth_request_resource.attributes['metadata']['device_token'], auth_request_resource.attributes['mfa_uri'])
<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_option_parser(parser): """Hook to add global options Called from openstackclient.shell.OpenStackShell.__init__() after the builtin parser has been init...
parser.add_argument( '--os-rdomanager-oscplugin-api-version', metavar='<rdomanager-oscplugin-api-version>', default=utils.env( 'OS_RDOMANAGER_OSCPLUGIN_API_VERSION', default=DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION), help='RDO Manager OSC Plugin API version, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def baremetal(self): """Returns an baremetal service client"""
# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the # following client handling code should be removed in favor of the # upstream version. if self._baremetal is not None: return self._baremetal endpoint = self._instance.get_endpoint_for_service_type...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orchestration(self): """Returns an orchestration service client"""
# TODO(d0ugal): This code is based on the upstream WIP implementation # and should be removed when it lands: # https://review.openstack.org/#/c/111786 if self._orchestration is not None: return self._orchestration API_VERSIONS = { '1': 'heatclient.v1.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def management(self): """Returns an management service client"""
endpoint = self._instance.get_endpoint_for_service_type( "management", region_name=self._instance._region_name, ) token = self._instance.auth.get_token(self._instance.session) self._management = tuskar_client.get_client( 2, os_auth_token=token, tus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def media_type_matches(lhs, rhs): """ Returns ``True`` if the media type in the first argument <= the media type in the second argument. The media types are stri...
lhs = _MediaType(lhs) rhs = _MediaType(rhs) return lhs.match(rhs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def subclasses(cls, lst=None): '''Recursively gather subclasses of cls. ''' if lst is None: lst = [] for sc in cls.__subclasses__(): if sc not in lst: lst.append(sc) subclasses(sc, lst=lst) return 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 nearest_base(cls, bases): '''Returns the closest ancestor to cls in bases. ''' if cls in bases: return cls dists = {base: index(mro(cls), base) for base in bases} dists2 = {dist: base for base, dist in dists.items() if dist is not None} if not dists2: return None return ...
<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_typename(x): '''Returns the name of the type of x, if x is an object. Otherwise, returns the name of x. ''' if isinstance(x, type): ret = x.__name__ else: ret = x.__class__.__name__ return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getfunc(obj, name=''): '''Get the function corresponding to name from obj, not the method.''' if name: obj = getattr(obj, name) return getattr(obj, '__func__', obj)
<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_mod(cls): '''Returns the string identifying the module that cls is defined in. ''' if isinstance(cls, (type, types.FunctionType)): ret = cls.__module__ else: ret = cls.__class__.__module__ return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def this_module(npop=1): '''Returns the module object of the module this function is called from ''' stack = inspect.stack() st = stack[npop] frame = st[0] return inspect.getmodule(frame)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_equivalent(o1, o2): '''Asserts that o1 and o2 are distinct, yet equivalent objects ''' if not (isinstance(o1, type) and isinstance(o2, type)): assert o1 is not o2 assert o1 == o2 assert o2 == o1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_inequivalent(o1, o2): '''Asserts that o1 and o2 are distinct and inequivalent objects ''' if not (isinstance(o1, type) and isinstance(o2, type)): assert o1 is not o2 assert not o1 == o2 and o1 != o2 assert not o2 == o1 and o2 != o1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_type_equivalent(o1, o2): '''Asserts that o1 and o2 are distinct, yet equivalent objects of the same type ''' assert o1 == o2 assert o2 == o1 assert type(o1) is type(o2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''): '''For logging exception-raising function invocations during randomized unit tests. ''' from .str import safe_str args = args if args else () kwargs = kwargs if kwargs else {} name = '{}.{}'.format(get_mod(func), 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 get_body(self): """Get the body of the email message"""
if self.is_multipart(): # get the plain text version only text_parts = [part for part in typed_subpart_iterator(self, 'text', 'plain')] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(self): """Blocking call on widgets. """
while self._listen: key = u'' key = self.term.inkey(timeout=0.2) try: if key.code == KEY_ENTER: self.on_enter(key=key) elif key.code in (KEY_DOWN, KEY_UP): self.on_key_arrow(key=key) 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 add(self, widget, *args, **kwargs): """Insert new element. Usage: window.add(widget, **{ 'prop1': val, 'prop2': val2 }) """
ins_widget = widget(*args, **kwargs) self.__iadd__(ins_widget) return ins_widget
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search_terms(q): '''Takes a search string and parses it into a list of keywords and phrases.''' tokens = parse_search_terms(q) # iterate through all the tokens and make a list of token values # (which are the actual words and phrases) values = [] for t in tokens: # word/phrase ...