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 _compare(self, dir1, dir2): """ Compare contents of two directories """
left = set() right = set() self._numdirs += 1 excl_patterns = set(self._exclude).union(self._ignore) for cwd, dirs, files in os.walk(dir1): self._numdirs += len(dirs) for f in dirs + files: path = os.path.relpath(os.path.join(cwd, 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 _dowork(self, dir1, dir2, copyfunc=None, updatefunc=None): """ Private attribute for doing work """
if self._verbose: self.log('Source directory: %s:' % dir1) self._dcmp = self._compare(dir1, dir2) # Files & directories only in target directory if self._purge: for f2 in self._dcmp.right_only: fullf2 = os.path.join(self._dir2, f2) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _copy(self, filename, dir1, dir2): """ Private function for copying a file """
# NOTE: dir1 is source & dir2 is target if self._copyfiles: rel_path = filename.replace('\\', '/').split('/') rel_dir = '/'.join(rel_path[:-1]) filename = rel_path[-1] dir2_root = dir2 dir1 = os.path.join(dir1, rel_dir) dir2 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update(self, filename, dir1, dir2): """ Private function for updating a file based on last time stamp of modification """
# NOTE: dir1 is source & dir2 is target if self._updatefiles: file1 = os.path.join(dir1, filename) file2 = os.path.join(dir2, filename) try: st1 = os.stat(file1) st2 = os.stat(file2) except os.error: retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dirdiffandcopy(self, dir1, dir2): """ Private function which does directory diff & copy """
self._dowork(dir1, dir2, self._copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dirdiffandupdate(self, dir1, dir2): """ Private function which does directory diff & update """
self._dowork(dir1, dir2, None, self._update)
<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, dir1, dir2): """ Private function which only does directory diff """
self._dcmp = self._compare(dir1, dir2) if self._dcmp.left_only: self.log('Only in %s' % dir1) for x in sorted(self._dcmp.left_only): self.log('>> %s' % x) self.log('') if self._dcmp.right_only: self.log('Only in %s' % dir2) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """ Update will try to update the target directory w.r.t source directory. Only files that are common to both directories will be updated, no n...
self._copyfiles = False self._updatefiles = True self._purge = False self._creatdirs = False if self._verbose: self.log('Updating directory %s with %s\n' % (self._dir2, self._dir1)) self._dirdiffandupdate(self._dir1, self._dir2)
<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): """ Only report difference in content between two directories """
self._copyfiles = False self._updatefiles = False self._purge = False self._creatdirs = False self._updatefiles = False self.log('Difference of directory %s from %s\n' % (self._dir2, self._dir1)) self._diff(self._dir1, self._dir2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self): """ Print report of work at the end """
# We need only the first 4 significant digits tt = (str(self._endtime - self._starttime))[:4] self.log('\n%s finished in %s seconds.' % (__pkg_name__, tt)) self.log('%d directories parsed, %d files copied' % (self._numdirs, self._numfiles)) if self._numdelfile...
<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 set_action(self, on=None, bri=None, hue=None, sat=None, xy=None, ct=None, alert=None, effect=None, transitiontime=None, bri_inc=None, sat_inc=None, hue_...
data = { key: value for key, value in { 'on': on, 'bri': bri, 'hue': hue, 'sat': sat, 'xy': xy, 'ct': ct, 'alert': alert, 'effect': effect, 'transitiontime...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pre_tasks(self): """ Pre-tasks handler. """
if self.flushdb: management.call_command('flush', verbosity=0, interactive=False) logger.info('Flushed database')
<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_users(self): """ Creates users. """
rn = RandomNicknames() for name in rn.random_nicks(count=50): username = '%s%d' % (slugify(name), random.randrange(1, 99)) user = User.objects.create_user( username=username, email='%s@example.com' % username, password='secret') ...
<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_badges(self): """ Creates badges. """
rn = RandomNicknames() for name in rn.random_nicks(count=20): slug = slugify(name) badge = Badge.objects.create( name=name, slug=slug, description='Lorem ipsum dolor sit amet, consectetur adipisicing elit') logger.info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_awards(self): """ Creates awards. """
users = User.objects.all() for user in users: everyone_badge = Badge.objects.last() badge = Badge.objects.order_by('?')[0] try: award = Award.objects.create(user=user, badge=badge) everyone_award = Award.objects.create(user=user, badg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(l, n): """ Yields successive n-sized chunks from l. """
for i in _range(0, len(l), n): yield l[i:i + 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 sanitize_command_options(options): """ Sanitizes command options. """
multiples = [ 'badges', 'exclude_badges', ] for option in multiples: if options.get(option): value = options[option] if value: options[option] = [v for v in value.split(' ') if v] return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, recipe): """ Registers a new recipe class. """
if not isinstance(recipe, (list, tuple)): recipe = [recipe, ] for item in recipe: recipe = self.get_recipe_instance_from_class(item) self._registry[recipe.slug] = recipe
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unregister(self, recipe): """ Unregisters a given recipe class. """
recipe = self.get_recipe_instance_from_class(recipe) if recipe.slug in self._registry: del self._registry[recipe.slug]
<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_recipe_instance(self, badge): """ Returns the recipe instance for the given badge slug. If badge has not been registered, raises ``exceptions.BadgeNotFou...
from .exceptions import BadgeNotFound if badge in self._registry: return self.recipes[badge] raise BadgeNotFound()
<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_recipe_instances(self, badges=None, excluded=None): """ Returns all recipe instances or just those for the given badges. """
if badges: if not isinstance(badges, (list, tuple)): badges = [badges] if excluded: if not isinstance(excluded, (list, tuple)): excluded = [excluded] badges = list(set(self.registered) - set(excluded)) if badges: ...
<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_taskqueue_stub(self, **stub_kwargs): """Initializes the taskqueue stub using nosegae config magic"""
task_args = {} # root_path is required so the stub can find 'queue.yaml' or 'queue.yml' if 'root_path' not in stub_kwargs: for p in self._app_path: # support --gae-application values that may be a .yaml file dir_ = os.path.dirname(p) if os.path.isfile...
<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_datastore_v3_stub(self, **stub_kwargs): """Initializes the datastore stub using nosegae config magic"""
task_args = dict(datastore_file=self._data_path) task_args.update(stub_kwargs) self.testbed.init_datastore_v3_stub(**task_args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_user_stub(self, **stub_kwargs): """Initializes the user stub using nosegae config magic"""
# do a little dance to keep the same kwargs for multiple tests in the same class # because the user stub will barf if you pass these items into it # stub = user_service_stub.UserServiceStub(**stub_kw_args) # TypeError: __init__() got an unexpected keyword argument 'USER_IS_ADMIN' ...
<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_modules_stub(self, **_): """Initializes the modules stub based off of your current yaml files Implements solution from http://stackoverflow.com/questio...
from google.appengine.api import request_info # edit all_versions per modules & versions thereof needing tests all_versions = {} # {'default': [1], 'andsome': [2], 'others': [1]} def_versions = {} # {m: all_versions[m][0] for m in all_versions} m2h = {} # {m: {def_versions[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 _init_stub(self, stub_init, **stub_kwargs): """Initializes all other stubs for consistency's sake"""
getattr(self.testbed, stub_init, lambda **kwargs: None)(**stub_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 html_for_env_var(key): """Returns an HTML snippet for an environment variable. Args: key: A string representing an environment variable name. Returns: String...
value = os.getenv(key) return KEY_VALUE_TEMPLATE.format(key, 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 html_for_cgi_argument(argument, form): """Returns an HTML snippet for a CGI argument. Args: argument: A string representing an CGI argument name in a form. f...
value = form[argument].value if argument in form else None return KEY_VALUE_TEMPLATE.format(argument, 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 html_for_modules_method(method_name, *args, **kwargs): """Returns an HTML snippet for a Modules API method. Args: method_name: A string containing a Modules ...
method = getattr(modules, method_name) value = method(*args, **kwargs) return KEY_VALUE_TEMPLATE.format(method_name, 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(self): """GET handler that serves environment data."""
environment_variables_output = [html_for_env_var(key) for key in sorted(os.environ)] cgi_arguments_output = [] if os.getenv('CONTENT_TYPE') == 'application/x-www-form-urlencoded': # Note: a blank Content-type header will still sometimes ...
<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_badges(**kwargs): """ Iterates over registered recipes and creates missing badges. """
update = kwargs.get('update', False) created_badges = [] instances = registry.get_recipe_instances() for instance in instances: reset_queries() badge, created = instance.create_badge(update=update) if created: created_badges.append(badge) log_queries(instanc...
<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_awards(**kwargs): """ Iterates over registered recipes and possibly creates awards. """
badges = kwargs.get('badges') excluded = kwargs.get('exclude_badges') disable_signals = kwargs.get('disable_signals') batch_size = kwargs.get('batch_size', None) db_read = kwargs.get('db_read', None) award_post_save = True if disable_signals: settings.AUTO_DENORMALIZE = 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 show_stats(**kwargs): """ Shows badges stats. """
db_read = kwargs.get('db_read', DEFAULT_DB_ALIAS) badges = (Badge.objects.using(db_read) .all() .annotate(u_count=Count('users')) .order_by('u_count')) for badge in badges: logger.info('{:<20} {:>10} users awarded | ...
<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_current_user_ids(self, db_read=None): """ Returns current user ids and the count. """
db_read = db_read or self.db_read return self.user_ids.using(db_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 add_arguments(self, parser): """ Command arguments. """
super(Command, self).add_arguments(parser) parser.add_argument('--badges', action='store', dest='badges', type=str) parser.add_argument('--db-read', action='store', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare(cls, match, subject): """ Accepts two OrganizationName objects and returns an arbitrary, numerical score based upon how well the names match. """
if match.expand().lower() == subject.expand().lower(): return 4 elif match.kernel().lower() == subject.kernel().lower(): return 3 # law and lobbying firms in CRP data typically list only the first two partners # before 'et al' elif ',' in subject.expand()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def badgify_badges(**kwargs): """ Returns all badges or only awarded badges for the given user. """
User = get_user_model() user = kwargs.get('user', None) username = kwargs.get('username', None) if username: try: user = User.objects.get(username=username) except User.DoesNotExist: pass if user: awards = Award.objects.filter(user=user).select_relate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def without_extra_phrases(self): """Removes parenthethical and dashed phrases"""
# the last parenthesis is optional, because sometimes they are truncated name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name) name = re.sub(r'(?i)\s* formerly.*$', '', name) name = re.sub(r'(?i)\s*and its affiliates$', '', name) name = re.sub(r'\bet al\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 kernel(self): """ The 'kernel' is an attempt to get at just the most pithy words in the name """
stop_words = [ y.lower() for y in self.abbreviations.values() + self.filler_words ] kernel = ' '.join([ x for x in self.expand().split() if x.lower() not in stop_words ]) # this is a hack to get around the fact that this is the only two-word phrase we want to block # amongst our stop w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_and_fix_two_part_surname(self, args): """ This detects common family name prefixes and joins them to the last name, so names like "De Kuyper" don't en...
i = 0 while i < len(args) - 1: if args[i].lower() in self.family_name_prefixes: args[i] = ' '.join(args[i:i+2]) del(args[i+1]) break else: i += 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 case_name_parts(self): """ """
if not self.is_mixed_case(): self.honorific = self.honorific.title() if self.honorific else None self.nick = self.nick.title() if self.nick else None if self.first: self.first = self.first.title() self.first = self.capitalize_and_punctuate_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 main(args=None): """Print metadata as JSON strings."""
args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument("safe_file", type=str, nargs='+') parser.add_argument("--granules", action="store_true") parsed = parser.parse_args(args) pp = pprint.PrettyPrinter() for safe_file in parsed.safe_file: with s2reader.open(saf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(safe_file): """Return a SentinelDataSet object."""
if os.path.isdir(safe_file) or os.path.isfile(safe_file): return SentinelDataSet(safe_file) else: raise IOError("file not found: %s" % safe_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 _granule_identifier_to_xml_name(granule_identifier): """ Very ugly way to convert the granule identifier. e.g. From Granule Identifier: S2A_OPER_MSI_L1C_TL_S...
# Replace "MSI" with "MTD". changed_item_type = re.sub("_MSI_", "_MTD_", granule_identifier) # Split string up by underscores. split_by_underscores = changed_item_type.split("_") del split_by_underscores[-1] cleaned = str() # Stitch string list together, adding the previously removed unders...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _polygon_from_coords(coords, fix_geom=False, swap=True, dims=2): """ Return Shapely Polygon from coordinates. - coords: list of alterating latitude / longitu...
assert len(coords) % dims == 0 number_of_points = len(coords)/dims coords_as_array = np.array(coords) reshaped = coords_as_array.reshape(number_of_points, dims) points = [ (float(i[1]), float(i[0])) if swap else ((float(i[0]), float(i[1]))) for i in reshaped.tolist() ] p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def product_metadata_path(self): """Return path to product metadata XML file."""
data_object_section = self._manifest_safe.find("dataObjectSection") for data_object in data_object_section: # Find product metadata XML. if data_object.attrib.get("ID") == "S2_Level-1C_Product_Metadata": relpath = os.path.relpath( data_object....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def footprint(self): """Return product footprint."""
product_footprint = self._product_metadata.iter("Product_Footprint") # I don't know why two "Product_Footprint" items are found. for element in product_footprint: global_footprint = None for global_footprint in element.iter("Global_Footprint"): coords = 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 granules(self): """Return list of SentinelGranule objects."""
for element in self._product_metadata.iter("Product_Info"): product_organisation = element.find("Product_Organisation") if self.product_format == 'SAFE': return [ SentinelGranule(_id.find("Granules"), self) for _id in product_organisation.findall(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def granule_paths(self, band_id): """Return the path of all granules of a given band."""
band_id = str(band_id).zfill(2) try: assert isinstance(band_id, str) assert band_id in BAND_IDS except AssertionError: raise AttributeError( "band ID not valid: %s" % band_id ) return [ granule.band_path(ban...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metadata_path(self): """Determine the metadata path."""
xml_name = _granule_identifier_to_xml_name(self.granule_identifier) metadata_path = os.path.join(self.granule_path, xml_name) try: assert os.path.isfile(metadata_path) or \ metadata_path in self.dataset._zipfile.namelist() except AssertionError: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tci_path(self): """Return the path to the granules TrueColorImage."""
tci_paths = [ path for path in self.dataset._product_metadata.xpath( ".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()" % self.granule_identifier ) if path.endswith('TCI') ] try: tci_path = tci_paths[0] except Inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloud_percent(self): """Return percentage of cloud coverage."""
image_content_qi = self._metadata.findtext( ( """n1:Quality_Indicators_Info/Image_Content_QI/""" """CLOUDY_PIXEL_PERCENTAGE""" ), namespaces=self._nsmap) return float(image_content_qi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def footprint(self): """Find and return footprint as Shapely Polygon."""
# Check whether product or granule footprint needs to be calculated. tile_geocoding = self._metadata.iter("Tile_Geocoding").next() resolution = 10 searchstring = ".//*[@resolution='%s']" % resolution size, geoposition = tile_geocoding.findall(searchstring) nrows, ncols =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloudmask(self): """Return cloudmask as a shapely geometry."""
polys = list(self._get_mask(mask_type="MSK_CLOUDS")) return MultiPolygon([ poly["geometry"] for poly in polys if poly["attributes"]["maskType"] == "OPAQUE" ]).buffer(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 band_path(self, band_id, for_gdal=False, absolute=False): """Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2) if not isinstance(band_id, str) or band_id not in BAND_IDS: raise ValueError("band ID not valid: %s" % band_id) if self.dataset.is_zip and for_gdal: zip_prefix = "/vsizip/" if absolute: granule_basepath = zip_pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geo_to_pixel(geo, level): """Transform from geo coordinates to pixel coordinates"""
lat, lon = float(geo[0]), float(geo[1]) lat = TileSystem.clip(lat, TileSystem.LATITUDE_RANGE) lon = TileSystem.clip(lon, TileSystem.LONGITUDE_RANGE) x = (lon + 180) / 360 sin_lat = sin(lat * pi / 180) y = 0.5 - log((1 + sin_lat) / (1 - sin_lat)) / (4 * pi) # migh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pixel_to_geo(pixel, level): """Transform from pixel to geo coordinates"""
pixel_x = pixel[0] pixel_y = pixel[1] map_size = float(TileSystem.map_size(level)) x = (TileSystem.clip(pixel_x, (0, map_size - 1)) / map_size) - 0.5 y = 0.5 - (TileSystem.clip(pixel_y, (0, map_size - 1)) / map_size) lat = 90 - 360 * atan(exp(-y * 2 * pi)) / pi l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tile_to_pixel(tile, centered=False): """Transform tile to pixel coordinates"""
pixel = [tile[0] * 256, tile[1] * 256] if centered: # should clip on max map size pixel = [pix + 128 for pix in pixel] return pixel[0], pixel[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 tile_to_quadkey(tile, level): """Transform tile coordinates to a quadkey"""
tile_x = tile[0] tile_y = tile[1] quadkey = "" for i in xrange(level): bit = level - i digit = ord('0') mask = 1 << (bit - 1) # if (bit - 1) > 0 else 1 >> (bit - 1) if (tile_x & mask) is not 0: digit += 1 if (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 quadkey_to_tile(quadkey): """Transform quadkey to tile coordinates"""
tile_x, tile_y = (0, 0) level = len(quadkey) for i in xrange(level): bit = level - i mask = 1 << (bit - 1) if quadkey[level - bit] == '1': tile_x |= mask if quadkey[level - bit] == '2': tile_y |= mask 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 authorize_url(self, state=''): """ return user authorize url """
url = 'https://openapi.youku.com/v2/oauth2/authorize?' params = { 'client_id': self.client_id, 'response_type': 'code', 'state': state, 'redirect_uri': self.redirect_uri } return url + urlencode(params)
<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_none_value(data): """remove item from dict if value is None. return new dict. """
return dict((k, v) for k, v in data.items() if v 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 get_dataset(ds,dataDir,removecompressed=1): """ A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset. PARAMETE...
#Convert input ds to string incase it is put in via function ds = str(ds) #The final character of the dataset can be a letter lettersuffix='' if re.search('[A-Za-z]$',ds): lettersuffix = ds[-1] ds = ds[:-1] openfMRI_dataset_string = '{0:06d}'.format(int(ds)) + lettersuffix #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_video_params(self, title=None, tags='Others', description='', copyright_type='original', public_type='all', category=None, watch_password=None, latitu...
params = {} if title is None: title = self.file_name elif len(title) > 80: title = title[:80] if len(description) > 2000: description = description[0:2000] params['title'] = title params['tags'] = tags params['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 _save_upload_state_to_file(self): """if create and create_file has execute, save upload state to file for next resume upload if current upload process is int...
if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK): save_file = self.file + '.upload' data = { 'upload_token': self.upload_token, 'upload_server_ip': self.upload_server_ip } with open(save_file, 'w') as f: jso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, params={}): """start uploading the file until upload is complete or error. This is the main method to used, If you do not care about state of pr...
if self.upload_token is not None: # resume upload status = self.check() if status['status'] != 4: return self.commit() else: self.new_slice() while self.slice_task_id != 0: self.upload_slice() ...
<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_users(self): """Synchronize LDAP users with local user model."""
if self.settings.USER_FILTER: user_attributes = self.settings.USER_ATTRIBUTES.keys() + self.settings.USER_EXTRA_ATTRIBUTES ldap_users = self.ldap.search(self.settings.USER_FILTER, user_attributes) self._sync_ldap_users(ldap_users) logger.info("Users are synchroni...
<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(args=sys.argv[1:]): """Generate EO O&M XML metadata."""
parser = argparse.ArgumentParser() parser.add_argument("filename", nargs=1) parser.add_argument("--granule-id", dest="granule_id", help=( "Optional. Specify a granule to export metadata from." ) ) parser.add_argument("--single-granule", dest="single_granule", act...
<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_ancestor(self, node): """ If node is ancestor of self Get the difference in level If not, None """
if self.level <= node.level or self.key[:len(node.key)] != node.key: return None return self.level - node.level
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xdifference(self, to): """ Generator Gives the difference of quadkeys between self and to Generator in case done on a low level Only works with quadkeys of s...
x,y = 0,1 assert self.level == to.level self_tile = list(self.to_tile()[0]) to_tile = list(to.to_tile()[0]) if self_tile[x] >= to_tile[x] and self_tile[y] <= self_tile[y]: ne_tile, sw_tile = self_tile, to_tile else: sw_tile, ne_tile = self_tile, 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 unwind(self): """ Get a list of all ancestors in descending order of level, including a new instance of self """
return [ QuadKey(self.key[:l+1]) for l in reversed(range(len(self.key))) ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self): """Apply validation rules for loaded settings."""
if self.GROUP_ATTRIBUTES and self.GROUPNAME_FIELD not in self.GROUP_ATTRIBUTES.values(): raise ImproperlyConfigured("LDAP_SYNC_GROUP_ATTRIBUTES must contain '%s'" % self.GROUPNAME_FIELD) if not self.model._meta.get_field(self.USERNAME_FIELD).unique: raise ImproperlyConfigured("...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, filterstr, attrlist): """Query the configured LDAP server."""
return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr, attrlist=attrlist, page_size=self.settings.PAGE_SIZE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_lid(self, woeid): """Fetch a location's corresponding LID. Args: woeid: (string) the location's WOEID. Returns: a string containing the requested LID o...
rss = self._fetch_xml(LID_LOOKUP_URL.format(woeid, "f")) # We are pulling the LID from the permalink tag in the XML file # returned by Yahoo. try: link = rss.find("channel/link").text except AttributeError: return None # use regex or string.spl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_woeid(self, location): """Fetch a location's corresponding WOEID. Args: location: (string) a location (e.g. 23454 or Berlin, Germany). Returns: a strin...
rss = self._fetch_xml( WOEID_LOOKUP_URL.format(quote(location))) try: woeid = rss.find("results/Result/woeid").text except AttributeError: return None return woeid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _degrees_to_direction(self, degrees): """Convert wind direction from degrees to compass direction."""
try: degrees = float(degrees) except ValueError: return None if degrees < 0 or degrees > 360: return None if degrees <= 11.25 or degrees >= 348.76: return "N" elif degrees <= 33.75: return "NNE" elif degrees <= ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_xml(self, url): """Fetch a url and parse the document's XML."""
with contextlib.closing(urlopen(url)) as f: return xml.etree.ElementTree.parse(f).getroot()
<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_value(self, value): """ Get a specific canned value :type value: str :param value: Canned value to show :rtype: dict :return: A dictionnary containing c...
values = self.get_values() values = [x for x in values if x['label'] == value] if len(values) == 0: raise Exception("Unknown value") else: return values[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 show_key(self, value): """ Get a specific canned key :type value: str :param value: Canned key to show :rtype: dict :return: A dictionnary containing canned ...
keys = self.get_keys() keys = [x for x in keys if x['label'] == value] if len(keys) == 0: raise Exception("Unknown key") else: return keys[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 download(self, dest_pattern="{originalFilename}", override=True, parent=False): """ Download the original image. Parameters dest_pattern : str, optional Dest...
if self.id is None: raise ValueError("Cannot download image with no ID.") pattern = re.compile("{(.*?)}") dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern) parameters = {"parent": parent} destination = os.path.di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self, dest_pattern="{id}.jpg", override=True, max_size=None, bits=8, contrast=None, gamma=None, colormap=None, inverse=None): """ Download the image wit...
if self.id is None: raise ValueError("Cannot dump an annotation with no ID.") pattern = re.compile("{(.*?)}") dest_pattern = re.sub(pattern, lambda m: str(getattr(self, str(m.group(0))[1:-1], "_")), dest_pattern) destination = os.path.dirname(dest_pattern) 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 filtered_elements(self, model): """Return iterator based on `element_type`."""
if isinstance(model, self.element_type): yield model yield from (e for e in model.eAllContents() if isinstance(e, self.element_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 folder_path_for_package(cls, package: ecore.EPackage): """Returns path to folder holding generated artifact for given element."""
parent = package.eContainer() if parent: return os.path.join(cls.folder_path_for_package(parent), package.name) return package.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 imported_classifiers_package(p: ecore.EPackage): """Determines which classifiers have to be imported into given package."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)} references = itertools.chain(*(c.eAllReferences() for c in classes)) references_types = (r.eType for r in references) imported = {c for c in references_types if getattr(c, 'ePackage', p) is not p} imported_di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def imported_classifiers(p: ecore.EPackage): """Determines which classifiers have to be imported into given module."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)} supertypes = itertools.chain(*(c.eAllSuperTypes() for c in classes)) imported = {c for c in supertypes if c.ePackage is not p} attributes = itertools.chain(*(c.eAttributes for c in classes)) attributes_types ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classes(p: ecore.EPackage): """Returns classes in package in ordered by number of bases."""
classes = (c for c in p.eClassifiers if isinstance(c, ecore.EClass)) return sorted(classes, key=lambda c: len(set(c.eAllSuperTypes())))
<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_pyfqn(cls, value, relative_to=0): """ Returns Python form of fully qualified name. Args: relative_to: If greater 0, the returned path is relative to t...
def collect_packages(element, packages): parent = element.eContainer() if parent: collect_packages(parent, packages) packages.append(element.name) packages = [] collect_packages(value, packages) if relative_to < 0 or relative_to > l...
<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_environment(self, **kwargs): """ Return a new Jinja environment. Derived classes may override method to pass additional parameters or to change the te...
environment = super().create_environment(**kwargs) environment.tests.update({ 'type': self.test_type, 'kind': self.test_kind, 'opposite_before_self': self.test_opposite_before_self, }) environment.filters.update({ 'docstringline': self.fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self, model, outfolder, *, exclude=None): """ Generate model code. Args: model: The meta-model to generate code for. outfolder: Path to the directot...
with pythonic_names(): super().generate(model, outfolder) check_dependency = self.with_dependencies and model.eResource if check_dependency: if exclude is None: exclude = set() resource = model.eResource # ...
<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_group(self, group_id): """ Get information about a group :type group_id: int :param group_id: Group ID Number :rtype: dict :return: a dictionary contain...
res = self.post('loadGroups', {'groupId': group_id}) if isinstance(res, list): return _fix_group(res[0]) else: return _fix_group(res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_organism_permissions(self, group): """ Get the group's organism permissions :type group: str :param group: group name :rtype: list :return: a list contai...
data = { 'name': group, } response = _fix_group(self.post('getOrganismPermissionsForGroup', data)) return response
<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_group_admin(self, group): """ Get the group's admins :type group: str :param group: group name :rtype: list :return: a list containing group admins """
data = { 'name': group, } response = _fix_group(self.post('getGroupAdmin', data)) return response
<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_group_creator(self, group): """ Get the group's creator :type group: str :param group: group name :rtype: list :return: creator userId """
data = { 'name': group, } response = _fix_group(self.post('getGroupCreator', data)) return response
<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_query_string(params): """ Support Elasticsearch 5.X """
parameters = params or {} for param, value in parameters.items(): param_value = str(value).lower() if isinstance(value, bool) else value parameters[param] = param_value return urlencode(parameters)
<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_status(self, status): """ Get a specific status :type status: str :param status: Status to show :rtype: dict :return: A dictionnary containing status de...
statuses = self.get_statuses() statuses = [x for x in statuses if x['value'] == status] if len(statuses) == 0: raise Exception("Unknown status value") else: return statuses[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 add_attribute(self, feature_id, attribute_key, attribute_value, organism=None, sequence=None): """ Add an attribute to a feature :type feature_id: str :param...
data = { 'features': [ { 'uniquename': feature_id, 'non_reserved_properties': [ { 'tag': attribute_key, 'value': attribute_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 add_dbxref(self, feature_id, db, accession, organism=None, sequence=None): """ Add a dbxref to a feature :type feature_id: str :param feature_id: Feature UUI...
data = { 'features': [ { 'uniquename': feature_id, 'dbxrefs': [ { 'db': db, 'accession': accession, } ] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_empty(self, user, response): """Apollo likes to return empty user arrays, even when you REALLY
if len(response.keys()) == 0: response = self.show_user(user) # And sometimes show_user can return nothing. Ask again... if len(response) == 0: response = self.show_user(user) return response
<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_user(self, user): """ Get a specific user :type user: str :param user: User Email :rtype: dict :return: a dictionary containing user information """
res = self.post('loadUsers', {'userId': user}) if isinstance(res, list) and len(res) > 0: res = res[0] return _fix_user(res)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def require_user(wa, email): """Require that the user has an account"""
cache_key = 'user-list' try: # Get the cached value data = userCache[cache_key] except KeyError: # If we hit a key error above, indicating that # we couldn't find the key, we'll simply re-request # the data data = wa.users.loadUsers() userCache[cache_...