id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
14,400
opendatateam/udata
udata/models/owned.py
owned_post_save
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 signature: ``def handler(document, previous)`` ''' if isinstance(document, Owned) and hasattr(document, '_previous_owner'): Owned.on_owner_change.send(document, previous=document._previous_owner)
python
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 signature: ``def handler(document, previous)`` ''' if isinstance(document, Owned) and hasattr(document, '_previous_owner'): Owned.on_owner_change.send(document, previous=document._previous_owner)
[ "def", "owned_post_save", "(", "sender", ",", "document", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "document", ",", "Owned", ")", "and", "hasattr", "(", "document", ",", "'_previous_owner'", ")", ":", "Owned", ".", "on_owner_change", ".", "send", "(", "document", ",", "previous", "=", "document", ".", "_previous_owner", ")" ]
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 signature: ``def handler(document, previous)``
[ "Owned", "mongoengine", ".", "post_save", "signal", "handler", "Dispatch", "the", "Owned", ".", "on_owner_change", "signal", "once", "the", "document", "has", "been", "saved", "including", "the", "previous", "owner", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/owned.py#L71-L81
14,401
opendatateam/udata
udata/core/dataset/preview.py
get_enabled_plugins
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 plugin in plugins: if plugin not in valid: clsname = plugin.__name__ msg = '{0} is not a valid preview plugin'.format(clsname) warnings.warn(msg, PreviewWarning) return [p() for p in sorted(valid, key=lambda p: 1 if p.fallback else 0)]
python
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 plugin in plugins: if plugin not in valid: clsname = plugin.__name__ msg = '{0} is not a valid preview plugin'.format(clsname) warnings.warn(msg, PreviewWarning) return [p() for p in sorted(valid, key=lambda p: 1 if p.fallback else 0)]
[ "def", "get_enabled_plugins", "(", ")", ":", "plugins", "=", "entrypoints", ".", "get_enabled", "(", "'udata.preview'", ",", "current_app", ")", ".", "values", "(", ")", "valid", "=", "[", "p", "for", "p", "in", "plugins", "if", "issubclass", "(", "p", ",", "PreviewPlugin", ")", "]", "for", "plugin", "in", "plugins", ":", "if", "plugin", "not", "in", "valid", ":", "clsname", "=", "plugin", ".", "__name__", "msg", "=", "'{0} is not a valid preview plugin'", ".", "format", "(", "clsname", ")", "warnings", ".", "warn", "(", "msg", ",", "PreviewWarning", ")", "return", "[", "p", "(", ")", "for", "p", "in", "sorted", "(", "valid", ",", "key", "=", "lambda", "p", ":", "1", "if", "p", ".", "fallback", "else", "0", ")", "]" ]
Returns enabled preview plugins. Plugins are sorted, defaults come last
[ "Returns", "enabled", "preview", "plugins", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/preview.py#L64-L77
14,402
opendatateam/udata
udata/core/dataset/preview.py
get_preview_url
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: HttpResponse ''' candidates = (p.preview_url(resource) for p in get_enabled_plugins() if p.can_preview(resource)) return next(iter(candidates), None)
python
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: HttpResponse ''' candidates = (p.preview_url(resource) for p in get_enabled_plugins() if p.can_preview(resource)) return next(iter(candidates), None)
[ "def", "get_preview_url", "(", "resource", ")", ":", "candidates", "=", "(", "p", ".", "preview_url", "(", "resource", ")", "for", "p", "in", "get_enabled_plugins", "(", ")", "if", "p", ".", "can_preview", "(", "resource", ")", ")", "return", "next", "(", "iter", "(", "candidates", ")", ",", "None", ")" ]
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: HttpResponse
[ "Returns", "the", "most", "pertinent", "preview", "URL", "associated", "to", "the", "resource", "if", "any", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/preview.py#L80-L91
14,403
opendatateam/udata
udata/utils.py
get_by
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
python
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
[ "def", "get_by", "(", "lst", ",", "field", ",", "value", ")", ":", "for", "row", "in", "lst", ":", "if", "(", "(", "isinstance", "(", "row", ",", "dict", ")", "and", "row", ".", "get", "(", "field", ")", "==", "value", ")", "or", "(", "getattr", "(", "row", ",", "field", ",", "None", ")", "==", "value", ")", ")", ":", "return", "row" ]
Find an object in a list given a field value
[ "Find", "an", "object", "in", "a", "list", "given", "a", "field", "value" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L22-L27
14,404
opendatateam/udata
udata/utils.py
multi_to_dict
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() )
python
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() )
[ "def", "multi_to_dict", "(", "multi", ")", ":", "return", "dict", "(", "(", "key", ",", "value", "[", "0", "]", "if", "len", "(", "value", ")", "==", "1", "else", "value", ")", "for", "key", ",", "value", "in", "multi", ".", "to_dict", "(", "False", ")", ".", "items", "(", ")", ")" ]
Transform a Werkzeug multidictionnary into a flat dictionnary
[ "Transform", "a", "Werkzeug", "multidictionnary", "into", "a", "flat", "dictionnary" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L30-L35
14,405
opendatateam/udata
udata/utils.py
daterange_start
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() dashes = value.count('-') if dashes >= 2: return result elif dashes == 1: # Year/Month only return result.replace(day=1) else: # Year only return result.replace(day=1, month=1)
python
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() dashes = value.count('-') if dashes >= 2: return result elif dashes == 1: # Year/Month only return result.replace(day=1) else: # Year only return result.replace(day=1, month=1)
[ "def", "daterange_start", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "elif", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", "elif", "isinstance", "(", "value", ",", "date", ")", ":", "return", "value", "result", "=", "parse_dt", "(", "value", ")", ".", "date", "(", ")", "dashes", "=", "value", ".", "count", "(", "'-'", ")", "if", "dashes", ">=", "2", ":", "return", "result", "elif", "dashes", "==", "1", ":", "# Year/Month only", "return", "result", ".", "replace", "(", "day", "=", "1", ")", "else", ":", "# Year only", "return", "result", ".", "replace", "(", "day", "=", "1", ",", "month", "=", "1", ")" ]
Parse a date range start boundary
[ "Parse", "a", "date", "range", "start", "boundary" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L100-L119
14,406
opendatateam/udata
udata/utils.py
daterange_end
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 = value.count('-') if dashes >= 2: # Full date return result elif dashes == 1: # Year/Month return result + relativedelta(months=+1, days=-1, day=1) else: # Year only return result.replace(month=12, day=31)
python
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 = value.count('-') if dashes >= 2: # Full date return result elif dashes == 1: # Year/Month return result + relativedelta(months=+1, days=-1, day=1) else: # Year only return result.replace(month=12, day=31)
[ "def", "daterange_end", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "elif", "isinstance", "(", "value", ",", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", "elif", "isinstance", "(", "value", ",", "date", ")", ":", "return", "value", "result", "=", "parse_dt", "(", "value", ")", ".", "date", "(", ")", "dashes", "=", "value", ".", "count", "(", "'-'", ")", "if", "dashes", ">=", "2", ":", "# Full date", "return", "result", "elif", "dashes", "==", "1", ":", "# Year/Month", "return", "result", "+", "relativedelta", "(", "months", "=", "+", "1", ",", "days", "=", "-", "1", ",", "day", "=", "1", ")", "else", ":", "# Year only", "return", "result", ".", "replace", "(", "month", "=", "12", ",", "day", "=", "31", ")" ]
Parse a date range end boundary
[ "Parse", "a", "date", "range", "end", "boundary" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L122-L142
14,407
opendatateam/udata
udata/utils.py
to_iso
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)
python
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)
[ "def", "to_iso", "(", "dt", ")", ":", "if", "isinstance", "(", "dt", ",", "datetime", ")", ":", "return", "to_iso_datetime", "(", "dt", ")", "elif", "isinstance", "(", "dt", ",", "date", ")", ":", "return", "to_iso_date", "(", "dt", ")" ]
Format a date or datetime into an ISO-8601 string Support dates before 1900.
[ "Format", "a", "date", "or", "datetime", "into", "an", "ISO", "-", "8601", "string" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L145-L154
14,408
opendatateam/udata
udata/utils.py
to_iso_datetime
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}:{dt.second:02d}'.format( dt=dt) if isinstance(dt, datetime) else '00:00:00' return 'T'.join((date_str, time_str))
python
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}:{dt.second:02d}'.format( dt=dt) if isinstance(dt, datetime) else '00:00:00' return 'T'.join((date_str, time_str))
[ "def", "to_iso_datetime", "(", "dt", ")", ":", "if", "dt", ":", "date_str", "=", "to_iso_date", "(", "dt", ")", "time_str", "=", "'{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'", ".", "format", "(", "dt", "=", "dt", ")", "if", "isinstance", "(", "dt", ",", "datetime", ")", "else", "'00:00:00'", "return", "'T'", ".", "join", "(", "(", "date_str", ",", "time_str", ")", ")" ]
Format a date or datetime into an ISO-8601 datetime string. Time is set to 00:00:00 for dates. Support dates before 1900.
[ "Format", "a", "date", "or", "datetime", "into", "an", "ISO", "-", "8601", "datetime", "string", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L167-L179
14,409
opendatateam/udata
udata/utils.py
recursive_get
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 ''' if not obj or not key: return parts = key.split('.') if isinstance(key, basestring) else key key = parts.pop(0) if isinstance(obj, dict): value = obj.get(key, None) else: value = getattr(obj, key, None) return recursive_get(value, parts) if parts else value
python
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 ''' if not obj or not key: return parts = key.split('.') if isinstance(key, basestring) else key key = parts.pop(0) if isinstance(obj, dict): value = obj.get(key, None) else: value = getattr(obj, key, None) return recursive_get(value, parts) if parts else value
[ "def", "recursive_get", "(", "obj", ",", "key", ")", ":", "if", "not", "obj", "or", "not", "key", ":", "return", "parts", "=", "key", ".", "split", "(", "'.'", ")", "if", "isinstance", "(", "key", ",", "basestring", ")", "else", "key", "key", "=", "parts", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "value", "=", "obj", ".", "get", "(", "key", ",", "None", ")", "else", ":", "value", "=", "getattr", "(", "obj", ",", "key", ",", "None", ")", "return", "recursive_get", "(", "value", ",", "parts", ")", "if", "parts", "else", "value" ]
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
[ "Get", "an", "attribute", "or", "a", "key", "recursively", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L218-L235
14,410
opendatateam/udata
udata/utils.py
unique_string
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
python
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
[ "def", "unique_string", "(", "length", "=", "UUID_LENGTH", ")", ":", "# 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" ]
Generate a unique string
[ "Generate", "a", "unique", "string" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L238-L242
14,411
opendatateam/udata
udata/utils.py
safe_unicode
def safe_unicode(string): '''Safely transform any object into utf8 encoded bytes''' if not isinstance(string, basestring): string = unicode(string) if isinstance(string, unicode): string = string.encode('utf8') return string
python
def safe_unicode(string): '''Safely transform any object into utf8 encoded bytes''' if not isinstance(string, basestring): string = unicode(string) if isinstance(string, unicode): string = string.encode('utf8') return string
[ "def", "safe_unicode", "(", "string", ")", ":", "if", "not", "isinstance", "(", "string", ",", "basestring", ")", ":", "string", "=", "unicode", "(", "string", ")", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf8'", ")", "return", "string" ]
Safely transform any object into utf8 encoded bytes
[ "Safely", "transform", "any", "object", "into", "utf8", "encoded", "bytes" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L277-L283
14,412
opendatateam/udata
udata/features/territories/views.py
redirect_territory
def redirect_territory(level, code): """ Implicit redirect given the INSEE code. Optimistically redirect to the latest valid/known INSEE code. """ territory = GeoZone.objects.valid_at(datetime.now()).filter( code=code, level='fr:{level}'.format(level=level)).first() return redirect(url_for('territories.territory', territory=territory))
python
def redirect_territory(level, code): """ Implicit redirect given the INSEE code. Optimistically redirect to the latest valid/known INSEE code. """ territory = GeoZone.objects.valid_at(datetime.now()).filter( code=code, level='fr:{level}'.format(level=level)).first() return redirect(url_for('territories.territory', territory=territory))
[ "def", "redirect_territory", "(", "level", ",", "code", ")", ":", "territory", "=", "GeoZone", ".", "objects", ".", "valid_at", "(", "datetime", ".", "now", "(", ")", ")", ".", "filter", "(", "code", "=", "code", ",", "level", "=", "'fr:{level}'", ".", "format", "(", "level", "=", "level", ")", ")", ".", "first", "(", ")", "return", "redirect", "(", "url_for", "(", "'territories.territory'", ",", "territory", "=", "territory", ")", ")" ]
Implicit redirect given the INSEE code. Optimistically redirect to the latest valid/known INSEE code.
[ "Implicit", "redirect", "given", "the", "INSEE", "code", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/territories/views.py#L86-L94
14,413
opendatateam/udata
udata/core/jobs/commands.py
scheduled
def scheduled(): ''' List scheduled jobs. ''' for job in sorted(schedulables(), key=lambda s: s.name): for task in PeriodicTask.objects(task=job.name): label = job_label(task.task, task.args, task.kwargs) echo(SCHEDULE_LINE.format( name=white(task.name.encode('utf8')), label=label, schedule=task.schedule_display ).encode('utf8'))
python
def scheduled(): ''' List scheduled jobs. ''' for job in sorted(schedulables(), key=lambda s: s.name): for task in PeriodicTask.objects(task=job.name): label = job_label(task.task, task.args, task.kwargs) echo(SCHEDULE_LINE.format( name=white(task.name.encode('utf8')), label=label, schedule=task.schedule_display ).encode('utf8'))
[ "def", "scheduled", "(", ")", ":", "for", "job", "in", "sorted", "(", "schedulables", "(", ")", ",", "key", "=", "lambda", "s", ":", "s", ".", "name", ")", ":", "for", "task", "in", "PeriodicTask", ".", "objects", "(", "task", "=", "job", ".", "name", ")", ":", "label", "=", "job_label", "(", "task", ".", "task", ",", "task", ".", "args", ",", "task", ".", "kwargs", ")", "echo", "(", "SCHEDULE_LINE", ".", "format", "(", "name", "=", "white", "(", "task", ".", "name", ".", "encode", "(", "'utf8'", ")", ")", ",", "label", "=", "label", ",", "schedule", "=", "task", ".", "schedule_display", ")", ".", "encode", "(", "'utf8'", ")", ")" ]
List scheduled jobs.
[ "List", "scheduled", "jobs", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/jobs/commands.py#L140-L151
14,414
opendatateam/udata
udata/commands/purge.py
purge
def purge(datasets, reuses, organizations): ''' Permanently remove data flagged as deleted. If no model flag is given, all models are purged. ''' purge_all = not any((datasets, reuses, organizations)) if purge_all or datasets: log.info('Purging datasets') purge_datasets() if purge_all or reuses: log.info('Purging reuses') purge_reuses() if purge_all or organizations: log.info('Purging organizations') purge_organizations() success('Done')
python
def purge(datasets, reuses, organizations): ''' Permanently remove data flagged as deleted. If no model flag is given, all models are purged. ''' purge_all = not any((datasets, reuses, organizations)) if purge_all or datasets: log.info('Purging datasets') purge_datasets() if purge_all or reuses: log.info('Purging reuses') purge_reuses() if purge_all or organizations: log.info('Purging organizations') purge_organizations() success('Done')
[ "def", "purge", "(", "datasets", ",", "reuses", ",", "organizations", ")", ":", "purge_all", "=", "not", "any", "(", "(", "datasets", ",", "reuses", ",", "organizations", ")", ")", "if", "purge_all", "or", "datasets", ":", "log", ".", "info", "(", "'Purging datasets'", ")", "purge_datasets", "(", ")", "if", "purge_all", "or", "reuses", ":", "log", ".", "info", "(", "'Purging reuses'", ")", "purge_reuses", "(", ")", "if", "purge_all", "or", "organizations", ":", "log", ".", "info", "(", "'Purging organizations'", ")", "purge_organizations", "(", ")", "success", "(", "'Done'", ")" ]
Permanently remove data flagged as deleted. If no model flag is given, all models are purged.
[ "Permanently", "remove", "data", "flagged", "as", "deleted", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/purge.py#L21-L41
14,415
opendatateam/udata
udata/search/query.py
SearchQuery.clean_parameters
def clean_parameters(self, params): '''Only keep known parameters''' return {k: v for k, v in params.items() if k in self.adapter.facets}
python
def clean_parameters(self, params): '''Only keep known parameters''' return {k: v for k, v in params.items() if k in self.adapter.facets}
[ "def", "clean_parameters", "(", "self", ",", "params", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "if", "k", "in", "self", ".", "adapter", ".", "facets", "}" ]
Only keep known parameters
[ "Only", "keep", "known", "parameters" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L40-L42
14,416
opendatateam/udata
udata/search/query.py
SearchQuery.extract_sort
def extract_sort(self, params): '''Extract and build sort query from parameters''' sorts = params.pop('sort', []) sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [(s[1:], 'desc') if s.startswith('-') else (s, 'asc') for s in sorts] self.sorts = [ {self.adapter.sorts[s]: d} for s, d in sorts if s in self.adapter.sorts ]
python
def extract_sort(self, params): '''Extract and build sort query from parameters''' sorts = params.pop('sort', []) sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [(s[1:], 'desc') if s.startswith('-') else (s, 'asc') for s in sorts] self.sorts = [ {self.adapter.sorts[s]: d} for s, d in sorts if s in self.adapter.sorts ]
[ "def", "extract_sort", "(", "self", ",", "params", ")", ":", "sorts", "=", "params", ".", "pop", "(", "'sort'", ",", "[", "]", ")", "sorts", "=", "[", "sorts", "]", "if", "isinstance", "(", "sorts", ",", "basestring", ")", "else", "sorts", "sorts", "=", "[", "(", "s", "[", "1", ":", "]", ",", "'desc'", ")", "if", "s", ".", "startswith", "(", "'-'", ")", "else", "(", "s", ",", "'asc'", ")", "for", "s", "in", "sorts", "]", "self", ".", "sorts", "=", "[", "{", "self", ".", "adapter", ".", "sorts", "[", "s", "]", ":", "d", "}", "for", "s", ",", "d", "in", "sorts", "if", "s", "in", "self", ".", "adapter", ".", "sorts", "]" ]
Extract and build sort query from parameters
[ "Extract", "and", "build", "sort", "query", "from", "parameters" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L44-L54
14,417
opendatateam/udata
udata/search/query.py
SearchQuery.extract_pagination
def extract_pagination(self, params): '''Extract and build pagination from parameters''' try: params_page = int(params.pop('page', 1) or 1) self.page = max(params_page, 1) except: # Failsafe, if page cannot be parsed, we falback on first page self.page = 1 try: params_page_size = params.pop('page_size', DEFAULT_PAGE_SIZE) self.page_size = int(params_page_size or DEFAULT_PAGE_SIZE) except: # Failsafe, if page_size cannot be parsed, we falback on default self.page_size = DEFAULT_PAGE_SIZE self.page_start = (self.page - 1) * self.page_size self.page_end = self.page_start + self.page_size
python
def extract_pagination(self, params): '''Extract and build pagination from parameters''' try: params_page = int(params.pop('page', 1) or 1) self.page = max(params_page, 1) except: # Failsafe, if page cannot be parsed, we falback on first page self.page = 1 try: params_page_size = params.pop('page_size', DEFAULT_PAGE_SIZE) self.page_size = int(params_page_size or DEFAULT_PAGE_SIZE) except: # Failsafe, if page_size cannot be parsed, we falback on default self.page_size = DEFAULT_PAGE_SIZE self.page_start = (self.page - 1) * self.page_size self.page_end = self.page_start + self.page_size
[ "def", "extract_pagination", "(", "self", ",", "params", ")", ":", "try", ":", "params_page", "=", "int", "(", "params", ".", "pop", "(", "'page'", ",", "1", ")", "or", "1", ")", "self", ".", "page", "=", "max", "(", "params_page", ",", "1", ")", "except", ":", "# Failsafe, if page cannot be parsed, we falback on first page", "self", ".", "page", "=", "1", "try", ":", "params_page_size", "=", "params", ".", "pop", "(", "'page_size'", ",", "DEFAULT_PAGE_SIZE", ")", "self", ".", "page_size", "=", "int", "(", "params_page_size", "or", "DEFAULT_PAGE_SIZE", ")", "except", ":", "# Failsafe, if page_size cannot be parsed, we falback on default", "self", ".", "page_size", "=", "DEFAULT_PAGE_SIZE", "self", ".", "page_start", "=", "(", "self", ".", "page", "-", "1", ")", "*", "self", ".", "page_size", "self", ".", "page_end", "=", "self", ".", "page_start", "+", "self", ".", "page_size" ]
Extract and build pagination from parameters
[ "Extract", "and", "build", "pagination", "from", "parameters" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L56-L71
14,418
opendatateam/udata
udata/search/query.py
SearchQuery.aggregate
def aggregate(self, search): """ Add aggregations representing the facets selected """ for f, facet in self.facets.items(): agg = facet.get_aggregation() if isinstance(agg, Bucket): search.aggs.bucket(f, agg) elif isinstance(agg, Pipeline): search.aggs.pipeline(f, agg) else: search.aggs.metric(f, agg)
python
def aggregate(self, search): """ Add aggregations representing the facets selected """ for f, facet in self.facets.items(): agg = facet.get_aggregation() if isinstance(agg, Bucket): search.aggs.bucket(f, agg) elif isinstance(agg, Pipeline): search.aggs.pipeline(f, agg) else: search.aggs.metric(f, agg)
[ "def", "aggregate", "(", "self", ",", "search", ")", ":", "for", "f", ",", "facet", "in", "self", ".", "facets", ".", "items", "(", ")", ":", "agg", "=", "facet", ".", "get_aggregation", "(", ")", "if", "isinstance", "(", "agg", ",", "Bucket", ")", ":", "search", ".", "aggs", ".", "bucket", "(", "f", ",", "agg", ")", "elif", "isinstance", "(", "agg", ",", "Pipeline", ")", ":", "search", ".", "aggs", ".", "pipeline", "(", "f", ",", "agg", ")", "else", ":", "search", ".", "aggs", ".", "metric", "(", "f", ",", "agg", ")" ]
Add aggregations representing the facets selected
[ "Add", "aggregations", "representing", "the", "facets", "selected" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L73-L84
14,419
opendatateam/udata
udata/search/query.py
SearchQuery.filter
def filter(self, search): ''' Perform filtering instead of default post-filtering. ''' if not self._filters: return search filters = Q('match_all') for f in self._filters.values(): filters &= f return search.filter(filters)
python
def filter(self, search): ''' Perform filtering instead of default post-filtering. ''' if not self._filters: return search filters = Q('match_all') for f in self._filters.values(): filters &= f return search.filter(filters)
[ "def", "filter", "(", "self", ",", "search", ")", ":", "if", "not", "self", ".", "_filters", ":", "return", "search", "filters", "=", "Q", "(", "'match_all'", ")", "for", "f", "in", "self", ".", "_filters", ".", "values", "(", ")", ":", "filters", "&=", "f", "return", "search", ".", "filter", "(", "filters", ")" ]
Perform filtering instead of default post-filtering.
[ "Perform", "filtering", "instead", "of", "default", "post", "-", "filtering", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L86-L95
14,420
opendatateam/udata
udata/search/query.py
SearchQuery.query
def query(self, search, query): ''' Customize the search query if necessary. It handles the following features: - negation support - optional fuzziness - optional analyzer - optional match_type ''' if not query: return search included, excluded = [], [] for term in query.split(' '): if not term.strip(): continue if term.startswith('-'): excluded.append(term[1:]) else: included.append(term) if included: search = search.query(self.multi_match(included)) for term in excluded: search = search.query(~self.multi_match([term])) return search
python
def query(self, search, query): ''' Customize the search query if necessary. It handles the following features: - negation support - optional fuzziness - optional analyzer - optional match_type ''' if not query: return search included, excluded = [], [] for term in query.split(' '): if not term.strip(): continue if term.startswith('-'): excluded.append(term[1:]) else: included.append(term) if included: search = search.query(self.multi_match(included)) for term in excluded: search = search.query(~self.multi_match([term])) return search
[ "def", "query", "(", "self", ",", "search", ",", "query", ")", ":", "if", "not", "query", ":", "return", "search", "included", ",", "excluded", "=", "[", "]", ",", "[", "]", "for", "term", "in", "query", ".", "split", "(", "' '", ")", ":", "if", "not", "term", ".", "strip", "(", ")", ":", "continue", "if", "term", ".", "startswith", "(", "'-'", ")", ":", "excluded", ".", "append", "(", "term", "[", "1", ":", "]", ")", "else", ":", "included", ".", "append", "(", "term", ")", "if", "included", ":", "search", "=", "search", ".", "query", "(", "self", ".", "multi_match", "(", "included", ")", ")", "for", "term", "in", "excluded", ":", "search", "=", "search", ".", "query", "(", "~", "self", ".", "multi_match", "(", "[", "term", "]", ")", ")", "return", "search" ]
Customize the search query if necessary. It handles the following features: - negation support - optional fuzziness - optional analyzer - optional match_type
[ "Customize", "the", "search", "query", "if", "necessary", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L114-L139
14,421
opendatateam/udata
udata/search/query.py
SearchQuery.to_url
def to_url(self, url=None, replace=False, **kwargs): '''Serialize the query into an URL''' params = copy.deepcopy(self.filter_values) if self._query: params['q'] = self._query if self.page_size != DEFAULT_PAGE_SIZE: params['page_size'] = self.page_size if kwargs: for key, value in kwargs.items(): if not replace and key in params: if not isinstance(params[key], (list, tuple)): params[key] = [params[key], value] else: params[key].append(value) else: params[key] = value else: params['page'] = self.page href = Href(url or request.base_url) return href(params)
python
def to_url(self, url=None, replace=False, **kwargs): '''Serialize the query into an URL''' params = copy.deepcopy(self.filter_values) if self._query: params['q'] = self._query if self.page_size != DEFAULT_PAGE_SIZE: params['page_size'] = self.page_size if kwargs: for key, value in kwargs.items(): if not replace and key in params: if not isinstance(params[key], (list, tuple)): params[key] = [params[key], value] else: params[key].append(value) else: params[key] = value else: params['page'] = self.page href = Href(url or request.base_url) return href(params)
[ "def", "to_url", "(", "self", ",", "url", "=", "None", ",", "replace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "params", "=", "copy", ".", "deepcopy", "(", "self", ".", "filter_values", ")", "if", "self", ".", "_query", ":", "params", "[", "'q'", "]", "=", "self", ".", "_query", "if", "self", ".", "page_size", "!=", "DEFAULT_PAGE_SIZE", ":", "params", "[", "'page_size'", "]", "=", "self", ".", "page_size", "if", "kwargs", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "replace", "and", "key", "in", "params", ":", "if", "not", "isinstance", "(", "params", "[", "key", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "params", "[", "key", "]", "=", "[", "params", "[", "key", "]", ",", "value", "]", "else", ":", "params", "[", "key", "]", ".", "append", "(", "value", ")", "else", ":", "params", "[", "key", "]", "=", "value", "else", ":", "params", "[", "'page'", "]", "=", "self", ".", "page", "href", "=", "Href", "(", "url", "or", "request", ".", "base_url", ")", "return", "href", "(", "params", ")" ]
Serialize the query into an URL
[ "Serialize", "the", "query", "into", "an", "URL" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/query.py#L169-L188
14,422
opendatateam/udata
udata/frontend/csv.py
safestr
def safestr(value): '''Ensure type to string serialization''' if not value or isinstance(value, (int, float, bool, long)): return value elif isinstance(value, (date, datetime)): return value.isoformat() else: return unicode(value)
python
def safestr(value): '''Ensure type to string serialization''' if not value or isinstance(value, (int, float, bool, long)): return value elif isinstance(value, (date, datetime)): return value.isoformat() else: return unicode(value)
[ "def", "safestr", "(", "value", ")", ":", "if", "not", "value", "or", "isinstance", "(", "value", ",", "(", "int", ",", "float", ",", "bool", ",", "long", ")", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "(", "date", ",", "datetime", ")", ")", ":", "return", "value", ".", "isoformat", "(", ")", "else", ":", "return", "unicode", "(", "value", ")" ]
Ensure type to string serialization
[ "Ensure", "type", "to", "string", "serialization" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L30-L37
14,423
opendatateam/udata
udata/frontend/csv.py
yield_rows
def yield_rows(adapter): '''Yield a dataset catalog line by line''' csvfile = StringIO() writer = get_writer(csvfile) # Generate header writer.writerow(adapter.header()) yield csvfile.getvalue() del csvfile for row in adapter.rows(): csvfile = StringIO() writer = get_writer(csvfile) writer.writerow(row) yield csvfile.getvalue() del csvfile
python
def yield_rows(adapter): '''Yield a dataset catalog line by line''' csvfile = StringIO() writer = get_writer(csvfile) # Generate header writer.writerow(adapter.header()) yield csvfile.getvalue() del csvfile for row in adapter.rows(): csvfile = StringIO() writer = get_writer(csvfile) writer.writerow(row) yield csvfile.getvalue() del csvfile
[ "def", "yield_rows", "(", "adapter", ")", ":", "csvfile", "=", "StringIO", "(", ")", "writer", "=", "get_writer", "(", "csvfile", ")", "# Generate header", "writer", ".", "writerow", "(", "adapter", ".", "header", "(", ")", ")", "yield", "csvfile", ".", "getvalue", "(", ")", "del", "csvfile", "for", "row", "in", "adapter", ".", "rows", "(", ")", ":", "csvfile", "=", "StringIO", "(", ")", "writer", "=", "get_writer", "(", "csvfile", ")", "writer", ".", "writerow", "(", "row", ")", "yield", "csvfile", ".", "getvalue", "(", ")", "del", "csvfile" ]
Yield a dataset catalog line by line
[ "Yield", "a", "dataset", "catalog", "line", "by", "line" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L206-L220
14,424
opendatateam/udata
udata/frontend/csv.py
stream
def stream(queryset_or_adapter, basename=None): """Stream a csv file from an object list, a queryset or an instanciated adapter. """ if isinstance(queryset_or_adapter, Adapter): adapter = queryset_or_adapter elif isinstance(queryset_or_adapter, (list, tuple)): if not queryset_or_adapter: raise ValueError( 'Type detection is not possible with an empty list') cls = _adapters.get(queryset_or_adapter[0].__class__) adapter = cls(queryset_or_adapter) elif isinstance(queryset_or_adapter, db.BaseQuerySet): cls = _adapters.get(queryset_or_adapter._document) adapter = cls(queryset_or_adapter) else: raise ValueError('Unsupported object type') timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M') headers = { b'Content-Disposition': 'attachment; filename={0}-{1}.csv'.format( basename or 'export', timestamp), } streamer = stream_with_context(yield_rows(adapter)) return Response(streamer, mimetype="text/csv", headers=headers)
python
def stream(queryset_or_adapter, basename=None): """Stream a csv file from an object list, a queryset or an instanciated adapter. """ if isinstance(queryset_or_adapter, Adapter): adapter = queryset_or_adapter elif isinstance(queryset_or_adapter, (list, tuple)): if not queryset_or_adapter: raise ValueError( 'Type detection is not possible with an empty list') cls = _adapters.get(queryset_or_adapter[0].__class__) adapter = cls(queryset_or_adapter) elif isinstance(queryset_or_adapter, db.BaseQuerySet): cls = _adapters.get(queryset_or_adapter._document) adapter = cls(queryset_or_adapter) else: raise ValueError('Unsupported object type') timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M') headers = { b'Content-Disposition': 'attachment; filename={0}-{1}.csv'.format( basename or 'export', timestamp), } streamer = stream_with_context(yield_rows(adapter)) return Response(streamer, mimetype="text/csv", headers=headers)
[ "def", "stream", "(", "queryset_or_adapter", ",", "basename", "=", "None", ")", ":", "if", "isinstance", "(", "queryset_or_adapter", ",", "Adapter", ")", ":", "adapter", "=", "queryset_or_adapter", "elif", "isinstance", "(", "queryset_or_adapter", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "queryset_or_adapter", ":", "raise", "ValueError", "(", "'Type detection is not possible with an empty list'", ")", "cls", "=", "_adapters", ".", "get", "(", "queryset_or_adapter", "[", "0", "]", ".", "__class__", ")", "adapter", "=", "cls", "(", "queryset_or_adapter", ")", "elif", "isinstance", "(", "queryset_or_adapter", ",", "db", ".", "BaseQuerySet", ")", ":", "cls", "=", "_adapters", ".", "get", "(", "queryset_or_adapter", ".", "_document", ")", "adapter", "=", "cls", "(", "queryset_or_adapter", ")", "else", ":", "raise", "ValueError", "(", "'Unsupported object type'", ")", "timestamp", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d-%H-%M'", ")", "headers", "=", "{", "b'Content-Disposition'", ":", "'attachment; filename={0}-{1}.csv'", ".", "format", "(", "basename", "or", "'export'", ",", "timestamp", ")", ",", "}", "streamer", "=", "stream_with_context", "(", "yield_rows", "(", "adapter", ")", ")", "return", "Response", "(", "streamer", ",", "mimetype", "=", "\"text/csv\"", ",", "headers", "=", "headers", ")" ]
Stream a csv file from an object list, a queryset or an instanciated adapter.
[ "Stream", "a", "csv", "file", "from", "an", "object", "list" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L223-L248
14,425
opendatateam/udata
udata/frontend/csv.py
NestedAdapter.header
def header(self): '''Generate the CSV header row''' return (super(NestedAdapter, self).header() + [name for name, getter in self.get_nested_fields()])
python
def header(self): '''Generate the CSV header row''' return (super(NestedAdapter, self).header() + [name for name, getter in self.get_nested_fields()])
[ "def", "header", "(", "self", ")", ":", "return", "(", "super", "(", "NestedAdapter", ",", "self", ")", ".", "header", "(", ")", "+", "[", "name", "for", "name", ",", "getter", "in", "self", ".", "get_nested_fields", "(", ")", "]", ")" ]
Generate the CSV header row
[ "Generate", "the", "CSV", "header", "row" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L114-L117
14,426
opendatateam/udata
udata/frontend/csv.py
NestedAdapter.rows
def rows(self): '''Iterate over queryset objects''' return (self.nested_row(o, n) for o in self.queryset for n in getattr(o, self.attribute, []))
python
def rows(self): '''Iterate over queryset objects''' return (self.nested_row(o, n) for o in self.queryset for n in getattr(o, self.attribute, []))
[ "def", "rows", "(", "self", ")", ":", "return", "(", "self", ".", "nested_row", "(", "o", ",", "n", ")", "for", "o", "in", "self", ".", "queryset", "for", "n", "in", "getattr", "(", "o", ",", "self", ".", "attribute", ",", "[", "]", ")", ")" ]
Iterate over queryset objects
[ "Iterate", "over", "queryset", "objects" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L148-L152
14,427
opendatateam/udata
udata/frontend/csv.py
NestedAdapter.nested_row
def nested_row(self, obj, nested): '''Convert an object into a flat csv row''' row = self.to_row(obj) for name, getter in self.get_nested_fields(): content = '' if getter is not None: try: content = safestr(getter(nested)) except Exception, e: # Catch all errors intentionally. log.error('Error exporting CSV for {name}: {error}'.format( name=self.__class__.__name__, error=e)) row.append(content) return row
python
def nested_row(self, obj, nested): '''Convert an object into a flat csv row''' row = self.to_row(obj) for name, getter in self.get_nested_fields(): content = '' if getter is not None: try: content = safestr(getter(nested)) except Exception, e: # Catch all errors intentionally. log.error('Error exporting CSV for {name}: {error}'.format( name=self.__class__.__name__, error=e)) row.append(content) return row
[ "def", "nested_row", "(", "self", ",", "obj", ",", "nested", ")", ":", "row", "=", "self", ".", "to_row", "(", "obj", ")", "for", "name", ",", "getter", "in", "self", ".", "get_nested_fields", "(", ")", ":", "content", "=", "''", "if", "getter", "is", "not", "None", ":", "try", ":", "content", "=", "safestr", "(", "getter", "(", "nested", ")", ")", "except", "Exception", ",", "e", ":", "# Catch all errors intentionally.", "log", ".", "error", "(", "'Error exporting CSV for {name}: {error}'", ".", "format", "(", "name", "=", "self", ".", "__class__", ".", "__name__", ",", "error", "=", "e", ")", ")", "row", ".", "append", "(", "content", ")", "return", "row" ]
Convert an object into a flat csv row
[ "Convert", "an", "object", "into", "a", "flat", "csv", "row" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/csv.py#L154-L166
14,428
opendatateam/udata
udata/features/transfer/notifications.py
transfer_request_notifications
def transfer_request_notifications(user): '''Notify user about pending transfer requests''' orgs = [o for o in user.organizations if o.is_member(user)] notifications = [] qs = Transfer.objects(recipient__in=[user] + orgs, status='pending') # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = qs.only('id', 'created', 'subject') # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for transfer in qs.no_dereference(): notifications.append((transfer.created, { 'id': transfer.id, 'subject': { 'class': transfer.subject['_cls'].lower(), 'id': transfer.subject['_ref'].id } })) return notifications
python
def transfer_request_notifications(user): '''Notify user about pending transfer requests''' orgs = [o for o in user.organizations if o.is_member(user)] notifications = [] qs = Transfer.objects(recipient__in=[user] + orgs, status='pending') # Only fetch required fields for notification serialization # Greatly improve performances and memory usage qs = qs.only('id', 'created', 'subject') # Do not dereference subject (so it's a DBRef) # Also improve performances and memory usage for transfer in qs.no_dereference(): notifications.append((transfer.created, { 'id': transfer.id, 'subject': { 'class': transfer.subject['_cls'].lower(), 'id': transfer.subject['_ref'].id } })) return notifications
[ "def", "transfer_request_notifications", "(", "user", ")", ":", "orgs", "=", "[", "o", "for", "o", "in", "user", ".", "organizations", "if", "o", ".", "is_member", "(", "user", ")", "]", "notifications", "=", "[", "]", "qs", "=", "Transfer", ".", "objects", "(", "recipient__in", "=", "[", "user", "]", "+", "orgs", ",", "status", "=", "'pending'", ")", "# Only fetch required fields for notification serialization", "# Greatly improve performances and memory usage", "qs", "=", "qs", ".", "only", "(", "'id'", ",", "'created'", ",", "'subject'", ")", "# Do not dereference subject (so it's a DBRef)", "# Also improve performances and memory usage", "for", "transfer", "in", "qs", ".", "no_dereference", "(", ")", ":", "notifications", ".", "append", "(", "(", "transfer", ".", "created", ",", "{", "'id'", ":", "transfer", ".", "id", ",", "'subject'", ":", "{", "'class'", ":", "transfer", ".", "subject", "[", "'_cls'", "]", ".", "lower", "(", ")", ",", "'id'", ":", "transfer", ".", "subject", "[", "'_ref'", "]", ".", "id", "}", "}", ")", ")", "return", "notifications" ]
Notify user about pending transfer requests
[ "Notify", "user", "about", "pending", "transfer", "requests" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/transfer/notifications.py#L14-L35
14,429
opendatateam/udata
udata/mail.py
send
def send(subject, recipients, template_base, **kwargs): ''' Send a given email to multiple recipients. User prefered language is taken in account. To translate the subject in the right language, you should ugettext_lazy ''' sender = kwargs.pop('sender', None) if not isinstance(recipients, (list, tuple)): recipients = [recipients] debug = current_app.config.get('DEBUG', False) send_mail = current_app.config.get('SEND_MAIL', not debug) connection = send_mail and mail.connect or dummyconnection with connection() as conn: for recipient in recipients: lang = i18n._default_lang(recipient) with i18n.language(lang): log.debug( 'Sending mail "%s" to recipient "%s"', subject, recipient) msg = Message(subject, sender=sender, recipients=[recipient.email]) msg.body = theme.render( 'mail/{0}.txt'.format(template_base), subject=subject, sender=sender, recipient=recipient, **kwargs) msg.html = theme.render( 'mail/{0}.html'.format(template_base), subject=subject, sender=sender, recipient=recipient, **kwargs) conn.send(msg)
python
def send(subject, recipients, template_base, **kwargs): ''' Send a given email to multiple recipients. User prefered language is taken in account. To translate the subject in the right language, you should ugettext_lazy ''' sender = kwargs.pop('sender', None) if not isinstance(recipients, (list, tuple)): recipients = [recipients] debug = current_app.config.get('DEBUG', False) send_mail = current_app.config.get('SEND_MAIL', not debug) connection = send_mail and mail.connect or dummyconnection with connection() as conn: for recipient in recipients: lang = i18n._default_lang(recipient) with i18n.language(lang): log.debug( 'Sending mail "%s" to recipient "%s"', subject, recipient) msg = Message(subject, sender=sender, recipients=[recipient.email]) msg.body = theme.render( 'mail/{0}.txt'.format(template_base), subject=subject, sender=sender, recipient=recipient, **kwargs) msg.html = theme.render( 'mail/{0}.html'.format(template_base), subject=subject, sender=sender, recipient=recipient, **kwargs) conn.send(msg)
[ "def", "send", "(", "subject", ",", "recipients", ",", "template_base", ",", "*", "*", "kwargs", ")", ":", "sender", "=", "kwargs", ".", "pop", "(", "'sender'", ",", "None", ")", "if", "not", "isinstance", "(", "recipients", ",", "(", "list", ",", "tuple", ")", ")", ":", "recipients", "=", "[", "recipients", "]", "debug", "=", "current_app", ".", "config", ".", "get", "(", "'DEBUG'", ",", "False", ")", "send_mail", "=", "current_app", ".", "config", ".", "get", "(", "'SEND_MAIL'", ",", "not", "debug", ")", "connection", "=", "send_mail", "and", "mail", ".", "connect", "or", "dummyconnection", "with", "connection", "(", ")", "as", "conn", ":", "for", "recipient", "in", "recipients", ":", "lang", "=", "i18n", ".", "_default_lang", "(", "recipient", ")", "with", "i18n", ".", "language", "(", "lang", ")", ":", "log", ".", "debug", "(", "'Sending mail \"%s\" to recipient \"%s\"'", ",", "subject", ",", "recipient", ")", "msg", "=", "Message", "(", "subject", ",", "sender", "=", "sender", ",", "recipients", "=", "[", "recipient", ".", "email", "]", ")", "msg", ".", "body", "=", "theme", ".", "render", "(", "'mail/{0}.txt'", ".", "format", "(", "template_base", ")", ",", "subject", "=", "subject", ",", "sender", "=", "sender", ",", "recipient", "=", "recipient", ",", "*", "*", "kwargs", ")", "msg", ".", "html", "=", "theme", ".", "render", "(", "'mail/{0}.html'", ".", "format", "(", "template_base", ")", ",", "subject", "=", "subject", ",", "sender", "=", "sender", ",", "recipient", "=", "recipient", ",", "*", "*", "kwargs", ")", "conn", ".", "send", "(", "msg", ")" ]
Send a given email to multiple recipients. User prefered language is taken in account. To translate the subject in the right language, you should ugettext_lazy
[ "Send", "a", "given", "email", "to", "multiple", "recipients", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/mail.py#L40-L69
14,430
opendatateam/udata
udata/sentry.py
public_dsn
def public_dsn(dsn): '''Transform a standard Sentry DSN into a public one''' m = RE_DSN.match(dsn) if not m: log.error('Unable to parse Sentry DSN') public = '{scheme}://{client_id}@{domain}/{site_id}'.format( **m.groupdict()) return public
python
def public_dsn(dsn): '''Transform a standard Sentry DSN into a public one''' m = RE_DSN.match(dsn) if not m: log.error('Unable to parse Sentry DSN') public = '{scheme}://{client_id}@{domain}/{site_id}'.format( **m.groupdict()) return public
[ "def", "public_dsn", "(", "dsn", ")", ":", "m", "=", "RE_DSN", ".", "match", "(", "dsn", ")", "if", "not", "m", ":", "log", ".", "error", "(", "'Unable to parse Sentry DSN'", ")", "public", "=", "'{scheme}://{client_id}@{domain}/{site_id}'", ".", "format", "(", "*", "*", "m", ".", "groupdict", "(", ")", ")", "return", "public" ]
Transform a standard Sentry DSN into a public one
[ "Transform", "a", "standard", "Sentry", "DSN", "into", "a", "public", "one" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/sentry.py#L24-L31
14,431
opendatateam/udata
tasks.py
update
def update(ctx, migrate=False): '''Perform a development update''' msg = 'Update all dependencies' if migrate: msg += ' and migrate data' header(msg) info('Updating Python dependencies') lrun('pip install -r requirements/develop.pip') lrun('pip install -e .') info('Updating JavaScript dependencies') lrun('npm install') if migrate: info('Migrating database') lrun('udata db migrate')
python
def update(ctx, migrate=False): '''Perform a development update''' msg = 'Update all dependencies' if migrate: msg += ' and migrate data' header(msg) info('Updating Python dependencies') lrun('pip install -r requirements/develop.pip') lrun('pip install -e .') info('Updating JavaScript dependencies') lrun('npm install') if migrate: info('Migrating database') lrun('udata db migrate')
[ "def", "update", "(", "ctx", ",", "migrate", "=", "False", ")", ":", "msg", "=", "'Update all dependencies'", "if", "migrate", ":", "msg", "+=", "' and migrate data'", "header", "(", "msg", ")", "info", "(", "'Updating Python dependencies'", ")", "lrun", "(", "'pip install -r requirements/develop.pip'", ")", "lrun", "(", "'pip install -e .'", ")", "info", "(", "'Updating JavaScript dependencies'", ")", "lrun", "(", "'npm install'", ")", "if", "migrate", ":", "info", "(", "'Migrating database'", ")", "lrun", "(", "'udata db migrate'", ")" ]
Perform a development update
[ "Perform", "a", "development", "update" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks.py#L42-L55
14,432
opendatateam/udata
tasks.py
i18n
def i18n(ctx, update=False): '''Extract translatable strings''' header('Extract translatable strings') info('Extract Python strings') lrun('python setup.py extract_messages') # Fix crowdin requiring Language with `2-digit` iso code in potfile # to produce 2-digit iso code pofile # Opening the catalog also allows to set extra metadata potfile = join(ROOT, 'udata', 'translations', '{}.pot'.format(I18N_DOMAIN)) with open(potfile, 'rb') as infile: catalog = read_po(infile, 'en') catalog.copyright_holder = 'Open Data Team' catalog.msgid_bugs_address = 'i18n@opendata.team' catalog.language_team = 'Open Data Team <i18n@opendata.team>' catalog.last_translator = 'Open Data Team <i18n@opendata.team>' catalog.revision_date = datetime.now(LOCALTZ) with open(potfile, 'wb') as outfile: write_po(outfile, catalog, width=80) if update: lrun('python setup.py update_catalog') info('Extract JavaScript strings') keys = set() catalog = {} catalog_filename = join(ROOT, 'js', 'locales', '{}.en.json'.format(I18N_DOMAIN)) if exists(catalog_filename): with codecs.open(catalog_filename, encoding='utf8') as f: catalog = json.load(f) globs = '*.js', '*.vue', '*.hbs' regexps = [ re.compile(r'(?:|\.|\s|\{)_\(\s*(?:"|\')(.*?)(?:"|\')\s*(?:\)|,)'), # JS _('trad') re.compile(r'v-i18n="(.*?)"'), # Vue.js directive v-i18n="trad" re.compile(r'"\{\{\{?\s*\'(.*?)\'\s*\|\s*i18n\}\}\}?"'), # Vue.js filter {{ 'trad'|i18n }} re.compile(r'{{_\s*"(.*?)"\s*}}'), # Handlebars {{_ "trad" }} re.compile(r'{{_\s*\'(.*?)\'\s*}}'), # Handlebars {{_ 'trad' }} re.compile(r'\:[a-z0-9_\-]+="\s*_\(\'(.*?)\'\)\s*"'), # Vue.js binding :prop="_('trad')" ] for directory, _, _ in os.walk(join(ROOT, 'js')): glob_patterns = (iglob(join(directory, g)) for g in globs) for filename in itertools.chain(*glob_patterns): print('Extracting messages from {0}'.format(green(filename))) content = codecs.open(filename, encoding='utf8').read() for regexp in regexps: for match in regexp.finditer(content): key = match.group(1) key = key.replace('\\n', '\n') keys.add(key) if key not in catalog: catalog[key] = key # Remove old/not found translations for key in catalog.keys(): if key not in keys: del catalog[key] with codecs.open(catalog_filename, 'w', encoding='utf8') as f: json.dump(catalog, f, sort_keys=True, indent=4, ensure_ascii=False, encoding='utf8', separators=(',', ': '))
python
def i18n(ctx, update=False): '''Extract translatable strings''' header('Extract translatable strings') info('Extract Python strings') lrun('python setup.py extract_messages') # Fix crowdin requiring Language with `2-digit` iso code in potfile # to produce 2-digit iso code pofile # Opening the catalog also allows to set extra metadata potfile = join(ROOT, 'udata', 'translations', '{}.pot'.format(I18N_DOMAIN)) with open(potfile, 'rb') as infile: catalog = read_po(infile, 'en') catalog.copyright_holder = 'Open Data Team' catalog.msgid_bugs_address = 'i18n@opendata.team' catalog.language_team = 'Open Data Team <i18n@opendata.team>' catalog.last_translator = 'Open Data Team <i18n@opendata.team>' catalog.revision_date = datetime.now(LOCALTZ) with open(potfile, 'wb') as outfile: write_po(outfile, catalog, width=80) if update: lrun('python setup.py update_catalog') info('Extract JavaScript strings') keys = set() catalog = {} catalog_filename = join(ROOT, 'js', 'locales', '{}.en.json'.format(I18N_DOMAIN)) if exists(catalog_filename): with codecs.open(catalog_filename, encoding='utf8') as f: catalog = json.load(f) globs = '*.js', '*.vue', '*.hbs' regexps = [ re.compile(r'(?:|\.|\s|\{)_\(\s*(?:"|\')(.*?)(?:"|\')\s*(?:\)|,)'), # JS _('trad') re.compile(r'v-i18n="(.*?)"'), # Vue.js directive v-i18n="trad" re.compile(r'"\{\{\{?\s*\'(.*?)\'\s*\|\s*i18n\}\}\}?"'), # Vue.js filter {{ 'trad'|i18n }} re.compile(r'{{_\s*"(.*?)"\s*}}'), # Handlebars {{_ "trad" }} re.compile(r'{{_\s*\'(.*?)\'\s*}}'), # Handlebars {{_ 'trad' }} re.compile(r'\:[a-z0-9_\-]+="\s*_\(\'(.*?)\'\)\s*"'), # Vue.js binding :prop="_('trad')" ] for directory, _, _ in os.walk(join(ROOT, 'js')): glob_patterns = (iglob(join(directory, g)) for g in globs) for filename in itertools.chain(*glob_patterns): print('Extracting messages from {0}'.format(green(filename))) content = codecs.open(filename, encoding='utf8').read() for regexp in regexps: for match in regexp.finditer(content): key = match.group(1) key = key.replace('\\n', '\n') keys.add(key) if key not in catalog: catalog[key] = key # Remove old/not found translations for key in catalog.keys(): if key not in keys: del catalog[key] with codecs.open(catalog_filename, 'w', encoding='utf8') as f: json.dump(catalog, f, sort_keys=True, indent=4, ensure_ascii=False, encoding='utf8', separators=(',', ': '))
[ "def", "i18n", "(", "ctx", ",", "update", "=", "False", ")", ":", "header", "(", "'Extract translatable strings'", ")", "info", "(", "'Extract Python strings'", ")", "lrun", "(", "'python setup.py extract_messages'", ")", "# Fix crowdin requiring Language with `2-digit` iso code in potfile", "# to produce 2-digit iso code pofile", "# Opening the catalog also allows to set extra metadata", "potfile", "=", "join", "(", "ROOT", ",", "'udata'", ",", "'translations'", ",", "'{}.pot'", ".", "format", "(", "I18N_DOMAIN", ")", ")", "with", "open", "(", "potfile", ",", "'rb'", ")", "as", "infile", ":", "catalog", "=", "read_po", "(", "infile", ",", "'en'", ")", "catalog", ".", "copyright_holder", "=", "'Open Data Team'", "catalog", ".", "msgid_bugs_address", "=", "'i18n@opendata.team'", "catalog", ".", "language_team", "=", "'Open Data Team <i18n@opendata.team>'", "catalog", ".", "last_translator", "=", "'Open Data Team <i18n@opendata.team>'", "catalog", ".", "revision_date", "=", "datetime", ".", "now", "(", "LOCALTZ", ")", "with", "open", "(", "potfile", ",", "'wb'", ")", "as", "outfile", ":", "write_po", "(", "outfile", ",", "catalog", ",", "width", "=", "80", ")", "if", "update", ":", "lrun", "(", "'python setup.py update_catalog'", ")", "info", "(", "'Extract JavaScript strings'", ")", "keys", "=", "set", "(", ")", "catalog", "=", "{", "}", "catalog_filename", "=", "join", "(", "ROOT", ",", "'js'", ",", "'locales'", ",", "'{}.en.json'", ".", "format", "(", "I18N_DOMAIN", ")", ")", "if", "exists", "(", "catalog_filename", ")", ":", "with", "codecs", ".", "open", "(", "catalog_filename", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "catalog", "=", "json", ".", "load", "(", "f", ")", "globs", "=", "'*.js'", ",", "'*.vue'", ",", "'*.hbs'", "regexps", "=", "[", "re", ".", "compile", "(", "r'(?:|\\.|\\s|\\{)_\\(\\s*(?:\"|\\')(.*?)(?:\"|\\')\\s*(?:\\)|,)'", ")", ",", "# JS _('trad')", "re", ".", "compile", "(", "r'v-i18n=\"(.*?)\"'", ")", ",", "# Vue.js directive v-i18n=\"trad\"", "re", ".", "compile", "(", "r'\"\\{\\{\\{?\\s*\\'(.*?)\\'\\s*\\|\\s*i18n\\}\\}\\}?\"'", ")", ",", "# Vue.js filter {{ 'trad'|i18n }}", "re", ".", "compile", "(", "r'{{_\\s*\"(.*?)\"\\s*}}'", ")", ",", "# Handlebars {{_ \"trad\" }}", "re", ".", "compile", "(", "r'{{_\\s*\\'(.*?)\\'\\s*}}'", ")", ",", "# Handlebars {{_ 'trad' }}", "re", ".", "compile", "(", "r'\\:[a-z0-9_\\-]+=\"\\s*_\\(\\'(.*?)\\'\\)\\s*\"'", ")", ",", "# Vue.js binding :prop=\"_('trad')\"", "]", "for", "directory", ",", "_", ",", "_", "in", "os", ".", "walk", "(", "join", "(", "ROOT", ",", "'js'", ")", ")", ":", "glob_patterns", "=", "(", "iglob", "(", "join", "(", "directory", ",", "g", ")", ")", "for", "g", "in", "globs", ")", "for", "filename", "in", "itertools", ".", "chain", "(", "*", "glob_patterns", ")", ":", "print", "(", "'Extracting messages from {0}'", ".", "format", "(", "green", "(", "filename", ")", ")", ")", "content", "=", "codecs", ".", "open", "(", "filename", ",", "encoding", "=", "'utf8'", ")", ".", "read", "(", ")", "for", "regexp", "in", "regexps", ":", "for", "match", "in", "regexp", ".", "finditer", "(", "content", ")", ":", "key", "=", "match", ".", "group", "(", "1", ")", "key", "=", "key", ".", "replace", "(", "'\\\\n'", ",", "'\\n'", ")", "keys", ".", "add", "(", "key", ")", "if", "key", "not", "in", "catalog", ":", "catalog", "[", "key", "]", "=", "key", "# Remove old/not found translations", "for", "key", "in", "catalog", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "keys", ":", "del", "catalog", "[", "key", "]", "with", "codecs", ".", "open", "(", "catalog_filename", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "f", ":", "json", ".", "dump", "(", "catalog", ",", "f", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "ensure_ascii", "=", "False", ",", "encoding", "=", "'utf8'", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
Extract translatable strings
[ "Extract", "translatable", "strings" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/tasks.py#L134-L197
14,433
opendatateam/udata
udata/api/__init__.py
output_json
def output_json(data, code, headers=None): '''Use Flask JSON to serialize''' resp = make_response(json.dumps(data), code) resp.headers.extend(headers or {}) return resp
python
def output_json(data, code, headers=None): '''Use Flask JSON to serialize''' resp = make_response(json.dumps(data), code) resp.headers.extend(headers or {}) return resp
[ "def", "output_json", "(", "data", ",", "code", ",", "headers", "=", "None", ")", ":", "resp", "=", "make_response", "(", "json", ".", "dumps", "(", "data", ")", ",", "code", ")", "resp", ".", "headers", ".", "extend", "(", "headers", "or", "{", "}", ")", "return", "resp" ]
Use Flask JSON to serialize
[ "Use", "Flask", "JSON", "to", "serialize" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L191-L195
14,434
opendatateam/udata
udata/api/__init__.py
extract_name_from_path
def extract_name_from_path(path): """Return a readable name from a URL path. Useful to log requests on Piwik with categories tree structure. See: http://piwik.org/faq/how-to/#faq_62 """ base_path, query_string = path.split('?') infos = base_path.strip('/').split('/')[2:] # Removes api/version. if len(infos) > 1: # This is an object. name = '{category} / {name}'.format( category=infos[0].title(), name=infos[1].replace('-', ' ').title() ) else: # This is a collection. name = '{category}'.format(category=infos[0].title()) return safe_unicode(name)
python
def extract_name_from_path(path): """Return a readable name from a URL path. Useful to log requests on Piwik with categories tree structure. See: http://piwik.org/faq/how-to/#faq_62 """ base_path, query_string = path.split('?') infos = base_path.strip('/').split('/')[2:] # Removes api/version. if len(infos) > 1: # This is an object. name = '{category} / {name}'.format( category=infos[0].title(), name=infos[1].replace('-', ' ').title() ) else: # This is a collection. name = '{category}'.format(category=infos[0].title()) return safe_unicode(name)
[ "def", "extract_name_from_path", "(", "path", ")", ":", "base_path", ",", "query_string", "=", "path", ".", "split", "(", "'?'", ")", "infos", "=", "base_path", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "[", "2", ":", "]", "# Removes api/version.", "if", "len", "(", "infos", ")", ">", "1", ":", "# This is an object.", "name", "=", "'{category} / {name}'", ".", "format", "(", "category", "=", "infos", "[", "0", "]", ".", "title", "(", ")", ",", "name", "=", "infos", "[", "1", "]", ".", "replace", "(", "'-'", ",", "' '", ")", ".", "title", "(", ")", ")", "else", ":", "# This is a collection.", "name", "=", "'{category}'", ".", "format", "(", "category", "=", "infos", "[", "0", "]", ".", "title", "(", ")", ")", "return", "safe_unicode", "(", "name", ")" ]
Return a readable name from a URL path. Useful to log requests on Piwik with categories tree structure. See: http://piwik.org/faq/how-to/#faq_62
[ "Return", "a", "readable", "name", "from", "a", "URL", "path", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L206-L221
14,435
opendatateam/udata
udata/api/__init__.py
handle_unauthorized_file_type
def handle_unauthorized_file_type(error): '''Error occuring when the user try to upload a non-allowed file type''' url = url_for('api.allowed_extensions', _external=True) msg = ( 'This file type is not allowed.' 'The allowed file type list is available at {url}' ).format(url=url) return {'message': msg}, 400
python
def handle_unauthorized_file_type(error): '''Error occuring when the user try to upload a non-allowed file type''' url = url_for('api.allowed_extensions', _external=True) msg = ( 'This file type is not allowed.' 'The allowed file type list is available at {url}' ).format(url=url) return {'message': msg}, 400
[ "def", "handle_unauthorized_file_type", "(", "error", ")", ":", "url", "=", "url_for", "(", "'api.allowed_extensions'", ",", "_external", "=", "True", ")", "msg", "=", "(", "'This file type is not allowed.'", "'The allowed file type list is available at {url}'", ")", ".", "format", "(", "url", "=", "url", ")", "return", "{", "'message'", ":", "msg", "}", ",", "400" ]
Error occuring when the user try to upload a non-allowed file type
[ "Error", "occuring", "when", "the", "user", "try", "to", "upload", "a", "non", "-", "allowed", "file", "type" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L259-L266
14,436
opendatateam/udata
udata/api/__init__.py
UDataApi.authentify
def authentify(self, func): '''Authentify the user if credentials are given''' @wraps(func) def wrapper(*args, **kwargs): if current_user.is_authenticated: return func(*args, **kwargs) apikey = request.headers.get(HEADER_API_KEY) if apikey: try: user = User.objects.get(apikey=apikey) except User.DoesNotExist: self.abort(401, 'Invalid API Key') if not login_user(user, False): self.abort(401, 'Inactive user') else: oauth2.check_credentials() return func(*args, **kwargs) return wrapper
python
def authentify(self, func): '''Authentify the user if credentials are given''' @wraps(func) def wrapper(*args, **kwargs): if current_user.is_authenticated: return func(*args, **kwargs) apikey = request.headers.get(HEADER_API_KEY) if apikey: try: user = User.objects.get(apikey=apikey) except User.DoesNotExist: self.abort(401, 'Invalid API Key') if not login_user(user, False): self.abort(401, 'Inactive user') else: oauth2.check_credentials() return func(*args, **kwargs) return wrapper
[ "def", "authentify", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "current_user", ".", "is_authenticated", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "apikey", "=", "request", ".", "headers", ".", "get", "(", "HEADER_API_KEY", ")", "if", "apikey", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "apikey", "=", "apikey", ")", "except", "User", ".", "DoesNotExist", ":", "self", ".", "abort", "(", "401", ",", "'Invalid API Key'", ")", "if", "not", "login_user", "(", "user", ",", "False", ")", ":", "self", ".", "abort", "(", "401", ",", "'Inactive user'", ")", "else", ":", "oauth2", ".", "check_credentials", "(", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
Authentify the user if credentials are given
[ "Authentify", "the", "user", "if", "credentials", "are", "given" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L118-L137
14,437
opendatateam/udata
udata/api/__init__.py
UDataApi.validate
def validate(self, form_cls, obj=None): '''Validate a form from the request and handle errors''' if 'application/json' not in request.headers.get('Content-Type'): errors = {'Content-Type': 'expecting application/json'} self.abort(400, errors=errors) form = form_cls.from_json(request.json, obj=obj, instance=obj, csrf_enabled=False) if not form.validate(): self.abort(400, errors=form.errors) return form
python
def validate(self, form_cls, obj=None): '''Validate a form from the request and handle errors''' if 'application/json' not in request.headers.get('Content-Type'): errors = {'Content-Type': 'expecting application/json'} self.abort(400, errors=errors) form = form_cls.from_json(request.json, obj=obj, instance=obj, csrf_enabled=False) if not form.validate(): self.abort(400, errors=form.errors) return form
[ "def", "validate", "(", "self", ",", "form_cls", ",", "obj", "=", "None", ")", ":", "if", "'application/json'", "not", "in", "request", ".", "headers", ".", "get", "(", "'Content-Type'", ")", ":", "errors", "=", "{", "'Content-Type'", ":", "'expecting application/json'", "}", "self", ".", "abort", "(", "400", ",", "errors", "=", "errors", ")", "form", "=", "form_cls", ".", "from_json", "(", "request", ".", "json", ",", "obj", "=", "obj", ",", "instance", "=", "obj", ",", "csrf_enabled", "=", "False", ")", "if", "not", "form", ".", "validate", "(", ")", ":", "self", ".", "abort", "(", "400", ",", "errors", "=", "form", ".", "errors", ")", "return", "form" ]
Validate a form from the request and handle errors
[ "Validate", "a", "form", "from", "the", "request", "and", "handle", "errors" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L139-L148
14,438
opendatateam/udata
udata/api/__init__.py
UDataApi.unauthorized
def unauthorized(self, response): '''Override to change the WWW-Authenticate challenge''' realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData') challenge = 'Bearer realm="{0}"'.format(realm) response.headers['WWW-Authenticate'] = challenge return response
python
def unauthorized(self, response): '''Override to change the WWW-Authenticate challenge''' realm = current_app.config.get('HTTP_OAUTH_REALM', 'uData') challenge = 'Bearer realm="{0}"'.format(realm) response.headers['WWW-Authenticate'] = challenge return response
[ "def", "unauthorized", "(", "self", ",", "response", ")", ":", "realm", "=", "current_app", ".", "config", ".", "get", "(", "'HTTP_OAUTH_REALM'", ",", "'uData'", ")", "challenge", "=", "'Bearer realm=\"{0}\"'", ".", "format", "(", "realm", ")", "response", ".", "headers", "[", "'WWW-Authenticate'", "]", "=", "challenge", "return", "response" ]
Override to change the WWW-Authenticate challenge
[ "Override", "to", "change", "the", "WWW", "-", "Authenticate", "challenge" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/api/__init__.py#L153-L159
14,439
opendatateam/udata
udata/core/followers/api.py
FollowAPI.get
def get(self, id): '''List all followers for a given object''' args = parser.parse_args() model = self.model.objects.only('id').get_or_404(id=id) qs = Follow.objects(following=model, until=None) return qs.paginate(args['page'], args['page_size'])
python
def get(self, id): '''List all followers for a given object''' args = parser.parse_args() model = self.model.objects.only('id').get_or_404(id=id) qs = Follow.objects(following=model, until=None) return qs.paginate(args['page'], args['page_size'])
[ "def", "get", "(", "self", ",", "id", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "model", "=", "self", ".", "model", ".", "objects", ".", "only", "(", "'id'", ")", ".", "get_or_404", "(", "id", "=", "id", ")", "qs", "=", "Follow", ".", "objects", "(", "following", "=", "model", ",", "until", "=", "None", ")", "return", "qs", ".", "paginate", "(", "args", "[", "'page'", "]", ",", "args", "[", "'page_size'", "]", ")" ]
List all followers for a given object
[ "List", "all", "followers", "for", "a", "given", "object" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L47-L52
14,440
opendatateam/udata
udata/core/followers/api.py
FollowAPI.post
def post(self, id): '''Follow an object given its ID''' model = self.model.objects.only('id').get_or_404(id=id) follow, created = Follow.objects.get_or_create( follower=current_user.id, following=model, until=None) count = Follow.objects.followers(model).count() if not current_app.config['TESTING']: tracking.send_signal(on_new_follow, request, current_user) return {'followers': count}, 201 if created else 200
python
def post(self, id): '''Follow an object given its ID''' model = self.model.objects.only('id').get_or_404(id=id) follow, created = Follow.objects.get_or_create( follower=current_user.id, following=model, until=None) count = Follow.objects.followers(model).count() if not current_app.config['TESTING']: tracking.send_signal(on_new_follow, request, current_user) return {'followers': count}, 201 if created else 200
[ "def", "post", "(", "self", ",", "id", ")", ":", "model", "=", "self", ".", "model", ".", "objects", ".", "only", "(", "'id'", ")", ".", "get_or_404", "(", "id", "=", "id", ")", "follow", ",", "created", "=", "Follow", ".", "objects", ".", "get_or_create", "(", "follower", "=", "current_user", ".", "id", ",", "following", "=", "model", ",", "until", "=", "None", ")", "count", "=", "Follow", ".", "objects", ".", "followers", "(", "model", ")", ".", "count", "(", ")", "if", "not", "current_app", ".", "config", "[", "'TESTING'", "]", ":", "tracking", ".", "send_signal", "(", "on_new_follow", ",", "request", ",", "current_user", ")", "return", "{", "'followers'", ":", "count", "}", ",", "201", "if", "created", "else", "200" ]
Follow an object given its ID
[ "Follow", "an", "object", "given", "its", "ID" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L56-L64
14,441
opendatateam/udata
udata/core/followers/api.py
FollowAPI.delete
def delete(self, id): '''Unfollow an object given its ID''' model = self.model.objects.only('id').get_or_404(id=id) follow = Follow.objects.get_or_404(follower=current_user.id, following=model, until=None) follow.until = datetime.now() follow.save() count = Follow.objects.followers(model).count() return {'followers': count}, 200
python
def delete(self, id): '''Unfollow an object given its ID''' model = self.model.objects.only('id').get_or_404(id=id) follow = Follow.objects.get_or_404(follower=current_user.id, following=model, until=None) follow.until = datetime.now() follow.save() count = Follow.objects.followers(model).count() return {'followers': count}, 200
[ "def", "delete", "(", "self", ",", "id", ")", ":", "model", "=", "self", ".", "model", ".", "objects", ".", "only", "(", "'id'", ")", ".", "get_or_404", "(", "id", "=", "id", ")", "follow", "=", "Follow", ".", "objects", ".", "get_or_404", "(", "follower", "=", "current_user", ".", "id", ",", "following", "=", "model", ",", "until", "=", "None", ")", "follow", ".", "until", "=", "datetime", ".", "now", "(", ")", "follow", ".", "save", "(", ")", "count", "=", "Follow", ".", "objects", ".", "followers", "(", "model", ")", ".", "count", "(", ")", "return", "{", "'followers'", ":", "count", "}", ",", "200" ]
Unfollow an object given its ID
[ "Unfollow", "an", "object", "given", "its", "ID" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/followers/api.py#L68-L77
14,442
opendatateam/udata
udata/commands/__init__.py
error
def error(msg, details=None): '''Display an error message with optional details''' msg = '{0} {1}'.format(red(KO), white(safe_unicode(msg))) msg = safe_unicode(msg) if details: msg = b'\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg))
python
def error(msg, details=None): '''Display an error message with optional details''' msg = '{0} {1}'.format(red(KO), white(safe_unicode(msg))) msg = safe_unicode(msg) if details: msg = b'\n'.join((msg, safe_unicode(details))) echo(format_multiline(msg))
[ "def", "error", "(", "msg", ",", "details", "=", "None", ")", ":", "msg", "=", "'{0} {1}'", ".", "format", "(", "red", "(", "KO", ")", ",", "white", "(", "safe_unicode", "(", "msg", ")", ")", ")", "msg", "=", "safe_unicode", "(", "msg", ")", "if", "details", ":", "msg", "=", "b'\\n'", ".", "join", "(", "(", "msg", ",", "safe_unicode", "(", "details", ")", ")", ")", "echo", "(", "format_multiline", "(", "msg", ")", ")" ]
Display an error message with optional details
[ "Display", "an", "error", "message", "with", "optional", "details" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/__init__.py#L62-L68
14,443
opendatateam/udata
udata/commands/__init__.py
UdataGroup.main
def main(self, *args, **kwargs): ''' Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app ''' obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) # This is the import line: allows create_app to access the settings obj.settings = kwargs.pop('settings', 'udata.settings.Defaults') kwargs['obj'] = obj return super(UdataGroup, self).main(*args, **kwargs)
python
def main(self, *args, **kwargs): ''' Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app ''' obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) # This is the import line: allows create_app to access the settings obj.settings = kwargs.pop('settings', 'udata.settings.Defaults') kwargs['obj'] = obj return super(UdataGroup, self).main(*args, **kwargs)
[ "def", "main", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "kwargs", ".", "get", "(", "'obj'", ")", "if", "obj", "is", "None", ":", "obj", "=", "ScriptInfo", "(", "create_app", "=", "self", ".", "create_app", ")", "# This is the import line: allows create_app to access the settings", "obj", ".", "settings", "=", "kwargs", ".", "pop", "(", "'settings'", ",", "'udata.settings.Defaults'", ")", "kwargs", "[", "'obj'", "]", "=", "obj", "return", "super", "(", "UdataGroup", ",", "self", ")", ".", "main", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Instanciate ScriptInfo before parent does to ensure the `settings` parameters is available to `create_app
[ "Instanciate", "ScriptInfo", "before", "parent", "does", "to", "ensure", "the", "settings", "parameters", "is", "available", "to", "create_app" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/__init__.py#L240-L251
14,444
opendatateam/udata
udata/entrypoints.py
get_plugins_dists
def get_plugins_dists(app, name=None): '''Return a list of Distributions with enabled udata plugins''' if name: plugins = set(e.name for e in iter_all(name) if e.name in app.config['PLUGINS']) else: plugins = set(app.config['PLUGINS']) return [ d for d in known_dists() if any(set(v.keys()) & plugins for v in d.get_entry_map().values()) ]
python
def get_plugins_dists(app, name=None): '''Return a list of Distributions with enabled udata plugins''' if name: plugins = set(e.name for e in iter_all(name) if e.name in app.config['PLUGINS']) else: plugins = set(app.config['PLUGINS']) return [ d for d in known_dists() if any(set(v.keys()) & plugins for v in d.get_entry_map().values()) ]
[ "def", "get_plugins_dists", "(", "app", ",", "name", "=", "None", ")", ":", "if", "name", ":", "plugins", "=", "set", "(", "e", ".", "name", "for", "e", "in", "iter_all", "(", "name", ")", "if", "e", ".", "name", "in", "app", ".", "config", "[", "'PLUGINS'", "]", ")", "else", ":", "plugins", "=", "set", "(", "app", ".", "config", "[", "'PLUGINS'", "]", ")", "return", "[", "d", "for", "d", "in", "known_dists", "(", ")", "if", "any", "(", "set", "(", "v", ".", "keys", "(", ")", ")", "&", "plugins", "for", "v", "in", "d", ".", "get_entry_map", "(", ")", ".", "values", "(", ")", ")", "]" ]
Return a list of Distributions with enabled udata plugins
[ "Return", "a", "list", "of", "Distributions", "with", "enabled", "udata", "plugins" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/entrypoints.py#L64-L73
14,445
opendatateam/udata
udata/routing.py
lazy_raise_or_redirect
def lazy_raise_or_redirect(): ''' Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed ''' if not request.view_args: return for name, value in request.view_args.items(): if isinstance(value, NotFound): request.routing_exception = value break elif isinstance(value, LazyRedirect): new_args = request.view_args new_args[name] = value.arg new_url = url_for(request.endpoint, **new_args) return redirect(new_url)
python
def lazy_raise_or_redirect(): ''' Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed ''' if not request.view_args: return for name, value in request.view_args.items(): if isinstance(value, NotFound): request.routing_exception = value break elif isinstance(value, LazyRedirect): new_args = request.view_args new_args[name] = value.arg new_url = url_for(request.endpoint, **new_args) return redirect(new_url)
[ "def", "lazy_raise_or_redirect", "(", ")", ":", "if", "not", "request", ".", "view_args", ":", "return", "for", "name", ",", "value", "in", "request", ".", "view_args", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "NotFound", ")", ":", "request", ".", "routing_exception", "=", "value", "break", "elif", "isinstance", "(", "value", ",", "LazyRedirect", ")", ":", "new_args", "=", "request", ".", "view_args", "new_args", "[", "name", "]", "=", "value", ".", "arg", "new_url", "=", "url_for", "(", "request", ".", "endpoint", ",", "*", "*", "new_args", ")", "return", "redirect", "(", "new_url", ")" ]
Raise exception lazily to ensure request.endpoint is set Also perform redirect if needed
[ "Raise", "exception", "lazily", "to", "ensure", "request", ".", "endpoint", "is", "set", "Also", "perform", "redirect", "if", "needed" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L199-L214
14,446
opendatateam/udata
udata/routing.py
TerritoryConverter.to_python
def to_python(self, value): """ `value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted. """ if '/' not in value: return level, code = value.split('/')[:2] # Ignore optional slug geoid = GeoZone.SEPARATOR.join([level, code]) zone = GeoZone.objects.resolve(geoid) if not zone and GeoZone.SEPARATOR not in level: # Try implicit default prefix level = GeoZone.SEPARATOR.join([self.DEFAULT_PREFIX, level]) geoid = GeoZone.SEPARATOR.join([level, code]) zone = GeoZone.objects.resolve(geoid) return zone or NotFound()
python
def to_python(self, value): """ `value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted. """ if '/' not in value: return level, code = value.split('/')[:2] # Ignore optional slug geoid = GeoZone.SEPARATOR.join([level, code]) zone = GeoZone.objects.resolve(geoid) if not zone and GeoZone.SEPARATOR not in level: # Try implicit default prefix level = GeoZone.SEPARATOR.join([self.DEFAULT_PREFIX, level]) geoid = GeoZone.SEPARATOR.join([level, code]) zone = GeoZone.objects.resolve(geoid) return zone or NotFound()
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "'/'", "not", "in", "value", ":", "return", "level", ",", "code", "=", "value", ".", "split", "(", "'/'", ")", "[", ":", "2", "]", "# Ignore optional slug", "geoid", "=", "GeoZone", ".", "SEPARATOR", ".", "join", "(", "[", "level", ",", "code", "]", ")", "zone", "=", "GeoZone", ".", "objects", ".", "resolve", "(", "geoid", ")", "if", "not", "zone", "and", "GeoZone", ".", "SEPARATOR", "not", "in", "level", ":", "# Try implicit default prefix", "level", "=", "GeoZone", ".", "SEPARATOR", ".", "join", "(", "[", "self", ".", "DEFAULT_PREFIX", ",", "level", "]", ")", "geoid", "=", "GeoZone", ".", "SEPARATOR", ".", "join", "(", "[", "level", ",", "code", "]", ")", "zone", "=", "GeoZone", ".", "objects", ".", "resolve", "(", "geoid", ")", "return", "zone", "or", "NotFound", "(", ")" ]
`value` has slashs in it, that's why we inherit from `PathConverter`. E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or `region/76@2016-01-01/Auvergne-Rhone-Alpes/`. Note that the slug is not significative but cannot be omitted.
[ "value", "has", "slashs", "in", "it", "that", "s", "why", "we", "inherit", "from", "PathConverter", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L152-L175
14,447
opendatateam/udata
udata/routing.py
TerritoryConverter.to_url
def to_url(self, obj): """ Reconstruct the URL from level name, code or datagouv id and slug. """ level_name = getattr(obj, 'level_name', None) if not level_name: raise ValueError('Unable to serialize "%s" to url' % obj) code = getattr(obj, 'code', None) slug = getattr(obj, 'slug', None) validity = getattr(obj, 'validity', None) if code and slug: return '{level_name}/{code}@{start_date}/{slug}'.format( level_name=level_name, code=code, start_date=getattr(validity, 'start', None) or 'latest', slug=slug ) else: raise ValueError('Unable to serialize "%s" to url' % obj)
python
def to_url(self, obj): """ Reconstruct the URL from level name, code or datagouv id and slug. """ level_name = getattr(obj, 'level_name', None) if not level_name: raise ValueError('Unable to serialize "%s" to url' % obj) code = getattr(obj, 'code', None) slug = getattr(obj, 'slug', None) validity = getattr(obj, 'validity', None) if code and slug: return '{level_name}/{code}@{start_date}/{slug}'.format( level_name=level_name, code=code, start_date=getattr(validity, 'start', None) or 'latest', slug=slug ) else: raise ValueError('Unable to serialize "%s" to url' % obj)
[ "def", "to_url", "(", "self", ",", "obj", ")", ":", "level_name", "=", "getattr", "(", "obj", ",", "'level_name'", ",", "None", ")", "if", "not", "level_name", ":", "raise", "ValueError", "(", "'Unable to serialize \"%s\" to url'", "%", "obj", ")", "code", "=", "getattr", "(", "obj", ",", "'code'", ",", "None", ")", "slug", "=", "getattr", "(", "obj", ",", "'slug'", ",", "None", ")", "validity", "=", "getattr", "(", "obj", ",", "'validity'", ",", "None", ")", "if", "code", "and", "slug", ":", "return", "'{level_name}/{code}@{start_date}/{slug}'", ".", "format", "(", "level_name", "=", "level_name", ",", "code", "=", "code", ",", "start_date", "=", "getattr", "(", "validity", ",", "'start'", ",", "None", ")", "or", "'latest'", ",", "slug", "=", "slug", ")", "else", ":", "raise", "ValueError", "(", "'Unable to serialize \"%s\" to url'", "%", "obj", ")" ]
Reconstruct the URL from level name, code or datagouv id and slug.
[ "Reconstruct", "the", "URL", "from", "level", "name", "code", "or", "datagouv", "id", "and", "slug", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/routing.py#L177-L196
14,448
opendatateam/udata
udata/tasks.py
job
def job(name, **kwargs): '''A shortcut decorator for declaring jobs''' return task(name=name, schedulable=True, base=JobTask, bind=True, **kwargs)
python
def job(name, **kwargs): '''A shortcut decorator for declaring jobs''' return task(name=name, schedulable=True, base=JobTask, bind=True, **kwargs)
[ "def", "job", "(", "name", ",", "*", "*", "kwargs", ")", ":", "return", "task", "(", "name", "=", "name", ",", "schedulable", "=", "True", ",", "base", "=", "JobTask", ",", "bind", "=", "True", ",", "*", "*", "kwargs", ")" ]
A shortcut decorator for declaring jobs
[ "A", "shortcut", "decorator", "for", "declaring", "jobs" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/tasks.py#L80-L83
14,449
opendatateam/udata
udata/tasks.py
Scheduler.apply_async
def apply_async(self, entry, **kwargs): '''A MongoScheduler storing the last task_id''' result = super(Scheduler, self).apply_async(entry, **kwargs) entry._task.last_run_id = result.id return result
python
def apply_async(self, entry, **kwargs): '''A MongoScheduler storing the last task_id''' result = super(Scheduler, self).apply_async(entry, **kwargs) entry._task.last_run_id = result.id return result
[ "def", "apply_async", "(", "self", ",", "entry", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "Scheduler", ",", "self", ")", ".", "apply_async", "(", "entry", ",", "*", "*", "kwargs", ")", "entry", ".", "_task", ".", "last_run_id", "=", "result", ".", "id", "return", "result" ]
A MongoScheduler storing the last task_id
[ "A", "MongoScheduler", "storing", "the", "last", "task_id" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/tasks.py#L40-L44
14,450
opendatateam/udata
udata/commands/info.py
config
def config(): '''Display some details about the local configuration''' if hasattr(current_app, 'settings_file'): log.info('Loaded configuration from %s', current_app.settings_file) log.info(white('Current configuration')) for key in sorted(current_app.config): if key.startswith('__') or not key.isupper(): continue echo('{0}: {1}'.format(white(key), current_app.config[key]))
python
def config(): '''Display some details about the local configuration''' if hasattr(current_app, 'settings_file'): log.info('Loaded configuration from %s', current_app.settings_file) log.info(white('Current configuration')) for key in sorted(current_app.config): if key.startswith('__') or not key.isupper(): continue echo('{0}: {1}'.format(white(key), current_app.config[key]))
[ "def", "config", "(", ")", ":", "if", "hasattr", "(", "current_app", ",", "'settings_file'", ")", ":", "log", ".", "info", "(", "'Loaded configuration from %s'", ",", "current_app", ".", "settings_file", ")", "log", ".", "info", "(", "white", "(", "'Current configuration'", ")", ")", "for", "key", "in", "sorted", "(", "current_app", ".", "config", ")", ":", "if", "key", ".", "startswith", "(", "'__'", ")", "or", "not", "key", ".", "isupper", "(", ")", ":", "continue", "echo", "(", "'{0}: {1}'", ".", "format", "(", "white", "(", "key", ")", ",", "current_app", ".", "config", "[", "key", "]", ")", ")" ]
Display some details about the local configuration
[ "Display", "some", "details", "about", "the", "local", "configuration" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/info.py#L34-L43
14,451
opendatateam/udata
udata/commands/info.py
plugins
def plugins(): '''Display some details about the local plugins''' plugins = current_app.config['PLUGINS'] for name, description in entrypoints.ENTRYPOINTS.items(): echo('{0} ({1})'.format(white(description), name)) if name == 'udata.themes': actives = [current_app.config['THEME']] elif name == 'udata.avatars': actives = [avatar_config('provider')] else: actives = plugins for ep in sorted(entrypoints.iter_all(name), key=by_name): echo('> {0}: {1}'.format(ep.name, is_active(ep, actives)))
python
def plugins(): '''Display some details about the local plugins''' plugins = current_app.config['PLUGINS'] for name, description in entrypoints.ENTRYPOINTS.items(): echo('{0} ({1})'.format(white(description), name)) if name == 'udata.themes': actives = [current_app.config['THEME']] elif name == 'udata.avatars': actives = [avatar_config('provider')] else: actives = plugins for ep in sorted(entrypoints.iter_all(name), key=by_name): echo('> {0}: {1}'.format(ep.name, is_active(ep, actives)))
[ "def", "plugins", "(", ")", ":", "plugins", "=", "current_app", ".", "config", "[", "'PLUGINS'", "]", "for", "name", ",", "description", "in", "entrypoints", ".", "ENTRYPOINTS", ".", "items", "(", ")", ":", "echo", "(", "'{0} ({1})'", ".", "format", "(", "white", "(", "description", ")", ",", "name", ")", ")", "if", "name", "==", "'udata.themes'", ":", "actives", "=", "[", "current_app", ".", "config", "[", "'THEME'", "]", "]", "elif", "name", "==", "'udata.avatars'", ":", "actives", "=", "[", "avatar_config", "(", "'provider'", ")", "]", "else", ":", "actives", "=", "plugins", "for", "ep", "in", "sorted", "(", "entrypoints", ".", "iter_all", "(", "name", ")", ",", "key", "=", "by_name", ")", ":", "echo", "(", "'> {0}: {1}'", ".", "format", "(", "ep", ".", "name", ",", "is_active", "(", "ep", ",", "actives", ")", ")", ")" ]
Display some details about the local plugins
[ "Display", "some", "details", "about", "the", "local", "plugins" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/commands/info.py#L47-L59
14,452
opendatateam/udata
udata/frontend/views.py
BaseView.can
def can(self, *args, **kwargs): '''Overwrite this method to implement custom contextual permissions''' if isinstance(self.require, auth.Permission): return self.require.can() elif callable(self.require): return self.require() elif isinstance(self.require, bool): return self.require else: return True
python
def can(self, *args, **kwargs): '''Overwrite this method to implement custom contextual permissions''' if isinstance(self.require, auth.Permission): return self.require.can() elif callable(self.require): return self.require() elif isinstance(self.require, bool): return self.require else: return True
[ "def", "can", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "require", ",", "auth", ".", "Permission", ")", ":", "return", "self", ".", "require", ".", "can", "(", ")", "elif", "callable", "(", "self", ".", "require", ")", ":", "return", "self", ".", "require", "(", ")", "elif", "isinstance", "(", "self", ".", "require", ",", "bool", ")", ":", "return", "self", ".", "require", "else", ":", "return", "True" ]
Overwrite this method to implement custom contextual permissions
[ "Overwrite", "this", "method", "to", "implement", "custom", "contextual", "permissions" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/views.py#L36-L45
14,453
opendatateam/udata
udata/core/storages/utils.py
extension
def extension(filename): '''Properly extract the extension from filename''' filename = os.path.basename(filename) extension = None while '.' in filename: filename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] extension = ext if not extension else ext + '.' + extension return extension
python
def extension(filename): '''Properly extract the extension from filename''' filename = os.path.basename(filename) extension = None while '.' in filename: filename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] extension = ext if not extension else ext + '.' + extension return extension
[ "def", "extension", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "extension", "=", "None", "while", "'.'", "in", "filename", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", ".", "startswith", "(", "'.'", ")", ":", "ext", "=", "ext", "[", "1", ":", "]", "extension", "=", "ext", "if", "not", "extension", "else", "ext", "+", "'.'", "+", "extension", "return", "extension" ]
Properly extract the extension from filename
[ "Properly", "extract", "the", "extension", "from", "filename" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/storages/utils.py#L48-L59
14,454
opendatateam/udata
udata/theme/__init__.py
theme_static_with_version
def theme_static_with_version(ctx, filename, external=False): '''Override the default theme static to add cache burst''' if current_app.theme_manager.static_folder: url = assets.cdn_for('_themes.static', filename=current.identifier + '/' + filename, _external=external) else: url = assets.cdn_for('_themes.static', themeid=current.identifier, filename=filename, _external=external) if url.endswith('/'): # this is a directory, no need for cache burst return url if current_app.config['DEBUG']: burst = time() else: burst = current.entrypoint.dist.version return '{url}?_={burst}'.format(url=url, burst=burst)
python
def theme_static_with_version(ctx, filename, external=False): '''Override the default theme static to add cache burst''' if current_app.theme_manager.static_folder: url = assets.cdn_for('_themes.static', filename=current.identifier + '/' + filename, _external=external) else: url = assets.cdn_for('_themes.static', themeid=current.identifier, filename=filename, _external=external) if url.endswith('/'): # this is a directory, no need for cache burst return url if current_app.config['DEBUG']: burst = time() else: burst = current.entrypoint.dist.version return '{url}?_={burst}'.format(url=url, burst=burst)
[ "def", "theme_static_with_version", "(", "ctx", ",", "filename", ",", "external", "=", "False", ")", ":", "if", "current_app", ".", "theme_manager", ".", "static_folder", ":", "url", "=", "assets", ".", "cdn_for", "(", "'_themes.static'", ",", "filename", "=", "current", ".", "identifier", "+", "'/'", "+", "filename", ",", "_external", "=", "external", ")", "else", ":", "url", "=", "assets", ".", "cdn_for", "(", "'_themes.static'", ",", "themeid", "=", "current", ".", "identifier", ",", "filename", "=", "filename", ",", "_external", "=", "external", ")", "if", "url", ".", "endswith", "(", "'/'", ")", ":", "# this is a directory, no need for cache burst", "return", "url", "if", "current_app", ".", "config", "[", "'DEBUG'", "]", ":", "burst", "=", "time", "(", ")", "else", ":", "burst", "=", "current", ".", "entrypoint", ".", "dist", ".", "version", "return", "'{url}?_={burst}'", ".", "format", "(", "url", "=", "url", ",", "burst", "=", "burst", ")" ]
Override the default theme static to add cache burst
[ "Override", "the", "default", "theme", "static", "to", "add", "cache", "burst" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L48-L65
14,455
opendatateam/udata
udata/theme/__init__.py
render
def render(template, **context): ''' Render a template with uData frontend specifics * Theme ''' theme = current_app.config['THEME'] return render_theme_template(get_theme(theme), template, **context)
python
def render(template, **context): ''' Render a template with uData frontend specifics * Theme ''' theme = current_app.config['THEME'] return render_theme_template(get_theme(theme), template, **context)
[ "def", "render", "(", "template", ",", "*", "*", "context", ")", ":", "theme", "=", "current_app", ".", "config", "[", "'THEME'", "]", "return", "render_theme_template", "(", "get_theme", "(", "theme", ")", ",", "template", ",", "*", "*", "context", ")" ]
Render a template with uData frontend specifics * Theme
[ "Render", "a", "template", "with", "uData", "frontend", "specifics" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L141-L148
14,456
opendatateam/udata
udata/theme/__init__.py
context
def context(name): '''A decorator for theme context processors''' def wrapper(func): g.theme.context_processors[name] = func return func return wrapper
python
def context(name): '''A decorator for theme context processors''' def wrapper(func): g.theme.context_processors[name] = func return func return wrapper
[ "def", "context", "(", "name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "g", ".", "theme", ".", "context_processors", "[", "name", "]", "=", "func", "return", "func", "return", "wrapper" ]
A decorator for theme context processors
[ "A", "decorator", "for", "theme", "context", "processors" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L159-L164
14,457
opendatateam/udata
udata/theme/__init__.py
ConfigurableTheme.variant
def variant(self): '''Get the current theme variant''' variant = current_app.config['THEME_VARIANT'] if variant not in self.variants: log.warning('Unkown theme variant: %s', variant) return 'default' else: return variant
python
def variant(self): '''Get the current theme variant''' variant = current_app.config['THEME_VARIANT'] if variant not in self.variants: log.warning('Unkown theme variant: %s', variant) return 'default' else: return variant
[ "def", "variant", "(", "self", ")", ":", "variant", "=", "current_app", ".", "config", "[", "'THEME_VARIANT'", "]", "if", "variant", "not", "in", "self", ".", "variants", ":", "log", ".", "warning", "(", "'Unkown theme variant: %s'", ",", "variant", ")", "return", "'default'", "else", ":", "return", "variant" ]
Get the current theme variant
[ "Get", "the", "current", "theme", "variant" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/theme/__init__.py#L110-L117
14,458
opendatateam/udata
udata/core/dataset/views.py
resource_redirect
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
python
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
[ "def", "resource_redirect", "(", "id", ")", ":", "resource", "=", "get_resource", "(", "id", ")", "return", "redirect", "(", "resource", ".", "url", ".", "strip", "(", ")", ")", "if", "resource", "else", "abort", "(", "404", ")" ]
Redirect to the latest version of a resource given its identifier.
[ "Redirect", "to", "the", "latest", "version", "of", "a", "resource", "given", "its", "identifier", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/views.py#L130-L135
14,459
opendatateam/udata
udata/core/dataset/views.py
group_resources_by_type
def group_resources_by_type(resources): """Group a list of `resources` by `type` with order""" groups = defaultdict(list) for resource in resources: groups[getattr(resource, 'type')].append(resource) ordered = OrderedDict() for rtype, rtype_label in RESOURCE_TYPES.items(): if groups[rtype]: ordered[(rtype, rtype_label)] = groups[rtype] return ordered
python
def group_resources_by_type(resources): """Group a list of `resources` by `type` with order""" groups = defaultdict(list) for resource in resources: groups[getattr(resource, 'type')].append(resource) ordered = OrderedDict() for rtype, rtype_label in RESOURCE_TYPES.items(): if groups[rtype]: ordered[(rtype, rtype_label)] = groups[rtype] return ordered
[ "def", "group_resources_by_type", "(", "resources", ")", ":", "groups", "=", "defaultdict", "(", "list", ")", "for", "resource", "in", "resources", ":", "groups", "[", "getattr", "(", "resource", ",", "'type'", ")", "]", ".", "append", "(", "resource", ")", "ordered", "=", "OrderedDict", "(", ")", "for", "rtype", ",", "rtype_label", "in", "RESOURCE_TYPES", ".", "items", "(", ")", ":", "if", "groups", "[", "rtype", "]", ":", "ordered", "[", "(", "rtype", ",", "rtype_label", ")", "]", "=", "groups", "[", "rtype", "]", "return", "ordered" ]
Group a list of `resources` by `type` with order
[ "Group", "a", "list", "of", "resources", "by", "type", "with", "order" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/views.py#L166-L175
14,460
opendatateam/udata
udata/core/metrics/__init__.py
Metric.aggregate
def aggregate(self, start, end): ''' This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value. ''' last = self.objects( level='daily', date__lte=self.iso(end), date__gte=self.iso(start)).order_by('-date').first() return last.values[self.name]
python
def aggregate(self, start, end): ''' This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value. ''' last = self.objects( level='daily', date__lte=self.iso(end), date__gte=self.iso(start)).order_by('-date').first() return last.values[self.name]
[ "def", "aggregate", "(", "self", ",", "start", ",", "end", ")", ":", "last", "=", "self", ".", "objects", "(", "level", "=", "'daily'", ",", "date__lte", "=", "self", ".", "iso", "(", "end", ")", ",", "date__gte", "=", "self", ".", "iso", "(", "start", ")", ")", ".", "order_by", "(", "'-date'", ")", ".", "first", "(", ")", "return", "last", ".", "values", "[", "self", ".", "name", "]" ]
This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value.
[ "This", "method", "encpsualte", "the", "metric", "aggregation", "logic", ".", "Override", "this", "method", "when", "you", "inherit", "this", "class", ".", "By", "default", "it", "takes", "the", "last", "value", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/metrics/__init__.py#L92-L101
14,461
opendatateam/udata
udata/harvest/actions.py
paginate_sources
def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(page, page_size)
python
def paginate_sources(owner=None, page=1, page_size=DEFAULT_PAGE_SIZE): '''Paginate harvest sources''' sources = _sources_queryset(owner=owner) page = max(page or 1, 1) return sources.paginate(page, page_size)
[ "def", "paginate_sources", "(", "owner", "=", "None", ",", "page", "=", "1", ",", "page_size", "=", "DEFAULT_PAGE_SIZE", ")", ":", "sources", "=", "_sources_queryset", "(", "owner", "=", "owner", ")", "page", "=", "max", "(", "page", "or", "1", ",", "1", ")", "return", "sources", ".", "paginate", "(", "page", ",", "page_size", ")" ]
Paginate harvest sources
[ "Paginate", "harvest", "sources" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L45-L49
14,462
opendatateam/udata
udata/harvest/actions.py
update_source
def update_source(ident, data): '''Update an harvest source''' source = get_source(ident) source.modify(**data) signals.harvest_source_updated.send(source) return source
python
def update_source(ident, data): '''Update an harvest source''' source = get_source(ident) source.modify(**data) signals.harvest_source_updated.send(source) return source
[ "def", "update_source", "(", "ident", ",", "data", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "modify", "(", "*", "*", "data", ")", "signals", ".", "harvest_source_updated", ".", "send", "(", "source", ")", "return", "source" ]
Update an harvest source
[ "Update", "an", "harvest", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L90-L95
14,463
opendatateam/udata
udata/harvest/actions.py
validate_source
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated: source.validation.by = current_user._get_current_object() source.save() schedule(ident, cron=current_app.config['HARVEST_DEFAULT_SCHEDULE']) launch(ident) return source
python
def validate_source(ident, comment=None): '''Validate a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_ACCEPTED if current_user.is_authenticated: source.validation.by = current_user._get_current_object() source.save() schedule(ident, cron=current_app.config['HARVEST_DEFAULT_SCHEDULE']) launch(ident) return source
[ "def", "validate_source", "(", "ident", ",", "comment", "=", "None", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "validation", ".", "on", "=", "datetime", ".", "now", "(", ")", "source", ".", "validation", ".", "comment", "=", "comment", "source", ".", "validation", ".", "state", "=", "VALIDATION_ACCEPTED", "if", "current_user", ".", "is_authenticated", ":", "source", ".", "validation", ".", "by", "=", "current_user", ".", "_get_current_object", "(", ")", "source", ".", "save", "(", ")", "schedule", "(", "ident", ",", "cron", "=", "current_app", ".", "config", "[", "'HARVEST_DEFAULT_SCHEDULE'", "]", ")", "launch", "(", "ident", ")", "return", "source" ]
Validate a source for automatic harvesting
[ "Validate", "a", "source", "for", "automatic", "harvesting" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L98-L109
14,464
opendatateam/udata
udata/harvest/actions.py
reject_source
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated: source.validation.by = current_user._get_current_object() source.save() return source
python
def reject_source(ident, comment): '''Reject a source for automatic harvesting''' source = get_source(ident) source.validation.on = datetime.now() source.validation.comment = comment source.validation.state = VALIDATION_REFUSED if current_user.is_authenticated: source.validation.by = current_user._get_current_object() source.save() return source
[ "def", "reject_source", "(", "ident", ",", "comment", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "validation", ".", "on", "=", "datetime", ".", "now", "(", ")", "source", ".", "validation", ".", "comment", "=", "comment", "source", ".", "validation", ".", "state", "=", "VALIDATION_REFUSED", "if", "current_user", ".", "is_authenticated", ":", "source", ".", "validation", ".", "by", "=", "current_user", ".", "_get_current_object", "(", ")", "source", ".", "save", "(", ")", "return", "source" ]
Reject a source for automatic harvesting
[ "Reject", "a", "source", "for", "automatic", "harvesting" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L112-L121
14,465
opendatateam/udata
udata/harvest/actions.py
delete_source
def delete_source(ident): '''Delete an harvest source''' source = get_source(ident) source.deleted = datetime.now() source.save() signals.harvest_source_deleted.send(source) return source
python
def delete_source(ident): '''Delete an harvest source''' source = get_source(ident) source.deleted = datetime.now() source.save() signals.harvest_source_deleted.send(source) return source
[ "def", "delete_source", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "source", ".", "deleted", "=", "datetime", ".", "now", "(", ")", "source", ".", "save", "(", ")", "signals", ".", "harvest_source_deleted", ".", "send", "(", "source", ")", "return", "source" ]
Delete an harvest source
[ "Delete", "an", "harvest", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L124-L130
14,466
opendatateam/udata
udata/harvest/actions.py
run
def run(ident): '''Launch or resume an harvesting for a given source if none is running''' source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
python
def run(ident): '''Launch or resume an harvesting for a given source if none is running''' source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
[ "def", "run", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "cls", "=", "backends", ".", "get", "(", "current_app", ",", "source", ".", "backend", ")", "backend", "=", "cls", "(", "source", ")", "backend", ".", "harvest", "(", ")" ]
Launch or resume an harvesting for a given source if none is running
[ "Launch", "or", "resume", "an", "harvesting", "for", "a", "given", "source", "if", "none", "is", "running" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L138-L143
14,467
opendatateam/udata
udata/harvest/actions.py
preview
def preview(ident): '''Preview an harvesting for a given source''' source = get_source(ident) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
python
def preview(ident): '''Preview an harvesting for a given source''' source = get_source(ident) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
[ "def", "preview", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "cls", "=", "backends", ".", "get", "(", "current_app", ",", "source", ".", "backend", ")", "max_items", "=", "current_app", ".", "config", "[", "'HARVEST_PREVIEW_MAX_ITEMS'", "]", "backend", "=", "cls", "(", "source", ",", "dryrun", "=", "True", ",", "max_items", "=", "max_items", ")", "return", "backend", ".", "harvest", "(", ")" ]
Preview an harvesting for a given source
[ "Preview", "an", "harvesting", "for", "a", "given", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L151-L157
14,468
opendatateam/udata
udata/harvest/actions.py
preview_from_config
def preview_from_config(name, url, backend, description=None, frequency=DEFAULT_HARVEST_FREQUENCY, owner=None, organization=None, config=None, ): '''Preview an harvesting from a source created with the given parameters''' if owner and not isinstance(owner, User): owner = User.get(owner) if organization and not isinstance(organization, Organization): organization = Organization.get(organization) source = HarvestSource( name=name, url=url, backend=backend, description=description, frequency=frequency or DEFAULT_HARVEST_FREQUENCY, owner=owner, organization=organization, config=config, ) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
python
def preview_from_config(name, url, backend, description=None, frequency=DEFAULT_HARVEST_FREQUENCY, owner=None, organization=None, config=None, ): '''Preview an harvesting from a source created with the given parameters''' if owner and not isinstance(owner, User): owner = User.get(owner) if organization and not isinstance(organization, Organization): organization = Organization.get(organization) source = HarvestSource( name=name, url=url, backend=backend, description=description, frequency=frequency or DEFAULT_HARVEST_FREQUENCY, owner=owner, organization=organization, config=config, ) cls = backends.get(current_app, source.backend) max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS'] backend = cls(source, dryrun=True, max_items=max_items) return backend.harvest()
[ "def", "preview_from_config", "(", "name", ",", "url", ",", "backend", ",", "description", "=", "None", ",", "frequency", "=", "DEFAULT_HARVEST_FREQUENCY", ",", "owner", "=", "None", ",", "organization", "=", "None", ",", "config", "=", "None", ",", ")", ":", "if", "owner", "and", "not", "isinstance", "(", "owner", ",", "User", ")", ":", "owner", "=", "User", ".", "get", "(", "owner", ")", "if", "organization", "and", "not", "isinstance", "(", "organization", ",", "Organization", ")", ":", "organization", "=", "Organization", ".", "get", "(", "organization", ")", "source", "=", "HarvestSource", "(", "name", "=", "name", ",", "url", "=", "url", ",", "backend", "=", "backend", ",", "description", "=", "description", ",", "frequency", "=", "frequency", "or", "DEFAULT_HARVEST_FREQUENCY", ",", "owner", "=", "owner", ",", "organization", "=", "organization", ",", "config", "=", "config", ",", ")", "cls", "=", "backends", ".", "get", "(", "current_app", ",", "source", ".", "backend", ")", "max_items", "=", "current_app", ".", "config", "[", "'HARVEST_PREVIEW_MAX_ITEMS'", "]", "backend", "=", "cls", "(", "source", ",", "dryrun", "=", "True", ",", "max_items", "=", "max_items", ")", "return", "backend", ".", "harvest", "(", ")" ]
Preview an harvesting from a source created with the given parameters
[ "Preview", "an", "harvesting", "from", "a", "source", "created", "with", "the", "given", "parameters" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L160-L187
14,469
opendatateam/udata
udata/harvest/actions.py
schedule
def schedule(ident, cron=None, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*'): '''Schedule an harvesting on a source given a crontab''' source = get_source(ident) if cron: minute, hour, day_of_month, month_of_year, day_of_week = cron.split() crontab = PeriodicTask.Crontab( minute=str(minute), hour=str(hour), day_of_week=str(day_of_week), day_of_month=str(day_of_month), month_of_year=str(month_of_year) ) if source.periodic_task: source.periodic_task.modify(crontab=crontab) else: source.modify(periodic_task=PeriodicTask.objects.create( task='harvest', name='Harvest {0}'.format(source.name), description='Periodic Harvesting', enabled=True, args=[str(source.id)], crontab=crontab, )) signals.harvest_source_scheduled.send(source) return source
python
def schedule(ident, cron=None, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*'): '''Schedule an harvesting on a source given a crontab''' source = get_source(ident) if cron: minute, hour, day_of_month, month_of_year, day_of_week = cron.split() crontab = PeriodicTask.Crontab( minute=str(minute), hour=str(hour), day_of_week=str(day_of_week), day_of_month=str(day_of_month), month_of_year=str(month_of_year) ) if source.periodic_task: source.periodic_task.modify(crontab=crontab) else: source.modify(periodic_task=PeriodicTask.objects.create( task='harvest', name='Harvest {0}'.format(source.name), description='Periodic Harvesting', enabled=True, args=[str(source.id)], crontab=crontab, )) signals.harvest_source_scheduled.send(source) return source
[ "def", "schedule", "(", "ident", ",", "cron", "=", "None", ",", "minute", "=", "'*'", ",", "hour", "=", "'*'", ",", "day_of_week", "=", "'*'", ",", "day_of_month", "=", "'*'", ",", "month_of_year", "=", "'*'", ")", ":", "source", "=", "get_source", "(", "ident", ")", "if", "cron", ":", "minute", ",", "hour", ",", "day_of_month", ",", "month_of_year", ",", "day_of_week", "=", "cron", ".", "split", "(", ")", "crontab", "=", "PeriodicTask", ".", "Crontab", "(", "minute", "=", "str", "(", "minute", ")", ",", "hour", "=", "str", "(", "hour", ")", ",", "day_of_week", "=", "str", "(", "day_of_week", ")", ",", "day_of_month", "=", "str", "(", "day_of_month", ")", ",", "month_of_year", "=", "str", "(", "month_of_year", ")", ")", "if", "source", ".", "periodic_task", ":", "source", ".", "periodic_task", ".", "modify", "(", "crontab", "=", "crontab", ")", "else", ":", "source", ".", "modify", "(", "periodic_task", "=", "PeriodicTask", ".", "objects", ".", "create", "(", "task", "=", "'harvest'", ",", "name", "=", "'Harvest {0}'", ".", "format", "(", "source", ".", "name", ")", ",", "description", "=", "'Periodic Harvesting'", ",", "enabled", "=", "True", ",", "args", "=", "[", "str", "(", "source", ".", "id", ")", "]", ",", "crontab", "=", "crontab", ",", ")", ")", "signals", ".", "harvest_source_scheduled", ".", "send", "(", "source", ")", "return", "source" ]
Schedule an harvesting on a source given a crontab
[ "Schedule", "an", "harvesting", "on", "a", "source", "given", "a", "crontab" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L190-L218
14,470
opendatateam/udata
udata/harvest/actions.py
unschedule
def unschedule(ident): '''Unschedule an harvesting on a source''' source = get_source(ident) if not source.periodic_task: msg = 'Harvesting on source {0} is ot scheduled'.format(source.name) raise ValueError(msg) source.periodic_task.delete() signals.harvest_source_unscheduled.send(source) return source
python
def unschedule(ident): '''Unschedule an harvesting on a source''' source = get_source(ident) if not source.periodic_task: msg = 'Harvesting on source {0} is ot scheduled'.format(source.name) raise ValueError(msg) source.periodic_task.delete() signals.harvest_source_unscheduled.send(source) return source
[ "def", "unschedule", "(", "ident", ")", ":", "source", "=", "get_source", "(", "ident", ")", "if", "not", "source", ".", "periodic_task", ":", "msg", "=", "'Harvesting on source {0} is ot scheduled'", ".", "format", "(", "source", ".", "name", ")", "raise", "ValueError", "(", "msg", ")", "source", ".", "periodic_task", ".", "delete", "(", ")", "signals", ".", "harvest_source_unscheduled", ".", "send", "(", "source", ")", "return", "source" ]
Unschedule an harvesting on a source
[ "Unschedule", "an", "harvesting", "on", "a", "source" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L221-L230
14,471
opendatateam/udata
udata/harvest/actions.py
attach
def attach(domain, filename): '''Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns order and extras columns does not matter ''' count = 0 errors = 0 with open(filename) as csvfile: reader = csv.DictReader(csvfile, delimiter=b';', quotechar=b'"') for row in reader: try: dataset = Dataset.objects.get(id=ObjectId(row['local'])) except: # noqa (Never stop on failure) log.warning('Unable to attach dataset : %s', row['local']) errors += 1 continue # Detach previously attached dataset Dataset.objects(**{ 'extras__harvest:domain': domain, 'extras__harvest:remote_id': row['remote'] }).update(**{ 'unset__extras__harvest:domain': True, 'unset__extras__harvest:remote_id': True }) dataset.extras['harvest:domain'] = domain dataset.extras['harvest:remote_id'] = row['remote'] dataset.last_modified = datetime.now() dataset.save() count += 1 return AttachResult(count, errors)
python
def attach(domain, filename): '''Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns order and extras columns does not matter ''' count = 0 errors = 0 with open(filename) as csvfile: reader = csv.DictReader(csvfile, delimiter=b';', quotechar=b'"') for row in reader: try: dataset = Dataset.objects.get(id=ObjectId(row['local'])) except: # noqa (Never stop on failure) log.warning('Unable to attach dataset : %s', row['local']) errors += 1 continue # Detach previously attached dataset Dataset.objects(**{ 'extras__harvest:domain': domain, 'extras__harvest:remote_id': row['remote'] }).update(**{ 'unset__extras__harvest:domain': True, 'unset__extras__harvest:remote_id': True }) dataset.extras['harvest:domain'] = domain dataset.extras['harvest:remote_id'] = row['remote'] dataset.last_modified = datetime.now() dataset.save() count += 1 return AttachResult(count, errors)
[ "def", "attach", "(", "domain", ",", "filename", ")", ":", "count", "=", "0", "errors", "=", "0", "with", "open", "(", "filename", ")", "as", "csvfile", ":", "reader", "=", "csv", ".", "DictReader", "(", "csvfile", ",", "delimiter", "=", "b';'", ",", "quotechar", "=", "b'\"'", ")", "for", "row", "in", "reader", ":", "try", ":", "dataset", "=", "Dataset", ".", "objects", ".", "get", "(", "id", "=", "ObjectId", "(", "row", "[", "'local'", "]", ")", ")", "except", ":", "# noqa (Never stop on failure)", "log", ".", "warning", "(", "'Unable to attach dataset : %s'", ",", "row", "[", "'local'", "]", ")", "errors", "+=", "1", "continue", "# Detach previously attached dataset", "Dataset", ".", "objects", "(", "*", "*", "{", "'extras__harvest:domain'", ":", "domain", ",", "'extras__harvest:remote_id'", ":", "row", "[", "'remote'", "]", "}", ")", ".", "update", "(", "*", "*", "{", "'unset__extras__harvest:domain'", ":", "True", ",", "'unset__extras__harvest:remote_id'", ":", "True", "}", ")", "dataset", ".", "extras", "[", "'harvest:domain'", "]", "=", "domain", "dataset", ".", "extras", "[", "'harvest:remote_id'", "]", "=", "row", "[", "'remote'", "]", "dataset", ".", "last_modified", "=", "datetime", ".", "now", "(", ")", "dataset", ".", "save", "(", ")", "count", "+=", "1", "return", "AttachResult", "(", "count", ",", "errors", ")" ]
Attach existing dataset to their harvest remote id before harvesting. The expected csv file format is the following: - a column with header "local" and the local IDs or slugs - a column with header "remote" and the remote IDs The delimiter should be ";". columns order and extras columns does not matter
[ "Attach", "existing", "dataset", "to", "their", "harvest", "remote", "id", "before", "harvesting", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/actions.py#L236-L276
14,472
opendatateam/udata
udata/models/extras_fields.py
ExtrasField.register
def register(self, key, dbtype): '''Register a DB type to add constraint on a given extra key''' if not issubclass(dbtype, (BaseField, EmbeddedDocument)): msg = 'ExtrasField can only register MongoEngine fields' raise TypeError(msg) self.registered[key] = dbtype
python
def register(self, key, dbtype): '''Register a DB type to add constraint on a given extra key''' if not issubclass(dbtype, (BaseField, EmbeddedDocument)): msg = 'ExtrasField can only register MongoEngine fields' raise TypeError(msg) self.registered[key] = dbtype
[ "def", "register", "(", "self", ",", "key", ",", "dbtype", ")", ":", "if", "not", "issubclass", "(", "dbtype", ",", "(", "BaseField", ",", "EmbeddedDocument", ")", ")", ":", "msg", "=", "'ExtrasField can only register MongoEngine fields'", "raise", "TypeError", "(", "msg", ")", "self", ".", "registered", "[", "key", "]", "=", "dbtype" ]
Register a DB type to add constraint on a given extra key
[ "Register", "a", "DB", "type", "to", "add", "constraint", "on", "a", "given", "extra", "key" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/extras_fields.py#L22-L27
14,473
opendatateam/udata
udata/core/user/commands.py
delete
def delete(): '''Delete an existing user''' email = click.prompt('Email') user = User.objects(email=email).first() if not user: exit_with_error('Invalid user') user.delete() success('User deleted successfully')
python
def delete(): '''Delete an existing user''' email = click.prompt('Email') user = User.objects(email=email).first() if not user: exit_with_error('Invalid user') user.delete() success('User deleted successfully')
[ "def", "delete", "(", ")", ":", "email", "=", "click", ".", "prompt", "(", "'Email'", ")", "user", "=", "User", ".", "objects", "(", "email", "=", "email", ")", ".", "first", "(", ")", "if", "not", "user", ":", "exit_with_error", "(", "'Invalid user'", ")", "user", ".", "delete", "(", ")", "success", "(", "'User deleted successfully'", ")" ]
Delete an existing user
[ "Delete", "an", "existing", "user" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/user/commands.py#L66-L73
14,474
opendatateam/udata
udata/core/user/commands.py
set_admin
def set_admin(email): '''Set an user as administrator''' user = datastore.get_user(email) log.info('Adding admin role to user %s (%s)', user.fullname, user.email) role = datastore.find_or_create_role('admin') datastore.add_role_to_user(user, role) success('User %s (%s) is now administrator' % (user.fullname, user.email))
python
def set_admin(email): '''Set an user as administrator''' user = datastore.get_user(email) log.info('Adding admin role to user %s (%s)', user.fullname, user.email) role = datastore.find_or_create_role('admin') datastore.add_role_to_user(user, role) success('User %s (%s) is now administrator' % (user.fullname, user.email))
[ "def", "set_admin", "(", "email", ")", ":", "user", "=", "datastore", ".", "get_user", "(", "email", ")", "log", ".", "info", "(", "'Adding admin role to user %s (%s)'", ",", "user", ".", "fullname", ",", "user", ".", "email", ")", "role", "=", "datastore", ".", "find_or_create_role", "(", "'admin'", ")", "datastore", ".", "add_role_to_user", "(", "user", ",", "role", ")", "success", "(", "'User %s (%s) is now administrator'", "%", "(", "user", ".", "fullname", ",", "user", ".", "email", ")", ")" ]
Set an user as administrator
[ "Set", "an", "user", "as", "administrator" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/user/commands.py#L78-L84
14,475
opendatateam/udata
udata/core/storages/api.py
combine_chunks
def combine_chunks(storage, args, prefix=None): ''' Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage. ''' uuid = args['uuid'] # Normalize filename including extension target = utils.normalize(args['filename']) if prefix: target = os.path.join(prefix, target) with storage.open(target, 'wb') as out: for i in xrange(args['totalparts']): partname = chunk_filename(uuid, i) out.write(chunks.read(partname)) chunks.delete(partname) chunks.delete(chunk_filename(uuid, META)) return target
python
def combine_chunks(storage, args, prefix=None): ''' Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage. ''' uuid = args['uuid'] # Normalize filename including extension target = utils.normalize(args['filename']) if prefix: target = os.path.join(prefix, target) with storage.open(target, 'wb') as out: for i in xrange(args['totalparts']): partname = chunk_filename(uuid, i) out.write(chunks.read(partname)) chunks.delete(partname) chunks.delete(chunk_filename(uuid, META)) return target
[ "def", "combine_chunks", "(", "storage", ",", "args", ",", "prefix", "=", "None", ")", ":", "uuid", "=", "args", "[", "'uuid'", "]", "# Normalize filename including extension", "target", "=", "utils", ".", "normalize", "(", "args", "[", "'filename'", "]", ")", "if", "prefix", ":", "target", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "target", ")", "with", "storage", ".", "open", "(", "target", ",", "'wb'", ")", "as", "out", ":", "for", "i", "in", "xrange", "(", "args", "[", "'totalparts'", "]", ")", ":", "partname", "=", "chunk_filename", "(", "uuid", ",", "i", ")", "out", ".", "write", "(", "chunks", ".", "read", "(", "partname", ")", ")", "chunks", ".", "delete", "(", "partname", ")", "chunks", ".", "delete", "(", "chunk_filename", "(", "uuid", ",", "META", ")", ")", "return", "target" ]
Combine a chunked file into a whole file again. Goes through each part, in order, and appends that part's bytes to another destination file. Chunks are stored in the chunks storage.
[ "Combine", "a", "chunked", "file", "into", "a", "whole", "file", "again", ".", "Goes", "through", "each", "part", "in", "order", "and", "appends", "that", "part", "s", "bytes", "to", "another", "destination", "file", ".", "Chunks", "are", "stored", "in", "the", "chunks", "storage", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/storages/api.py#L111-L129
14,476
opendatateam/udata
udata/models/__init__.py
UDataMongoEngine.resolve_model
def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ''' if not model: raise ValueError('Unsupported model specifications') if isinstance(model, basestring): classname = model elif isinstance(model, dict) and 'class' in model: classname = model['class'] else: raise ValueError('Unsupported model specifications') try: return get_document(classname) except self.NotRegistered: message = 'Model "{0}" does not exist'.format(classname) raise ValueError(message)
python
def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ''' if not model: raise ValueError('Unsupported model specifications') if isinstance(model, basestring): classname = model elif isinstance(model, dict) and 'class' in model: classname = model['class'] else: raise ValueError('Unsupported model specifications') try: return get_document(classname) except self.NotRegistered: message = 'Model "{0}" does not exist'.format(classname) raise ValueError(message)
[ "def", "resolve_model", "(", "self", ",", "model", ")", ":", "if", "not", "model", ":", "raise", "ValueError", "(", "'Unsupported model specifications'", ")", "if", "isinstance", "(", "model", ",", "basestring", ")", ":", "classname", "=", "model", "elif", "isinstance", "(", "model", ",", "dict", ")", "and", "'class'", "in", "model", ":", "classname", "=", "model", "[", "'class'", "]", "else", ":", "raise", "ValueError", "(", "'Unsupported model specifications'", ")", "try", ":", "return", "get_document", "(", "classname", ")", "except", "self", ".", "NotRegistered", ":", "message", "=", "'Model \"{0}\" does not exist'", ".", "format", "(", "classname", ")", "raise", "ValueError", "(", "message", ")" ]
Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists
[ "Resolve", "a", "model", "given", "a", "name", "or", "dict", "with", "class", "entry", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/models/__init__.py#L60-L79
14,477
opendatateam/udata
udata/frontend/helpers.py
tooltip_ellipsis
def tooltip_ellipsis(source, length=0): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.''' try: length = int(length) except ValueError: # invalid literal for int() return source # Fail silently. ellipsis = '<a href v-tooltip title="{0}">...</a>'.format(source) return Markup((source[:length] + ellipsis) if len(source) > length and length > 0 else source)
python
def tooltip_ellipsis(source, length=0): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.''' try: length = int(length) except ValueError: # invalid literal for int() return source # Fail silently. ellipsis = '<a href v-tooltip title="{0}">...</a>'.format(source) return Markup((source[:length] + ellipsis) if len(source) > length and length > 0 else source)
[ "def", "tooltip_ellipsis", "(", "source", ",", "length", "=", "0", ")", ":", "try", ":", "length", "=", "int", "(", "length", ")", "except", "ValueError", ":", "# invalid literal for int()", "return", "source", "# Fail silently.", "ellipsis", "=", "'<a href v-tooltip title=\"{0}\">...</a>'", ".", "format", "(", "source", ")", "return", "Markup", "(", "(", "source", "[", ":", "length", "]", "+", "ellipsis", ")", "if", "len", "(", "source", ")", ">", "length", "and", "length", ">", "0", "else", "source", ")" ]
return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.
[ "return", "the", "plain", "text", "representation", "of", "markdown", "encoded", "text", ".", "That", "is", "the", "texted", "without", "any", "html", "tags", ".", "If", "length", "is", "0", "then", "it", "will", "not", "be", "truncated", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/helpers.py#L254-L264
14,478
opendatateam/udata
udata/frontend/helpers.py
filesize
def filesize(value): '''Display a human readable filesize''' suffix = 'o' for unit in '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z': if abs(value) < 1024.0: return "%3.1f%s%s" % (value, unit, suffix) value /= 1024.0 return "%.1f%s%s" % (value, 'Y', suffix)
python
def filesize(value): '''Display a human readable filesize''' suffix = 'o' for unit in '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z': if abs(value) < 1024.0: return "%3.1f%s%s" % (value, unit, suffix) value /= 1024.0 return "%.1f%s%s" % (value, 'Y', suffix)
[ "def", "filesize", "(", "value", ")", ":", "suffix", "=", "'o'", "for", "unit", "in", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", "'P'", ",", "'E'", ",", "'Z'", ":", "if", "abs", "(", "value", ")", "<", "1024.0", ":", "return", "\"%3.1f%s%s\"", "%", "(", "value", ",", "unit", ",", "suffix", ")", "value", "/=", "1024.0", "return", "\"%.1f%s%s\"", "%", "(", "value", ",", "'Y'", ",", "suffix", ")" ]
Display a human readable filesize
[ "Display", "a", "human", "readable", "filesize" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/frontend/helpers.py#L399-L406
14,479
opendatateam/udata
udata/rdf.py
negociate_content
def negociate_content(default='json-ld'): '''Perform a content negociation on the format given the Accept header''' mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys()) return ACCEPTED_MIME_TYPES.get(mimetype, default)
python
def negociate_content(default='json-ld'): '''Perform a content negociation on the format given the Accept header''' mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys()) return ACCEPTED_MIME_TYPES.get(mimetype, default)
[ "def", "negociate_content", "(", "default", "=", "'json-ld'", ")", ":", "mimetype", "=", "request", ".", "accept_mimetypes", ".", "best_match", "(", "ACCEPTED_MIME_TYPES", ".", "keys", "(", ")", ")", "return", "ACCEPTED_MIME_TYPES", ".", "get", "(", "mimetype", ",", "default", ")" ]
Perform a content negociation on the format given the Accept header
[ "Perform", "a", "content", "negociation", "on", "the", "format", "given", "the", "Accept", "header" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L97-L100
14,480
opendatateam/udata
udata/rdf.py
url_from_rdf
def url_from_rdf(rdf, prop): ''' Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal ''' value = rdf.value(prop) if isinstance(value, (URIRef, Literal)): return value.toPython() elif isinstance(value, RdfResource): return value.identifier.toPython()
python
def url_from_rdf(rdf, prop): ''' Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal ''' value = rdf.value(prop) if isinstance(value, (URIRef, Literal)): return value.toPython() elif isinstance(value, RdfResource): return value.identifier.toPython()
[ "def", "url_from_rdf", "(", "rdf", ",", "prop", ")", ":", "value", "=", "rdf", ".", "value", "(", "prop", ")", "if", "isinstance", "(", "value", ",", "(", "URIRef", ",", "Literal", ")", ")", ":", "return", "value", ".", "toPython", "(", ")", "elif", "isinstance", "(", "value", ",", "RdfResource", ")", ":", "return", "value", ".", "identifier", ".", "toPython", "(", ")" ]
Try to extract An URL from a resource property. It can be expressed in many forms as a URIRef or a Literal
[ "Try", "to", "extract", "An", "URL", "from", "a", "resource", "property", ".", "It", "can", "be", "expressed", "in", "many", "forms", "as", "a", "URIRef", "or", "a", "Literal" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L224-L233
14,481
opendatateam/udata
udata/rdf.py
graph_response
def graph_response(graph, format): ''' Return a proper flask response for a RDF resource given an expected format. ''' fmt = guess_format(format) if not fmt: abort(404) headers = { 'Content-Type': RDF_MIME_TYPES[fmt] } kwargs = {} if fmt == 'json-ld': kwargs['context'] = context if isinstance(graph, RdfResource): graph = graph.graph return graph.serialize(format=fmt, **kwargs), 200, headers
python
def graph_response(graph, format): ''' Return a proper flask response for a RDF resource given an expected format. ''' fmt = guess_format(format) if not fmt: abort(404) headers = { 'Content-Type': RDF_MIME_TYPES[fmt] } kwargs = {} if fmt == 'json-ld': kwargs['context'] = context if isinstance(graph, RdfResource): graph = graph.graph return graph.serialize(format=fmt, **kwargs), 200, headers
[ "def", "graph_response", "(", "graph", ",", "format", ")", ":", "fmt", "=", "guess_format", "(", "format", ")", "if", "not", "fmt", ":", "abort", "(", "404", ")", "headers", "=", "{", "'Content-Type'", ":", "RDF_MIME_TYPES", "[", "fmt", "]", "}", "kwargs", "=", "{", "}", "if", "fmt", "==", "'json-ld'", ":", "kwargs", "[", "'context'", "]", "=", "context", "if", "isinstance", "(", "graph", ",", "RdfResource", ")", ":", "graph", "=", "graph", ".", "graph", "return", "graph", ".", "serialize", "(", "format", "=", "fmt", ",", "*", "*", "kwargs", ")", ",", "200", ",", "headers" ]
Return a proper flask response for a RDF resource given an expected format.
[ "Return", "a", "proper", "flask", "response", "for", "a", "RDF", "resource", "given", "an", "expected", "format", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/rdf.py#L236-L251
14,482
opendatateam/udata
udata/core/spatial/models.py
GeoZoneQuerySet.valid_at
def valid_at(self, valid_date): '''Limit current QuerySet to zone valid at a given date''' is_valid = db.Q(validity__end__gt=valid_date, validity__start__lte=valid_date) no_validity = db.Q(validity=None) return self(is_valid | no_validity)
python
def valid_at(self, valid_date): '''Limit current QuerySet to zone valid at a given date''' is_valid = db.Q(validity__end__gt=valid_date, validity__start__lte=valid_date) no_validity = db.Q(validity=None) return self(is_valid | no_validity)
[ "def", "valid_at", "(", "self", ",", "valid_date", ")", ":", "is_valid", "=", "db", ".", "Q", "(", "validity__end__gt", "=", "valid_date", ",", "validity__start__lte", "=", "valid_date", ")", "no_validity", "=", "db", ".", "Q", "(", "validity", "=", "None", ")", "return", "self", "(", "is_valid", "|", "no_validity", ")" ]
Limit current QuerySet to zone valid at a given date
[ "Limit", "current", "QuerySet", "to", "zone", "valid", "at", "a", "given", "date" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L44-L49
14,483
opendatateam/udata
udata/core/spatial/models.py
GeoZoneQuerySet.resolve
def resolve(self, geoid, id_only=False): ''' Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_only` is True, the result will be the resolved GeoID instead of the resolved zone. ''' level, code, validity = geoids.parse(geoid) qs = self(level=level, code=code) if id_only: qs = qs.only('id') if validity == 'latest': result = qs.latest() else: result = qs.valid_at(validity).first() return result.id if id_only and result else result
python
def resolve(self, geoid, id_only=False): ''' Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_only` is True, the result will be the resolved GeoID instead of the resolved zone. ''' level, code, validity = geoids.parse(geoid) qs = self(level=level, code=code) if id_only: qs = qs.only('id') if validity == 'latest': result = qs.latest() else: result = qs.valid_at(validity).first() return result.id if id_only and result else result
[ "def", "resolve", "(", "self", ",", "geoid", ",", "id_only", "=", "False", ")", ":", "level", ",", "code", ",", "validity", "=", "geoids", ".", "parse", "(", "geoid", ")", "qs", "=", "self", "(", "level", "=", "level", ",", "code", "=", "code", ")", "if", "id_only", ":", "qs", "=", "qs", ".", "only", "(", "'id'", ")", "if", "validity", "==", "'latest'", ":", "result", "=", "qs", ".", "latest", "(", ")", "else", ":", "result", "=", "qs", ".", "valid_at", "(", "validity", ")", ".", "first", "(", ")", "return", "result", ".", "id", "if", "id_only", "and", "result", "else", "result" ]
Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_only` is True, the result will be the resolved GeoID instead of the resolved zone.
[ "Resolve", "a", "GeoZone", "given", "a", "GeoID", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L60-L81
14,484
opendatateam/udata
udata/core/spatial/models.py
GeoZone.keys_values
def keys_values(self): """Key values might be a list or not, always return a list.""" keys_values = [] for value in self.keys.values(): if isinstance(value, list): keys_values += value elif isinstance(value, basestring) and not value.startswith('-'): # Avoid -99. Should be fixed in geozones keys_values.append(value) elif isinstance(value, int) and value >= 0: # Avoid -99. Should be fixed in geozones keys_values.append(str(value)) return keys_values
python
def keys_values(self): """Key values might be a list or not, always return a list.""" keys_values = [] for value in self.keys.values(): if isinstance(value, list): keys_values += value elif isinstance(value, basestring) and not value.startswith('-'): # Avoid -99. Should be fixed in geozones keys_values.append(value) elif isinstance(value, int) and value >= 0: # Avoid -99. Should be fixed in geozones keys_values.append(str(value)) return keys_values
[ "def", "keys_values", "(", "self", ")", ":", "keys_values", "=", "[", "]", "for", "value", "in", "self", ".", "keys", ".", "values", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "keys_values", "+=", "value", "elif", "isinstance", "(", "value", ",", "basestring", ")", "and", "not", "value", ".", "startswith", "(", "'-'", ")", ":", "# Avoid -99. Should be fixed in geozones", "keys_values", ".", "append", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "int", ")", "and", "value", ">=", "0", ":", "# Avoid -99. Should be fixed in geozones", "keys_values", ".", "append", "(", "str", "(", "value", ")", ")", "return", "keys_values" ]
Key values might be a list or not, always return a list.
[ "Key", "values", "might", "be", "a", "list", "or", "not", "always", "return", "a", "list", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L134-L146
14,485
opendatateam/udata
udata/core/spatial/models.py
GeoZone.level_i18n_name
def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
python
def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
[ "def", "level_i18n_name", "(", "self", ")", ":", "for", "level", ",", "name", "in", "spatial_granularities", ":", "if", "self", ".", "level", "==", "level", ":", "return", "name", "return", "self", ".", "level_name" ]
In use within templates for dynamic translations.
[ "In", "use", "within", "templates", "for", "dynamic", "translations", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L164-L169
14,486
opendatateam/udata
udata/core/spatial/models.py
GeoZone.ancestors_objects
def ancestors_objects(self): """Ancestors objects sorted by name.""" ancestors_objects = [] for ancestor in self.ancestors: try: ancestor_object = GeoZone.objects.get(id=ancestor) except GeoZone.DoesNotExist: continue ancestors_objects.append(ancestor_object) ancestors_objects.sort(key=lambda a: a.name) return ancestors_objects
python
def ancestors_objects(self): """Ancestors objects sorted by name.""" ancestors_objects = [] for ancestor in self.ancestors: try: ancestor_object = GeoZone.objects.get(id=ancestor) except GeoZone.DoesNotExist: continue ancestors_objects.append(ancestor_object) ancestors_objects.sort(key=lambda a: a.name) return ancestors_objects
[ "def", "ancestors_objects", "(", "self", ")", ":", "ancestors_objects", "=", "[", "]", "for", "ancestor", "in", "self", ".", "ancestors", ":", "try", ":", "ancestor_object", "=", "GeoZone", ".", "objects", ".", "get", "(", "id", "=", "ancestor", ")", "except", "GeoZone", ".", "DoesNotExist", ":", "continue", "ancestors_objects", ".", "append", "(", "ancestor_object", ")", "ancestors_objects", ".", "sort", "(", "key", "=", "lambda", "a", ":", "a", ".", "name", ")", "return", "ancestors_objects" ]
Ancestors objects sorted by name.
[ "Ancestors", "objects", "sorted", "by", "name", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L172-L182
14,487
opendatateam/udata
udata/core/spatial/models.py
GeoZone.child_level
def child_level(self): """Return the child level given handled levels.""" HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS') try: return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1] except (IndexError, ValueError): return None
python
def child_level(self): """Return the child level given handled levels.""" HANDLED_LEVELS = current_app.config.get('HANDLED_LEVELS') try: return HANDLED_LEVELS[HANDLED_LEVELS.index(self.level) - 1] except (IndexError, ValueError): return None
[ "def", "child_level", "(", "self", ")", ":", "HANDLED_LEVELS", "=", "current_app", ".", "config", ".", "get", "(", "'HANDLED_LEVELS'", ")", "try", ":", "return", "HANDLED_LEVELS", "[", "HANDLED_LEVELS", ".", "index", "(", "self", ".", "level", ")", "-", "1", "]", "except", "(", "IndexError", ",", "ValueError", ")", ":", "return", "None" ]
Return the child level given handled levels.
[ "Return", "the", "child", "level", "given", "handled", "levels", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/models.py#L185-L191
14,488
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.harvest
def harvest(self): '''Start the harvesting process''' if self.perform_initialization() is not None: self.process_items() self.finalize() return self.job
python
def harvest(self): '''Start the harvesting process''' if self.perform_initialization() is not None: self.process_items() self.finalize() return self.job
[ "def", "harvest", "(", "self", ")", ":", "if", "self", ".", "perform_initialization", "(", ")", "is", "not", "None", ":", "self", ".", "process_items", "(", ")", "self", ".", "finalize", "(", ")", "return", "self", ".", "job" ]
Start the harvesting process
[ "Start", "the", "harvesting", "process" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L127-L132
14,489
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.perform_initialization
def perform_initialization(self): '''Initialize the harvesting for a given job''' log.debug('Initializing backend') factory = HarvestJob if self.dryrun else HarvestJob.objects.create self.job = factory(status='initializing', started=datetime.now(), source=self.source) before_harvest_job.send(self) try: self.initialize() self.job.status = 'initialized' if not self.dryrun: self.job.save() except HarvestValidationError as e: log.info('Initialization failed for "%s" (%s)', safe_unicode(self.source.name), self.source.backend) error = HarvestError(message=safe_unicode(e)) self.job.errors.append(error) self.job.status = 'failed' self.end() return except Exception as e: self.job.status = 'failed' error = HarvestError(message=safe_unicode(e)) self.job.errors.append(error) self.end() msg = 'Initialization failed for "{0.name}" ({0.backend})' log.exception(msg.format(self.source)) return if self.max_items: self.job.items = self.job.items[:self.max_items] if self.job.items: log.debug('Queued %s items', len(self.job.items)) return len(self.job.items)
python
def perform_initialization(self): '''Initialize the harvesting for a given job''' log.debug('Initializing backend') factory = HarvestJob if self.dryrun else HarvestJob.objects.create self.job = factory(status='initializing', started=datetime.now(), source=self.source) before_harvest_job.send(self) try: self.initialize() self.job.status = 'initialized' if not self.dryrun: self.job.save() except HarvestValidationError as e: log.info('Initialization failed for "%s" (%s)', safe_unicode(self.source.name), self.source.backend) error = HarvestError(message=safe_unicode(e)) self.job.errors.append(error) self.job.status = 'failed' self.end() return except Exception as e: self.job.status = 'failed' error = HarvestError(message=safe_unicode(e)) self.job.errors.append(error) self.end() msg = 'Initialization failed for "{0.name}" ({0.backend})' log.exception(msg.format(self.source)) return if self.max_items: self.job.items = self.job.items[:self.max_items] if self.job.items: log.debug('Queued %s items', len(self.job.items)) return len(self.job.items)
[ "def", "perform_initialization", "(", "self", ")", ":", "log", ".", "debug", "(", "'Initializing backend'", ")", "factory", "=", "HarvestJob", "if", "self", ".", "dryrun", "else", "HarvestJob", ".", "objects", ".", "create", "self", ".", "job", "=", "factory", "(", "status", "=", "'initializing'", ",", "started", "=", "datetime", ".", "now", "(", ")", ",", "source", "=", "self", ".", "source", ")", "before_harvest_job", ".", "send", "(", "self", ")", "try", ":", "self", ".", "initialize", "(", ")", "self", ".", "job", ".", "status", "=", "'initialized'", "if", "not", "self", ".", "dryrun", ":", "self", ".", "job", ".", "save", "(", ")", "except", "HarvestValidationError", "as", "e", ":", "log", ".", "info", "(", "'Initialization failed for \"%s\" (%s)'", ",", "safe_unicode", "(", "self", ".", "source", ".", "name", ")", ",", "self", ".", "source", ".", "backend", ")", "error", "=", "HarvestError", "(", "message", "=", "safe_unicode", "(", "e", ")", ")", "self", ".", "job", ".", "errors", ".", "append", "(", "error", ")", "self", ".", "job", ".", "status", "=", "'failed'", "self", ".", "end", "(", ")", "return", "except", "Exception", "as", "e", ":", "self", ".", "job", ".", "status", "=", "'failed'", "error", "=", "HarvestError", "(", "message", "=", "safe_unicode", "(", "e", ")", ")", "self", ".", "job", ".", "errors", ".", "append", "(", "error", ")", "self", ".", "end", "(", ")", "msg", "=", "'Initialization failed for \"{0.name}\" ({0.backend})'", "log", ".", "exception", "(", "msg", ".", "format", "(", "self", ".", "source", ")", ")", "return", "if", "self", ".", "max_items", ":", "self", ".", "job", ".", "items", "=", "self", ".", "job", ".", "items", "[", ":", "self", ".", "max_items", "]", "if", "self", ".", "job", ".", "items", ":", "log", ".", "debug", "(", "'Queued %s items'", ",", "len", "(", "self", ".", "job", ".", "items", ")", ")", "return", "len", "(", "self", ".", "job", ".", "items", ")" ]
Initialize the harvesting for a given job
[ "Initialize", "the", "harvesting", "for", "a", "given", "job" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L134-L172
14,490
opendatateam/udata
udata/harvest/backends/base.py
BaseBackend.validate
def validate(self, data, schema): '''Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against ''' try: return schema(data) except MultipleInvalid as ie: errors = [] for error in ie.errors: if error.path: field = '.'.join(str(p) for p in error.path) path = error.path value = data while path: attr = path.pop(0) try: if isinstance(value, (list, tuple)): attr = int(attr) value = value[attr] except Exception: value = None txt = safe_unicode(error).replace('for dictionary value', '') txt = txt.strip() if isinstance(error, RequiredFieldInvalid): msg = '[{0}] {1}' else: msg = '[{0}] {1}: {2}' try: msg = msg.format(field, txt, str(value)) except Exception: msg = '[{0}] {1}'.format(field, txt) else: msg = str(error) errors.append(msg) msg = '\n- '.join(['Validation error:'] + errors) raise HarvestValidationError(msg)
python
def validate(self, data, schema): '''Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against ''' try: return schema(data) except MultipleInvalid as ie: errors = [] for error in ie.errors: if error.path: field = '.'.join(str(p) for p in error.path) path = error.path value = data while path: attr = path.pop(0) try: if isinstance(value, (list, tuple)): attr = int(attr) value = value[attr] except Exception: value = None txt = safe_unicode(error).replace('for dictionary value', '') txt = txt.strip() if isinstance(error, RequiredFieldInvalid): msg = '[{0}] {1}' else: msg = '[{0}] {1}: {2}' try: msg = msg.format(field, txt, str(value)) except Exception: msg = '[{0}] {1}'.format(field, txt) else: msg = str(error) errors.append(msg) msg = '\n- '.join(['Validation error:'] + errors) raise HarvestValidationError(msg)
[ "def", "validate", "(", "self", ",", "data", ",", "schema", ")", ":", "try", ":", "return", "schema", "(", "data", ")", "except", "MultipleInvalid", "as", "ie", ":", "errors", "=", "[", "]", "for", "error", "in", "ie", ".", "errors", ":", "if", "error", ".", "path", ":", "field", "=", "'.'", ".", "join", "(", "str", "(", "p", ")", "for", "p", "in", "error", ".", "path", ")", "path", "=", "error", ".", "path", "value", "=", "data", "while", "path", ":", "attr", "=", "path", ".", "pop", "(", "0", ")", "try", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "attr", "=", "int", "(", "attr", ")", "value", "=", "value", "[", "attr", "]", "except", "Exception", ":", "value", "=", "None", "txt", "=", "safe_unicode", "(", "error", ")", ".", "replace", "(", "'for dictionary value'", ",", "''", ")", "txt", "=", "txt", ".", "strip", "(", ")", "if", "isinstance", "(", "error", ",", "RequiredFieldInvalid", ")", ":", "msg", "=", "'[{0}] {1}'", "else", ":", "msg", "=", "'[{0}] {1}: {2}'", "try", ":", "msg", "=", "msg", ".", "format", "(", "field", ",", "txt", ",", "str", "(", "value", ")", ")", "except", "Exception", ":", "msg", "=", "'[{0}] {1}'", ".", "format", "(", "field", ",", "txt", ")", "else", ":", "msg", "=", "str", "(", "error", ")", "errors", ".", "append", "(", "msg", ")", "msg", "=", "'\\n- '", ".", "join", "(", "[", "'Validation error:'", "]", "+", "errors", ")", "raise", "HarvestValidationError", "(", "msg", ")" ]
Perform a data validation against a given schema. :param data: an object to validate :param schema: a Voluptous schema to validate against
[ "Perform", "a", "data", "validation", "against", "a", "given", "schema", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/harvest/backends/base.py#L265-L304
14,491
opendatateam/udata
udata/core/badges/api.py
add
def add(obj): ''' Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added ''' Form = badge_form(obj.__class__) form = api.validate(Form) kind = form.kind.data badge = obj.get_badge(kind) if badge: return badge else: return obj.add_badge(kind), 201
python
def add(obj): ''' Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added ''' Form = badge_form(obj.__class__) form = api.validate(Form) kind = form.kind.data badge = obj.get_badge(kind) if badge: return badge else: return obj.add_badge(kind), 201
[ "def", "add", "(", "obj", ")", ":", "Form", "=", "badge_form", "(", "obj", ".", "__class__", ")", "form", "=", "api", ".", "validate", "(", "Form", ")", "kind", "=", "form", ".", "kind", ".", "data", "badge", "=", "obj", ".", "get_badge", "(", "kind", ")", "if", "badge", ":", "return", "badge", "else", ":", "return", "obj", ".", "add_badge", "(", "kind", ")", ",", "201" ]
Handle a badge add API. - Expecting badge_fieds as payload - Return the badge as payload - Return 200 if the badge is already - Return 201 if the badge is added
[ "Handle", "a", "badge", "add", "API", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/api.py#L16-L32
14,492
opendatateam/udata
udata/core/badges/api.py
remove
def remove(obj, kind): ''' Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success ''' if not obj.get_badge(kind): api.abort(404, 'Badge does not exists') obj.remove_badge(kind) return '', 204
python
def remove(obj, kind): ''' Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success ''' if not obj.get_badge(kind): api.abort(404, 'Badge does not exists') obj.remove_badge(kind) return '', 204
[ "def", "remove", "(", "obj", ",", "kind", ")", ":", "if", "not", "obj", ".", "get_badge", "(", "kind", ")", ":", "api", ".", "abort", "(", "404", ",", "'Badge does not exists'", ")", "obj", ".", "remove_badge", "(", "kind", ")", "return", "''", ",", "204" ]
Handle badge removal API - Returns 404 if the badge for this kind is absent - Returns 204 on success
[ "Handle", "badge", "removal", "API" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/badges/api.py#L35-L45
14,493
opendatateam/udata
udata/features/territories/__init__.py
check_for_territories
def check_for_territories(query): """ Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first). """ if not query or not current_app.config.get('ACTIVATE_TERRITORIES'): return [] dbqs = db.Q() query = query.lower() is_digit = query.isdigit() query_length = len(query) for level in current_app.config.get('HANDLED_LEVELS'): if level == 'country': continue # Level not fully handled yet. q = db.Q(level=level) if (query_length == 2 and level == 'fr:departement' and (is_digit or query in ('2a', '2b'))): # Counties + Corsica. q &= db.Q(code=query) elif query_length == 3 and level == 'fr:departement' and is_digit: # French DROM-COM. q &= db.Q(code=query) elif query_length == 5 and level == 'fr:commune' and ( is_digit or query.startswith('2a') or query.startswith('2b')): # INSEE code then postal codes with Corsica exceptions. q &= db.Q(code=query) | db.Q(keys__postal__contains=query) elif query_length >= 4: # Check names starting with query or exact match. q &= db.Q(name__istartswith=query) | db.Q(name__iexact=query) else: continue # Meta Q object, ready to be passed to a queryset. dbqs |= q if dbqs.empty: return [] # Sort matching results by population and area. return GeoZone.objects(dbqs).order_by('-population', '-area')
python
def check_for_territories(query): """ Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first). """ if not query or not current_app.config.get('ACTIVATE_TERRITORIES'): return [] dbqs = db.Q() query = query.lower() is_digit = query.isdigit() query_length = len(query) for level in current_app.config.get('HANDLED_LEVELS'): if level == 'country': continue # Level not fully handled yet. q = db.Q(level=level) if (query_length == 2 and level == 'fr:departement' and (is_digit or query in ('2a', '2b'))): # Counties + Corsica. q &= db.Q(code=query) elif query_length == 3 and level == 'fr:departement' and is_digit: # French DROM-COM. q &= db.Q(code=query) elif query_length == 5 and level == 'fr:commune' and ( is_digit or query.startswith('2a') or query.startswith('2b')): # INSEE code then postal codes with Corsica exceptions. q &= db.Q(code=query) | db.Q(keys__postal__contains=query) elif query_length >= 4: # Check names starting with query or exact match. q &= db.Q(name__istartswith=query) | db.Q(name__iexact=query) else: continue # Meta Q object, ready to be passed to a queryset. dbqs |= q if dbqs.empty: return [] # Sort matching results by population and area. return GeoZone.objects(dbqs).order_by('-population', '-area')
[ "def", "check_for_territories", "(", "query", ")", ":", "if", "not", "query", "or", "not", "current_app", ".", "config", ".", "get", "(", "'ACTIVATE_TERRITORIES'", ")", ":", "return", "[", "]", "dbqs", "=", "db", ".", "Q", "(", ")", "query", "=", "query", ".", "lower", "(", ")", "is_digit", "=", "query", ".", "isdigit", "(", ")", "query_length", "=", "len", "(", "query", ")", "for", "level", "in", "current_app", ".", "config", ".", "get", "(", "'HANDLED_LEVELS'", ")", ":", "if", "level", "==", "'country'", ":", "continue", "# Level not fully handled yet.", "q", "=", "db", ".", "Q", "(", "level", "=", "level", ")", "if", "(", "query_length", "==", "2", "and", "level", "==", "'fr:departement'", "and", "(", "is_digit", "or", "query", "in", "(", "'2a'", ",", "'2b'", ")", ")", ")", ":", "# Counties + Corsica.", "q", "&=", "db", ".", "Q", "(", "code", "=", "query", ")", "elif", "query_length", "==", "3", "and", "level", "==", "'fr:departement'", "and", "is_digit", ":", "# French DROM-COM.", "q", "&=", "db", ".", "Q", "(", "code", "=", "query", ")", "elif", "query_length", "==", "5", "and", "level", "==", "'fr:commune'", "and", "(", "is_digit", "or", "query", ".", "startswith", "(", "'2a'", ")", "or", "query", ".", "startswith", "(", "'2b'", ")", ")", ":", "# INSEE code then postal codes with Corsica exceptions.", "q", "&=", "db", ".", "Q", "(", "code", "=", "query", ")", "|", "db", ".", "Q", "(", "keys__postal__contains", "=", "query", ")", "elif", "query_length", ">=", "4", ":", "# Check names starting with query or exact match.", "q", "&=", "db", ".", "Q", "(", "name__istartswith", "=", "query", ")", "|", "db", ".", "Q", "(", "name__iexact", "=", "query", ")", "else", ":", "continue", "# Meta Q object, ready to be passed to a queryset.", "dbqs", "|=", "q", "if", "dbqs", ".", "empty", ":", "return", "[", "]", "# Sort matching results by population and area.", "return", "GeoZone", ".", "objects", "(", "dbqs", ")", ".", "order_by", "(", "'-population'", ",", "'-area'", ")" ]
Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first).
[ "Return", "a", "geozone", "queryset", "of", "territories", "given", "the", "query", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/features/territories/__init__.py#L9-L50
14,494
opendatateam/udata
udata/core/spatial/geoids.py
build
def build(level, code, validity=None): '''Serialize a GeoID from its parts''' spatial = ':'.join((level, code)) if not validity: return spatial elif isinstance(validity, basestring): return '@'.join((spatial, validity)) elif isinstance(validity, datetime): return '@'.join((spatial, validity.date().isoformat())) elif isinstance(validity, date): return '@'.join((spatial, validity.isoformat())) else: msg = 'Unknown GeoID validity type: {0}' raise GeoIDError(msg.format(type(validity).__name__))
python
def build(level, code, validity=None): '''Serialize a GeoID from its parts''' spatial = ':'.join((level, code)) if not validity: return spatial elif isinstance(validity, basestring): return '@'.join((spatial, validity)) elif isinstance(validity, datetime): return '@'.join((spatial, validity.date().isoformat())) elif isinstance(validity, date): return '@'.join((spatial, validity.isoformat())) else: msg = 'Unknown GeoID validity type: {0}' raise GeoIDError(msg.format(type(validity).__name__))
[ "def", "build", "(", "level", ",", "code", ",", "validity", "=", "None", ")", ":", "spatial", "=", "':'", ".", "join", "(", "(", "level", ",", "code", ")", ")", "if", "not", "validity", ":", "return", "spatial", "elif", "isinstance", "(", "validity", ",", "basestring", ")", ":", "return", "'@'", ".", "join", "(", "(", "spatial", ",", "validity", ")", ")", "elif", "isinstance", "(", "validity", ",", "datetime", ")", ":", "return", "'@'", ".", "join", "(", "(", "spatial", ",", "validity", ".", "date", "(", ")", ".", "isoformat", "(", ")", ")", ")", "elif", "isinstance", "(", "validity", ",", "date", ")", ":", "return", "'@'", ".", "join", "(", "(", "spatial", ",", "validity", ".", "isoformat", "(", ")", ")", ")", "else", ":", "msg", "=", "'Unknown GeoID validity type: {0}'", "raise", "GeoIDError", "(", "msg", ".", "format", "(", "type", "(", "validity", ")", ".", "__name__", ")", ")" ]
Serialize a GeoID from its parts
[ "Serialize", "a", "GeoID", "from", "its", "parts" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/geoids.py#L41-L54
14,495
opendatateam/udata
udata/core/spatial/geoids.py
from_zone
def from_zone(zone): '''Build a GeoID from a given zone''' validity = zone.validity.start if zone.validity else None return build(zone.level, zone.code, validity)
python
def from_zone(zone): '''Build a GeoID from a given zone''' validity = zone.validity.start if zone.validity else None return build(zone.level, zone.code, validity)
[ "def", "from_zone", "(", "zone", ")", ":", "validity", "=", "zone", ".", "validity", ".", "start", "if", "zone", ".", "validity", "else", "None", "return", "build", "(", "zone", ".", "level", ",", "zone", ".", "code", ",", "validity", ")" ]
Build a GeoID from a given zone
[ "Build", "a", "GeoID", "from", "a", "given", "zone" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/spatial/geoids.py#L57-L60
14,496
opendatateam/udata
udata/core/dataset/rdf.py
temporal_from_rdf
def temporal_from_rdf(period_of_time): '''Failsafe parsing of a temporal coverage''' try: if isinstance(period_of_time, Literal): return temporal_from_literal(str(period_of_time)) elif isinstance(period_of_time, RdfResource): return temporal_from_resource(period_of_time) except Exception: # There are a lot of cases where parsing could/should fail # but we never want to break the whole dataset parsing # so we log the error for future investigation and improvement log.warning('Unable to parse temporal coverage', exc_info=True)
python
def temporal_from_rdf(period_of_time): '''Failsafe parsing of a temporal coverage''' try: if isinstance(period_of_time, Literal): return temporal_from_literal(str(period_of_time)) elif isinstance(period_of_time, RdfResource): return temporal_from_resource(period_of_time) except Exception: # There are a lot of cases where parsing could/should fail # but we never want to break the whole dataset parsing # so we log the error for future investigation and improvement log.warning('Unable to parse temporal coverage', exc_info=True)
[ "def", "temporal_from_rdf", "(", "period_of_time", ")", ":", "try", ":", "if", "isinstance", "(", "period_of_time", ",", "Literal", ")", ":", "return", "temporal_from_literal", "(", "str", "(", "period_of_time", ")", ")", "elif", "isinstance", "(", "period_of_time", ",", "RdfResource", ")", ":", "return", "temporal_from_resource", "(", "period_of_time", ")", "except", "Exception", ":", "# There are a lot of cases where parsing could/should fail", "# but we never want to break the whole dataset parsing", "# so we log the error for future investigation and improvement", "log", ".", "warning", "(", "'Unable to parse temporal coverage'", ",", "exc_info", "=", "True", ")" ]
Failsafe parsing of a temporal coverage
[ "Failsafe", "parsing", "of", "a", "temporal", "coverage" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/rdf.py#L284-L295
14,497
opendatateam/udata
udata/core/dataset/rdf.py
title_from_rdf
def title_from_rdf(rdf, url): ''' Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name. ''' title = rdf_value(rdf, DCT.title) if title: return title if url: last_part = url.split('/')[-1] if '.' in last_part and '?' not in last_part: return last_part fmt = rdf_value(rdf, DCT.term('format')) lang = current_app.config['DEFAULT_LANGUAGE'] with i18n.language(lang): if fmt: return i18n._('{format} resource').format(format=fmt.lower()) else: return i18n._('Nameless resource')
python
def title_from_rdf(rdf, url): ''' Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name. ''' title = rdf_value(rdf, DCT.title) if title: return title if url: last_part = url.split('/')[-1] if '.' in last_part and '?' not in last_part: return last_part fmt = rdf_value(rdf, DCT.term('format')) lang = current_app.config['DEFAULT_LANGUAGE'] with i18n.language(lang): if fmt: return i18n._('{format} resource').format(format=fmt.lower()) else: return i18n._('Nameless resource')
[ "def", "title_from_rdf", "(", "rdf", ",", "url", ")", ":", "title", "=", "rdf_value", "(", "rdf", ",", "DCT", ".", "title", ")", "if", "title", ":", "return", "title", "if", "url", ":", "last_part", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "'.'", "in", "last_part", "and", "'?'", "not", "in", "last_part", ":", "return", "last_part", "fmt", "=", "rdf_value", "(", "rdf", ",", "DCT", ".", "term", "(", "'format'", ")", ")", "lang", "=", "current_app", ".", "config", "[", "'DEFAULT_LANGUAGE'", "]", "with", "i18n", ".", "language", "(", "lang", ")", ":", "if", "fmt", ":", "return", "i18n", ".", "_", "(", "'{format} resource'", ")", ".", "format", "(", "format", "=", "fmt", ".", "lower", "(", ")", ")", "else", ":", "return", "i18n", ".", "_", "(", "'Nameless resource'", ")" ]
Try to extract a distribution title from a property. As it's not a mandatory property, it fallback on building a title from the URL then the format and in last ressort a generic resource name.
[ "Try", "to", "extract", "a", "distribution", "title", "from", "a", "property", ".", "As", "it", "s", "not", "a", "mandatory", "property", "it", "fallback", "on", "building", "a", "title", "from", "the", "URL", "then", "the", "format", "and", "in", "last", "ressort", "a", "generic", "resource", "name", "." ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/dataset/rdf.py#L313-L333
14,498
opendatateam/udata
udata/core/reuse/forms.py
check_url_does_not_exists
def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
python
def check_url_does_not_exists(form, field): '''Ensure a reuse URL is not yet registered''' if field.data != field.object_data and Reuse.url_exists(field.data): raise validators.ValidationError(_('This URL is already registered'))
[ "def", "check_url_does_not_exists", "(", "form", ",", "field", ")", ":", "if", "field", ".", "data", "!=", "field", ".", "object_data", "and", "Reuse", ".", "url_exists", "(", "field", ".", "data", ")", ":", "raise", "validators", ".", "ValidationError", "(", "_", "(", "'This URL is already registered'", ")", ")" ]
Ensure a reuse URL is not yet registered
[ "Ensure", "a", "reuse", "URL", "is", "not", "yet", "registered" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/core/reuse/forms.py#L13-L16
14,499
opendatateam/udata
udata/search/fields.py
obj_to_string
def obj_to_string(obj): '''Render an object into a unicode string if possible''' if not obj: return None elif isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, basestring): return obj elif is_lazy_string(obj): return obj.value elif hasattr(obj, '__html__'): return obj.__html__() else: return str(obj)
python
def obj_to_string(obj): '''Render an object into a unicode string if possible''' if not obj: return None elif isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, basestring): return obj elif is_lazy_string(obj): return obj.value elif hasattr(obj, '__html__'): return obj.__html__() else: return str(obj)
[ "def", "obj_to_string", "(", "obj", ")", ":", "if", "not", "obj", ":", "return", "None", "elif", "isinstance", "(", "obj", ",", "bytes", ")", ":", "return", "obj", ".", "decode", "(", "'utf-8'", ")", "elif", "isinstance", "(", "obj", ",", "basestring", ")", ":", "return", "obj", "elif", "is_lazy_string", "(", "obj", ")", ":", "return", "obj", ".", "value", "elif", "hasattr", "(", "obj", ",", "'__html__'", ")", ":", "return", "obj", ".", "__html__", "(", ")", "else", ":", "return", "str", "(", "obj", ")" ]
Render an object into a unicode string if possible
[ "Render", "an", "object", "into", "a", "unicode", "string", "if", "possible" ]
f016585af94b0ff6bd73738c700324adc8ba7f8f
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/search/fields.py#L41-L54