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 innerHTML(self): ''' innerHTML - Returns an HTML string of the inner contents of this tag, including children. @return - String of inner contents HTML ''' # If a self-closing tag, there are no contents if self.isSelfClosing is True: return '' # Assemble all the blocks. ret = [] # Iterate through blocks for block in self.blocks: # For each block: # If a tag, append the outer html (start tag, contents, and end tag) # Else, append the text node directly if isinstance(block, AdvancedTag): ret.append(block.outerHTML) else: ret.append(block) return ''.join(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 getAttributesDict(self): ''' getAttributesDict - Get a copy of all attributes as a dict map of name -> value ALL values are converted to string and copied, so modifications will not affect the original attributes. If you want types like "style" to work as before, you'll need to recreate those elements (like StyleAttribute(strValue) ). @return <dict ( str(name), str(value) )> - A dict of attrName to attrValue , all as strings and copies. ''' return { tostr(name)[:] : tostr(value)[:] for name, value in self._attributes.items() }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hasAttribute(self, attrName): ''' hasAttribute - Checks for the existance of an attribute. Attribute names are all lowercase. @param attrName <str> - The attribute name @return <bool> - True or False if attribute exists by that name ''' attrName = attrName.lower() # Check if requested attribute is present on this node return bool(attrName in self._attributes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addClass(self, className): ''' addClass - append a class name to the end of the "class" attribute, if not present @param className <str> - The name of the class to add ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.addClass(oneClassName) return myClassNames = self._classNames # Do not allow duplicates if className in myClassNames: return # Regenerate "classNames" and "class" attr. # TODO: Maybe those should be properties? myClassNames.append(className) 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 removeClass(self, className): ''' removeClass - remove a class name if present. Returns the class name if removed, otherwise None. @param className <str> - The name of the class to remove @return <str> - The class name removed if one was removed, otherwise None if #className wasn't present ''' className = stripWordsOnly(className) if not className: return None if ' ' in className: # Multiple class names passed, do one at a time for oneClassName in className.split(' '): self.removeClass(oneClassName) return myClassNames = self._classNames # If not present, this is a no-op if className not in myClassNames: return None myClassNames.remove(className) return className
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setStyles(self, styleUpdatesDict): ''' setStyles - Sets one or more style params. This all happens in one shot, so it is much much faster than calling setStyle for every value. To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. @param styleUpdatesDict - Dictionary of attribute : value styles. @return - String of current value of "style" after change is made. ''' setStyleMethod = self.setStyle for newName, newValue in styleUpdatesDict.items(): setStyleMethod(newName, newValue) return self.style
<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, _id): ''' getElementById - Search children of this tag for a tag containing an id @param _id - String of id @return - AdvancedTag or None ''' for child in self.children: if child.getAttribute('id') == _id: return child found = child.getElementById(_id) if found is not None: return found 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 getElementsByClassName(self, className): ''' getElementsByClassName - Search children of this tag for tags containing a given class name @param className - Class name @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.hasClass(className) is True: elements.append(child) elements += child.getElementsByClassName(className) return TagCollection(elements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getElementsWithAttrValues(self, attrName, attrValues): ''' getElementsWithAttrValues - Search children of this tag for tags with an attribute name and one of several values @param attrName <lowercase str> - Attribute name (lowercase) @param attrValues set<str> - set of acceptable attribute values @return - TagCollection of matching elements ''' elements = [] for child in self.children: if child.getAttribute(attrName) in attrValues: elements.append(child) elements += child.getElementsWithAttrValues(attrName, attrValues) return TagCollection(elements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Searches children of this tag for those matching a provided user function @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return - TagCollection of matching results @see getFirstElementCustomFilter ''' elements = [] for child in self.children: if filterFunc(child) is True: elements.append(child) elements += child.getElementsCustomFilter(filterFunc) return TagCollection(elements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getFirstElementCustomFilter(self, filterFunc): ''' getFirstElementCustomFilter - Gets the first element which matches a given filter func. Scans first child, to the bottom, then next child to the bottom, etc. Does not include "self" node. @param filterFunc <function> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getElementsCustomFilter ''' for child in self.children: if filterFunc(child) is True: return child childSearchResult = child.getFirstElementCustomFilter(filterFunc) if childSearchResult is not None: return childSearchResult 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 getParentElementCustomFilter(self, filterFunc): ''' getParentElementCustomFilter - Runs through parent on up to document root, returning the first tag which filterFunc(tag) returns True. @param filterFunc <function/lambda> - A function or lambda expression that should return "True" if the passed node matches criteria. @return <AdvancedTag/None> - First match, or None @see getFirstElementCustomFilter for matches against children ''' parentNode = self.parentNode while parentNode: if filterFunc(parentNode) is True: return parentNode parentNode = parentNode.parentNode 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 getPeersCustomFilter(self, filterFunc): ''' getPeersCustomFilter - Get elements who share a parent with this element and also pass a custom filter check @param filterFunc <lambda/function> - Passed in an element, and returns True if it should be treated as a match, otherwise False. @return <TagCollection> - Resulting peers, or None if no parent node. ''' peers = self.peers if peers is None: return None return TagCollection([peer for peer in peers if filterFunc(peer) is 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 isTagEqual(self, other): ''' isTagEqual - Compare if a tag contains the same tag name and attributes as another tag, i.e. if everything between < and > parts of this tag are the same. Does NOT compare children, etc. Does NOT compare if these are the same exact tag in the html (use regular == operator for that) So for example: tag1 = document.getElementById('something') tag2 = copy.copy(tag1) tag1 == tag2 # This is False tag1.isTagEqual(tag2) # This is True @return bool - True if tags have the same name and attributes, otherwise False ''' # if type(other) != type(self): # return False # NOTE: Instead of type check, # just see if we can get the needed attributes in case subclassing try: if self.tagName != other.tagName: return False myAttributes = self._attributes otherAttributes = other._attributes attributeKeysSelf = list(myAttributes.keys()) attributeKeysOther = list(otherAttributes.keys()) except: return False # Check that we have all the same attribute names if set(attributeKeysSelf) != set(attributeKeysOther): return False for key in attributeKeysSelf: if myAttributes.get(key) != otherAttributes.get(key): 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 append(self, tag): ''' append - Append an item to this tag collection @param tag - an AdvancedTag ''' list.append(self, tag) self.uids.add(tag.uid)
<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, toRemove): ''' remove - Remove an item from this tag collection @param toRemove - an AdvancedTag ''' list.remove(self, toRemove) self.uids.remove(toRemove.uid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filterCollection(self, filterFunc): ''' filterCollection - Filters only the immediate objects contained within this Collection against a function, not including any children @param filterFunc <function> - A function or lambda expression that returns True to have that element match @return TagCollection<AdvancedTag> ''' ret = TagCollection() if len(self) == 0: return ret for tag in self: if filterFunc(tag) is True: ret.append(tag) 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 getElementsByTagName(self, tagName): ''' getElementsByTagName - Gets elements within this collection having a specific tag name @param tagName - String of tag name @return - TagCollection of unique elements within this collection with given tag name ''' ret = TagCollection() if len(self) == 0: return ret tagName = tagName.lower() _cmpFunc = lambda tag : bool(tag.tagName == tagName) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) 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 getElementsByName(self, name): ''' getElementsByName - Get elements within this collection having a specific name @param name - String of "name" attribute @return - TagCollection of unique elements within this collection with given "name" ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : bool(tag.name == name) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) 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 getElementsByClassName(self, className): ''' getElementsByClassName - Get elements within this collection containing a specific class name @param className - A single class name @return - TagCollection of unique elements within this collection tagged with a specific class name ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : tag.hasClass(className) for tag in self: TagCollection._subset(ret, _cmpFunc, tag) 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 getElementById(self, _id): ''' getElementById - Gets an element within this collection by id @param _id - string of "id" attribute @return - a single tag matching the id, or None if none found ''' for tag in self: if tag.id == _id: return tag for subtag in tag.children: tmp = subtag.getElementById(_id) if tmp is not None: return tmp 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 getElementsWithAttrValues(self, attr, values): ''' getElementsWithAttrValues - Get elements within this collection possessing an attribute name matching one of several values @param attr <lowercase str> - Attribute name (lowerase) @param values set<str> - Set of possible matching values @return - TagCollection of all elements matching criteria ''' ret = TagCollection() if len(self) == 0: return ret if type(values) != set: values = set(values) attr = attr.lower() _cmpFunc = lambda tag : tag.getAttribute(attr) in values for tag in self: TagCollection._subset(ret, _cmpFunc, tag) 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 getElementsCustomFilter(self, filterFunc): ''' getElementsCustomFilter - Get elements within this collection that match a user-provided function. @param filterFunc <function> - A function that returns True if the element matches criteria @return - TagCollection of all elements that matched criteria ''' ret = TagCollection() if len(self) == 0: return ret _cmpFunc = lambda tag : filterFunc(tag) is True for tag in self: TagCollection._subset(ret, _cmpFunc, tag) 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 getAllNodes(self): ''' getAllNodes - Gets all the nodes, and all their children for every node within this collection ''' ret = TagCollection() for tag in self: ret.append(tag) ret += tag.getAllChildNodes() 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 getAllNodeUids(self): ''' getAllNodeUids - Gets all the internal uids of all nodes, their children, and all their children so on.. @return set<uuid.UUID> ''' ret = set() for child in self: ret.update(child.getAllNodeUids()) 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 filterAll(self, **kwargs): ''' filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterAnd(**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 filterAllOr(self, **kwargs): ''' filterAllOr - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ANY the filter criteria. for ALL, use the *And methods For just the nodes in this collection, use "filterOr" on a TagCollection For special filter keys, @see #AdvancedHTMLParser.AdvancedHTMLParser.filter Requires the QueryableList module to be installed (i.e. AdvancedHTMLParser was installed without '--no-deps' flag.) For alternative without QueryableList, consider #AdvancedHTMLParser.AdvancedHTMLParser.find method or the getElement* methods @return TagCollection<AdvancedTag> ''' if canFilterTags is False: raise NotImplementedError('filter methods requires QueryableList installed, it is not. Either install QueryableList, or try the less-robust "find" method, or the getElement* methods.') allNodes = self.getAllNodes() filterableNodes = FilterableTagCollection(allNodes) return filterableNodes.filterOr(**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 handle_starttag(self, tagName, attributeList, isSelfClosing=False): ''' handle_starttag - Internal for parsing ''' tagName = tagName.lower() inTag = self._inTag if isSelfClosing is False and tagName in IMPLICIT_SELF_CLOSING_TAGS: isSelfClosing = True newTag = AdvancedTag(tagName, attributeList, isSelfClosing) if self.root is None: self.root = newTag elif len(inTag) > 0: inTag[-1].appendChild(newTag) else: raise MultipleRootNodeException() if self.inPreformatted is 0: newTag._indent = self._getIndent() if tagName in PREFORMATTED_TAGS: self.inPreformatted += 1 if isSelfClosing is False: inTag.append(newTag) if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel += 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 handle_endtag(self, tagName): ''' handle_endtag - Internal for parsing ''' inTag = self._inTag try: # Handle closing tags which should have been closed but weren't foundIt = False for i in range(len(inTag)): if inTag[i].tagName == tagName: foundIt = True break if not foundIt: sys.stderr.write('WARNING: found close tag with no matching start.\n') return while inTag[-1].tagName != tagName: oldTag = inTag.pop() if oldTag.tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 self.currentIndentLevel -= 1 inTag.pop() if tagName != INVISIBLE_ROOT_TAG: self.currentIndentLevel -= 1 if tagName in PREFORMATTED_TAGS: self.inPreformatted -= 1 except: 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_data(self, data): ''' handle_data - Internal for parsing ''' if data: inTag = self._inTag if len(inTag) > 0: if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS: data = data.replace('\t', ' ').strip('\r\n') if data.startswith(' '): data = ' ' + data.lstrip() if data.endswith(' '): data = data.rstrip() + ' ' inTag[-1].appendText(data) elif data.strip(): # Must be text prior to or after root node raise MultipleRootNodeException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getStartTag(self, *args, **kwargs): ''' getStartTag - Override the end-spacing rules @see AdvancedTag.getStartTag ''' ret = AdvancedTag.getStartTag(self, *args, **kwargs) if ret.endswith(' >'): ret = ret[:-2] + '>' elif object.__getattribute__(self, 'slimSelfClosing') and ret.endswith(' />'): ret = ret[:-3] + '/>' 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 stripIEConditionals(contents, addHtmlIfMissing=True): ''' stripIEConditionals - Strips Internet Explorer conditional statements. @param contents <str> - Contents String @param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing. ''' allMatches = IE_CONDITIONAL_PATTERN.findall(contents) if not allMatches: return contents for match in allMatches: contents = contents.replace(match, '') if END_HTML.match(contents) and not START_HTML.match(contents): contents = addStartTag(contents, '<html>') return contents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addStartTag(contents, startTag): ''' addStartTag - Safetly add a start tag to the document, taking into account the DOCTYPE @param contents <str> - Contents @param startTag <str> - Fully formed tag, i.e. <html> ''' matchObj = DOCTYPE_MATCH.match(contents) if matchObj: idx = matchObj.end() else: idx = 0 return "%s\n%s\n%s" %(contents[:idx], startTag, contents[idx:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convertToBooleanString(val=None): ''' convertToBooleanString - Converts a value to either a string of "true" or "false" @param val <int/str/bool> - Value ''' if hasattr(val, 'lower'): val = val.lower() # Technically, if you set one of these attributes (like "spellcheck") to a string of 'false', # it gets set to true. But we will retain "false" here. if val in ('false', '0'): return 'false' else: return 'true' try: if bool(val): return "true" except: pass 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 convertToPositiveInt(val=None, invalidDefault=0): ''' convertToPositiveInt - Convert to a positive integer, and if invalid use a given value ''' if val is None: return invalidDefault try: val = int(val) except: return invalidDefault if val < 0: return invalidDefault return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convertPossibleValues(val, possibleValues, invalidDefault, emptyValue=''): ''' convertPossibleValues - Convert input value to one of several possible values, with a default for invalid entries @param val <None/str> - The input value @param possibleValues list<str> - A list of possible values @param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None and "val" is not in #possibleValues If instantiated Exception (like ValueError('blah')): Raise this exception If an Exception type ( like ValueError ) - Instantiate and raise this exception type Otherwise, use this raw value @param emptyValue Default '', used for an empty value (empty string or None) ''' from .utils import tostr # If null, retain null if val is None: if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Convert to a string val = tostr(val).lower() # If empty string, same as null if val == '': if emptyValue is EMPTY_IS_INVALID: return _handleInvalid(invalidDefault) return emptyValue # Check if this is a valid value if val not in possibleValues: return _handleInvalid(invalidDefault) return val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _setTag(self, tag): ''' _setTag - INTERNAL METHOD. Associated a given AdvancedTag to this attributes dict. If bool(#tag) is True, will set the weakref to that tag. Otherwise, will clear the reference @param tag <AdvancedTag/None> - Either the AdvancedTag to associate, or None to clear current association ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = 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 _handleClassAttr(self): ''' _handleClassAttr - Hack to ensure "class" and "style" show up in attributes when classes are set, and doesn't when no classes are present on associated tag. TODO: I don't like this hack. ''' if len(self.tag._classNames) > 0: dict.__setitem__(self, "class", self.tag.className) else: try: dict.__delitem__(self, "class") except: pass styleAttr = self.tag.style if styleAttr.isEmpty() is False: dict.__setitem__(self, "style", styleAttr) else: try: dict.__delitem__(self, "style") except: 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 get(self, key, default=None): ''' get - Gets an attribute by key with the chance to provide a default value @param key <str> - The key to query @param default <Anything> Default None - The value to return if key is not found @return - The value of attribute at #key, or #default if not present. ''' key = key.lower() if key == 'class': return self.tag.className if key in ('style', 'class') or key in self.keys(): return self[key] return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _direct_set(self, key, value): ''' _direct_set - INTERNAL USE ONLY!!!! Directly sets a value on the underlying dict, without running through the setitem logic ''' dict.__setitem__(self, key, value) 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 setTag(self, tag): ''' setTag - Set the tag association for this style. This will handle the underlying weakref to the tag. Call setTag(None) to clear the association, otherwise setTag(tag) to associate this style to that tag. @param tag <AdvancedTag/None> - The new association. If None, the association is cleared, otherwise the passed tag becomes associated with this style. ''' if tag: self._tagRef = weakref.ref(tag) else: self._tagRef = 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 _ensureHtmlAttribute(self): ''' _ensureHtmlAttribute - INTERNAL METHOD. Ensure the "style" attribute is present in the html attributes when is has a value, and absent when it does not. This requires special linkage. ''' tag = self.tag if tag: styleDict = self._styleDict tagAttributes = tag._attributes # If this is called before we have _attributes setup if not issubclass(tagAttributes.__class__, SpecialAttributesDict): return # If we have any styles set, ensure we have the style="whatever" in the HTML representation, # otherwise ensure we don't have style="" if not styleDict: tagAttributes._direct_del('style') else: #if 'style' not in tagAttributes.keys(): tagAttributes._direct_set('style', self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setProperty(self, name, value): ''' setProperty - Set a style property to a value. NOTE: To remove a style, use a value of empty string, or None @param name <str> - The style name. NOTE: The dash names are expected here, whereas dot-access expects the camel case names. Example: name="font-weight" versus the dot-access style.fontWeight @param value <str> - The style value, or empty string to remove property ''' styleDict = self._styleDict if value in ('', None): try: del styleDict[name] except KeyError: pass else: styleDict[name] = str(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 _asStr(self): ''' _asStr - Get the string representation of this style @return <str> - A string representation of this style (semicolon separated, key: value format) ''' styleDict = self._styleDict if styleDict: return '; '.join([name + ': ' + value for name, value in styleDict.items()]) 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 _special_value_rows(em): ''' _special_value_rows - Handle "rows" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('rows', 2), minValue=1, maxValue=None, invalidDefault=2) else: # frameset return em.getAttribute('rows', '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _special_value_cols(em): ''' _special_value_cols - Handle "cols" special attribute, which differs if tagName is a textarea or frameset ''' if em.tagName == 'textarea': return convertToIntRange(em.getAttribute('cols', 20), minValue=1, maxValue=None, invalidDefault=20) else: # frameset return em.getAttribute('cols', '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _special_value_autocomplete(em): ''' handle "autocomplete" property, which has different behaviour for form vs input" ''' if em.tagName == 'form': return convertPossibleValues(em.getAttribute('autocomplete', 'on'), POSSIBLE_VALUES_ON_OFF, invalidDefault='on', emptyValue=EMPTY_IS_INVALID) # else: input return convertPossibleValues(em.getAttribute('autocomplete', ''), POSSIBLE_VALUES_ON_OFF, invalidDefault="", emptyValue='')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _special_value_size(em): ''' handle "size" property, which has different behaviour for input vs everything else ''' if em.tagName == 'input': # TODO: "size" on an input is implemented very weirdly. Negative values are treated as invalid, # A value of "0" raises an exception (and does not set HTML attribute) # No upper limit. return convertToPositiveInt(em.getAttribute('size', 20), invalidDefault=20) return em.getAttribute('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 _special_value_maxLength(em, newValue=NOT_PROVIDED): ''' _special_value_maxLength - Handle the special "maxLength" property @param em <AdvancedTag> - The tag element @param newValue - Default NOT_PROVIDED, if provided will use that value instead of the current .getAttribute value on the tag. This is because this method can be used for both validation and getting/setting ''' if newValue is NOT_PROVIDED: if not em.hasAttribute('maxlength'): return -1 curValue = em.getAttribute('maxlength', '-1') # If we are accessing, the invalid default should be negative invalidDefault = -1 else: curValue = newValue # If we are setting, we should raise an exception upon invalid value invalidDefault = IndexSizeErrorException return convertToIntRange(curValue, minValue=0, maxValue=None, emptyValue='0', invalidDefault=invalidDefault)
<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_run_breadcrumbs(cls, source_type, data_object, task_attempt): """Create a path for a given file, in such a way that files end up being organized and browsable by run """
# We cannot generate the path unless connect to a TaskAttempt # and a run if not task_attempt: return [] # If multiple tasks exist, use the original. task = task_attempt.tasks.earliest('datetime_created') if task is None: return [] run = task.run if run is None: return [] breadcrumbs = [ run.name, "task-%s" % str(task.uuid)[0:8], "attempt-%s" % str(task_attempt.uuid)[0:8], ] # Include any ancestors if run is nested while run.parent is not None: run = run.parent breadcrumbs = [run.name] + breadcrumbs # Prepend first breadcrumb with datetime and id breadcrumbs[0] = "%s-%s-%s" % ( run.datetime_created.strftime('%Y-%m-%dT%H.%M.%SZ'), str(run.uuid)[0:8], breadcrumbs[0]) breadcrumbs = ['runs'] + breadcrumbs return breadcrumbs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, *args, **kwargs): """ This save method protects against two processesses concurrently modifying the same object. Normally the second save would silently overwrite the changes from the first. Instead we raise a ConcurrentModificationError. """
cls = self.__class__ if self.pk: rows = cls.objects.filter( pk=self.pk, _change=self._change).update( _change=self._change + 1) if not rows: raise ConcurrentModificationError(cls.__name__, self.pk) self._change += 1 count = 0 max_retries=3 while True: try: return super(BaseModel, self).save(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 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 setattrs_and_save_with_retries(self, assignments, max_retries=5): """ If the object is being edited by other processes, save may fail due to concurrent modification. This method recovers and retries the edit. assignments is a dict of {attribute: value} """
count = 0 obj=self while True: for attribute, value in assignments.iteritems(): setattr(obj, attribute, value) try: obj.full_clean() obj.save() except ConcurrentModificationError: if count >= max_retries: raise SaveRetriesExceededError( 'Exceeded retries when saving "%s" of id "%s" '\ 'with assigned values "%s"' % (self.__class__, self.id, assignments)) count += 1 obj = self.__class__.objects.get(id=self.id) continue return 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 delete(self, *args, **kwargs): """ This method implements retries for object deletion. """
count = 0 max_retries=3 while True: try: return super(BaseModel, self).delete(*args, **kwargs) except django.db.utils.OperationalError: if count >= max_retries: raise count += 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 get_server_type(): """Checks server.ini for server type."""
server_location_file = os.path.expanduser(SERVER_LOCATION_FILE) if not os.path.exists(server_location_file): raise Exception( "%s not found. Please run 'loom server set " "<servertype>' first." % server_location_file) config = ConfigParser.SafeConfigParser() config.read(server_location_file) server_type = config.get('server', 'type') return server_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 _set_upload_status(self, file_data_object, upload_status): """ Set file_data_object.file_resource.upload_status """
uuid = file_data_object['uuid'] return self.connection.update_data_object( uuid, {'uuid': uuid, 'value': { 'upload_status': upload_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 _substitute_file_uuids_throughout_template(self, template, file_dependencies): """Anywhere in "template" that refers to a data object but does not give a specific UUID, if a matching file can be found in "file_dependencies", we will change the data object reference to use that UUID. That way templates have a preference to connect to files nested under their ".dependencies" over files that were previously imported to the server. """
if not isinstance(template, dict): # Nothing to do if this is a reference to a previously imported template. return for input in template.get('inputs', []): self._substitute_file_uuids_in_input(input, file_dependencies) for step in template.get('steps', []): self._substitute_file_uuids_throughout_template(step, file_dependencies)
<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, validated_data): """ This is a standard method called indirectly by calling 'save' on the serializer. This method expects the 'parent_field' and 'parent_instance' to be included in the Serializer context. """
if self.context.get('parent_field') \ and self.context.get('parent_instance'): validated_data.update({ self.context.get('parent_field'): self.context.get('parent_instance')}) instance = self.Meta.model(**validated_data) instance.full_clean() instance.save() return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_insecure_request_warning(): """Suppress warning about untrusted SSL certificate."""
import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_request_to_server(self, query_function, raise_for_status=True, time_limit_seconds=2, retry_delay_seconds=0.2): """Retry sending request until timeout or until receiving a response. """
start_time = datetime.datetime.now() while datetime.datetime.now() - start_time < datetime.timedelta( 0, time_limit_seconds): error = None response = None try: response = query_function() except requests.exceptions.ConnectionError as e: error = ServerConnectionError( "No response from server.\n%s" % e) except: if response: logger.info(response.text) raise if response is not None and raise_for_status: # raises requests.exceptions.HTTPError self._raise_for_status(response) if error: time.sleep(retry_delay_seconds) continue else: return response raise error
<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_resource(self, relative_url, params=None): """Convenience function for retrieving a resource. If resource does not exist, return None. """
response = self._get(relative_url, params=params, raise_for_status=False) if response.status_code == 404: return None self._raise_for_status(response) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TaskAttemptInput(input, task_attempt): """Returns the correct Input class for a given data type and gather mode """
(data_type, mode) = _get_input_info(input) if data_type != 'file': return NoOpInput(None, task_attempt) if mode == 'no_gather': return FileInput(input['data']['contents'], task_attempt) else: assert mode.startswith('gather') return FileListInput(input['data']['contents'], task_attempt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(task_function, *args, **kwargs): """Run a task asynchronously """
if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously logger.debug('Running function "%s" synchronously because '\ 'TEST_DISABLE_ASYNC_DELAY is True' % task_function.__name__) return task_function(*args, **kwargs) db.connections.close_all() task_function.delay(*args, **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 execute_with_delay(task_function, *args, **kwargs): """Run a task asynchronously after at least delay_seconds """
delay = kwargs.pop('delay', 0) if get_setting('TEST_DISABLE_ASYNC_DELAY'): # Delay disabled, run synchronously logger.debug('Running function "%s" synchronously because '\ 'TEST_DISABLE_ASYNC_DELAY is True' % task_function.__name__) return task_function(*args, **kwargs) db.connections.close_all() task_function.apply_async(args=args, kwargs=kwargs, countdown=delay)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_stalled_tasks(): """Check for tasks that are no longer sending a heartbeat """
from api.models.tasks import Task for task in Task.objects.filter(status_is_running=True): if not task.is_responsive(): task.system_error() if task.is_timed_out(): task.timeout_error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_for_missed_cleanup(): """Check for TaskAttempts that were never cleaned up """
if get_setting('PRESERVE_ALL'): return from api.models.tasks import TaskAttempt if get_setting('PRESERVE_ON_FAILURE'): for task_attempt in TaskAttempt.objects.filter( status_is_running=False).filter( status_is_cleaned_up=False).exclude( status_is_failed=True): task_attempt.cleanup() else: for task_attempt in TaskAttempt.objects.filter( status_is_running=False).filter(status_is_cleaned_up=False): task_attempt.cleanup()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute_with_retries(retryable_function, retryable_errors, logger, human_readable_action_name='Action', nonretryable_errors=None): """This attempts to execute "retryable_function" with exponential backoff on delay time. 10 retries adds up to about 34 minutes total delay before the last attempt. "human_readable_action_name" is an option input to customize retry message. """
max_retries = 10 attempt = 0 if not nonretryable_errors: nonretryable_errors = () while True: try: return retryable_function() except tuple(nonretryable_errors): raise except tuple(retryable_errors) as e: attempt += 1 if attempt > max_retries: raise # Exponentional backoff on retry delay as suggested by # https://cloud.google.com/storage/docs/exponential-backoff delay = 2**attempt + random.random() logger.info('"%s" failed with error "%s". '\ 'Retry number %s of %s in %s seconds' % (human_readable_action_name, str(e), attempt, max_retries, delay)) time.sleep(delay)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_file(self, data_object, destination_directory=None, destination_filename=None, retry=False, export_metadata=False, export_raw_file=True): """Export a file from Loom to some file storage location. Default destination_directory is cwd. Default destination_filename is the filename from the file data object associated with the given file_id. """
if not destination_directory: destination_directory = os.getcwd() # We get filename from the dataobject if not destination_filename: destination_filename = data_object['value']['filename'] destination_file_url = os.path.join(destination_directory, destination_filename) logger.info('Exporting file %s@%s ...' % ( data_object['value']['filename'], data_object['uuid'])) if export_raw_file: destination = File( destination_file_url, self.storage_settings, retry=retry) if destination.exists(): raise FileAlreadyExistsError( 'File already exists at %s' % destination_file_url) logger.info('...copying file to %s' % ( destination.get_url())) # Copy from the first file location file_resource = data_object.get('value') md5 = file_resource.get('md5') source_url = data_object['value']['file_url'] File(source_url, self.storage_settings, retry=retry).copy_to( destination, expected_md5=md5) data_object['value'] = self._create_new_file_resource( data_object['value'], destination.get_url()) else: logger.info('...skipping raw file') if export_metadata: data_object['value'].pop('link', None) data_object['value'].pop('upload_status', None) destination_metadata_url = os.path.join( destination_file_url + '.metadata.yaml') logger.info('...writing metadata to %s' % destination_metadata_url) metadata = yaml.safe_dump(data_object, default_flow_style=False) metadata_file = File(destination_metadata_url, self.storage_settings, retry=retry) metadata_file.write(metadata) else: logger.info('...skipping metadata') logger.info('...finished file export')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FilePattern(pattern, settings, **kwargs): """Factory method returns LocalFilePattern or GoogleStorageFilePattern """
url = _urlparse(pattern) if url.scheme == 'gs': return GoogleStorageFilePattern(pattern, settings, **kwargs) else: assert url.scheme == 'file' return LocalFilePattern(pattern, settings, **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 Copier(source, destination): """Factory method to select the right copier for a given source and destination. """
if source.type == 'local' and destination.type == 'local': return LocalCopier(source, destination) elif source.type == 'local' and destination.type == 'google_storage': return Local2GoogleStorageCopier(source, destination) elif source.type == 'google_storage' and destination.type == 'local': return GoogleStorage2LocalCopier(source, destination) elif source.type == 'google_storage' and destination.type == 'google_storage': return GoogleStorageCopier(source, destination) else: raise FileUtilsError('Could not find method to copy from source '\ '"%s" to destination "%s".' % (source, destination))
<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_from_data_channel(cls, data_channel): """Scan the data tree on the given data_channel to create a corresponding InputSetGenerator tree. """
gather_depth = cls._get_gather_depth(data_channel) generator = InputSetGeneratorNode() for (data_path, data_node) in data_channel.get_ready_data_nodes( [], gather_depth): flat_data_node = data_node.flattened_clone(save=False) input_item = InputItem( flat_data_node, data_channel.channel, data_channel.as_channel, mode=data_channel.mode) generator._add_input_item(data_path, input_item) return generator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TaskAttemptOutput(output, task_attempt): """Returns the correct Output class for a given data type, source type, and scatter mode """
(data_type, mode, source_type) = _get_output_info(output) if data_type == 'file': if mode == 'scatter': assert source_type in ['filenames', 'glob'], \ 'source type "%s" not allowed' % source_type if source_type == 'filenames': return FileListScatterOutput(output, task_attempt) return GlobScatterOutput(output, task_attempt) else: assert mode == 'no_scatter' assert source_type == 'filename', \ 'source type "%s" not allowed' % source_type return FileOutput(output, task_attempt) else: # data_type is non-file if mode == 'scatter': assert source_type in [ 'filename', 'filenames', 'glob', 'stream'], \ 'source type "%s" not allowed' % source_type if source_type == 'filename': return FileContentsScatterOutput(output, task_attempt) if source_type == 'filenames': return FileListContentsScatterOutput(output, task_attempt) if source_type == 'glob': return GlobContentsScatterOutput(output, task_attempt) assert source_type == 'stream' return StreamScatterOutput(output, task_attempt) else: assert mode == 'no_scatter' assert source_type in ['filename', 'stream'], \ 'source type "%s" not allowed' % source_type if source_type == 'filename': return FileContentsOutput(output, task_attempt) assert source_type == 'stream' return StreamOutput(output, task_attempt)
<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_leaf(self, index, data_object, save=False): """Adds a new leaf node at the given index with the given data_object """
assert self.type == data_object.type, 'data type mismatch' if self._get_child_by_index(index) is not None: raise NodeAlreadyExistsError( 'Leaf data node already exists at this index') else: data_node = DataNode( parent=self, index=index, data_object=data_object, type=self.type) if save: data_node.full_clean() data_node.save() self._add_unsaved_child(data_node) return data_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 _check_index(self, index): """Verify that the given index is consistent with the degree of the node. """
if self.degree is None: raise UnknownDegreeError( 'Cannot access child DataNode on a parent with degree of None. '\ 'Set the degree on the parent first.') if index < 0 or index >= self.degree: raise IndexOutOfRangeError( 'Out of range index %s. DataNode parent has degree %s, so index '\ 'should be in the range 0 to %s' % ( index, self.degree, self.degree-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_gcloud_vm(): """ Determines if we're running on a GCE instance."""
r = None try: r = requests.get('http://metadata.google.internal') except requests.ConnectionError: return False try: if r.headers['Metadata-Flavor'] == 'Google' and \ r.headers['Server'] == 'Metadata Server for VM': return True except KeyError: 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 get_gcloud_pricelist(): """Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. """
try: r = requests.get('http://cloudpricingcalculator.appspot.com' '/static/data/pricelist.json') content = json.loads(r.content) except ConnectionError: logger.warning( "Couldn't get updated pricelist from " "http://cloudpricingcalculator.appspot.com" "/static/data/pricelist.json. Falling back to cached " "copy, but prices may be out of date.") with open('gcloudpricelist.json') as infile: content = json.load(infile) pricelist = content['gcp_price_list'] return pricelist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sanitize_instance_name(name, max_length): """Instance names must start with a lowercase letter. All following characters must be a dash, lowercase letter, or digit. """
name = str(name).lower() # make all letters lowercase name = re.sub(r'[^-a-z0-9]', '', name) # remove invalid characters # remove non-lowercase letters from the beginning name = re.sub(r'^[^a-z]+', '', name) name = name[:max_length] name = re.sub(r'-+$', '', name) # remove hyphens from the end return 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_all_data_from_cache(self, filename=''): ''' Reads the JSON inventory from the cache file. Returns Python dictionary. ''' data = '' if not filename: filename = self.cache_path_cache with open(filename, 'r') as cache: data = cache.read() return json.loads(data)
<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_to_cache(self, data, filename=''): ''' Writes data to file as JSON. Returns True. ''' if not filename: filename = self.cache_path_cache json_data = json.dumps(data) with open(filename, 'w') as cache: cache.write(json_data) 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 get_config(self): """ Reads the settings from the gce.ini file. Populates a SafeConfigParser object with defaults and attempts to read an .ini-style configuration from the filename specified in GCE_INI_PATH. If the environment variable is not present, the filename defaults to gce.ini in the current working directory. """
gce_ini_default_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "gce.ini") gce_ini_path = os.environ.get('GCE_INI_PATH', gce_ini_default_path) # Create a ConfigParser. # This provides empty defaults to each key, so that environment # variable configuration (as opposed to INI configuration) is able # to work. config = ConfigParser.SafeConfigParser(defaults={ 'gce_service_account_email_address': '', 'gce_service_account_pem_file_path': '', 'gce_project_id': '', 'libcloud_secrets': '', 'inventory_ip_type': '', 'cache_path': '~/.ansible/tmp', 'cache_max_age': '300' }) if 'gce' not in config.sections(): config.add_section('gce') if 'inventory' not in config.sections(): config.add_section('inventory') if 'cache' not in config.sections(): config.add_section('cache') config.read(gce_ini_path) ######### # Section added for processing ini settings ######### # Set the instance_states filter based on config file options self.instance_states = [] if config.has_option('gce', 'instance_states'): states = config.get('gce', 'instance_states') # Ignore if instance_states is an empty string. if states: self.instance_states = states.split(',') # Caching cache_path = config.get('cache', 'cache_path') cache_max_age = config.getint('cache', 'cache_max_age') # TOOD(supertom): support project-specific caches cache_name = 'ansible-gce.cache' self.cache = CloudInventoryCache(cache_path=cache_path, cache_max_age=cache_max_age, cache_name=cache_name) return config
<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_inventory_options(self): """Determine inventory options. Environment variables always take precedence over configuration files."""
ip_type = self.config.get('inventory', 'inventory_ip_type') # If the appropriate environment variables are set, they override # other configuration ip_type = os.environ.get('INVENTORY_IP_TYPE', ip_type) return ip_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 get_gce_driver(self): """Determine the GCE authorization settings and return a libcloud driver. """
# Attempt to get GCE params from a configuration file, if one # exists. secrets_path = self.config.get('gce', 'libcloud_secrets') secrets_found = False try: import secrets args = list(getattr(secrets, 'GCE_PARAMS', [])) kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {}) secrets_found = True except: pass if not secrets_found and secrets_path: if not secrets_path.endswith('secrets.py'): err = "Must specify libcloud secrets file as " err += "/absolute/path/to/secrets.py" sys.exit(err) sys.path.append(os.path.dirname(secrets_path)) try: import secrets args = list(getattr(secrets, 'GCE_PARAMS', [])) kwargs = getattr(secrets, 'GCE_KEYWORD_PARAMS', {}) secrets_found = True except: pass if not secrets_found: args = [ self.config.get('gce','gce_service_account_email_address'), self.config.get('gce','gce_service_account_pem_file_path') ] kwargs = {'project': self.config.get('gce', 'gce_project_id')} # If the appropriate environment variables are set, they override # other configuration; process those into our args and kwargs. args[0] = os.environ.get('GCE_EMAIL', args[0]) args[1] = os.environ.get('GCE_PEM_FILE_PATH', args[1]) kwargs['project'] = os.environ.get('GCE_PROJECT', kwargs['project']) # Retrieve and return the GCE driver. gce = get_driver(Provider.GCE)(*args, **kwargs) gce.connection.user_agent_append( '%s/%s' % (USER_AGENT_PRODUCT, USER_AGENT_VERSION), ) return gce
<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_env_zones(self): '''returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call''' import csv reader = csv.reader([os.environ.get('GCE_ZONE',"")], skipinitialspace=True) zones = [r for r in reader] return [z for z in zones[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 parse_cli_args(self): ''' Command line argument processing ''' parser = argparse.ArgumentParser( description='Produce an Ansible Inventory file based on GCE') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all information about an instance') parser.add_argument('--pretty', action='store_true', default=False, help='Pretty format (default: False)') parser.add_argument( '--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests (default: False - use cache files)') self.args = parser.parse_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 load_inventory_from_cache(self): ''' Loads inventory from JSON on disk. ''' try: self.inventory = self.cache.get_all_data_from_cache() hosts = self.inventory['_meta']['hostvars'] except Exception as e: print( "Invalid inventory file %s. Please rebuild with -refresh-cache option." % (self.cache.cache_path_cache)) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_api_calls_update_cache(self): ''' Do API calls and save data in cache. ''' zones = self.parse_env_zones() data = self.group_instances(zones) self.cache.write_to_cache(data) self.inventory = data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def group_instances(self, zones=None): '''Group all instances''' groups = {} meta = {} meta["hostvars"] = {} for node in self.list_nodes(): # This check filters on the desired instance states defined in the # config file with the instance_states config option. # # If the instance_states list is _empty_ then _ALL_ states are returned. # # If the instance_states list is _populated_ then check the current # state against the instance_states list if self.instance_states and not node.extra['status'] in self.instance_states: continue name = node.name meta["hostvars"][name] = self.node_to_dict(node) zone = node.extra['zone'].name # To avoid making multiple requests per zone # we list all nodes and then filter the results if zones and zone not in zones: continue if zone in groups: groups[zone].append(name) else: groups[zone] = [name] tags = node.extra['tags'] for t in tags: if t.startswith('group-'): tag = t[6:] else: tag = 'tag_%s' % t if tag in groups: groups[tag].append(name) else: groups[tag] = [name] net = node.extra['networkInterfaces'][0]['network'].split('/')[-1] net = 'network_%s' % net if net in groups: groups[net].append(name) else: groups[net] = [name] machine_type = node.size if machine_type in groups: groups[machine_type].append(name) else: groups[machine_type] = [name] image = node.image and node.image or 'persistent_disk' if image in groups: groups[image].append(name) else: groups[image] = [name] status = node.extra['status'] stat = 'status_%s' % status.lower() if stat in groups: groups[stat].append(name) else: groups[stat] = [name] groups["_meta"] = meta return groups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def json_format_dict(self, data, pretty=False): ''' Converts a dict to a JSON object and dumps it as a formatted string ''' if pretty: return json.dumps(data, sort_keys=True, indent=2) else: return json.dumps(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stream_docker_logs(self): """Stream stdout and stderr from the task container to this process's stdout and stderr, respectively. """
thread = threading.Thread(target=self._stderr_stream_worker) thread.start() for line in self.docker_client.logs(self.container, stdout=True, stderr=False, stream=True): sys.stdout.write(line) thread.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_internal_value(self, data): """Because we allow template ID string values, where serializers normally expect a dict """
converted_data = _convert_template_id_to_dict(data) return super(TemplateSerializer, self)\ .to_internal_value(converted_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce(cls, version_string, partial=False): """Coerce an arbitrary version string into a semver-compatible one. The rule is: - If not enough components, fill minor/patch with zeroes; unless partial=True - If more than 3 dot-separated components, extra components are "build" data. If some "build" data already appeared, append it to the extra components Examples: Version(0, 1, 0) Version(0, 1, 2, (), ('3',)) Version(0, 1, 2, (), ('3', '4')) Version(0, 1, 0, (), ('2-3', '4-5')) """
base_re = re.compile(r'^\d+(?:\.\d+(?:\.\d+)?)?') match = base_re.match(version_string) if not match: raise ValueError( "Version string lacks a numerical component: %r" % version_string ) version = version_string[:match.end()] if not partial: # We need a not-partial version. while version.count('.') < 2: version += '.0' if match.end() == len(version_string): return Version(version, partial=partial) rest = version_string[match.end():] # Cleanup the 'rest' rest = re.sub(r'[^a-zA-Z0-9+.-]', '-', rest) if rest[0] == '+': # A 'build' component prerelease = '' build = rest[1:] elif rest[0] == '.': # An extra version component, probably 'build' prerelease = '' build = rest[1:] elif rest[0] == '-': rest = rest[1:] if '+' in rest: prerelease, build = rest.split('+', 1) else: prerelease, build = rest, '' elif '+' in rest: prerelease, build = rest.split('+', 1) else: prerelease, build = rest, '' build = build.replace('+', '.') if prerelease: version = '%s-%s' % (version, prerelease) if build: version = '%s+%s' % (version, build) return cls(version, partial=partial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _comparison_functions(cls, partial=False): """Retrieve comparison methods to apply on version components. This is a private API. Args: partial (bool): whether to provide 'partial' or 'strict' matching. Returns: 5-tuple of cmp-like functions. """
def prerelease_cmp(a, b): """Compare prerelease components. Special rule: a version without prerelease component has higher precedence than one with a prerelease component. """ if a and b: return identifier_list_cmp(a, b) elif a: # Versions with prerelease field have lower precedence return -1 elif b: return 1 else: return 0 def build_cmp(a, b): """Compare build metadata. Special rule: there is no ordering on build metadata. """ if a == b: return 0 else: return NotImplemented def make_optional(orig_cmp_fun): """Convert a cmp-like function to consider 'None == *'.""" @functools.wraps(orig_cmp_fun) def alt_cmp_fun(a, b): if a is None or b is None: return 0 return orig_cmp_fun(a, b) return alt_cmp_fun if partial: return [ base_cmp, # Major is still mandatory make_optional(base_cmp), make_optional(base_cmp), make_optional(prerelease_cmp), make_optional(build_cmp), ] else: return [ base_cmp, base_cmp, base_cmp, prerelease_cmp, build_cmp, ]
<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_helper(self, other, condition, notimpl_target): """Helper for comparison. Allows the caller to provide: - The condition - The return value if the comparison is meaningless (ie versions with build metadata). """
if not isinstance(other, self.__class__): return NotImplemented cmp_res = self.__cmp__(other) if cmp_res is NotImplemented: return notimpl_target return condition(cmp_res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, version): """Check whether a Version satisfies the Spec."""
return all(spec.match(version) for spec in self.specs)
<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(self, versions): """Select the best compatible version among an iterable of options."""
options = list(self.filter(versions)) if options: return max(options) 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 deconstruct(self): """Handle django.db.migrations."""
name, path, args, kwargs = super(VersionField, self).deconstruct() kwargs['partial'] = self.partial kwargs['coerce'] = self.coerce return name, path, args, 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 to_python(self, value): """Converts any value to a base.Version field."""
if value is None or value == '': return value if isinstance(value, base.Version): return value if self.coerce: return base.Version.coerce(value, partial=self.partial) else: return base.Version(value, partial=self.partial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_python(self, value): """Converts any value to a base.Spec field."""
if value is None or value == '': return value if isinstance(value, base.Spec): return value return base.Spec(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 move_left(self): """Make the drone move left."""
self.at(ardrone.at.pcmd, True, -self.speed, 0, 0, 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 move_right(self): """Make the drone move right."""
self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 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 move_up(self): """Make the drone rise upwards."""
self.at(ardrone.at.pcmd, True, 0, 0, self.speed, 0)