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 config_dir(mkcustom=False): """Returns the configuration directory for custom package settings. """
from acorn.utility import reporoot from acorn.base import testmode from os import path alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if testmode or (not path.isdir(alternate) and not mkcustom): return path.join(reporoot, "acorn", "config") else: if mkcustom...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _package_path(package): """Returns the full path to the default package configuration file. Args: package (str): name of the python package to return a path...
from os import path confdir = config_dir() return path.join(confdir, "{}.cfg".format(package))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_single(parser, filepath): """Reads a single config file into the parser, silently failing if the file does not exist. Args: parser (ConfigParser): par...
from os import path global packages if path.isfile(filepath): parser.readfp(open(filepath))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settings(package, reload_=False): """Returns the config settings for the specified package. Args: package (str): name of the python package to get settings ...
global packages if package not in packages or reload_: from os import path result = CaseConfigParser() if package != "acorn": confpath = _package_path(package) _read_single(result, confpath) _read_single(result, _package_path("acorn")) packages[pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def descriptors(package): """Returns a dictionary of descriptors deserialized from JSON for the specified package. Args: package (str): name of the python packa...
from os import path dpath = _descriptor_path(package) if path.isfile(dpath): import json with open(dpath) as f: jdb = json.load(f) return jdb else: 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_magnet(magnet_uri): """returns a dictionary of parameters contained in a magnet uri"""
data = defaultdict(list) if not magnet_uri.startswith('magnet:'): return data else: magnet_uri = magnet_uri.strip('magnet:?') for segment in magnet_uri.split('&'): key, value = segment.split('=') if key == 'dn': data['name'] = requests.utils.u...
<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_torrent_file(torrent): """parse local or remote torrent file"""
link_re = re.compile(r'^(http?s|ftp)') if link_re.match(torrent): response = requests.get(torrent, headers=HEADERS, timeout=20) data = parse_torrent_buffer(response.content) elif os.path.isfile(torrent): with open(torrent, 'rb') as f: data = parse_torrent_buffer(f.read()...
<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_torrent_buffer(torrent): """parse a torrent buffer"""
md = {} try: metadata = bencode.bdecode(torrent) except bencode.BTL.BTFailure: print 'Not a valid encoded torrent' return None if 'announce-list' in metadata: md['trackers'] = [] for tracker in metadata['announce-list']: md['trackers'].append(tracker[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hsize(bytes): """converts a bytes to human-readable format"""
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'] if bytes == 0: return '0 Byte' i = int(math.floor(math.log(bytes) / math.log(1024))) r = round(bytes / math.pow(1024, i), 2) return str(r) + '' + sizes[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 ratio(leechs, seeds): """ computes the torrent ratio"""
try: ratio = float(seeds) / float(leechs) except ZeroDivisionError: ratio = int(seeds) return ratio
<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_torrent(magnet_link): """turn a magnet link to a link to a torrent file"""
infoHash = parse_magnet(magnet_link)['infoHash'] torcache = 'http://torcache.net/torrent/' + infoHash + '.torrent' torrage = 'https://torrage.com/torrent/' + infoHash + '.torrent' reflektor = 'http://reflektor.karmorra.info/torrent/' + \ infoHash + '.torrent' thetorrent = 'http://TheTorrent...
<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_story(): """ Returns a boiler plate story as an object. """
return Story( slug="la-data-latimes-ipsum", headline="This is not a headline", byline="This is not a byline", pub_date=datetime.now(), canonical_url="http://www.example.com/", kicker="This is not a kicker", description=lorem_ipsum.COMMON_P.split(".")[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 get_related_items(count=4): """ Returns the requested number of boiler plate related items as a list. """
defaults = dict( headline="This is not a headline", url="http://www.example.com/", image=get_image(400, 400) ) return [RelatedItem(**defaults) for x in range(0, count)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_image(width, height=None, background_color="cccccc", random_background_color=False): """ Returns image with caption, credit, and random background color ...
return Image( url=placeholdit.get_url( width, height=height, background_color=background_color, random_background_color=random_background_color ), credit="This is not an image credit", caption="This is not a caption" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_queryset(self, value, queryset): """ Filter the queryset to all instances matching the given attribute. """
filter_kwargs = {self.field_name: value} return queryset.filter(**filter_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 exclude_current_instance(self, queryset): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """
if self.instance is not None: return queryset.exclude(pk=self.instance.pk) return queryset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enforce_required_fields(self, attrs): """ The `UniqueTogetherValidator` always forces an implied 'required' state on the fields it applies to. """
if self.instance is not None: return missing = { field_name: self.missing_message for field_name in self.fields if field_name not in attrs } if missing: raise ValidationError(missing)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_queryset(self, attrs, queryset): """ Filter the queryset to all instances matching the given attributes. """
# If this is an update, then any unprovided field should # have it's value set based on the existing instance attribute. if self.instance is not None: for field_name in self.fields: if field_name not in attrs: attrs[field_name] = getattr(self.inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, view): """ adds the get item as extra context """
view.params['extra_context'][self.get['name']] = self.get['value'] return view
<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_bucket_list(): """ Get list of S3 Buckets """
args = parser.parse_args() for b in s3_conn(args.aws_access_key_id, args.aws_secret_access_key).get_all_buckets(): print(''.join([i if ord(i) < 128 else ' ' for i in b.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_back_up_generator(frame_function, *args, **kwargs): """Create a generator for the provided animation function that backs up the cursor after a frame. As...
lines = next(frame_function(*args, **kwargs)).split('\n') width = len(lines[0]) height = len(lines) if height == 1: return util.BACKSPACE_GEN(width) return util.BACKLINE_GEN(height)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _backspaced_single_line_animation(animation_, *args, **kwargs): """Turn an animation into an automatically backspaced animation. Args: animation: A function ...
animation_gen = animation_(*args, **kwargs) yield next(animation_gen) # no backing up on the first frame yield from util.concatechain( util.BACKSPACE_GEN(kwargs['width']), animation_gen)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raise_if_annotated(self, func): """Raise TypeError if a function is decorated with Annotate, as such functions cause visual bugs when decorated with Animate...
if hasattr(func, ANNOTATED) and getattr(func, ANNOTATED): msg = ('Functions decorated with {!r} ' 'should not be decorated with {!r}.\n' 'Please reverse the order of the decorators!'.format( self.__class__.__name__, Annotate.__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 _start_print(self): """Print the start message with or without newline depending on the self._start_no_nl variable. """
if self._start_no_nl: sys.stdout.write(self._start_msg) sys.stdout.flush() else: print(self._start_msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the current animation generator."""
animation_gen = self._frame_function(*self._animation_args, **self._animation_kwargs) self._current_generator = itertools.cycle( util.concatechain(animation_gen, self._back_up_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 get_erase_frame(self): """Return a frame that completely erases the current frame, and then backs up. Assumes that the current frame is of constant width."""
lines = self._current_frame.split('\n') width = len(lines[0]) height = len(lines) line = ' ' * width if height == 1: frame = line + BACKSPACE * width else: frame = '\n'.join([line] * height) + BACKLINE * (height - 1) return frame
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def string(self): # noqa: C901 """ Return a human-readable version of the decoded report. """
lines = ["station: %s" % self.station_id] if self.type: lines.append("type: %s" % self.report_type()) if self.time: lines.append("time: %s" % self.time.ctime()) if self.temp: lines.append("temperature: %s" % self.temp.string("C")) if self.dewp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handlePressure(self, d): """ Parse an altimeter-pressure group. The following attributes are set: press [int] """
press = d['press'] if press != '////': press = float(press.replace('O', '0')) if d['unit']: if d['unit'] == 'A' or (d['unit2'] and d['unit2'] == 'INS'): self.press = CustomPressure(press / 100, 'IN') elif d['unit'] == 'SLP': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handleSealvlPressRemark(self, d): """ Parse the sea-level pressure remark group. """
value = float(d['press']) / 10.0 if value < 50: value += 1000 else: value += 900 if not self.press: self.press = CustomPressure(value) self.press_sea_level = CustomPressure(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 get_tasklogger(name="TaskLogger"): """Get a TaskLogger object Parameters logger : str, optional (default: "TaskLogger") Unique name of the logger to retrieve...
try: return logging.getLogger(name).tasklogger except AttributeError: return logger.TaskLogger(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 log_debug(msg, logger="TaskLogger"): """Log a DEBUG message Convenience function to log a message to the default Logger Parameters msg : str Message to be lo...
tasklogger = get_tasklogger(logger) tasklogger.debug(msg) return tasklogger
<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_info(msg, logger="TaskLogger"): """Log an INFO message Convenience function to log a message to the default Logger Parameters msg : str Message to be log...
tasklogger = get_tasklogger(logger) tasklogger.info(msg) return tasklogger
<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_warning(msg, logger="TaskLogger"): """Log a WARNING message Convenience function to log a message to the default Logger Parameters msg : str Message to b...
tasklogger = get_tasklogger(logger) tasklogger.warning(msg) return tasklogger
<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_error(msg, logger="TaskLogger"): """Log an ERROR message Convenience function to log a message to the default Logger Parameters msg : str Message to be l...
tasklogger = get_tasklogger(logger) tasklogger.error(msg) return tasklogger
<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_critical(msg, logger="TaskLogger"): """Log a CRITICAL message Convenience function to log a message to the default Logger Parameters msg : str Message to...
tasklogger = get_tasklogger(logger) tasklogger.critical(msg) return tasklogger
<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_indent(indent=2, logger="TaskLogger"): """Set the indent function Convenience function to set the indent size Parameters indent : int, optional (default:...
tasklogger = get_tasklogger(logger) tasklogger.set_indent(indent) return tasklogger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(miz_path): """ Artifact from earlier development """
from emiz.miz import Miz with Miz(miz_path) as m: mis = m.mission result = defaultdict(dict) for unit in mis.units: airport, spot = unit.group_name.split('#') spot = int(spot) # print(airport, int(spot), unit.unit_position) result[airport][spot] = unit.unit_posi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _traverse(self, name, create_missing=False, action=None, value=NO_DEFAULT): """Traverse to the item specified by ``name``. To create missing items on the way...
obj = self segments = self._parse_path(name) for segment, next_segment in zip(segments, segments[1:] + [None]): last = next_segment is None if create_missing: self._create_segment(obj, segment, next_segment) try: next_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 _parse_path(self, path): """Parse ``path`` into segments. Paths must start with a WORD (i.e., a top level Django setting name). Path segments are separated b...
if not path: raise ValueError('path cannot be empty') segments = [] path_iter = zip(iter(path), chain(path[1:], (None,))) if six.PY2: # zip() returns a list on Python 2 path_iter = iter(path_iter) convert_name = self._convert_name cur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_name(self, name): """Convert ``name`` to int if it looks like an int. Otherwise, return it as is. """
if re.search('^\d+$', name): if len(name) > 1 and name[0] == '0': # Don't treat strings beginning with "0" as ints return name return int(name) 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: async def basic_consume(self, queue_name='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, no_wait=False, arguments=None, wait_message=True, tim...
# If a consumer tag was not passed, create one consumer_tag = consumer_tag or 'ctag%i.%s' % ( self.channel_id, uuid.uuid4().hex) if arguments is None: arguments = {} frame = amqp_frame.AmqpRequest( self.protocol._stream_writer, amqp_constants.TYPE_M...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPluginVersion(): """The version must be updated in the .cdmp file"""
desc_file = os.path.join('cdmplugins', 'gc', plugin_desc_file) if not os.path.exists(desc_file): print('Cannot find the plugin description file. Expected here: ' + desc_file, file=sys.stderr) sys.exit(1) with open(desc_file) as dec_file: for line in dec_file: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chainCerts(data): """ Matches and returns any certificates found except the first match. Regex code copied from L{twisted.internet.endpoints._parseSSL}. Rela...
matches = re.findall( r'(-----BEGIN CERTIFICATE-----\n.+?\n-----END CERTIFICATE-----)', data, flags=re.DOTALL) chainCertificates = [ Certificate.loadPEM(chainCertPEM).original for chainCertPEM in matches] return chainCertificates[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 directories(self): """ Return the names of directories to be created. """
directories_description = [ self.project_name, self.project_name + '/conf', self.project_name + '/static', ] return directories_description
<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_job_resolver(self, job_resolver): """Remove job_resolver from the list of job resolvers. Keyword arguments: job_resolver -- Function reference of the ...
for i, r in enumerate(self.job_resolvers()): if job_resolver == r: del self._job_resolvers[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 resolve_job(self, name): """Attempt to resolve the task name in to a job name. If no job resolver can resolve the task, i.e. they all return None, return Non...
for r in self.job_resolvers(): resolved_name = r(name) if resolved_name is not None: return resolved_name 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 setColor(self, id, color): """ Command 0x01 sets the color of a specific light Data: """
header = bytearray() header.append(LightProtocolCommand.SetColor) if not isinstance(id, list): id = [id] if not isinstance(color, list): color = [color] header.extend(struct.pack('<H', len(id))) i = 0 light = bytearray() for curr_id in id: light.extend(struct.pack('<H', curr_id)) lig...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setSeries(self, startId, length, color): """ Command 0x07 sets all lights in the series starting from "startId" to "endId" to "color" Data: [0x07][...
buff = bytearray() buff.append(LightProtocolCommand.SetSeries) buff.extend(struct.pack('<H', startId)) buff.extend(struct.pack('<H', length)) buff.extend(color) return self.send(buff)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v0_highlighter_post(request, response, tfidf, cid): '''Obtain highlights for a document POSTed as the body, which is the pre-design-thinking structure of the highlights API. See v1 below. NB: This end point will soon be deleted. The route for this endpoint is: ``POST /dossier/v0/highlighter/<...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def v1_highlights_get(response, kvlclient, file_id_str, max_elapsed = 300): '''Obtain highlights for a document POSTed previously to this end point. See documentation for v1_highlights_post for further details. If the `state` is still `pending` for more than `max_elapsed` after the start of the `WorkU...
<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_highlights(data, tfidf): '''compute highlights for `data`, store it in the store using `kvlclient`, and return a `highlights` response payload. ''' try: fc = etl.create_fc_from_html( data['content-location'], data['body'], tfidf=tfidf, encoding=None) except Exception,...
<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_xpath_ranges(html, phrase): '''Given a HTML string and a `phrase`, build a regex to find offsets for the phrase, and then build a list of `XPathRange` objects for it. If this fails, return empty list. ''' if not html: return [] if not isinstance(phrase, unicode): 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 eval_poly(uvec, nvec, Jvec): '''Evaluate multi-dimensional polynomials through tensor multiplication. :param list uvec: vector value of the uncertain parameters at which to evaluate the polynomial :param list nvec: order in each dimension at which to evaluate the polynomial :param list Jv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def train(self, ftrain): '''Trains the polynomial expansion. :param numpy.ndarray/function ftrain: output values corresponding to the quadrature points given by the getQuadraturePoints method to which the expansion should be trained. Or a function that should be evaluated ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getQuadraturePointsAndWeights(self): '''Gets the quadrature points and weights for gaussian quadrature integration of inner products from the definition of the polynomials in each dimension. :return: (u_points, w_points) - np.ndarray of shape (num_polynomials, num_dimen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _model_columns(ins): """ Get columns info :type ins: sqlalchemy.orm.mapper.Mapper :rtype: list[SaColumnDoc] """
columns = [] for c in ins.column_attrs: # Skip protected if c.key.startswith('_'): continue # Collect columns.append(SaColumnDoc( key=c.key, doc=c.doc or '', type=str(c.columns[0].type), # FIXME: support multi-column properties ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _model_foreign(ins): """ Get foreign keys info :type ins: sqlalchemy.orm.mapper.Mapper :rtype: list[SaForeignkeyDoc] """
fks = [] for t in ins.tables: fks.extend([ SaForeignkeyDoc( key=fk.column.key, target=fk.target_fullname, onupdate=fk.onupdate, ondelete=fk.ondelete ) for fk in t.foreign_keys]) return fks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _model_unique(ins): """ Get unique constraints info :type ins: sqlalchemy.orm.mapper.Mapper :rtype: list[tuple[str]] """
unique = [] for t in ins.tables: for c in t.constraints: if isinstance(c, UniqueConstraint): unique.append(tuple(col.key for col in c.columns)) return unique
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _model_relations(ins): """ Get relationships info :type ins: sqlalchemy.orm.mapper.Mapper :rtype: list[SaRelationshipDoc] """
relations = [] for r in ins.relationships: # Hard times with the foreign model :) if isinstance(r.argument, Mapper): model_name = r.argument.class_.__name__ elif hasattr(r.argument, 'arg'): model_name = r.argument.arg else: model_name = r.argu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc(model): """ Get documentation object for an SqlAlchemy model :param model: Model :type model: sqlalchemy.ext.declarative.DeclarativeBase :rtype: SaModelD...
ins = inspect(model) return SaModelDoc( name=model.__name__, table=[t.name for t in ins.tables], doc=getdoc(ins.class_), columns=_model_columns(ins), primary=_model_primary(ins), foreign=_model_foreign(ins), unique=_model_unique(ins), relations=_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetModuleBaseNameFromWSDL(wsdl): """By default try to construct a reasonable base name for all generated modules. Otherwise return None. """
base_name = wsdl.name or wsdl.services[0].name base_name = SplitQName(base_name)[1] if base_name is None: return None return NCName_to_ModuleName(base_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 condense(ss_unescaped): """ Given multiple strings, returns a compressed regular expression just for these strings 'he(moglobin|r)?|she' """
def estimated_len(longg, short): return (3 + len(short) + sum(map(len, longg)) - len(longg) * (len(short) - 1) - 1 ) def stupid_len(longg): return sum(map(len, longg)) + len(longg) ss = [re.escape(s) for s 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 is_solid(regex): """ Check the given regular expression is solid. True True True True False False """
shape = re.sub(r'(\\.|[^\[\]\(\)\|\?\+\*])', '#', regex) skeleton = shape.replace('#', '') if len(shape) <= 1: return True if re.match(r'^\[[^\]]*\][\*\+\?]?$', shape): return True if re.match(r'^\([^\(]*\)[\*\+\?]?$', shape): return True if re.match(r'^\(\)#*?\)\)', sk...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def danger_unpack(regex): """ Remove the outermost parens 'abc' 'abc' 'abc' '[abc]' """
if is_packed(regex): return re.sub(r'^\((\?(:|P<.*?>))?(?P<content>.*?)\)$', r'\g<content>', regex) else: return regex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def concat(regex_list): """ Concat multiple regular expression into one, if the given regular expression is not packed, a pair of paren will be add. (a|b)(c|d|e)...
output_list = [] for regex in regex_list: output_list.append(consolidate(regex)) return r''.join(output_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 set_cache(config_fpath, cache_dir): """Write the cache directory to the dtool config file. :param config_fpath: path to the dtool config file :param cache_di...
cache_dir = os.path.abspath(cache_dir) return write_config_value_to_file( CACHE_DIRECTORY_KEY, cache_dir, config_fpath )
<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_azure_secret_access_key(config_fpath, container, az_secret_access_key): """Write the ECS access key id to the dtool config file. :param config_fpath: pat...
key = AZURE_KEY_PREFIX + container return write_config_value_to_file(key, az_secret_access_key, config_fpath)
<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_azure_containers(config_fpath): """List the azure storage containers in the config file. :param config_fpath: path to the dtool config file :returns: th...
config_content = _get_config_dict_from_file(config_fpath) az_container_names = [] for key in config_content.keys(): if key.startswith(AZURE_KEY_PREFIX): name = key[len(AZURE_KEY_PREFIX):] az_container_names.append(name) return sorted(az_container_names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, filename, create = None, default_conf = {}): """Load the config file Args: filename (str): the filename of the config, without any path create (s...
filenames, tries = self.__search_config_files(filename) if len(filenames): self.__loaded_config_file = filenames if self.__nested else filenames[0] return self.__load_config_files(filenames if self.__nested else filenames[:1]) if create is not None: 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 save(self, data): """Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so the...
if self.__nested: raise ConfigLoaderException("Cannot save the config if the 'nested' paramter is True!") if self.__loaded_config_file is None: raise ConfigLoaderException("Load not called yet!") try: with open(self.__loaded_config_file, 'w') as f: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metar_to_speech(metar: str) -> str: """ Creates a speakable text from a METAR Args: metar: METAR string to use Returns: speakable METAR for TTS """
LOGGER.info('getting speech text from METAR: %s', metar) metar_data, metar_units = emiz.avwx.metar.parse_in(metar) speech = emiz.avwx.speech.metar(metar_data, metar_units) speech = str(speech).replace('Altimeter', 'Q N H') LOGGER.debug('resulting speech: %s', speech) 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 run(self): """Return rel path to a downloaded file as `include` node argument."""
document = self.state.document env = document.settings.env buildpath = env.app.outdir link = self.arguments[0] try: r = requests.get(link) r.raise_for_status() downloadpath = os.path.join(buildpath, '_downloads') if not os.path.is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(self, body): """ Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a r...
resource = body['data'] data = {'rtype': resource['type']} if 'attributes' in resource: attributes = resource['attributes'] attributes = self._normalize_attributes(attributes) data.update(attributes) if 'relationships' in resource: rel...
<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_attributes(self, attributes): """ Ensure compliance with the spec's attributes section Specifically, the attributes object of the single resource obje...
link = 'jsonapi.org/format/#document-resource-object-attributes' if not isinstance(attributes, dict): self.fail('The JSON API resource object attributes key MUST ' 'be a hash.', link) elif 'id' in attributes or 'type' in attributes: self.fail('A f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_relationships(self, relationships): """ Ensure compliance with the spec's relationships section Specifically, the relationships object of the single r...
link = 'jsonapi.org/format/#document-resource-object-relationships' if not isinstance(relationships, dict): self.fail('The JSON API resource object relationships key MUST ' 'be a hash & comply with the spec\'s resource linkage ' 'section.', link...
<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_resource(self, resource): """ Ensure compliance with the spec's resource objects section :param resource: dict JSON API resource object """
link = 'jsonapi.org/format/#document-resource-objects' rid = isinstance(resource.get('id'), unicode) rtype = isinstance(resource.get('type'), unicode) if not rtype or (self.req.is_patching and not rid): self.fail('JSON API requires that every resource object MUST ' ...
<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_top_level(self, body): """ Ensure compliance with the spec's top-level section """
link = 'jsonapi.org/format/#document-top-level' try: if not isinstance(body['data'], dict): raise TypeError except (KeyError, TypeError): self.fail('JSON API payloads MUST be a hash at the most ' 'top-level; rooted at a key named `...
<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(self, body): """ Invoke the JSON API spec compliant parser Order is important. Start from the request body root key & work your way down so exception h...
self._parse_top_level(body) self._parse_resource(body['data']) resource = body['data'] if 'attributes' in resource: self._parse_attributes(resource['attributes']) if 'relationships' in resource: self._parse_relationships(resource['relationships'])
<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_signer_by_version(digest, ver): """Returns a new signer object for a digest and version combination. Keyword arguments: digest -- a callable that may be ...
if int(ver) == 1: return V1Signer(digest) elif int(ver) == 2: return V2Signer(digest) else: 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 identify(self, header): """Identifies a signature and returns the appropriate Signer object. This is done by reading an authorization header and matching it ...
for ver, signer in self.signers.items(): if signer.matches(header): return signer 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 load_transforms(transforms): """ Load transform modules and return instance of transform class. Parameters transforms : [str] or [[str]] array of transform m...
from . import Transform import inspect # normalize arguments to form as [(name, [option, ...]), ...] transforms_with_argv = map(lambda t: (t[0], t[1:]) if isinstance(t, list) else (t, []), transforms) def instantiate_transform(module_name, argv): tr_module ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def date_tuple(ovls): """ We should have a list of overlays from which to extract day month year. """
day = month = year = 0 for o in ovls: if 'day' in o.props: day = o.value if 'month' in o.props: month = o.value if 'year' in o.props: year = o.value if 'date' in o.props: day, month, year = [(o or n) for o, n in zip((day, month...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def longest_overlap(ovls): """ From a list of overlays if any overlap keep the longest. """
# Ovls know how to compare to each other. ovls = sorted(ovls) # I know this could be better but ovls wont be more than 50 or so. for i, s in enumerate(ovls): passing = True for l in ovls[i + 1:]: if s.start in Rng(l.start, l.end, rng=(True, True)) or \ s.en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetSchema(component): """convience function for finding the parent XMLSchema instance. """
parent = component while not isinstance(parent, XMLSchema): parent = parent._parent() return parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getXMLNS(self, prefix=None): """deference prefix or by default xmlns, returns namespace. """
if prefix == XMLSchemaComponent.xml: return XMLNS.XML parent = self ns = self.attributes[XMLSchemaComponent.xmlns].get(prefix or\ XMLSchemaComponent.xmlns_key) while not ns: parent = parent._parent() ns = parent.attributes[XMLSchemaCom...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAttribute(self, attribute): """return requested attribute value or None """
if type(attribute) in (list, tuple): if len(attribute) != 2: raise LookupError, 'To access attributes must use name or (namespace,name)' ns_dict = self.attributes.get(attribute[0]) if ns_dict is None: return None return ns_dict.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __setAttributeDefaults(self): """Looks for default values for unset attributes. If class variable representing attribute is None, then it must be defined as ...
for k,v in self.__class__.attributes.items(): if v is not None and self.attributes.has_key(k) is False: if isinstance(v, types.FunctionType): self.attributes[k] = v(self) else: self.attributes[k] = 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 isQualified(self): """ Local elements can be qualified or unqualifed according to the attribute form, or the elementFormDefault. By default local elements ar...
form = self.getAttribute('form') if form == 'qualified': return True if form == 'unqualified': return False raise SchemaError, 'Bad form (%s) for element: %s' %(form, self.getItemTrace())
<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_title_tag(context, is_og=False): """ Returns the title as string or a complete open graph meta tag. """
request = context['request'] content = '' # Try to get the title from the context object (e.g. DetailViews). if context.get('object'): try: content = context['object'].get_meta_title() except AttributeError: pass elif context.get('meta_tagger'): cont...
<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_description_meta_tag(context, is_og=False): """ Returns the description as meta or open graph tag. """
request = context['request'] content = '' # Try to get the description from the context object (e.g. DetailViews). if context.get('object'): try: content = context['object'].get_meta_description() except AttributeError: pass elif context.get('meta_tagger'): ...
<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_robots_meta_tag(context): """ Returns the robots meta tag. """
request = context['request'] robots_indexing = None robots_following = None # Prevent indexing any unwanted domains (e.g. staging). if context.request.get_host() in settings.META_TAGGER_ROBOTS_DOMAIN_WHITELIST: # Try to get the title from the context object (e.g. DetailViews). if ...
<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_buckets(self): ''' a method to retrieve a list of buckets on s3 :return: list of buckets ''' title = '%s.list_buckets' % self.__class__.__name__ bucket_list = [] # send request to s3 try: response = self.connection...
<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(self, bucket_name): ''' a method to delete a bucket in s3 and all its contents :param bucket_name: string with name of bucket :return: string with status of method ''' title = '%s.delete_bucket' % self.__class__.__name__ # validate 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 read_headers(self, bucket_name, record_key, record_version='', version_check=False): ''' a method for retrieving the headers of a record from s3 :param bucket_name: string with name of bucket :param record_key: string with key value of record :param record_version: [opt...
<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_record(self, bucket_name, record_key, record_version=''): ''' a method for deleting an object record in s3 :param bucket_name: string with name of bucket :param record_key: string with key value of record :param record_version: [optional] string with aws id of ve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def import_records(self, bucket_name, import_path='', overwrite=True): ''' a method to importing records from local files to a bucket :param bucket_name: string with name of bucket :param export_path: [optional] string with path to root directory of files :param overwrite: ...
<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, record_key, record_data, overwrite=True, secret_key=''): ''' a method to create a file in the collection folder on S3 :param record_key: string with name to assign to record (see NOTES below) :param record_data: byte data for record body :param overw...
<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(self, record_key, secret_key=''): ''' a method to retrieve byte data of an S3 record :param record_key: string with name of record :param secret_key: [optional] string used to decrypt data :return: byte data for record body ''' titl...
<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(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''): ''' a method to list keys in the collection :param prefix: string with prefix value to filter results :param delimiter: string with value results must not contain (after prefix) ...
<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, record_key): ''' a method to delete a record from S3 :param record_key: string with key of record :return: string reporting outcome ''' title = '%s.delete' % self.__class__.__name__ # validate inputs input_fields = { 'r...