Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def locked(*args, **kwargs): def decorator(f): attr_name = kwargs.get('lock', '_lock') logger = kwargs.get('logger') @six.wraps(f) def wrapper(self, *args, **kwargs): attr_value = getattr(self, attr_name) if ...
[ "A locking **method** decorator.\n\n It will look for a provided attribute (typically a lock or a list\n of locks) on the first argument of the function decorated (typically this\n is the 'self' object) and before executing the decorated function it\n activates the given lock or list of locks as a conte...
Please provide a description of the function:def is_writer(self, check_pending=True): me = self._current_thread() if self._writer == me: return True if check_pending: return me in self._pending_writers else: return False
[ "Returns if the caller is the active writer or a pending writer." ]
Please provide a description of the function:def owner(self): if self._writer is not None: return self.WRITER if self._readers: return self.READER return None
[ "Returns whether the lock is locked by a writer or reader." ]
Please provide a description of the function:def read_lock(self): me = self._current_thread() if me in self._pending_writers: raise RuntimeError("Writer %s can not acquire a read lock" " while waiting for the write lock" ...
[ "Context manager that grants a read lock.\n\n Will wait until no active or pending writers.\n\n Raises a ``RuntimeError`` if a pending writer tries to acquire\n a read lock.\n " ]
Please provide a description of the function:def write_lock(self): me = self._current_thread() i_am_writer = self.is_writer(check_pending=False) if self.is_reader() and not i_am_writer: raise RuntimeError("Reader %s to writer privilege" " escal...
[ "Context manager that grants a write lock.\n\n Will wait until no active readers. Blocks readers after acquiring.\n\n Guaranteed for locks to be processed in fair order (FIFO).\n\n Raises a ``RuntimeError`` if an active reader attempts to acquire\n a lock.\n " ]
Please provide a description of the function:def send_sms(self, text, **kw): params = { 'user': self._user, 'pass': self._passwd, 'msg': text } kw.setdefault("verify", False) if not kw["verify"]: # remove SSL warning ...
[ "\n Send an SMS. Since Free only allows us to send SMSes to ourselves you\n don't have to provide your phone number.\n " ]
Please provide a description of the function:def formatted_prefix(self, **format_info): prefix_name = self.prefix_template.format(**format_info) file_number = format_info.pop('file_number', 0) if prefix_name == self.prefix_template: prefix_name += '{:04d}'.format(file_number...
[ "\n Gets a dict with format info, and formats a prefix template with that info. For example:\n if our prefix template is:\n 'some_file_{groups[0]}_{file_number}'\n\n And we have this method called with:\n\n formatted_prefix(groups=[US], file_number=0)\n\n The returned forma...
Please provide a description of the function:def create_filebase_name(self, group_info, extension='gz', file_name=None): dirname = self.filebase.formatted_dirname(groups=group_info) if not file_name: file_name = self.filebase.prefix_template + '.' + extension return dirname,...
[ "\n Return tuple of resolved destination folder name and file name\n " ]
Please provide a description of the function:def write_batch(self, batch): for item in batch: for key in item: self.aggregated_info['occurrences'][key] += 1 self.increment_written_items() if self.items_limit and self.items_limit == self.get_metadata('...
[ "\n Receives the batch and writes it. This method is usually called from a manager.\n " ]
Please provide a description of the function:def _get_aggregated_info(self): agg_results = {} for key in self.aggregated_info['occurrences']: agg_results[key] = { 'occurrences': self.aggregated_info['occurrences'].get(key), 'coverage': (float(self.agg...
[ "\n Keeps track of aggregated info in a dictionary called self.aggregated_info\n " ]
Please provide a description of the function:def create_document_batches(jsonlines, id_field, max_batch_size=CLOUDSEARCH_MAX_BATCH_SIZE): batch = [] fixed_initial_size = 2 def create_entry(line): try: record = json.loads(line) except: raise ValueError('Could not...
[ "Create batches in expected AWS Cloudsearch format, limiting the\n byte size per batch according to given max_batch_size\n\n See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/preparing-data.html\n " ]
Please provide a description of the function:def _post_document_batch(self, batch): # noqa target_batch = '/2013-01-01/documents/batch' url = self.endpoint_url + target_batch return requests.post(url, data=batch, headers={'Content-type': 'application/json'})
[ "\n Send a batch to Cloudsearch endpoint\n\n See: http://docs.aws.amazon.com/cloudsearch/latest/developerguide/submitting-doc-requests.html\n " ]
Please provide a description of the function:def _create_path_if_not_exist(self, path): if path and not os.path.exists(path): os.makedirs(path)
[ "\n Creates a folders path if it doesn't exist\n " ]
Please provide a description of the function:def get_file_suffix(self, path, prefix): try: number_of_files = len(glob.glob(os.path.join(path, prefix) + '*')) except: number_of_files = 0 return '{0:04}'.format(number_of_files)
[ "\n Gets a valid filename\n " ]
Please provide a description of the function:def get_next_batch(self): if self.iterator is None: self.iterator = self.iteritems() count = 0 while count < self.batch_size: count += 1 yield next(self.iterator) self.logger.debug('Done reading ba...
[ "\n This method is called from the manager. It must return a list or a generator\n of BaseRecord objects.\n When it has nothing else to read, it must set class variable \"finished\" to True.\n " ]
Please provide a description of the function:def set_last_position(self, last_position): last_position = last_position or {} last_position.setdefault('readed_streams', []) last_position.setdefault('stream_offset', {}) self.last_position = last_position
[ "\n Called from the manager, it is in charge of updating the last position of data commited\n by the writer, in order to have resume support\n " ]
Please provide a description of the function:def close(self): if self.read_option('save_pointer'): self._update_last_pointer() super(S3Writer, self).close()
[ "\n Called to clean all possible tmp files created during the process.\n " ]
Please provide a description of the function:def get_boto_connection(aws_access_key_id, aws_secret_access_key, region=None, bucketname=None, host=None): m = _AWS_ACCESS_KEY_ID_RE.match(aws_access_key_id) if m is None or m.group() != aws_access_key_id: logging.error('The prov...
[ "\n Conection parameters must be different only if bucket name has a period\n " ]
Please provide a description of the function:def maybe_cast_list(value, types): if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): try: return li...
[ "\n Try to coerce list values into more specific list subclasses in types.\n " ]
Please provide a description of the function:def iterate_chunks(file, chunk_size): chunk = file.read(chunk_size) while chunk: yield chunk chunk = file.read(chunk_size)
[ "\n Iterate chunks of size chunk_size from a file-like object\n " ]
Please provide a description of the function:def unshift(self, chunk): if chunk: self._pos -= len(chunk) self._unconsumed.append(chunk)
[ "\n Pushes a chunk of data back into the internal buffer. This is useful\n in certain situations where a stream is being consumed by code that\n needs to \"un-consume\" some amount of data that it has optimistically\n pulled out of the source, so that the data can be passed on to some\n ...
Please provide a description of the function:def next_chunk(self): if self._unconsumed: data = self._unconsumed.pop() else: data = self._iterator.next() # Might raise StopIteration self._pos += len(data) return data
[ "\n Read a chunk of arbitrary size from the underlying iterator. To get a\n chunk of an specific size, use read()\n " ]
Please provide a description of the function:def read(self, size=None): if size is None or size < 0: return "".join(list(self)) else: data_chunks = [] data_readed = 0 try: while data_readed < size: chunk = self....
[ "\n read([size]) -> read at most size bytes, returned as a string.\n\n If the size argument is negative or None, read until EOF is reached.\n Return an empty string at EOF.\n " ]
Please provide a description of the function:def readline(self): line = "" n_pos = -1 try: while n_pos < 0: line += self.next_chunk() n_pos = line.find('\n') except StopIteration: pass if n_pos >= 0: li...
[ "\n Read until a new-line character is encountered\n " ]
Please provide a description of the function:def close(self): if callable(getattr(self._file, 'close', None)): self._iterator.close() self._iterator = None self._unconsumed = None self.closed = True
[ "\n Disable al operations and close the underlying file-like object, if any\n " ]
Please provide a description of the function:def seek(self, offset, from_what=0): if from_what == 0: # From the begining if offset >= self.tell(): self.seek(offset - self.tell(), from_what=1) else: raise NotImplementedError("Can't seek backwards"...
[ "\n seek(offset, from_what=0) -> int. Change stream position.\n\n Seek to byte offset pos relative to position indicated by whence:\n 0 Start of stream (the default). pos should be >= tell();\n 1 Current position - negative pos not implemented;\n 2 End of strea...
Please provide a description of the function:def _create_target_dir_if_needed(self, target, depth_limit=20): if depth_limit <= 0: raise FtpCreateDirsException('Depth limit exceeded') if not target: return target_dir = os.path.dirname(target) parent_dir, ...
[ "Creates the directory for the path given, recursively creating\n parent directories when needed" ]
Please provide a description of the function:def get_next_batch(self): try: batch = self.get_from_kafka() for message in batch: item = BaseRecord(message) self.increase_read() yield item except: self.finished = ...
[ "\n This method is called from the manager. It must return a list or a generator\n of BaseRecord objects.\n When it has nothing else to read, it must set class variable \"finished\" to True.\n " ]
Please provide a description of the function:def get_next_batch(self): number_of_items = self.read_option('number_of_items') for i in range(0, self.batch_size): to_read = self.last_read + 1 if to_read >= number_of_items: self.finished = True ...
[ "\n This method is called from the manager. It must return a list or a generator\n of BaseRecord objects.\n When it has nothing else to read, it must set class variable \"finished\" to True.\n " ]
Please provide a description of the function:def set_last_position(self, last_position): self.last_position = last_position if last_position is not None and last_position.get('last_read') is not None: self.last_read = last_position['last_read'] else: self.last_re...
[ "\n Called from the manager, it is in charge of updating the last position of data commited\n by the writer, in order to have resume support\n " ]
Please provide a description of the function:def configuration_from_uri(uri, uri_regex): file_path = re.match(uri_regex, uri).groups()[0] with open(file_path) as f: configuration = pickle.load(f)['configuration'] configuration = yaml.safe_load(configuration) configur...
[ "\n returns a configuration object.\n " ]
Please provide a description of the function:def check_for_errors(config, raise_exception=True): errors = {} for section in ['reader', 'writer', 'filter', 'filter_before', 'filter_after', 'transform', 'persistence', 'decompressor', 'deserializer']: config_sec...
[ "\n Returns config validation errors if raise_exception is False,\n otherwise raises ConfigurationError with those errors in it.\n Errors are represented as nested dicts (sections & options in them).\n " ]
Please provide a description of the function:def buffer(self, item): key = self.get_key_from_item(item) if not self.grouping_info.is_first_file_item(key): self.items_group_files.add_item_separator_to_file(key) self.grouping_info.ensure_group_info(key) self.items_grou...
[ "\n Receive an item and write it.\n " ]
Please provide a description of the function:def pack_buffer(self, key): self.finish_buffer_write(key) file_path = self.items_group_files.get_current_buffer_file_for_group(key).path file_hash = None if self.hash_algorithm: file_hash = hash_for_file(file_path, self.ha...
[ "Prepare current buffer file for group of given key to be written\n (by gathering statistics).\n " ]
Please provide a description of the function:def parse_persistence_uri(cls, persistence_uri): regex = cls.persistence_uri_re match = re.match(regex, persistence_uri) if not match: raise ValueError("Couldn't parse persistence URI: %s -- regex: %s)" ...
[ "Parse a database URI and the persistence state ID from\n the given persistence URI\n " ]
Please provide a description of the function:def configuration_from_uri(cls, persistence_uri): db_uri, persistence_state_id = cls.parse_persistence_uri(persistence_uri) engine = create_engine(db_uri) Base.metadata.create_all(engine) Base.metadata.bind = engine DBSession ...
[ "\n Return a configuration object.\n " ]
Please provide a description of the function:def _get_input_files(cls, input_specification): if isinstance(input_specification, (basestring, dict)): input_specification = [input_specification] elif not isinstance(input_specification, list): raise ConfigurationError("Inpu...
[ "Get list of input files according to input definition.\n\n Input definition can be:\n\n - str: specifying a filename\n\n - list of str: specifying list a of filenames\n\n - dict with \"dir\" and optional \"pattern\" parameters: specifying the\n toplevel directory under which inpu...
Please provide a description of the function:def get_next_batch(self): messages = self.get_from_kafka() if messages: for message in messages: item = BaseRecord(message) self.increase_read() yield item self.logger.debug('Done r...
[ "\n This method is called from the manager. It must return a list or a generator\n of BaseRecord objects.\n When it has nothing else to read, it must set class variable \"finished\" to True.\n " ]
Please provide a description of the function:def consume_messages(self, batchsize): if not self._reservoir: self.finished = True return for msg in self._reservoir[:batchsize]: yield msg self._reservoir = self._reservoir[batchsize:]
[ " Get messages batch from the reservoir " ]
Please provide a description of the function:def decompress_messages(self, offmsgs): for offmsg in offmsgs: yield offmsg.message.key, self.decompress_fun(offmsg.message.value)
[ " Decompress pre-defined compressed fields for each message.\n Msgs should be unpacked before this step. " ]
Please provide a description of the function:def unpack_messages(msgs): import msgpack for key, msg in msgs: record = msgpack.unpackb(msg) record['_key'] = key yield record
[ " Deserialize a message to python structures " ]
Please provide a description of the function:def set_last_position(self, last_position): if last_position is None: self.last_position = {} for partition in self.partitions: self.last_position[partition] = 0 self.consumer.offsets = self.last_position.c...
[ "\n Called from the manager, it is in charge of updating the last position of data commited\n by the writer, in order to have resume support\n " ]
Please provide a description of the function:def get_next_batch(self): if self.collection_scanner.is_enabled: batch = self.collection_scanner.get_new_batch() for item in batch: base_item = BaseRecord(item) self.increase_read() self...
[ "\n This method is called from the manager. It must return a list or a generator\n of BaseRecord objects.\n When it has nothing else to read, it must set class variable \"finished\" to True.\n " ]
Please provide a description of the function:def set_last_position(self, last_position): if last_position: if isinstance(last_position, six.string_types): last_key = last_position else: last_key = last_position.get('last_key', '') self...
[ "\n Called from the manager, it is in charge of updating the last position of data commited\n by the writer, in order to have resume support\n " ]
Please provide a description of the function:def filter_batch(self, batch): for item in batch: if self.filter(item): yield item else: self.set_metadata('filtered_out', self.get_metadata('filtered_out') + 1) ...
[ "\n Receives the batch, filters it, and returns it.\n " ]
Please provide a description of the function:def write_batch(self, batch): for item in batch: self.write_buffer.buffer(item) key = self.write_buffer.get_key_from_item(item) if self.write_buffer.should_write_buffer(key): self._write_current_buffer_for_...
[ "\n Buffer a batch of items to be written and update internal counters.\n\n Calling this method doesn't guarantee that all items have been written.\n To ensure everything has been written you need to call flush().\n " ]
Please provide a description of the function:def _check_items_limit(self): if self.items_limit and self.items_limit == self.get_metadata('items_count'): raise ItemsLimitReached('Finishing job after items_limit reached:' ' {} items written.'.format(self.ge...
[ "\n Raise ItemsLimitReached if the writer reached the configured items limit.\n " ]
Please provide a description of the function:def flush(self): for key in self.grouping_info.keys(): if self._should_flush(key): self._write_current_buffer_for_group_key(key)
[ "\n Ensure all remaining buffers are written.\n " ]
Please provide a description of the function:def _write_current_buffer_for_group_key(self, key): write_info = self.write_buffer.pack_buffer(key) self.write(write_info.get('file_path'), self.write_buffer.grouping_info[key]['membership']) self.write_buffer.clean_tmp_fil...
[ "\n Find the buffer for a given group key, prepare it to be written\n and writes it calling write() method.\n " ]
Please provide a description of the function:def get_file_suffix(self, path, prefix): parent = self._ensure_folder_path(path) file_list = self.drive.ListFile({ 'q': "'{}' in parents and trashed=false and title contains '{}'".format( parent['id'], prefix)}).GetList()...
[ "\n Gets a valid filename\n " ]
Please provide a description of the function:def _ensure_folder_path(self, filebase_path): folders = filebase_path.split('/') parent = {"id": "root"} for folder in folders: file_list = self.drive.ListFile( {'q': "'{}' in parents and trashed=false and title = ...
[ "Creates the directory for the path given, recursively creating\n parent directories when needed" ]
Please provide a description of the function:def save(self, commit=True, **kwargs): ''' PeriodicTask is dynamic and save behavior changed See: https://github.com/zakird/celerybeat-mongo/commit/dfbbd20edde91134b57f5406d0ce4eac59d6899b ''' if not self.instance: self.ins...
[]
Please provide a description of the function:def has_manifest(app, filename='manifest.json'): '''Verify the existance of a JSON assets manifest''' try: return pkg_resources.resource_exists(app, filename) except ImportError: return os.path.isabs(filename) and os.path.exists(filename)
[]
Please provide a description of the function:def register_manifest(app, filename='manifest.json'): '''Register an assets json manifest''' if current_app.config.get('TESTING'): return # Do not spend time here when testing if not has_manifest(app, filename): msg = '{filename} not found for {a...
[]
Please provide a description of the function:def load_manifest(app, filename='manifest.json'): '''Load an assets json manifest''' if os.path.isabs(filename): path = filename else: path = pkg_resources.resource_filename(app, filename) with io.open(path, mode='r', encoding='utf8') as strea...
[]
Please provide a description of the function:def from_manifest(app, filename, raw=False, **kwargs): ''' Get the path to a static file for a given app entry of a given type. :param str app: The application key to which is tied this manifest :param str filename: the original filename (without hash) :...
[]
Please provide a description of the function:def cdn_for(endpoint, **kwargs): ''' Get a CDN URL for a static assets. Do not use a replacement for all flask.url_for calls as it is only meant for CDN assets URLS. (There is some extra round trip which cost is justified by the CDN assets prformance...
[]
Please provide a description of the function:def get_or_create(self, write_concern=None, auto_save=True, *q_objs, **query): defaults = query.pop('defaults', {}) try: doc = self.get(*q_objs, **query) return doc, False except self._document.Do...
[ "Retrieve unique object or create, if it doesn't exist.\n\n Returns a tuple of ``(object, created)``, where ``object`` is\n the retrieved or created object and ``created`` is a boolean\n specifying whether a new object was created.\n\n Taken back from:\n\n https://github.com/Mongo...
Please provide a description of the function:def generic_in(self, **kwargs): '''Bypass buggy GenericReferenceField querying issue''' query = {} for key, value in kwargs.items(): if not value: continue # Optimize query for when there is only one value ...
[]
Please provide a description of the function:def issues_notifications(user): '''Notify user about open issues''' notifications = [] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = issues_for(user).only('id', 'title', 'created', 'subje...
[]
Please provide a description of the function:def get_config(key): ''' Get an identicon configuration parameter. Precedance order is: - application config (`udata.cfg`) - theme config - default ''' key = 'AVATAR_{0}'.format(key.upper()) local_config = current_app.config.g...
[]
Please provide a description of the function:def get_provider(): '''Get the current provider from config''' name = get_config('provider') available = entrypoints.get_all('udata.avatars') if name not in available: raise ValueError('Unknown avatar provider: {0}'.format(name)) return available[...
[]
Please provide a description of the function:def generate_pydenticon(identifier, size): ''' Use pydenticon to generate an identicon image. All parameters are extracted from configuration. ''' blocks_size = get_internal_config('size') foreground = get_internal_config('foreground') background ...
[]
Please provide a description of the function:def internal(identifier, size): ''' Internal provider Use pydenticon to generate an identicon. ''' identicon = generate_pydenticon(identifier, size) response = send_file(io.BytesIO(identicon), mimetype='image/png') etag = hashlib.sha1(identicon)....
[]
Please provide a description of the function:def adorable(identifier, size): ''' Adorable Avatars provider Simply redirect to the external API. See: http://avatars.adorable.io/ ''' url = ADORABLE_AVATARS_URL.format(identifier=identifier, size=size) return redirect(url)
[]
Please provide a description of the function:def robohash(identifier, size): ''' Robohash provider Redirect to the Robohash API with parameters extracted from configuration. See: https://robohash.org/ ''' skin = get_config('robohash_skin') background = get_config('robohash_background')...
[]
Please provide a description of the function:def licenses(source=DEFAULT_LICENSE_FILE): '''Feed the licenses from a JSON file''' if source.startswith('http'): json_licenses = requests.get(source).json() else: with open(source) as fp: json_licenses = json.load(fp) if len(json...
[]
Please provide a description of the function:def fetch_objects(self, geoids): ''' Custom object retrieval. Zones are resolved from their identifier instead of the default bulk fetch by ID. ''' zones = [] no_match = [] for geoid in geoids: zone...
[]
Please provide a description of the function:def lrun(command, *args, **kwargs): '''Run a local command from project root''' return run('cd {0} && {1}'.format(ROOT, command), *args, **kwargs)
[]
Please provide a description of the function:def initialize(self): '''List all datasets for a given ...''' fmt = guess_format(self.source.url) # if format can't be guessed from the url # we fallback on the declared Content-Type if not fmt: response = requests.head(sel...
[]
Please provide a description of the function:def get_tasks(): '''Get a list of known tasks with their routing queue''' return { name: get_task_queue(name, cls) for name, cls in celery.tasks.items() # Exclude celery internal tasks if not name.startswith('celery.') # Exclud...
[]
Please provide a description of the function:def tasks(): '''Display registered tasks with their queue''' tasks = get_tasks() longest = max(tasks.keys(), key=len) size = len(longest) for name, queue in sorted(tasks.items()): print('* {0}: {1}'.format(name.ljust(size), queue))
[]
Please provide a description of the function:def status(queue, munin, munin_config): if munin_config: return status_print_config(queue) queues = get_queues(queue) for queue in queues: status_print_queue(queue, munin=munin) if not munin: print('-' * 40)
[ "List queued tasks aggregated by name" ]
Please provide a description of the function:def pre_validate(self, form): '''Calls preprocessors before pre_validation''' for preprocessor in self._preprocessors: preprocessor(form, self) super(FieldHelper, self).pre_validate(form)
[]
Please provide a description of the function:def process_formdata(self, valuelist): '''Replace empty values by None''' super(EmptyNone, self).process_formdata(valuelist) self.data = self.data or None
[]
Please provide a description of the function:def fetch_objects(self, oids): ''' This methods is used to fetch models from a list of identifiers. Default implementation performs a bulk query on identifiers. Override this method to customize the objects retrieval. ''' ...
[]
Please provide a description of the function:def validate(self, form, extra_validators=tuple()): '''Perform validation only if data has been submitted''' if not self.has_data: return True if self.is_list_data: if not isinstance(self._formdata[self.name], (list, tuple)): ...
[]
Please provide a description of the function:def _add_entry(self, formdata=None, data=unset_value, index=None): ''' Fill the form with previous data if necessary to handle partial update ''' if formdata: prefix = '-'.join((self.name, str(index))) basekey = '-'.joi...
[]
Please provide a description of the function:def parse(self, data): '''Parse fields and store individual errors''' self.field_errors = {} return dict( (k, self._parse_value(k, v)) for k, v in data.items() )
[]
Please provide a description of the function:def update(site=False, organizations=False, users=False, datasets=False, reuses=False): '''Update all metrics for the current date''' do_all = not any((site, organizations, users, datasets, reuses)) if do_all or site: log.info('Update site met...
[]
Please provide a description of the function:def list(): '''List all known metrics''' for cls, metrics in metric_catalog.items(): echo(white(cls.__name__)) for metric in metrics.keys(): echo('> {0}'.format(metric))
[]
Please provide a description of the function:def labels_for_zone(zone): ''' Extract all known zone labels - main code - keys (postal...) - name translation in every supported languages ''' labels = set([zone.name, zone.code] + zone.keys_values) for lang in current_app.config['LANGUAGES']...
[]
Please provide a description of the function:def json_to_file(data, filename, pretty=False): '''Dump JSON data to a file''' kwargs = dict(indent=4) if pretty else {} dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) dump = json.dumps(api.__schema__, **k...
[]
Please provide a description of the function:def postman(filename, pretty, urlvars, swagger): '''Dump the API as a Postman collection''' data = api.as_postman(urlvars=urlvars, swagger=swagger) json_to_file(data, filename, pretty)
[]
Please provide a description of the function:def validate(): '''Validate the Swagger/OpenAPI specification with your config''' with current_app.test_request_context(): schema = json.loads(json.dumps(api.__schema__)) try: schemas.validate(schema) success('API specifications are valid'...
[]
Please provide a description of the function:def notify_badge_added_certified(sender, kind=''): ''' Send an email when a `CERTIFIED` badge is added to an `Organization` Parameters ---------- sender The object that emitted the event. kind: str The kind of `Badge` object awarded. ...
[]
Please provide a description of the function:def discussions_notifications(user): '''Notify user about open discussions''' notifications = [] # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = discussions_for(user).only('id', 'created', ...
[]
Please provide a description of the function:def send_signal(signal, request, user, **kwargs): '''Generic method to send signals to Piwik given that we always have to compute IP and UID for instance. ''' params = { 'user_ip': request.remote_addr } params.update(kwargs) if user.is_au...
[]
Please provide a description of the function:def membership_request_notifications(user): '''Notify user about pending membership requests''' orgs = [o for o in user.organizations if o.is_admin(user)] notifications = [] for org in orgs: for request in org.pending_requests: notificati...
[]
Please provide a description of the function:def create(name, url, backend, frequency=None, owner=None, org=None): '''Create a new harvest source''' log.info('Creating a new Harvest source "%s"', name) source = actions.create_source(name, url, backend, frequency=frequency,...
[]
Please provide a description of the function:def validate(identifier): '''Validate a source given its identifier''' source = actions.validate_source(identifier) log.info('Source %s (%s) has been validated', source.slug, str(source.id))
[]
Please provide a description of the function:def delete(identifier): '''Delete a harvest source''' log.info('Deleting source "%s"', identifier) actions.delete_source(identifier) log.info('Deleted source "%s"', identifier)
[]
Please provide a description of the function:def sources(scheduled=False): '''List all harvest sources''' sources = actions.list_sources() if scheduled: sources = [s for s in sources if s.periodic_task] if sources: for source in sources: msg = '{source.name} ({source.backend}...
[]
Please provide a description of the function:def backends(): '''List available backends''' log.info('Available backends:') for backend in actions.list_backends(): log.info('%s (%s)', backend.name, backend.display_name or backend.name)
[]
Please provide a description of the function:def schedule(identifier, **kwargs): '''Schedule a harvest job to run periodically''' source = actions.schedule(identifier, **kwargs) msg = 'Scheduled {source.name} with the following crontab: {cron}' log.info(msg.format(source=source, cron=source.periodic_tas...
[]
Please provide a description of the function:def unschedule(identifier): '''Unschedule a periodical harvest job''' source = actions.unschedule(identifier) log.info('Unscheduled harvest source "%s"', source.name)
[]
Please provide a description of the function:def attach(domain, filename): ''' Attach existing datasets to their harvest remote id Mapping between identifiers should be in FILENAME CSV file. ''' log.info('Attaching datasets for domain %s', domain) result = actions.attach(domain, filename) l...
[]
Please provide a description of the function:def request_transfer(subject, recipient, comment): '''Initiate a transfer request''' TransferPermission(subject).test() if recipient == (subject.organization or subject.owner): raise ValueError( 'Recipient should be different than the current ...
[]
Please provide a description of the function:def accept_transfer(transfer, comment=None): '''Accept an incoming a transfer request''' TransferResponsePermission(transfer).test() transfer.responded = datetime.now() transfer.responder = current_user._get_current_object() transfer.status = 'accepted' ...
[]
Please provide a description of the function:def refuse_transfer(transfer, comment=None): '''Refuse an incoming a transfer request''' TransferResponsePermission(transfer).test() transfer.responded = datetime.now() transfer.responder = current_user._get_current_object() transfer.status = 'refused' ...
[]