text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_assets(cls, lat, lon, begin=None, end=None): """ Returns date and ids of flyovers Args: lat: latitude float lon: longitude float begin: date instance end...
instance = cls('planetary/earth/assets') filters = { 'lat': lat, 'lon': lon, 'begin': begin, 'end': end, } return instance.get_resource(**filters)
<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_imagery(cls, lat, lon, date=None, dim=None, cloud_score=False): """ Returns satellite image Args: lat: latitude float lon: longitude float date: date ins...
instance = cls('planetary/earth/imagery') filters = { 'lat': lat, 'lon': lon, 'date': date, 'dim': dim, 'cloud_score': cloud_score } return instance.get_resource(**filters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_station(station: str): """ Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed ...
station = station.strip() if len(station) != 4: raise BadStation('ICAO station idents must be four characters long') uses_na_format(station)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """
if station[0] in NA_REGIONS: return True if station[0] in IN_REGIONS: return False if station[:2] in M_NA_REGIONS: return True if station[:2] in M_IN_REGIONS: return False raise BadStation("Station doesn't start with a recognized character set")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_leading_zeros(num: str) -> str: """ Strips zeros while handling -, M, and empty strings """
if not num: return num if num.startswith('M'): ret = 'M' + num[1:].lstrip('0') elif num.startswith('-'): ret = '-' + num[1:].lstrip('0') else: ret = num.lstrip('0') return '0' if ret in ('', 'M', '-') else 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 spoken_number(num: str) -> str: """ Returns the spoken version of a number Ex: 1.2 -> one point two 1 1/2 -> one and one half """
ret = [] for part in num.split(' '): if part in FRACTIONS: ret.append(FRACTIONS[part]) else: ret.append(' '.join([NUMBER_REPL[char] for char in part if char in NUMBER_REPL])) return ' and '.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 make_number(num: str, repr_: str = None, speak: str = None): """ Returns a Number or Fraction dataclass for a number string """
if not num or is_unknown(num): return # Check CAVOK if num == 'CAVOK': return Number('CAVOK', 9999, 'ceiling and visibility ok') # type: ignore # Check special if num in SPECIAL_NUMBERS: return Number(repr_ or num, None, SPECIAL_NUMBERS[num]) # type: ignore # Create Fr...
<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_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: fi...
start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -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_remarks(txt: str) -> ([str], str): # type: ignore """ Returns the report split into components and the remarks string Remarks can include items like RMK ...
txt = txt.replace('?', '').strip() # First look for Altimeter in txt alt_index = len(txt) + 1 for item in [' A2', ' A3', ' Q1', ' Q0', ' Q9']: index = txt.find(item) if len(txt) - 6 > index > -1 and txt[index + 2:index + 6].isdigit(): alt_index = index # Then look for ea...
<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_taf_remarks(txt: str) -> (str, str): # type: ignore """ Returns report and remarks separated if found """
remarks_start = find_first_in_list(txt, TAF_RMK) if remarks_start == -1: return txt, '' remarks = txt[remarks_start:] txt = txt[:remarks_start].strip() return txt, remarks
<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_report_string(txt: str) -> str: """ Provides sanitization for operations that work better when the report is a string Returns the first pass sanitize...
if len(txt) < 4: return txt # Standardize whitespace txt = ' '.join(txt.split()) # Prevent changes to station ID stid, txt = txt[:4], txt[4:] # Replace invalid key-value pairs for key, rep in STR_REPL.items(): txt = txt.replace(key, rep) # Check for missing spaces in fro...
<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_line(txt: str) -> str: """ Fixes common mistakes with 'new line' signifiers so that they can be recognized """
for key in LINE_FIXES: index = txt.find(key) if index > -1: txt = txt[:index] + LINE_FIXES[key] + txt[index + len(key):] # Fix when space is missing following new line signifiers for item in ['BECMG', 'TEMPO']: if item in txt and item + ' ' not in txt: index ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extra_space_exists(str1: str, str2: str) -> bool: # noqa """ Return True if a space shouldn't exist between two items """
ls1, ls2 = len(str1), len(str2) if str1.isdigit(): # 10 SM if str2 in ['SM', '0SM']: return True # 12 /10 if ls2 > 2 and str2[0] == '/' and str2[1:].isdigit(): return True if str2.isdigit(): # OVC 040 if str1 in CLOUD_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 get_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number): # type: ignore # noqa """ Returns the report list and the removed altimet...
if not wxdata: return wxdata, None altimeter = '' target = wxdata[-1] if version == 'NA': # Version target if target[0] == 'A': altimeter = wxdata.pop()[1:] # Other version but prefer normal if available elif target[0] == 'Q': if wxdata[-2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_station_and_time(wxdata: [str]) -> ([str], str, str): # type: ignore """ Returns the report list and removed station ident and time strings """
station = wxdata.pop(0) qtime = wxdata[0] if wxdata and qtime.endswith('Z') and qtime[:-1].isdigit(): rtime = wxdata.pop(0) elif wxdata and len(qtime) == 6 and qtime.isdigit(): rtime = wxdata.pop(0) + 'Z' else: rtime = '' return wxdata, station, rtime
<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_visibility(wxdata: [str], units: Units) -> ([str], Number): # type: ignore """ Returns the report list and removed visibility string """
visibility = '' # type: ignore if wxdata: item = copy(wxdata[0]) # Vis reported in statue miles if item.endswith('SM'): # 10SM if item in ('P6SM', 'M1/4SM'): visibility = item[:-2] elif '/' not in item: visibility = str(int(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 starts_new_line(item: str) -> bool: """ Returns True if the given element should start a new report line """
if item in TAF_NEWLINE: return True for start in TAF_NEWLINE_STARTSWITH: if item.startswith(start): return True 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 split_taf(txt: str) -> [str]: # type: ignore """ Splits a TAF report into each distinct time period """
lines = [] split = txt.split() last_index = 0 for i, item in enumerate(split): if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'): lines.append(' '.join(split[last_index:i])) last_index = i lines.append(' '.join(split[last_index:])) retur...
<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_next_time(lines: [dict], target: str) -> str: # type: ignore """ Returns the next FROM target value or empty """
for line in lines: if line[target] and not _is_tempo_or_prob(line['type']): return line[target] 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_temp_min_and_max(wxlist: [str]) -> ([str], str, str): # type: ignore """ Pull out Max temp at time and Min temp at time items from wx list """
temp_max, temp_min = '', '' for i, item in reversed(list(enumerate(wxlist))): if len(item) > 6 and item[0] == 'T' and '/' in item: # TX12/1316Z if item[1] == 'X': temp_max = wxlist.pop(i) # TNM03/1404Z elif item[1] == 'N': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_digit_list(alist: [str], from_index: int) -> ([str], [str]): # type: ignore """ Returns a list of items removed from a given list of strings that are al...
ret = [] alist.pop(from_index) while len(alist) > from_index and alist[from_index].isdigit(): ret.append(alist.pop(from_index)) return alist, 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 get_oceania_temp_and_alt(wxlist: [str]) -> ([str], [str], [str]): # type: ignore """ Get Temperature and Altimeter lists for Oceania TAFs """
tlist, qlist = [], [] # type: ignore if 'T' in wxlist: wxlist, tlist = _get_digit_list(wxlist, wxlist.index('T')) if 'Q' in wxlist: wxlist, qlist = _get_digit_list(wxlist, wxlist.index('Q')) return wxlist, tlist, qlist
<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_cloud(cloud: str) -> str: """ Fix rare cloud layer issues """
if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] != '/': if cloud[3] == 'O': cloud = cloud[:3] + '0' + cloud[4:] # Bad "O": FEWO03 -> FEW003 else: # Move modifiers to end: BKNC015 -> BKN015C cloud = cloud[:3] + cloud[4:] + cloud[3] 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 get_clouds(wxdata: [str]) -> ([str], list): # type: ignore """ Returns the report list and removed list of split cloud layers """
clouds = [] for i, item in reversed(list(enumerate(wxdata))): if item[:3] in CLOUD_LIST or item[:2] == 'VV': cloud = wxdata.pop(i) clouds.append(make_cloud(cloud)) return wxdata, sorted(clouds, key=lambda cloud: (cloud.altitude, cloud.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_flight_rules(vis: Number, ceiling: Cloud) -> int: """ Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: ...
# Parse visibility if not vis: return 2 if vis.repr == 'CAVOK' or vis.repr.startswith('P6'): vis = 10 # type: ignore elif vis.repr.startswith('M'): vis = 0 # type: ignore # Convert meters to miles elif len(vis.repr) == 4: vis = vis.value * 0.000621371 # 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_taf_flight_rules(lines: [dict]) -> [dict]: # type: ignore """ Get flight rules by looking for missing data in prior reports """
for i, line in enumerate(lines): temp_vis, temp_cloud = line['visibility'], line['clouds'] for report in reversed(lines[:i]): if not _is_tempo_or_prob(report['type']): if temp_vis == '': temp_vis = report['visibility'] if 'SKC' in repo...
<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_ceiling(clouds: [Cloud]) -> Cloud: # type: ignore """ Returns ceiling layer from Cloud-List or None if none found Assumes that the clouds are already sort...
for cloud in clouds: if cloud.altitude and cloud.type in ('OVC', 'BKN', 'VV'): return cloud 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 parse_date(date: str, hour_threshold: int = 200): """ Parses a report timestamp in ddhhZ or ddhhmmZ format This function assumes the given timestamp is withi...
# Format date string date = date.strip('Z') if len(date) == 4: date += '00' if not (len(date) == 6 and date.isdigit()): return # Create initial guess now = datetime.utcnow() guess = now.replace(day=int(date[0:2]), hour=int(date[2:4]) % 24, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_one(self, aws_syncr, amazon, bucket): """Make sure this bucket exists and has only attributes we want it to have"""
if bucket.permission.statements: permission_document = bucket.permission.document else: permission_document = "" bucket_info = amazon.s3.bucket_info(bucket.name) if not bucket_info.creation_date: amazon.s3.create_bucket(bucket.name, permission_docume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_python_inside(self, file_path): # type: (str) -> bool """ If .py, yes. If extensionless, open file and check shebang TODO: support variations on this: #!/...
if file_path.endswith(".py"): return True # duh. # not supporting surprising extensions, ege. .py2, .python, .corn_chowder # extensionless if "." not in file_path: try: firstline = self.open_this(file_path, "r").readline() if fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def toXMLname(string): """Convert string to a XML name."""
if string.find(':') != -1 : (prefix, localname) = string.split(':',1) else: prefix = None localname = string T = unicode(localname) N = len(localname) X = []; for i in range(N) : if i< N-1 and T[i]==u'_' and T[i+1]==u'x': X.append(u'_x005F_') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromXMLname(string): """Convert XML name to unicode string."""
retval = sub(r'_xFFFF_','', string ) def fun( matchobj ): return _fromUnicodeHex( matchobj.group(0) ) retval = sub(r'_x[0-9A-Za-z]+_', fun, retval ) return retval
<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_sip_to_fc(fc, tfidf, limit=40): '''add "bowNP_sip" to `fc` using `tfidf` data ''' if 'bowNP' not in fc: return if tfidf is None: return sips = features.sip_noun_phrases(tfidf, fc['bowNP'].keys(), limit=limit) fc[u'bowNP_sip'] = StringCounter(sips)
<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_password(self): ''' a method to retrieve the password for the group mosquitto server :return: string with group mosquitto server password NOTE: result is added to self.password property ''' import requests url = '%s/mqtt' % self.endpoint ...
<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_position(self, user_id, track=False, confidence=False): ''' a method to retrieve the latest position of a user :param user_id: string with id of user :param track: [optional] boolean to add user to self.positions :param confidence: [optional] boolean to include the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_begin_message(message): """ Create and print a new log message waiting for an end log message """
global MESSAGE MESSAGE = message sys.stdout.write("[....] ") sys.stdout.write(message) sys.stdout.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_end_message(log): """ End a log message with a status defined by log """
if not log in MESSAGE_LOG.keys(): log = -1 res = colors.color_text(*MESSAGE_LOG[log][1]) sys.stdout.write("\r[" + res + "] " + MESSAGE + "\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _fetchFilesFromFolder(self, target, recursive): ''' Fetches files from the target directory, and - if recursive mode is on, all subdirectories. Returns a list of all found files ''' directory_items = os.walk(target) # If recursive is false, fetch...
<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, iid): ''' Deletes file from vault and removes database information ''' for index in iid: target = Target.getTarget(index) target.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deploy(self, iid): ''' Links an item from the vault to the original path ''' for index in iid: target = Target.getTarget(index) if target: verbose('Deploying id {} from {} to {} with the name {}' .format(index, targ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def deployAll(self): ''' Deploys all the items from the vault. Useful after a format ''' targets = [Target.getTarget(iid) for iid, n, p in self.db.listTargets()] for target in targets: target.deploy() verbose('Deploy all complete')
<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_delete(resc, req, resp, rid): # pylint: disable=unused-argument """ Delete the single item Upon a successful deletion an empty bodied 204 is returned. """
signals.pre_req.send(resc.model) signals.pre_req_delete.send(resc.model) model = find(resc.model, rid) goldman.sess.store.delete(model) resp.status = falcon.HTTP_204 signals.post_req.send(resc.model) signals.post_req_delete.send(resc.model)
<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_get(resc, req, resp, rid): """ Find the model by id & serialize it back """
signals.pre_req.send(resc.model) signals.pre_req_find.send(resc.model) model = find(resc.model, rid) props = to_rest_model(model, includes=req.includes) resp.last_modified = model.updated resp.serialize(props) signals.post_req.send(resc.model) signals.post_req_find.send(resc.model)
<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_patch(resc, req, resp, rid): """ Deserialize the payload & update the single item """
signals.pre_req.send(resc.model) signals.pre_req_update.send(resc.model) props = req.deserialize() model = find(resc.model, rid) from_rest(model, props) goldman.sess.store.update(model) props = to_rest_model(model, includes=req.includes) resp.last_modified = model.updated resp.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 decode(data): """ Handles decoding of the XML `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """
dom = None try: dom = dhtmlparser.parseString(data) except Exception, e: raise MetaParsingException("Can't parse your XML data: %s" % e.message) root = dom.find("root") # check whether there is <root>s if not root: raise MetaParsingException("All elements have to be in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate(self, ideSettings, ideGlobalData): """Activates the plugin. The plugin may override the method to do specific plugin activation handling. ideSetting...
WizardInterface.activate(self, ideSettings, ideGlobalData) self.__where = self.__getConfiguredWhere() self.ide.editorsManager.sigTabClosed.connect(self.__collectGarbage) self.ide.project.sigProjectChanged.connect(self.__collectGarbage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deactivate(self): """Deactivates the plugin. The plugin may override the method to do specific plugin deactivation handling. Note: if overriden do not forget...
self.ide.project.sigProjectChanged.disconnect(self.__collectGarbage) self.ide.editorsManager.sigTabClosed.disconnect(self.__collectGarbage) WizardInterface.deactivate(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 populateMainMenu(self, parentMenu): """Populates the main menu. The main menu looks as follows: Plugins - Plugin manager (fixed item) - Separator (fixed item...
parentMenu.addAction("Configure", self.configure) parentMenu.addAction("Collect garbage", self.__collectGarbage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def populateBufferContextMenu(self, parentMenu): """Populates the editing buffer context menu. The buffer context menu shown for the current edited/viewed file w...
parentMenu.addAction("Configure", self.configure) parentMenu.addAction("Collect garbage", self.__collectGarbage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self): """Configures the garbage collector plugin"""
dlg = GCPluginConfigDialog(self.__where) if dlg.exec_() == QDialog.Accepted: newWhere = dlg.getCheckedOption() if newWhere != self.__where: self.__where = newWhere self.__saveConfiguredWhere()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __getConfiguredWhere(self): """Provides the saved configured value"""
defaultSettings = {'where': GCPluginConfigDialog.SILENT} configFile = self.__getConfigFile() if not os.path.exists(configFile): values = defaultSettings else: values = loadJSON(configFile, 'garbage collector plugin settings', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, data, accepted_media_type=None, renderer_context=None): """ Render `data` into JSON, returning a bytestring. """
if data is None: return bytes() renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_context) if indent is None: separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS else: 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 render(self, data, accepted_media_type=None, renderer_context=None): """ Render serializer data and return an HTML form, as a string. """
form = data.serializer style = renderer_context.get('style', {}) if 'template_pack' not in style: style['template_pack'] = self.template_pack style['renderer'] = self template_pack = style['template_pack'].strip('/') template_name = template_pack + '/' + se...
<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_content(self, renderer, data, accepted_media_type, renderer_context): """ Get the content as if it had been rendered by the default non-documenting rende...
if not renderer: return '[No renderers were found]' renderer_context['indent'] = 4 content = renderer.render(data, accepted_media_type, renderer_context) render_style = getattr(renderer, 'render_style', 'text') assert render_style in ['text', 'binary'], 'Expected ....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def show_form_for_method(self, view, method, request, obj): """ Returns True if a form should be shown for this method. """
if method not in view.allowed_methods: return # Not a valid method try: view.check_permissions(request) if obj is not None: view.check_object_permissions(request, obj) except exceptions.APIException: return False # Doesn't have ...
<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_rendered_html_form(self, data, view, method, request): """ Return a string representing a rendered HTML form, possibly bound to either the input or outpu...
# See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) if isinstance(instance, Page): instance = None else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context(self, data, accepted_media_type, renderer_context): """ Returns the context used to render. """
view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] renderer = self.get_default_renderer(view) raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) raw_data_put_form = self.get_raw_data_form(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(package, **kwargs): """a template for the python setup.py installer routine * take setup information from the packages __init__.py file - __email__ - _...
def read(*paths): """Build a file path from *paths* and return the contents.""" p = os.path.join(*paths) if os.path.exists(p): with open(p, 'r') as f: return f.read() return '' setuptoolsSetup( name=package.__name__, version=package....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_object(self, correlation_id, parameters): """ Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_...
path = self.get_path() if path == None: raise ConfigException(correlation_id, "NO_PATH", "Missing config file path") if not os.path.isfile(path): raise FileException(correlation_id, 'FILE_NOT_FOUND', 'Config file was not found at ' + path) 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 read_config(self, correlation_id, parameters): """ Reads configuration and parameterize it with given values. :param correlation_id: (optional) transaction i...
value = self._read_object(correlation_id, parameters) return ConfigParams.from_value(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_config(correlation_id, path, parameters): """ Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object....
value = YamlConfigReader(path)._read_object(correlation_id, parameters) return ConfigParams.from_value(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 run(self): """ Perform the specified action """
if self.args['add']: self.action_add() elif self.args['rm']: self.action_rm() elif self.args['show']: self.action_show() elif self.args['rename']: self.action_rename() else: self.action_run_command()
<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_db(self): """ Init database and prepare tables """
# database file db_path = self.get_data_file("data.sqlite") # comect and create cursor self.db = sqlite3.connect(db_path) self.cursor = self.db.cursor() # prep tables self.db_exec(''' CREATE TABLE IF NOT EXISTS shortcuts ( id INTEGE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shortcut_str(self, path, cmd): """ Get a string with colors describing a shortcut """
s = colored('| path = ', 'cyan') + colored(path, 'yellow') + '\n' \ + colored('| cmd = ', 'cyan') + \ colored(cmd, 'green', attrs=['bold']) return 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 delete_bucket(): """ Delete S3 Bucket """
args = parser.parse_args s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name)().delete()
<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_instance_status(self, instance_id, wait=True): ''' a method to wait until AWS instance reports an OK status :param instance_id: string of instance id on AWS :param wait: [optional] boolean to wait for instance while initializing :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 list_instances(self, tag_values=None): ''' a method to retrieve the list of instances on AWS EC2 :param tag_values: [optional] list of tag values :return: list of strings with instance AWS ids ''' title = '%s.list_instances' % self.__class__.__name__ # 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 read_instance(self, instance_id): ''' a method to retrieving the details of a single instances on AWS EC2 :param instance_id: string of instance id on AWS :return: dictionary with instance attributes relevant fields: 'instance_id': '', 'image_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 delete_instance(self, instance_id): ''' method for removing an instance from AWS EC2 :param instance_id: string of instance id on AWS :return: string reporting state of instance ''' title = '%s.delete_instance' % self.__class__.__name__ # validate inputs ...
<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_images(self, tag_values=None): ''' a method to retrieve the list of images of account on AWS EC2 :param tag_values: [optional] list of tag values :return: list of image AWS ids ''' title = '%s.list_images' % self.__class__.__name__ # validate inputs ...
<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_image(self, image_id): ''' a method to retrieve the details of a single image on AWS EC2 :param image_id: string with AWS id of image :return: dictionary of image attributes relevant fields: 'image_id': '', 'snapshot_id': '', 'regi...
<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_image(self, image_id): ''' method for removing an image from AWS EC2 :param image_id: string with AWS id of instance :return: string with AWS response from snapshot delete ''' title = '%s.delete_image' % self.__class__.__name__ # validate inputs ...
<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_keypairs(self): ''' a method to discover the list of key pairs on AWS :return: list of key pairs ''' title = '%s.list_keypairs' % self.__class__.__name__ # request subnet list from AWS self.iam.printer('Querying AWS region %s for key pairs.' % self.ia...
<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_subnets(self, tag_values=None): ''' a method to discover the list of subnets on AWS EC2 :param tag_values: [optional] list of tag values :return: list of strings with subnet ids ''' title = '%s.list_subnets' % self.__class__.__name__ # validate inputs...
<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_subnet(self, subnet_id): ''' a method to retrieve the details about a subnet :param subnet_id: string with AWS id of subnet :return: dictionary with subnet details relevant fields: 'subnet_id': '', 'vpc_id': '', 'availability_zone'...
<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_security_group(self, group_id): ''' a method to retrieve the details about a security group :param group_id: string with AWS id of security group :return: dictionary with security group details relevant fields: 'group_id: '', 'vpc_id': '',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_help(self, file=None): """ recursively call all command parsers' helps """
output = file or self.stderr CustomStderrOptionParser.print_help(self, output) output.write("\nCommands:\n") for command_def in self.command_definitions.values(): command_def.opt_parser.print_help(output) output.write("\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_groups(user): """Return the set of associated TenantGroups for the given user."""
if user.is_active and user.is_authenticated(): if user.is_superuser: return TenantGroup.objects.all() else: return TenantGroup.objects.filter(tenantrole__user=user).distinct() else: return TenantGroup.objects.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 get_user_tenants(user, group): """Return the set of associated Tenants for the given user and group."""
if user.is_active and user.is_authenticated(): if user.is_superuser or is_group_manager(user, group.pk): return Tenant.objects.filter(group=group) else: return Tenant.objects.filter(group=group, tenantrole__user=user).distinct() else: return Tenant.objects.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 get_user_roles(user): """Return a list of all of the user's roles."""
if not hasattr(user, '_role_cache'): user._role_cache = list(TenantRole.objects.filter(user=user).values_list( 'group', 'role', 'tenant')) return user._role_cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_group_manager(user, group=None): """Returns True if user is a group manager either for the group or any group."""
roles = get_user_roles(user) return any(x[1] == TenantRole.ROLE_GROUP_MANAGER and (not group or x[0] == group) for x in roles)
<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 ConsumePage."""
global _instances if isinstance(page_to_consume, basestring): uri = page_to_consume page_to_consume = page.get_instance(uri) elif isinstance(page_to_consume, page.Page): uri = page_to_consume.uri else: raise TypeError( "get_instance() expects a parker.Page or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_key_value_dict_by_selectors( self, key_selector, value_selector, value_sub_selector=None ): """Return a dictionary of key value data."""
key_nodes = self.parsedpage.get_nodes_by_selector(key_selector) keys = [ self.parsedpage.get_text_from_node(node) for node in key_nodes ] value_nodes = self.parsedpage.get_nodes_by_selector(value_selector) if value_sub_selector is not None: v...
<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_crumb_list_by_selector(self, crumb_selector): """Return a list of crumbs."""
return [ self.parsedpage.get_text_from_node(crumb) for crumb in self.parsedpage.get_nodes_by_selector(crumb_selector) ]
<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_media_list_by_selector( self, media_selector, media_attribute="src" ): """Return a list of media."""
page_url = urlparse.urlparse(self.uri) return [ mediafile.get_instance( urlparse.urljoin( "%s://%s" % ( page_url.scheme, page_url.netloc ), urlparse.urlparse( ...
<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_data_dict_from_config(self, config_dict): """Return a dictionary of data inferred from config_dict."""
return { key: self.parsedpage.get_filtered_values_by_selector( item_dict['selector'], item_dict.get('regex_filter', None), item_dict.get('regex_group', 1) ) for key, item_dict in config_dict.iteritems() if item_dict...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_jobs(args, job_list, argument_string): """Generate actual scripts to be submitted to the cluster :param args: argparse argument collection :param jo...
mvtest_path = args.mvpath template = "".join(args.template.readlines()) logpath = os.path.abspath(args.logpath) respath = os.path.abspath(args.res_path) scriptpath = os.path.abspath(args.script_path) pwd = os.path.abspath(os.getcwd()) for jobname in job_list.keys(): filename = "%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_template_file(args): """Returns valid template file, generating the default template file if it doesn't exist and one wasn't specified on command line. :...
if args.template is None: template_filename = os.getenv("HOME") + "/.mvmany.template" try: template_filename = open(template_filename, "r") except: with open(template_filename, "w") as file: print >> file, """#SBATCH --job-name=$jobname #SBATCH --nod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_mach_jobs(args, filename): """Parse the MACH file and generate the list of jobs. :param args: Arguments from parseargs :param filename: name of file co...
max_snp_count = args.snps_per_job job_list = {} cur = None last_pos = None job_string = "" job_name = "" mach_count = 1 if args.mach_count: mach_count = args.mach_count ExitIf("mvmany doesn't support splitting mach jobs into pieces at this time", max_snp_count > 1) d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_impute_jobs(args, filename): """Parse the IMPUTE file and generate the list of jobs. :param args: parsearg object containing command line arguments :fi...
max_snp_count = args.snps_per_job if args.impute_count: impute_count = args.impute_count else: impute_count = 1 ExitIf("mvmany doesn't support splitting IMPUTE jobs into pieces at this time", max_snp_count > 1) job_list = {} gen_files = [] for line in open(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 split_chrom_jobs(args, chrom_file): """Split up GWAS jobs based on portions of a chromosome :param args: arguments from parseargs :param chrom_file: marker i...
max_snp_count = args.snps_per_job poscol = 3 if args.map3: poscol = 2 job_list = {} cur = None last_pos = None job_string = "" job_name = "" for line in sys_call("cut -f 1,%d %s" % (poscol, chrom_file)): pos = -1 values = line.split() if len(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 diff(self, *args): """Call forward_mode; discard value, only keep the derivative."""
arg_dicts = self._parse_args_forward_mode(*args) val, diff = self._forward_mode(*arg_dicts) return diff
<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_forward_mode_input_dict(self, var_tbl: dict) -> int: """ Check whether one forward mode input dict has elements of valid shape Returns inferred value o...
T: int = 1 for var_name in var_tbl: # The bound value to this variable name val = var_tbl[var_name] # case 1: this is a scalar; T=1 if isinstance(val, scalar_instance_types): t = 1 # case 2: this is an array; calulate 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 _check_forward_mode_input_array(self, X: np.ndarray) -> int: """ Check whether one forward mode input array is of valid shape Returns inferred value of T """
# Find the length of each variable to infer T if not isinstance(X, np.ndarray): raise ValueError('X must be a numpy array, dict, or scalar') # Get the shape and tensor rank shape = X.shape tensor_rank = len(shape) T = 0 # Only 1D and 2D arrays are sup...
<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_T_var(self,X) -> int: """Calculate the number of samples, T, from the shape of X"""
shape = X.shape tensor_rank: int = len(shape) if tensor_rank == 0: return 1 if tensor_rank == 1: return shape[0] if tensor_rank == 2: if shape[1] > 1: raise ValueError('Initial value of a variable must have dimension T*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 _forward_mode(self, *args): """Forward mode differentiation for a sum"""
# (f+g)(x) = f(x) + g(x) f_val, f_diff = self.f._forward_mode(*args) g_val, g_diff = self.g._forward_mode(*args) # The function value and derivative is the sum of f and g val = f_val + g_val diff = f_diff + g_diff return val, diff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _forward_mode(self, *args): """Forward mode differentiation for variables"""
# Parse arguments into two numpy arrays X: np.ndarray dX: np.ndarray X, dX = self._parse_dicts(*args) # The value is X if X is not None: val = X else: val = self.X # The derivative is the seed dX if dX is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(): """Command for applying upgrades."""
logfilename = os.path.join(current_app.config['CFG_LOGDIR'], 'invenio_upgrader.log') upgrader = InvenioUpgrader() logger = upgrader.get_logger(logfilename=logfilename) try: upgrades = upgrader.get_upgrades() if not upgrades: logger.info("All ...
<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(): """Command for checking upgrades."""
upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: # Run upgrade pre-checks upgrades = upgrader.get_upgrades() # Check if there's anything to upgrade if not upgrades: logger.info("All upgrades have been applied.") return logge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pending(): """Command for showing upgrades ready to be applied."""
upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: upgrades = upgrader.get_upgrades() if not upgrades: logger.info("All upgrades have been applied.") return logger.info("Following upgrade(s) are ready to be applied:") for u in upgrad...