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 parse_value(self, value): """Parse string into instance of `time`."""
if value is None: return value if isinstance(value, datetime.time): return value return parse(value).timetz()
<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_struct(self, value): """Cast `date` object to string."""
if self.str_format: return value.strftime(self.str_format) return value.strftime(self.default_format)
<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_value(self, value): """Parse string into instance of `datetime`."""
if isinstance(value, datetime.datetime): return value if value: return parse(value) 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 to_struct(model): """Cast instance of model to python structure. :param model: Model to be casted. :rtype: ``dict`` """
model.validate() resp = {} for _, name, field in model.iterate_with_name(): value = field.__get__(model) if value is None: continue value = field.to_struct(value) resp[name] = value return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def javascript(filename, type='text/javascript'): '''A simple shortcut to render a ``script`` tag to a static javascript file''' if '?' in filename and len(filename.split('?')) is 2: filename, params = filename.split('?') return '<script type="%s" src="%s?%s"></script>' % (type, staticfiles_stor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def jquery_js(version=None, migrate=False): '''A shortcut to render a ``script`` tag for the packaged jQuery''' version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (version, suffix))] if _boolean(migrate): libs.append(j...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def django_js(context, jquery=True, i18n=True, csrf=True, init=True): '''Include Django.js javascript library in the page''' return { 'js': { 'minified': not settings.DEBUG, 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def django_js_init(context, jquery=False, i18n=True, csrf=True, init=True): '''Include Django.js javascript library initialization in the page''' return { 'js': { 'jquery': _boolean(jquery), 'i18n': _boolean(i18n), 'csrf': _boolean(csrf), 'init': _boolean(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value in six.iteritems(context): if settings.JS_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. ''' # Dirty hack to fix non included default language_code = 'en-us' if language_co...
<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_user(self, data): ''' Insert user informations in data Override it to add extra user attributes. ''' # Default to unauthenticated anonymous user data['user'] = { 'username': '', 'is_authenticated': False, 'is_staff': 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 class_from_string(name): ''' Get a python class object from its name ''' module_name, class_name = name.rsplit('.', 1) __import__(module_name) module = sys.modules[module_name] return getattr(module, class_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 execute(self, command): ''' Execute a subprocess yielding output lines ''' process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True) while True: if process.poll() is not None: self.returncode = process.returncode # pylint: disa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def phantomjs(self, *args, **kwargs): ''' Execute PhantomJS by giving ``args`` as command line arguments. If test are run in verbose mode (``-v/--verbosity`` = 2), it output: - the title as header (with separators before and after) - modules and test names - assert...
<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_suite(self): ''' Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined. ''' if not self.phantomjs_runner: raise JsTestException('phantomjs_runner need to be defined') url = sel...
<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_bloom(self): """Prepare bloom for existing checks """
self.__bloom = pybloom_live.ScalableBloomFilter() columns = [getattr(self.__table.c, key) for key in self.__update_keys] keys = select(columns).execution_options(stream_results=True).execute() for key in keys: self.__bloom.add(tuple(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 __insert(self): """Insert rows to table """
if len(self.__buffer) > 0: # Insert data statement = self.__table.insert() if self.__autoincrement: statement = statement.returning( getattr(self.__table.c, self.__autoincrement)) statement = statement.values(self.__buffer)...
<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, row): """Update rows in table """
expr = self.__table.update().values(row) for key in self.__update_keys: expr = expr.where(getattr(self.__table.c, key) == row[key]) if self.__autoincrement: expr = expr.returning(getattr(self.__table.c, self.__autoincrement)) res = expr.execute() if res.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 __check_existing(self, row): """Check if row exists in table """
if self.__update_keys is not None: key = tuple(row[key] for key in self.__update_keys) if key in self.__bloom: return True self.__bloom.add(key) return False return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_table(self, bucket): """Get table by bucket """
table_name = self.__mapper.convert_bucket(bucket) if self.__dbschema: table_name = '.'.join((self.__dbschema, table_name)) return self.__metadata.tables[table_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_field_comment(field, separator=' - '): """ Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'titl...
title = field.descriptor.get('title') or '' description = field.descriptor.get('description') or '' return _get_comment(description, title, separator)
<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_descriptor(self, bucket, descriptor, index_fields=[], autoincrement=None): """Convert descriptor to SQL """
# Prepare columns = [] indexes = [] fallbacks = [] constraints = [] column_mapping = {} table_name = self.convert_bucket(bucket) table_comment = _get_comment(descriptor.get('title', ''), descriptor.get('description', '')) schema = tableschema.Sch...
<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_row(self, keyed_row, schema, fallbacks): """Convert row to SQL """
for key, value in list(keyed_row.items()): field = schema.get_field(key) if not field: del keyed_row[key] if key in fallbacks: value = _uncast_value(value, field=field) else: value = field.cast_value(value) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_type(self, type): """Convert type to SQL """
# Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'geojson': None, 'geopoint': None, 'integer': sa.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 restore_bucket(self, table_name): """Restore bucket from SQL """
if table_name.startswith(self.__prefix): return table_name.replace(self.__prefix, '', 1) 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 restore_descriptor(self, table_name, columns, constraints, autoincrement_column=None): """Restore descriptor from SQL """
# Fields fields = [] for column in columns: if column.name == autoincrement_column: continue field_type = self.restore_type(column.type) field = {'name': column.name, 'type': field_type} if not column.nullable: fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_row(self, row, schema): """Restore row from SQL """
row = list(row) for index, field in enumerate(schema.fields): if self.__dialect == 'postgresql': if field.type in ['array', 'object']: continue row[index] = field.cast_value(row[index]) return row
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_type(self, type): """Restore type from SQL """
# All dialects mapping = { ARRAY: 'array', sa.Boolean: 'boolean', sa.Date: 'date', sa.DateTime: 'datetime', sa.Float: 'number', sa.Integer: 'integer', JSONB: 'object', JSON: 'object', sa.Numeric...
<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_hierarchy(self, path, relative_to_object_id, object_id, create_file_type=0): """ CreateFileType 0 - Creates no new object. 1 - Creates a notebook with t...
try: return(self.process.OpenHierarchy(path, relative_to_object_id, "", create_file_type)) except Exception as e: print(e) print("Could not Open Hierarchy")
<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_new_page (self, section_id, new_page_style=0): """ NewPageStyle 0 - Create a Page that has Default Page Style 1 - Create a blank page with no title 2 ...
try: self.process.CreateNewPage(section_id, "", new_page_style) except Exception as e: print(e) print("Unable to create the page")
<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_page_content(self, page_id, page_info=0): """ PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the...
try: return(self.process.GetPageContent(page_id, "", page_info)) except Exception as e: print(e) print("Could not get Page Content")
<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_special_location(self, special_location=0): """ SpecialLocation 0 - Gets the path to the Backup Folders folder location. 1 - Gets the path to the Unfiled...
try: return(self.process.GetSpecialLocation(special_location)) except Exception as e: print(e) print("Could not retreive special location")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memory(): """Determine memory specifications of the machine. Returns ------- mem_info : dictonary Holds the current values for the total, free and used memor...
mem_info = dict() for k, v in psutil.virtual_memory()._asdict().items(): mem_info[k] = int(v) return mem_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 get_chunk_size(N, n): """Given a two-dimensional array with a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parame...
mem_free = memory()['free'] if mem_free > 60000000: chunk_size = int(((mem_free - 10000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 40000000: chunk_size = int(((mem_free - 7000000) * 1000) / (4 * n * N)) return chunk_size elif mem_free > 14000000: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ceEvalMutual(cluster_runs, cluster_ensemble = None, verbose = False): """Compute a weighted average of the mutual information with the known labels, the weig...
if cluster_ensemble is None: return 0.0 if reduce(operator.mul, cluster_runs.shape, 1) == max(cluster_runs.shape): cluster_runs = cluster_runs.reshape(1, -1) weighted_average_mutual_information = 0 N_labelled_indices = 0 for i in range(cluster_runs.shape[0]): labelled_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 checkcl(cluster_run, verbose = False): """Ensure that a cluster labelling is in a valid format. Parameters cluster_run : array of shape (n_samples,) A vector...
cluster_run = np.asanyarray(cluster_run) if cluster_run.size == 0: raise ValueError("\nERROR: Cluster_Ensembles: checkcl: " "empty vector provided as input.\n") elif reduce(operator.mul, cluster_run.shape, 1) != max(cluster_run.shape): raise ValueError("\nERRO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def one_to_max(array_in): """Alter a vector of cluster labels to a dense mapping. Given that this function is herein always called after passing a vector to the ...
x = np.asanyarray(array_in) N_in = x.size array_in = x.reshape(N_in) sorted_array = np.sort(array_in) sorting_indices = np.argsort(array_in) last = np.nan current_index = -1 for i in range(N_in): if last != sorted_array[i] or np.isnan(last): last = sorted_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checks(similarities, verbose = False): """Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters similarit...
if similarities.size == 0: raise ValueError("\nERROR: Cluster_Ensembles: checks: the similarities " "matrix provided as input happens to be empty.\n") elif np.where(np.isnan(similarities))[0].size != 0: raise ValueError("\nERROR: Cluster_Ensembles: checks: input si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metis(hdf5_file_name, N_clusters_max): """METIS algorithm by Karypis and Kumar. Partitions the induced similarity graph passed by CSPA. Parameters hdf5_file_...
file_name = wgraph(hdf5_file_name) labels = sgraph(N_clusters_max, file_name) subprocess.call(['rm', file_name]) return labels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hmetis(hdf5_file_name, N_clusters_max, w = None): """Gives cluster labels ranging from 1 to N_clusters_max for hypergraph partitioning required for HGPA. Par...
if w is None: file_name = wgraph(hdf5_file_name, None, 2) else: file_name = wgraph(hdf5_file_name, w, 3) labels = sgraph(N_clusters_max, file_name) labels = one_to_max(labels) subprocess.call(['rm', file_name]) return labels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obfuscate(p, action): """Obfuscate the auth details to avoid easy snatching. It's best to use a throw away account for these alerts to avoid having your auth...
key = "ru7sll3uQrGtDPcIW3okutpFLo6YYtd5bWSpbZJIopYQ0Du0a1WlhvJOaZEH" s = list() if action == 'store': if PY2: for i in range(len(p)): kc = key[i % len(key)] ec = chr((ord(p[i]) + ord(kc)) % 256) s.append(ec) return base64.urlsa...
<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_bootstrap(self): """Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module...
if not os.path.exists(CONFIG_PATH): os.makedirs(CONFIG_PATH) if not os.path.exists(CONFIG_FILE): json.dump(CONFIG_DEFAULTS, open(CONFIG_FILE, 'w'), indent=4, separators=(',', ': ')) config = CONFIG_DEFAULTS if self._email and self._password:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single ...
if not os.path.exists(SESSION_FILE): self._log.debug("Session file does not exist") return False with open(SESSION_FILE, 'rb') as f: cookies = requests.utils.cookiejar_from_dict(pickle.load(f)) self._session.cookies = cookies self._log.debug("...
<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_log_level(self, level): """Override the default log level of the class"""
if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERROR self._log.setLevel(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 _process_state(self): """Process the application state configuration. Google Alerts manages the account information and alert data through some custom state ...
self._log.debug("Capturing state from the request") response = self._session.get(url=self.ALERTS_URL, headers=self.HEADERS) soup = BeautifulSoup(response.content, "html.parser") for i in soup.findAll('script'): if i.text.find('window.STATE') == -1: continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self): """Authenticate the user and setup our state."""
valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._session.get(url=self.LOGIN_URL, headers=self.HEADERS) soup = BeautifulSoup(init.content, "html.parser") soup_login...
<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, term=None): """List alerts configured for the account."""
if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[1]: self._log.info("No monitors have been created yet.") return list() monitors = list() for monitor in self._stat...
<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, monitor_id): """Delete a monitor by ID."""
if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: if monitor_id != monitor['monitor_id']: continue bit = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_view(self, request, view_func, view_args, view_kwargs): """ Collect data on Class-Based Views """
# Purge data in view method cache # Python 3's keys() method returns an iterator, so force evaluation before iterating. view_keys = list(VIEW_METHOD_DATA.keys()) for key in view_keys: del VIEW_METHOD_DATA[key] self.view_data = {} try: cbv = vie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_response(self, request, response): """Let's handle old-style response processing here, as usual."""
# For debug only. if not settings.DEBUG: return response # Check for responses where the data can't be inserted. content_encoding = response.get('Content-Encoding', '') content_type = response.get('Content-Type', '').split(';')[0] if any((getattr(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_job_class(klass_str): """ Return the job class """
mod_name, klass_name = klass_str.rsplit('.', 1) try: mod = importlib.import_module(mod_name) except ImportError as e: logger.error("Error importing job module %s: '%s'", mod_name, e) return try: klass = getattr(mod, klass_name) except AttributeError: logger.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate(self, *raw_args, **raw_kwargs): """ Mark a cached item invalid and trigger an asynchronous job to refresh the cache """
args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: expiry, data = item self.store(key, self.timeout(*args, **kwargs), data) self.async_...
<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, *raw_args, **raw_kwargs): """ Remove an item from the cache """
args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwargs) item = self.cache.get(key) if item is not None: self.cache.delete(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 set(self, *raw_args, **raw_kwargs): """ Manually set the cache value with its appropriate expiry. """
if self.set_data_kwarg in raw_kwargs: data = raw_kwargs.pop(self.set_data_kwarg) else: raw_args = list(raw_args) data = raw_args.pop() args = self.prepare_args(*raw_args) kwargs = self.prepare_kwargs(**raw_kwargs) key = self.key(*args, **kwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store(self, key, expiry, data): """ Add a result to the cache :key: Cache key to use :expiry: The expiry timestamp after which the result is stale :data: The...
self.cache.set(key, (expiry, data), self.cache_ttl) if getattr(settings, 'CACHEBACK_VERIFY_CACHE_WRITE', True): # We verify that the item was cached correctly. This is to avoid a # Memcache problem where some values aren't cached correctly # without warning. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self, *args, **kwargs): """ Fetch the result SYNCHRONOUSLY and populate the cache """
result = self.fetch(*args, **kwargs) self.store(self.key(*args, **kwargs), self.expiry(*args, **kwargs), result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_refresh(self, *args, **kwargs): """ Trigger an asynchronous job to refresh the cache """
# We trigger the task with the class path to import as well as the # (a) args and kwargs for instantiating the class # (b) args and kwargs for calling the 'refresh' method try: enqueue_task( dict( klass_str=self.class_path, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_stale_item_be_fetched_synchronously(self, delta, *args, **kwargs): """ Return whether to refresh an item synchronously when it is found in the cache b...
if self.fetch_on_stale_threshold is None: return False return delta > (self.fetch_on_stale_threshold - self.lifetime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key(self, *args, **kwargs): """ Return the cache key to use. If you're passing anything but primitive types to the ``get`` method, it's likely that you'll ne...
if not args and not kwargs: return self.class_path try: if args and not kwargs: return "%s:%s" % (self.class_path, self.hash(args)) # The line might break if your passed values are un-hashable. If # it does, you need to override this meth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hash(self, value): """ Generate a hash of the given iterable. This is for use in a cache key. """
if is_iterable(value): value = tuple(to_bytestring(v) for v in value) return hashlib.md5(six.b(':').join(value)).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_async_refresh(cls, klass_str, obj_args, obj_kwargs, call_args, call_kwargs): """ Re-populate cache using the given job class. The job class is instan...
klass = get_job_class(klass_str) if klass is None: logger.error("Unable to construct %s with args %r and kwargs %r", klass_str, obj_args, obj_kwargs) return logger.info("Using %s with constructor args %r and kwargs %r", klass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cacheback(lifetime=None, fetch_on_miss=None, cache_alias=None, job_class=None, task_options=None, **job_class_kwargs): """ Decorate function to cache its ret...
if job_class is None: job_class = FunctionJob job = job_class(lifetime=lifetime, fetch_on_miss=fetch_on_miss, cache_alias=cache_alias, task_options=task_options, **job_class_kwargs) def _wrapper(fn): # using available_attrs to work around http://bugs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def angle(v1, v2): """Return the angle in radians between vectors 'v1' and 'v2'."""
v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keep_high_angle(vertices, min_angle_deg): """Keep vertices with angles higher then given minimum."""
accepted = [] v = vertices v1 = v[1] - v[0] accepted.append((v[0][0], v[0][1])) for i in range(1, len(v) - 2): v2 = v[i + 1] - v[i - 1] diff_angle = np.fabs(angle(v1, v2) * 180.0 / np.pi) if diff_angle > min_angle_deg: accepted.append((v[i][0], v[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 set_contourf_properties(stroke_width, fcolor, fill_opacity, contour_levels, contourf_idx, unit): """Set property values for Polygon."""
return { "stroke": fcolor, "stroke-width": stroke_width, "stroke-opacity": 1, "fill": fcolor, "fill-opacity": fill_opacity, "title": "%.2f" % contour_levels[contourf_idx] + ' ' + unit }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contour_to_geojson(contour, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, geojson_properties=None, strdump=False, serialize=T...
collections = contour.collections contour_index = 0 line_features = [] for collection in collections: color = collection.get_edgecolor() for path in collection.get_paths(): v = path.vertices if len(v) < 3: continue coordinates = keep_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None,...
polygon_features = [] contourf_idx = 0 for collection in contourf.collections: color = collection.get_facecolor() for path in collection.get_paths(): for coord in path.to_polygons(): if min_angle_deg: coord = keep_high_angle(coord, min_angle_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contourf_to_geojson(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump...
polygon_features = [] mps = [] contourf_idx = 0 for coll in contourf.collections: color = coll.get_facecolor() for path in coll.get_paths(): for coord in path.to_polygons(): if min_angle_deg: coord = keep_high_angle(coord, min_angle_deg) ...
<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_authorize_callback(endpoint, provider_id): """Get a qualified URL for the provider to return to upon authorization param: endpoint: Absolute path to appe...
endpoint_prefix = config_value('BLUEPRINT_NAME') url = url_for(endpoint_prefix + '.' + endpoint, provider_id=provider_id) return request.url_root[:-1] + url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(provider_id): """Starts the provider login OAuth flow"""
provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('login', provider_id) post_login = request.form.get('next', get_post_login_redirect()) session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')] = post_login return provider.authorize(callback_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(provider_id): """Starts the provider connection OAuth flow"""
provider = get_provider_or_404(provider_id) callback_url = get_authorize_callback('connect', provider_id) allow_view = get_url(config_value('CONNECT_ALLOW_VIEW')) pc = request.form.get('next', allow_view) session[config_value('POST_OAUTH_CONNECT_SESSION_KEY')] = pc return provider.authorize(cal...
<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_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """
provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user) deleted = _datastore.delete_connections(user_id=current_user.get_id(), provider_id=provider_id) if deleted: after_this_request(_commit) 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 remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """
provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user, provider_user_id=provider_user_id) deleted = _datastore.delete_connection(user_id=current_user.get_id(), provider_id=provider_id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :par...
cv.setdefault('user_id', current_user.get_id()) connection = _datastore.find_connection( provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id']) if connection is None: after_this_request(_commit) connection = _datastore.create_connection(**cv) msg = ('Connec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login_handler(response, provider, query): """Shared method to handle the signin process"""
connection = _datastore.find_connection(**query) if connection: after_this_request(_commit) token_pair = get_token_pair_from_oauth_response(provider, response) if (token_pair['access_token'] != connection.access_token or token_pair['secret'] != connection.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 init_app(self, app, datastore=None): """Initialize the application with the Social extension :param app: The Flask application :param datastore: Connection d...
datastore = datastore or self.datastore for key, value in default_config.items(): app.config.setdefault(key, value) providers = dict() for key, config in app.config.items(): if not key.startswith('SOCIAL_') or config is None or key in default_config: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def postman(host, port=587, auth=(None, None), force_tls=False, options=None): """ Creates a Postman object with TLS and Auth middleware. TLS is placed before au...
return Postman( host=host, port=port, middlewares=[ middleware.tls(force=force_tls), middleware.auth(*auth), ], **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 mime(self): """ Returns the finalised mime object, after applying the internal headers. Usually this is not to be overriden. """
mime = self.mime_object() self.headers.prepare(mime) return mime
<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_existing_model(model_name): """ Try to find existing model class named `model_name`. :param model_name: String name of the model class. """
try: model_cls = engine.get_document_cls(model_name) log.debug('Model `{}` already exists. Using existing one'.format( model_name)) return model_cls except ValueError: log.debug('Model `{}` does not exist'.format(model_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 prepare_relationship(config, model_name, raml_resource): """ Create referenced model if it doesn't exist. When preparing a relationship, we check to see if t...
if get_existing_model(model_name) is None: plural_route = '/' + pluralize(model_name.lower()) route = '/' + model_name.lower() for res in raml_resource.root.resources: if res.method.upper() != 'POST': continue if res.path.endswith(plural_route) or 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 generate_model_cls(config, schema, model_name, raml_resource, es_based=True): """ Generate model class. Engine DB field types are determined using `type_fiel...
from nefertari.authentication.models import AuthModelMethodsMixin base_cls = engine.ESBaseDocument if es_based else engine.BaseDocument model_name = str(model_name) metaclass = type(base_cls) auth_model = schema.get('_auth_model', False) bases = [] if config.registry.database_acls: ...
<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_model_generation(config, raml_resource): """ Generates model name and runs `setup_data_model` to get or generate actual model class. :param raml_resou...
model_name = generate_model_name(raml_resource) try: return setup_data_model(config, raml_resource, model_name) except ValueError as ex: raise ValueError('{}: {}'.format(model_name, str(ex)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_model_event_subscribers(config, model_cls, schema): """ Set up model event subscribers. :param config: Pyramid Configurator instance. :param model_cls:...
events_map = get_events_map() model_events = schema.get('_event_handlers', {}) event_kwargs = {'model': model_cls} for event_tag, subscribers in model_events.items(): type_, action = event_tag.split('_') event_objects = events_map[type_][action] if not isinstance(event_objects...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_fields_processors(config, model_cls, schema): """ Set up model fields' processors. :param config: Pyramid Configurator instance. :param model_cls: Mode...
properties = schema.get('properties', {}) for field_name, props in properties.items(): if not props: continue processors = props.get('_processors') backref_processors = props.get('_backref_processors') if processors: processors = [resolve_to_callable(va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_ticket_policy(config, params): """ Setup Pyramid AuthTktAuthenticationPolicy. Notes: * Initial `secret` params value is considered to be a name of con...
from nefertari.authentication.views import ( TicketAuthRegisterView, TicketAuthLoginView, TicketAuthLogoutView) log.info('Configuring Pyramid Ticket Authn policy') if 'secret' not in params: raise ValueError( 'Missing required security scheme settings: secret') para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_apikey_policy(config, params): """ Setup `nefertari.ApiKeyAuthenticationPolicy`. Notes: * User may provide model name in :params['user_model']: do def...
from nefertari.authentication.views import ( TokenAuthRegisterView, TokenAuthClaimView, TokenAuthResetView) log.info('Configuring ApiKey Authn policy') auth_model = config.registry.auth_model params['check'] = auth_model.get_groups_by_token params['credentials_callback'] = auth_mod...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_auth_policies(config, raml_root): """ Setup authentication, authorization policies. Performs basic validation to check all the required values are pres...
log.info('Configuring auth policies') secured_by_all = raml_root.secured_by or [] secured_by = [item for item in secured_by_all if item] if not secured_by: log.info('API is not secured. `secured_by` attribute ' 'value missing.') return secured_by = secured_by[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_authuser_model(): """ Define and return AuthUser model using nefertari base classes """
from nefertari.authentication.models import AuthUserMixin from nefertari import engine class AuthUser(AuthUserMixin, engine.BaseDocument): __tablename__ = 'ramses_authuser' return AuthUser
<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_acl(config, model_cls, raml_resource, es_based=True): """ Generate an ACL. Generated ACL class has a `item_model` attribute set to :model_cls:. ACLs...
schemes = raml_resource.security_schemes or [] schemes = [sch for sch in schemes if sch.type == 'x-ACL'] if not schemes: collection_acl = item_acl = [] log.debug('No ACL scheme applied. Using ACL: {}'.format(item_acl)) else: sec_scheme = schemes[0] log.debug('{} ACL sch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getitem_es(self, key): """ Override to support ACL filtering. To do so: passes `self.request` to `get_item` and uses `ACLFilterES`. """
from nefertari_guards.elasticsearch import ACLFilterES es = ACLFilterES(self.item_model.__name__) params = { 'id': key, 'request': self.request, } obj = es.get_item(**params) obj.__acl__ = self.item_acl(obj) obj.__parent__ = self o...
<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_model_name(raml_resource): """ Generate model name. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """
resource_uri = get_resource_uri(raml_resource).strip('/') resource_uri = re.sub('\W', ' ', resource_uri) model_name = inflection.titleize(resource_uri) return inflection.singularize(model_name).replace(' ', '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_view_attrs(raml_resource, singular=False): """ Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource ...
from .views import collection_methods, item_methods # Singular resource doesn't have collection methods though # it looks like a collection if singular: collection_methods = item_methods siblings = get_resource_siblings(raml_resource) http_methods = [sibl.method.lower() for sibl in sib...
<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_events_map(): """ Prepare map of event subscribers. * Extends copies of BEFORE_EVENTS and AFTER_EVENTS maps with 'set' action. * Returns map of {before/a...
from nefertari import events set_keys = ('create', 'update', 'replace', 'update_many', 'register') before_events = events.BEFORE_EVENTS.copy() before_events['set'] = [before_events[key] for key in set_keys] after_events = events.AFTER_EVENTS.copy() after_events['set'] = [after_events[key] for k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_view_model(view_cls, model_cls): """ Patches view_cls.Model with model_cls. :param view_cls: View class "Model" param of which should be patched :param...
original_model = view_cls.Model view_cls.Model = model_cls try: yield finally: view_cls.Model = original_model
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_route_name(resource_uri): """ Get route name from RAML resource URI. :param resource_uri: String representing RAML resource URI. :returns string: String ...
resource_uri = resource_uri.strip('/') resource_uri = re.sub('\W', '', resource_uri) return resource_uri
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_resource(config, raml_resource, parent_resource): """ Perform complete one resource configuration process This function generates: ACL, view, route,...
from .models import get_existing_model # Don't generate resources for dynamic routes as they are already # generated by their parent resource_uri = get_resource_uri(raml_resource) if is_dynamic_uri(resource_uri): if parent_resource.is_root: raise Exception("Top-level resources ...
<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_server(raml_root, config): """ Handle server generation process. :param raml_root: Instance of ramlfications.raml.RootNode. :param config: Pyramid C...
log.info('Server generation started') if not raml_root.resources: return root_resource = config.get_root_resource() generated_resources = {} for raml_resource in raml_root.resources: if raml_resource.path in generated_resources: continue # Get Nefertari paren...
<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_rest_view(config, model_cls, attrs=None, es_based=True, attr_view=False, singular=False): """ Generate REST view for a model class. :param model_cls...
valid_attrs = (list(collection_methods.values()) + list(item_methods.values())) missing_attrs = set(valid_attrs) - set(attrs) if singular: bases = [ItemSingularView] elif attr_view: bases = [ItemAttributeView] elif es_based: bases = [ESCollectionView] ...
<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_object_acl(self, obj): """ Set object ACL on creation if not already present. """
if not obj._acl: from nefertari_guards import engine as guards_engine acl = self._factory(self.request).generate_item_acl(obj) obj._acl = guards_engine.ACLField.stringify_acl(acl)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _location(self, obj): """ Get location of the `obj` Arguments: :obj: self.Model instance. """
field_name = self.clean_id_name return self.request.route_url( self._resource.uid, **{self._resource.id_name: getattr(obj, field_name)})