Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def clean(self):
'''Fill metrics with defaults on create'''
if not self.metrics:
self.metrics = dict(
(name, spec.default)
for name, spec in (metric_catalog.get(self.__class__, {})
... | [] |
Please provide a description of the function:def build_catalog(site, datasets, format=None):
'''Build the DCAT catalog for this site'''
site_url = url_for('site.home_redirect', _external=True)
catalog_url = url_for('site.rdf_catalog', _external=True)
graph = Graph(namespace_manager=namespace_manager)
... | [] |
Please provide a description of the function:def sendmail_proxy(subject, email, template, **context):
sendmail.delay(subject.value, email, template, **context) | [
"Cast the lazy_gettext'ed subject to string before passing to Celery"
] |
Please provide a description of the function:def collect(path, no_input):
'''Collect static files'''
if exists(path):
msg = '"%s" directory already exists and will be erased'
log.warning(msg, path)
if not no_input:
click.confirm('Are you sure?', abort=True)
log.info(... | [] |
Please provide a description of the function:def validate_harvester_notifications(user):
'''Notify admins about pending harvester validation'''
if not user.sysadmin:
return []
notifications = []
# Only fetch required fields for notification serialization
# Greatly improve performances and ... | [] |
Please provide a description of the function:def get(app, name):
'''Get a backend given its name'''
backend = get_all(app).get(name)
if not backend:
msg = 'Harvest backend "{0}" is not registered'.format(name)
raise EntrypointError(msg)
return backend | [] |
Please provide a description of the function:def search(self):
'''Override search to match on topic tags'''
s = super(TopicSearchMixin, self).search()
s = s.filter('bool', should=[
Q('term', tags=tag) for tag in self.topic.tags
])
return s | [] |
Please provide a description of the function:def clean(self):
'''Auto populate urlhash from url'''
if not self.urlhash or 'url' in self._get_changed_fields():
self.urlhash = hash_url(self.url)
super(Reuse, self).clean() | [] |
Please provide a description of the function:def serve(info, host, port, reload, debugger, eager_loading, with_threads):
'''
Runs a local udata development server.
This local server is recommended for development purposes only but it
can also be used for simple intranet deployments.
By default it ... | [] |
Please provide a description of the function:def enforce_filetype_file(form, field):
'''Only allowed domains in resource.url when filetype is file'''
if form._fields.get('filetype').data != RESOURCE_FILETYPE_FILE:
return
domain = urlparse(field.data).netloc
allowed_domains = current_app.config['... | [] |
Please provide a description of the function:def map_legacy_frequencies(form, field):
''' Map legacy frequencies to new ones'''
if field.data in LEGACY_FREQUENCIES:
field.data = LEGACY_FREQUENCIES[field.data] | [] |
Please provide a description of the function:def resources_availability(self):
# Flatten the list.
availabilities = list(
chain(
*[org.check_availability() for org in self.organizations]
)
)
# Filter out the unknown
availabilities ... | [
"Return the percentage of availability for resources."
] |
Please provide a description of the function:def datasets_org_count(self):
from udata.models import Dataset # Circular imports.
return sum(Dataset.objects(organization=org).visible().count()
for org in self.organizations) | [
"Return the number of datasets of user's organizations."
] |
Please provide a description of the function:def followers_org_count(self):
from udata.models import Follow # Circular imports.
return sum(Follow.objects(following=org).count()
for org in self.organizations) | [
"Return the number of followers of user's organizations."
] |
Please provide a description of the function:def get_badge(self, kind):
''' Get a badge given its kind if present'''
candidates = [b for b in self.badges if b.kind == kind]
return candidates[0] if candidates else None | [] |
Please provide a description of the function:def add_badge(self, kind):
'''Perform an atomic prepend for a new badge'''
badge = self.get_badge(kind)
if badge:
return badge
if kind not in getattr(self, '__badges__', {}):
msg = 'Unknown badge type for {model}: {kind... | [] |
Please provide a description of the function:def remove_badge(self, kind):
'''Perform an atomic removal for a given badge'''
self.update(__raw__={
'$pull': {
'badges': {'kind': kind}
}
})
self.reload()
on_badge_removed.send(self, kind=kind)... | [] |
Please provide a description of the function:def toggle_badge(self, kind):
'''Toggle a bdage given its kind'''
badge = self.get_badge(kind)
if badge:
return self.remove_badge(kind)
else:
return self.add_badge(kind) | [] |
Please provide a description of the function:def badge_label(self, badge):
'''Display the badge label for a given kind'''
kind = badge.kind if isinstance(badge, Badge) else badge
return self.__badges__[kind] | [] |
Please provide a description of the function:def discussions_for(user, only_open=True):
'''
Build a queryset to query discussions related to a given user's assets.
It includes discussions coming from the user's organizations
:param bool only_open: whether to include closed discussions or not.
'''
... | [] |
Please provide a description of the function:def nofollow_callback(attrs, new=False):
parsed_url = urlparse(attrs[(None, 'href')])
if parsed_url.netloc in ('', current_app.config['SERVER_NAME']):
attrs[(None, 'href')] = '{scheme}://{netloc}{path}'.format(
scheme='https' if request.is_se... | [
"\n Turn relative links into external ones and avoid `nofollow` for us,\n\n otherwise add `nofollow`.\n That callback is not splitted in order to parse the URL only once.\n "
] |
Please provide a description of the function:def bleach_clean(stream):
return bleach.clean(
stream,
tags=current_app.config['MD_ALLOWED_TAGS'],
attributes=current_app.config['MD_ALLOWED_ATTRIBUTES'],
styles=current_app.config['MD_ALLOWED_STYLES'],
strip_comments=False) | [
"\n Sanitize malicious attempts but keep the `EXCERPT_TOKEN`.\n By default, only keeps `bleach.ALLOWED_TAGS`.\n "
] |
Please provide a description of the function:def mdstrip(value, length=None, end='…'):
'''
Truncate and strip tags from a markdown source
The markdown source is truncated at the excerpt if present and
smaller than the required length. Then, all html tags are stripped.
'''
if not value:
... | [] |
Please provide a description of the function:def toggle(path_or_id, badge_kind):
'''Toggle a `badge_kind` for a given `path_or_id`
The `path_or_id` is either an id, a slug or a file containing a list
of ids or slugs.
'''
if exists(path_or_id):
with open(path_or_id) as open_file:
... | [] |
Please provide a description of the function:def upload(name):
'''Handle upload on POST if authorized.'''
storage = fs.by_name(name)
return jsonify(success=True, **handle_upload(storage)) | [] |
Please provide a description of the function:def reindex_model_on_save(sender, document, **kwargs):
'''(Re/Un)Index Mongo document on post_save'''
if current_app.config.get('AUTO_INDEX'):
reindex.delay(document) | [] |
Please provide a description of the function:def unindex_model_on_delete(sender, document, **kwargs):
'''Unindex Mongo document on post_delete'''
if current_app.config.get('AUTO_INDEX'):
unindex.delay(document) | [] |
Please provide a description of the function:def register(adapter):
'''Register a search adapter'''
# register the class in the catalog
if adapter.model and adapter.model not in adapter_catalog:
adapter_catalog[adapter.model] = adapter
# Automatically (re|un)index objects on save/delete
... | [] |
Please provide a description of the function:def initialize(self, index_name=None):
'''Create or update indices and mappings'''
index_name = index_name or self.index_name
index = Index(index_name, using=es.client)
for adapter_class in adapter_catalog.values():
index.doc_type(... | [] |
Please provide a description of the function:def process(self, formdata=None, obj=None, data=None, **kwargs):
'''Wrap the process method to store the current object instance'''
self._obj = obj
super(CommonFormMixin, self).process(formdata, obj, data, **kwargs) | [] |
Please provide a description of the function:def get(name):
'''Get a linkchecker given its name or fallback on default'''
linkcheckers = get_enabled(ENTRYPOINT, current_app)
linkcheckers.update(no_check=NoCheckLinkchecker) # no_check always enabled
selected_linkchecker = linkcheckers.get(name)
if n... | [] |
Please provide a description of the function:def get_notifications(user):
'''List notification for a given user'''
notifications = []
for name, func in _providers.items():
notifications.extend([{
'type': name,
'created_on': dt,
'details': details
} for dt... | [] |
Please provide a description of the function:def count_tags(self):
'''Count tag occurences by type and update the tag collection'''
for key, model in TAGGED.items():
collection = '{0}_tags'.format(key)
results = (model.objects(tags__exists=True)
.map_reduce(map_tags, redu... | [] |
Please provide a description of the function:def from_model(cls, document):
return cls(meta={'id': document.id}, **cls.serialize(document)) | [
"By default use the ``to_dict`` method\n\n and exclude ``_id``, ``_cls`` and ``owner`` fields\n "
] |
Please provide a description of the function:def completer_tokenize(cls, value, min_length=3):
'''Quick and dirty tokenizer for completion suggester'''
tokens = list(itertools.chain(*[
[m for m in n.split("'") if len(m) > min_length]
for n in value.split(' ')
]))
... | [] |
Please provide a description of the function:def facet_search(cls, *facets):
'''
Build a FacetSearch for a given list of facets
Elasticsearch DSL doesn't allow to list facets
once and for all and then later select them.
They are always all requested
As we don't use them... | [] |
Please provide a description of the function:def populate_slug(instance, field):
'''
Populate a slug field if needed.
'''
value = getattr(instance, field.db_field)
try:
previous = instance.__class__.objects.get(id=instance.id)
except Exception:
previous = None
# Field value... | [] |
Please provide a description of the function:def slugify(self, value):
'''
Apply slugification according to specified field rules
'''
if value is None:
return
return slugify.slugify(value, max_length=self.max_length,
separator=self.sepa... | [] |
Please provide a description of the function:def cleanup_on_delete(self, sender, document, **kwargs):
'''
Clean up slug redirections on object deletion
'''
if not self.follow or sender is not self.owner_document:
return
slug = getattr(document, self.db_field)
... | [] |
Please provide a description of the function:def badge_form(model):
'''A form factory for a given model badges'''
class BadgeForm(ModelForm):
model_class = Badge
kind = fields.RadioField(
_('Kind'), [validators.DataRequired()],
choices=model.__badges__.items(),
... | [] |
Please provide a description of the function:def delay(name, args, kwargs):
'''Run a job asynchronously'''
args = args or []
kwargs = dict(k.split() for k in kwargs) if kwargs else {}
if name not in celery.tasks:
log.error('Job %s not found', name)
job = celery.tasks[name]
log.info('Send... | [] |
Please provide a description of the function:def boolean(value):
'''
Convert the content of a string (or a number) to a boolean.
Do nothing when input value is already a boolean.
This filter accepts usual values for ``True`` and ``False``:
"0", "f", "false", "n", etc.
'''
if value is None o... | [] |
Please provide a description of the function:def is_url(default_scheme='http', **kwargs):
def converter(value):
if value is None:
return value
if '://' not in value and default_scheme:
value = '://'.join((default_scheme, value.strip()))
try:
return ur... | [
"Return a converter that converts a clean string to an URL."
] |
Please provide a description of the function:def hash(value):
'''Detect an hash type'''
if not value:
return
elif len(value) == 32:
type = 'md5'
elif len(value) == 40:
type = 'sha1'
elif len(value) == 64:
type = 'sha256'
else:
return None
return {'type... | [] |
Please provide a description of the function:def iter_adapters():
'''Iter over adapter in predictable way'''
adapters = adapter_catalog.values()
return sorted(adapters, key=lambda a: a.model.__name__) | [] |
Please provide a description of the function:def iter_qs(qs, adapter):
'''Safely iterate over a DB QuerySet yielding ES documents'''
for obj in qs.no_cache().no_dereference().timeout(False):
if adapter.is_indexable(obj):
try:
doc = adapter.from_model(obj).to_dict(include_meta... | [] |
Please provide a description of the function:def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.ex... | [] |
Please provide a description of the function:def enable_refresh(index_name):
'''
Enable refresh and force merge. To be used after indexing.
See: https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-update-settings.html#bulk
''' # noqa
refresh_interval = current_app.config['ELASTI... | [] |
Please provide a description of the function:def set_alias(index_name, delete=True):
'''
Properly end an indexation by creating an alias.
Previous alias is deleted if needed.
'''
log.info('Creating alias "{0}" on index "{1}"'.format(
es.index_name, index_name))
if es.indices.exists_alias... | [] |
Please provide a description of the function:def handle_error(index_name, keep=False):
'''
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signa... | [] |
Please provide a description of the function:def index(models=None, name=None, force=False, keep=False):
'''
Initialize or rebuild the search index
Models to reindex can optionally be specified as arguments.
If not, all models are reindexed.
'''
index_name = name or default_index_name()
do... | [] |
Please provide a description of the function:def create_app(config='udata.settings.Defaults', override=None,
init_logging=init_logging):
'''Factory for a minimal application'''
app = UDataApp(APP_NAME)
app.config.from_object(config)
settings = os.environ.get('UDATA_SETTINGS', join(os.get... | [] |
Please provide a description of the function:def standalone(app):
'''Factory for an all in one application'''
from udata import api, core, frontend
core.init_app(app)
frontend.init_app(app)
api.init_app(app)
register_features(app)
return app | [] |
Please provide a description of the function:def send_static_file(self, filename):
'''
Override default static handling:
- raises 404 if not debug
- handle static aliases
'''
if not self.debug:
self.logger.error('Static files are only served in debug')
... | [] |
Please provide a description of the function:def rdf_catalog():
'''Root RDF endpoint with content negociation handling'''
format = RDF_EXTENSIONS[negociate_content()]
url = url_for('site.rdf_catalog_format', format=format)
return redirect(url) | [] |
Please provide a description of the function:def get_migration(plugin, filename):
'''Get an existing migration record if exists'''
db = get_db()
return db.migrations.find_one({'plugin': plugin, 'filename': filename}) | [] |
Please provide a description of the function:def execute_migration(plugin, filename, script, dryrun=False):
'''Execute and record a migration'''
db = get_db()
js = SCRIPT_WRAPPER.format(script)
lines = script.splitlines()
success = True
if not dryrun:
try:
lines = db.eval(js,... | [] |
Please provide a description of the function:def record_migration(plugin, filename, script, **kwargs):
'''Only record a migration without applying it'''
db = get_db()
db.eval(RECORD_WRAPPER, plugin, filename, script)
return True | [] |
Please provide a description of the function:def available_migrations():
'''
List available migrations for udata and enabled plugins
Each row is tuple with following signature:
(plugin, package, filename)
'''
migrations = []
for filename in resource_listdir('udata', 'migrations'):
... | [] |
Please provide a description of the function:def log_status(plugin, filename, status):
'''Properly display a migration status line'''
display = ':'.join((plugin, filename)) + ' '
log.info('%s [%s]', '{:.<70}'.format(display), status) | [] |
Please provide a description of the function:def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:
status = green(migration['date'].strftime(DATE_FORMAT))
e... | [] |
Please provide a description of the function:def migrate(record, dry_run=False):
'''Perform database migrations'''
handler = record_migration if record else execute_migration
success = True
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
... | [] |
Please provide a description of the function:def unrecord(plugin_or_specs, filename):
'''
Remove a database migration record.
\b
A record can be expressed with the following syntaxes:
- plugin filename
- plugin fliename.js
- plugin:filename
- plugin:fliename.js
'''
plugin, f... | [] |
Please provide a description of the function:def validate(url, schemes=None, tlds=None, private=None, local=None,
credentials=None):
'''
Validate and normalize an URL
:param str url: The URL to validate and normalize
:return str: The normalized URL
:raises ValidationError: when URL doe... | [] |
Please provide a description of the function:def md(filename):
'''
Load .md (markdown) file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
- travis ci build badges
'''
content = io.open(filename).read()
for match in RE_BADGE.finditer(content):
... | [] |
Please provide a description of the function:def get_json_ld_extra(key, value):
'''Serialize an extras key, value pair into JSON-LD'''
value = value.serialize() if hasattr(value, 'serialize') else value
return {
'@type': 'http://schema.org/PropertyValue',
'name': key,
'value': value,... | [] |
Please provide a description of the function:def get_resource(id):
'''Fetch a resource given its UUID'''
dataset = Dataset.objects(resources__id=id).first()
if dataset:
return get_by(dataset.resources, 'id', id)
else:
return CommunityResource.objects(id=id).first() | [] |
Please provide a description of the function:def guess(cls, *strings, **kwargs):
'''
Try to guess a license from a list of strings.
Accept a `default` keyword argument which will be
the default fallback license.
'''
license = None
for string in strings:
... | [] |
Please provide a description of the function:def guess_one(cls, text):
'''
Try to guess license from a string.
Try to exact match on identifier then slugified title
and fallback on edit distance ranking (after slugification)
'''
if not text:
return
qs... | [] |
Please provide a description of the function:def need_check(self):
'''Does the resource needs to be checked against its linkchecker?
We check unavailable resources often, unless they go over the
threshold. Available resources are checked less and less frequently
based on their historica... | [] |
Please provide a description of the function:def check_availability(self):
# Only check remote resources.
remote_resources = [resource
for resource in self.resources
if resource.filetype == 'remote']
if not remote_resources:
... | [
"Check if resources from that dataset are available.\n\n Return a list of (boolean or 'unknown')\n "
] |
Please provide a description of the function:def next_update(self):
delta = None
if self.frequency == 'daily':
delta = timedelta(days=1)
elif self.frequency == 'weekly':
delta = timedelta(weeks=1)
elif self.frequency == 'fortnighly':
delta = t... | [
"Compute the next expected update date,\n\n given the frequency and last_update.\n Return None if the frequency is not handled.\n "
] |
Please provide a description of the function:def quality(self):
from udata.models import Discussion # noqa: Prevent circular imports
result = {}
if not self.id:
# Quality is only relevant on saved Datasets
return result
if self.next_update:
r... | [
"Return a dict filled with metrics related to the inner\n\n quality of the dataset:\n\n * number of tags\n * description length\n * and so on\n "
] |
Please provide a description of the function:def compute_quality_score(self, quality):
score = 0
UNIT = 2
if 'frequency' in quality:
# TODO: should be related to frequency.
if quality['update_in'] < 0:
score += UNIT
else:
... | [
"Compute the score related to the quality of that dataset."
] |
Please provide a description of the function:def add_resource(self, resource):
'''Perform an atomic prepend for a new resource'''
resource.validate()
self.update(__raw__={
'$push': {
'resources': {
'$each': [resource.to_mongo()],
... | [] |
Please provide a description of the function:def update_resource(self, resource):
'''Perform an atomic update for an existing resource'''
index = self.resources.index(resource)
data = {
'resources__{index}'.format(index=index): resource
}
self.update(**data)
s... | [] |
Please provide a description of the function:def get_aggregation(self, name):
'''
Fetch an aggregation result given its name
As there is no way at this point know the aggregation type
(ie. bucket, pipeline or metric)
we guess it from the response attributes.
Only bucket ... | [] |
Please provide a description of the function:def language(lang_code):
'''Force a given language'''
ctx = None
if not request:
ctx = current_app.test_request_context()
ctx.push()
backup = g.get('lang_code')
g.lang_code = lang_code
refresh()
yield
g.lang_code = backup
i... | [] |
Please provide a description of the function:def redirect_to_lang(*args, **kwargs):
'''Redirect non lang-prefixed urls to default language.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs['lang_code'] = default_lang... | [] |
Please provide a description of the function:def redirect_to_unlocalized(*args, **kwargs):
'''Redirect lang-prefixed urls to no prefixed URL.'''
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs.pop('lang_code', None)
... | [] |
Please provide a description of the function:def get_translations(self):
ctx = stack.top
if ctx is None:
return NullTranslations()
locale = get_locale()
cache = self.get_translations_cache(ctx)
translations = cache.get(str(locale))
if translations ... | [
"Returns the correct gettext translations that should be used for\n this request. This will never fail and return a dummy translation\n object if used outside of the request or if a translation cannot be\n found.\n "
] |
Please provide a description of the function:def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
# Static assets are not localized
if endpoint == 'static':
return super(I18nBlueprintSetupState, self).add_url_rule(
rule, endpoint=endpoint, view_fun... | [
"A helper method to register a rule (and optionally a view function)\n to the application. The endpoint is automatically prefixed with the\n blueprint's name.\n The URL rule is registered twice.\n "
] |
Please provide a description of the function:def organization_to_rdf(org, graph=None):
'''
Map a Resource domain model to a DCAT/RDF graph
'''
graph = graph or Graph(namespace_manager=namespace_manager)
if org.id:
org_url = url_for('organizations.show_redirect',
org... | [] |
Please provide a description of the function:def person_involved(self, person):
return any(message.posted_by == person for message in self.discussion) | [
"Return True if the given person has been involved in the\n\n discussion, False otherwise.\n "
] |
Please provide a description of the function:def _compute_count_availability(resource, status, previous_status):
'''Compute the `check:count-availability` extra value'''
count_availability = resource.extras.get('check:count-availability', 1)
return count_availability + 1 if status == previous_status else 1 | [] |
Please provide a description of the function:def is_ignored(resource):
'''Check of the resource's URL is part of LINKCHECKING_IGNORE_DOMAINS'''
ignored_domains = current_app.config['LINKCHECKING_IGNORE_DOMAINS']
url = resource.url
if url:
parsed_url = urlparse(url)
return parsed_url.netl... | [] |
Please provide a description of the function:def check_resource(resource):
'''
Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the `resource.extras['check:checker']` attribute with a key that points
to a valid `udata.... | [] |
Please provide a description of the function:def owned_pre_save(sender, document, **kwargs):
'''
Owned mongoengine.pre_save signal handler
Need to fetch original owner before the new one erase it.
'''
if not isinstance(document, Owned):
return
changed_fields = getattr(document, '_changed... | [] |
Please provide a description of the function:def owned_post_save(sender, document, **kwargs):
'''
Owned mongoengine.post_save signal handler
Dispatch the `Owned.on_owner_change` signal
once the document has been saved including the previous owner.
The signal handler should have the following signat... | [] |
Please provide a description of the function:def get_enabled_plugins():
'''
Returns enabled preview plugins.
Plugins are sorted, defaults come last
'''
plugins = entrypoints.get_enabled('udata.preview', current_app).values()
valid = [p for p in plugins if issubclass(p, PreviewPlugin)]
for p... | [] |
Please provide a description of the function:def get_preview_url(resource):
'''
Returns the most pertinent preview URL associated to the resource, if any.
:param ResourceMixin resource: the (community) resource to preview
:return: a preview url to be displayed into an iframe or a new window
:rtype:... | [] |
Please provide a description of the function:def get_by(lst, field, value):
'''Find an object in a list given a field value'''
for row in lst:
if ((isinstance(row, dict) and row.get(field) == value) or
(getattr(row, field, None) == value)):
return row | [] |
Please provide a description of the function:def multi_to_dict(multi):
'''Transform a Werkzeug multidictionnary into a flat dictionnary'''
return dict(
(key, value[0] if len(value) == 1 else value)
for key, value in multi.to_dict(False).items()
) | [] |
Please provide a description of the function:def daterange_start(value):
'''Parse a date range start boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
das... | [] |
Please provide a description of the function:def daterange_end(value):
'''Parse a date range end boundary'''
if not value:
return None
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
result = parse_dt(value).date()
dashes ... | [] |
Please provide a description of the function:def to_iso(dt):
'''
Format a date or datetime into an ISO-8601 string
Support dates before 1900.
'''
if isinstance(dt, datetime):
return to_iso_datetime(dt)
elif isinstance(dt, date):
return to_iso_date(dt) | [] |
Please provide a description of the function:def to_iso_datetime(dt):
'''
Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900.
'''
if dt:
date_str = to_iso_date(dt)
time_str = '{dt.hour:02d}:{dt.minute:02d}:{d... | [] |
Please provide a description of the function:def to_bool(value):
'''
Transform a value into a boolean with the following rules:
- a boolean is returned untouched
- a string value should match any casinf of 'true' to be True
- an integer should be superior to zero to be True
- all other values a... | [] |
Please provide a description of the function:def recursive_get(obj, key):
'''
Get an attribute or a key recursively.
:param obj: The object to fetch attribute or key on
:type obj: object|dict
:param key: Either a string in dotted-notation ar an array of string
:type key: string|list|tuple
'... | [] |
Please provide a description of the function:def unique_string(length=UUID_LENGTH):
'''Generate a unique string'''
# We need a string at least as long as length
string = str(uuid4()) * int(math.ceil(length / float(UUID_LENGTH)))
return string[:length] if length else string | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.