repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
edx/django-config-models
config_models/templatetags.py
submit_row
def submit_row(context): """ Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'. Manipulates the context going into that function by hiding all of the buttons in the submit row if the key `readonly` is set in the context. """ ctx = original_submit_row(context) if context...
python
def submit_row(context): """ Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'. Manipulates the context going into that function by hiding all of the buttons in the submit row if the key `readonly` is set in the context. """ ctx = original_submit_row(context) if context...
Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'. Manipulates the context going into that function by hiding all of the buttons in the submit row if the key `readonly` is set in the context.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/templatetags.py#L12-L30
edx/django-config-models
config_models/models.py
ConfigurationModelManager._current_ids_subquery
def _current_ids_subquery(self): """ Internal helper method to return an SQL string that will get the IDs of all the current entries (i.e. the most recent entry for each unique set of key values). Only useful if KEY_FIELDS is set. """ return self.values(*self.model.KEY_FI...
python
def _current_ids_subquery(self): """ Internal helper method to return an SQL string that will get the IDs of all the current entries (i.e. the most recent entry for each unique set of key values). Only useful if KEY_FIELDS is set. """ return self.values(*self.model.KEY_FI...
Internal helper method to return an SQL string that will get the IDs of all the current entries (i.e. the most recent entry for each unique set of key values). Only useful if KEY_FIELDS is set.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L33-L39
edx/django-config-models
config_models/models.py
ConfigurationModelManager.current_set
def current_set(self): """ A queryset for the active configuration entries only. Only useful if KEY_FIELDS is set. Active means the means recent entries for each unique combination of keys. It does not necessaryily mean enbled. """ assert self.model.KEY_FIELDS != (), "Ju...
python
def current_set(self): """ A queryset for the active configuration entries only. Only useful if KEY_FIELDS is set. Active means the means recent entries for each unique combination of keys. It does not necessaryily mean enbled. """ assert self.model.KEY_FIELDS != (), "Ju...
A queryset for the active configuration entries only. Only useful if KEY_FIELDS is set. Active means the means recent entries for each unique combination of keys. It does not necessaryily mean enbled.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L41-L53
edx/django-config-models
config_models/models.py
ConfigurationModelManager.with_active_flag
def with_active_flag(self): """ A query set where each result is annotated with an 'is_active' field that indicates if it's the most recent entry for that combination of keys. """ if self.model.KEY_FIELDS: return self.get_queryset().annotate( is_active...
python
def with_active_flag(self): """ A query set where each result is annotated with an 'is_active' field that indicates if it's the most recent entry for that combination of keys. """ if self.model.KEY_FIELDS: return self.get_queryset().annotate( is_active...
A query set where each result is annotated with an 'is_active' field that indicates if it's the most recent entry for that combination of keys.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L55-L72
edx/django-config-models
config_models/models.py
ConfigurationModel.save
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Clear the cached value when saving a new configuration entry """ # Always create a new entry, instead of updating an existing model self.pk = None # pylint: disable=invalid-n...
python
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Clear the cached value when saving a new configuration entry """ # Always create a new entry, instead of updating an existing model self.pk = None # pylint: disable=invalid-n...
Clear the cached value when saving a new configuration entry
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L106-L121
edx/django-config-models
config_models/models.py
ConfigurationModel.cache_key_name
def cache_key_name(cls, *args): """Return the name of the key to use to cache the current configuration""" if cls.KEY_FIELDS != (): if len(args) != len(cls.KEY_FIELDS): raise TypeError( "cache_key_name() takes exactly {} arguments ({} given)".format(len(cl...
python
def cache_key_name(cls, *args): """Return the name of the key to use to cache the current configuration""" if cls.KEY_FIELDS != (): if len(args) != len(cls.KEY_FIELDS): raise TypeError( "cache_key_name() takes exactly {} arguments ({} given)".format(len(cl...
Return the name of the key to use to cache the current configuration
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L124-L134
edx/django-config-models
config_models/models.py
ConfigurationModel.current
def current(cls, *args): """ Return the active configuration entry, either from cache, from the database, or by creating a new empty entry (which is not persisted). """ cached = cache.get(cls.cache_key_name(*args)) if cached is not None: return cached ...
python
def current(cls, *args): """ Return the active configuration entry, either from cache, from the database, or by creating a new empty entry (which is not persisted). """ cached = cache.get(cls.cache_key_name(*args)) if cached is not None: return cached ...
Return the active configuration entry, either from cache, from the database, or by creating a new empty entry (which is not persisted).
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L137-L154
edx/django-config-models
config_models/models.py
ConfigurationModel.key_values_cache_key_name
def key_values_cache_key_name(cls, *key_fields): """ Key for fetching unique key values from the cache """ key_fields = key_fields or cls.KEY_FIELDS return 'configuration/{}/key_values/{}'.format(cls.__name__, ','.join(key_fields))
python
def key_values_cache_key_name(cls, *key_fields): """ Key for fetching unique key values from the cache """ key_fields = key_fields or cls.KEY_FIELDS return 'configuration/{}/key_values/{}'.format(cls.__name__, ','.join(key_fields))
Key for fetching unique key values from the cache
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L168-L171
edx/django-config-models
config_models/models.py
ConfigurationModel.key_values
def key_values(cls, *key_fields, **kwargs): """ Get the set of unique values in the configuration table for the given key[s]. Calling cls.current(*value) for each value in the resulting list should always produce an entry, though any such entry may have enabled=False. Ar...
python
def key_values(cls, *key_fields, **kwargs): """ Get the set of unique values in the configuration table for the given key[s]. Calling cls.current(*value) for each value in the resulting list should always produce an entry, though any such entry may have enabled=False. Ar...
Get the set of unique values in the configuration table for the given key[s]. Calling cls.current(*value) for each value in the resulting list should always produce an entry, though any such entry may have enabled=False. Arguments: key_fields: The positional arguments are th...
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L174-L205
edx/django-config-models
config_models/models.py
ConfigurationModel.fields_equal
def fields_equal(self, instance, fields_to_ignore=("id", "change_date", "changed_by")): """ Compares this instance's fields to the supplied instance to test for equality. This will ignore any fields in `fields_to_ignore`. Note that this method ignores many-to-many fields. Args:...
python
def fields_equal(self, instance, fields_to_ignore=("id", "change_date", "changed_by")): """ Compares this instance's fields to the supplied instance to test for equality. This will ignore any fields in `fields_to_ignore`. Note that this method ignores many-to-many fields. Args:...
Compares this instance's fields to the supplied instance to test for equality. This will ignore any fields in `fields_to_ignore`. Note that this method ignores many-to-many fields. Args: instance: the model instance to compare fields_to_ignore: List of fields that shoul...
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L207-L226
edx/django-config-models
config_models/models.py
ConfigurationModel.equal_to_current
def equal_to_current(cls, json, fields_to_ignore=("id", "change_date", "changed_by")): """ Compares for equality this instance to a model instance constructed from the supplied JSON. This will ignore any fields in `fields_to_ignore`. Note that this method cannot handle fields with many-...
python
def equal_to_current(cls, json, fields_to_ignore=("id", "change_date", "changed_by")): """ Compares for equality this instance to a model instance constructed from the supplied JSON. This will ignore any fields in `fields_to_ignore`. Note that this method cannot handle fields with many-...
Compares for equality this instance to a model instance constructed from the supplied JSON. This will ignore any fields in `fields_to_ignore`. Note that this method cannot handle fields with many-to-many associations, as those can only be set on a saved model instance (and saving the model inst...
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/models.py#L229-L260
edx/django-config-models
config_models/views.py
AtomicMixin.create_atomic_wrapper
def create_atomic_wrapper(cls, wrapped_func): """Returns a wrapped function.""" def _create_atomic_wrapper(*args, **kwargs): """Actual wrapper.""" # When a view call fails due to a permissions error, it raises an exception. # An uncaught exception breaks the DB transa...
python
def create_atomic_wrapper(cls, wrapped_func): """Returns a wrapped function.""" def _create_atomic_wrapper(*args, **kwargs): """Actual wrapper.""" # When a view call fails due to a permissions error, it raises an exception. # An uncaught exception breaks the DB transa...
Returns a wrapped function.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/views.py#L23-L33
edx/django-config-models
config_models/views.py
AtomicMixin.as_view
def as_view(cls, **initkwargs): """Overrides as_view to add atomic transaction.""" view = super(AtomicMixin, cls).as_view(**initkwargs) return cls.create_atomic_wrapper(view)
python
def as_view(cls, **initkwargs): """Overrides as_view to add atomic transaction.""" view = super(AtomicMixin, cls).as_view(**initkwargs) return cls.create_atomic_wrapper(view)
Overrides as_view to add atomic transaction.
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/views.py#L36-L39
edx/django-config-models
config_models/decorators.py
require_config
def require_config(config_model): """ View decorator that enables/disables a view based on configuration. Arguments: config_model (ConfigurationModel subclass): The class of the configuration model to check. Returns: HttpResponse: 404 if the configuration model is disabled,...
python
def require_config(config_model): """ View decorator that enables/disables a view based on configuration. Arguments: config_model (ConfigurationModel subclass): The class of the configuration model to check. Returns: HttpResponse: 404 if the configuration model is disabled,...
View decorator that enables/disables a view based on configuration. Arguments: config_model (ConfigurationModel subclass): The class of the configuration model to check. Returns: HttpResponse: 404 if the configuration model is disabled, otherwise returns the response fr...
https://github.com/edx/django-config-models/blob/f22c05fe3ccb182a6be4dbe313e9d6749dffd3e4/config_models/decorators.py#L10-L36
tilezen/tilequeue
tilequeue/format/vtm.py
merge
def merge(file, feature_layers): ''' Retrieve a list of OSciMap4 tile responses and merge them into one. get_tiles() retrieves data and performs basic integrity checks. ''' tile = VectorTile(extents) for layer in feature_layers: tile.addFeatures(layer['features'], layer['name']) t...
python
def merge(file, feature_layers): ''' Retrieve a list of OSciMap4 tile responses and merge them into one. get_tiles() retrieves data and performs basic integrity checks. ''' tile = VectorTile(extents) for layer in feature_layers: tile.addFeatures(layer['features'], layer['name']) t...
Retrieve a list of OSciMap4 tile responses and merge them into one. get_tiles() retrieves data and performs basic integrity checks.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/vtm.py#L39-L53
tilezen/tilequeue
tilequeue/process.py
_make_valid_if_necessary
def _make_valid_if_necessary(shape): """ attempt to correct invalid shapes if necessary After simplification, even when preserving topology, invalid shapes can be returned. This appears to only occur with polygon types. As an optimization, we only check if the polygon types are valid. """ ...
python
def _make_valid_if_necessary(shape): """ attempt to correct invalid shapes if necessary After simplification, even when preserving topology, invalid shapes can be returned. This appears to only occur with polygon types. As an optimization, we only check if the polygon types are valid. """ ...
attempt to correct invalid shapes if necessary After simplification, even when preserving topology, invalid shapes can be returned. This appears to only occur with polygon types. As an optimization, we only check if the polygon types are valid.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/process.py#L150-L168
tilezen/tilequeue
tilequeue/process.py
_accumulate_props
def _accumulate_props(dest_props, src_props): """ helper to accumulate a dict of properties Mutates dest_props by adding the non None src_props and returns the new size """ props_size = 0 if src_props: for k, v in src_props.items(): if v is not None: prop...
python
def _accumulate_props(dest_props, src_props): """ helper to accumulate a dict of properties Mutates dest_props by adding the non None src_props and returns the new size """ props_size = 0 if src_props: for k, v in src_props.items(): if v is not None: prop...
helper to accumulate a dict of properties Mutates dest_props by adding the non None src_props and returns the new size
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/process.py#L215-L228
tilezen/tilequeue
tilequeue/process.py
metatile_children_with_size
def metatile_children_with_size(coord, metatile_zoom, nominal_zoom, tile_size): """ Return a list of all the coords which are children of the input metatile at `coord` with zoom `metatile_zoom` (i.e: 0 for a single tile metatile, 1 for 2x2, 2 for 4x4, etc...) with size `tile_size` corrected for the ...
python
def metatile_children_with_size(coord, metatile_zoom, nominal_zoom, tile_size): """ Return a list of all the coords which are children of the input metatile at `coord` with zoom `metatile_zoom` (i.e: 0 for a single tile metatile, 1 for 2x2, 2 for 4x4, etc...) with size `tile_size` corrected for the ...
Return a list of all the coords which are children of the input metatile at `coord` with zoom `metatile_zoom` (i.e: 0 for a single tile metatile, 1 for 2x2, 2 for 4x4, etc...) with size `tile_size` corrected for the `nominal_zoom`. For example, in a single tile metatile, the `tile_size` must be 256 and...
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/process.py#L611-L646
tilezen/tilequeue
tilequeue/process.py
calculate_sizes_by_zoom
def calculate_sizes_by_zoom(coord, metatile_zoom, cfg_tile_sizes, max_zoom): """ Returns a map of nominal zoom to the list of tile sizes to generate at that zoom. This is because we want to generate different metatile contents at different zoom levels. At the most detailed zoom level, we want to ge...
python
def calculate_sizes_by_zoom(coord, metatile_zoom, cfg_tile_sizes, max_zoom): """ Returns a map of nominal zoom to the list of tile sizes to generate at that zoom. This is because we want to generate different metatile contents at different zoom levels. At the most detailed zoom level, we want to ge...
Returns a map of nominal zoom to the list of tile sizes to generate at that zoom. This is because we want to generate different metatile contents at different zoom levels. At the most detailed zoom level, we want to generate the smallest tiles possible, as this allows "overzooming" by simply extrac...
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/process.py#L649-L707
tilezen/tilequeue
tilequeue/process.py
calculate_cut_coords_by_zoom
def calculate_cut_coords_by_zoom( coord, metatile_zoom, cfg_tile_sizes, max_zoom): """ Returns a map of nominal zoom to the list of cut coordinates at that nominal zoom. Note that max_zoom should be the maximum coordinate zoom, not nominal zoom. """ tile_sizes_by_zoom = calculate_s...
python
def calculate_cut_coords_by_zoom( coord, metatile_zoom, cfg_tile_sizes, max_zoom): """ Returns a map of nominal zoom to the list of cut coordinates at that nominal zoom. Note that max_zoom should be the maximum coordinate zoom, not nominal zoom. """ tile_sizes_by_zoom = calculate_s...
Returns a map of nominal zoom to the list of cut coordinates at that nominal zoom. Note that max_zoom should be the maximum coordinate zoom, not nominal zoom.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/process.py#L710-L732
tilezen/tilequeue
tilequeue/store.py
os_replace
def os_replace(src, dst): ''' Simple emulation of function `os.replace(..)` from modern version of Python. Implementation is not fully atomic, but enough for us. ''' orig_os_replace_func = getattr(os, 'replace', None) if orig_os_replace_func is not None: # not need for emulation: we us...
python
def os_replace(src, dst): ''' Simple emulation of function `os.replace(..)` from modern version of Python. Implementation is not fully atomic, but enough for us. ''' orig_os_replace_func = getattr(os, 'replace', None) if orig_os_replace_func is not None: # not need for emulation: we us...
Simple emulation of function `os.replace(..)` from modern version of Python. Implementation is not fully atomic, but enough for us.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/store.py#L254-L314
tilezen/tilequeue
tilequeue/store.py
tiles_are_equal
def tiles_are_equal(tile_data_1, tile_data_2, fmt): """ Returns True if the tile data is equal in tile_data_1 and tile_data_2. For most formats, this is a simple byte-wise equality check. For zipped metatiles, we need to check the contents, as the zip format includes metadata such as timestamps and ...
python
def tiles_are_equal(tile_data_1, tile_data_2, fmt): """ Returns True if the tile data is equal in tile_data_1 and tile_data_2. For most formats, this is a simple byte-wise equality check. For zipped metatiles, we need to check the contents, as the zip format includes metadata such as timestamps and ...
Returns True if the tile data is equal in tile_data_1 and tile_data_2. For most formats, this is a simple byte-wise equality check. For zipped metatiles, we need to check the contents, as the zip format includes metadata such as timestamps and doesn't control file ordering.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/store.py#L493-L505
tilezen/tilequeue
tilequeue/store.py
write_tile_if_changed
def write_tile_if_changed(store, tile_data, coord, format): """ Only write tile data if different from existing. Try to read the tile data from the store first. If the existing data matches, don't write. Returns whether the tile was written. """ existing_data = store.read_tile(coord, format) ...
python
def write_tile_if_changed(store, tile_data, coord, format): """ Only write tile data if different from existing. Try to read the tile data from the store first. If the existing data matches, don't write. Returns whether the tile was written. """ existing_data = store.read_tile(coord, format) ...
Only write tile data if different from existing. Try to read the tile data from the store first. If the existing data matches, don't write. Returns whether the tile was written.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/store.py#L508-L522
tilezen/tilequeue
tilequeue/config.py
_override_cfg
def _override_cfg(container, yamlkeys, value): """ Override a hierarchical key in the config, setting it to the value. Note that yamlkeys should be a non-empty list of strings. """ key = yamlkeys[0] rest = yamlkeys[1:] if len(rest) == 0: # no rest means we found the key to update....
python
def _override_cfg(container, yamlkeys, value): """ Override a hierarchical key in the config, setting it to the value. Note that yamlkeys should be a non-empty list of strings. """ key = yamlkeys[0] rest = yamlkeys[1:] if len(rest) == 0: # no rest means we found the key to update....
Override a hierarchical key in the config, setting it to the value. Note that yamlkeys should be a non-empty list of strings.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/config.py#L276-L298
tilezen/tilequeue
tilequeue/command.py
coord_pyramid
def coord_pyramid(coord, zoom_start, zoom_stop): """ generate full pyramid for coord Generate the full pyramid for a single coordinate. Note that zoom_stop is exclusive. """ if zoom_start <= coord.zoom: yield coord for child_coord in coord_children_range(coord, zoom_stop): i...
python
def coord_pyramid(coord, zoom_start, zoom_stop): """ generate full pyramid for coord Generate the full pyramid for a single coordinate. Note that zoom_stop is exclusive. """ if zoom_start <= coord.zoom: yield coord for child_coord in coord_children_range(coord, zoom_stop): i...
generate full pyramid for coord Generate the full pyramid for a single coordinate. Note that zoom_stop is exclusive.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L993-L1004
tilezen/tilequeue
tilequeue/command.py
coord_pyramids
def coord_pyramids(coords, zoom_start, zoom_stop): """ generate full pyramid for coords Generate the full pyramid for the list of coords. Note that zoom_stop is exclusive. """ for coord in coords: for child in coord_pyramid(coord, zoom_start, zoom_stop): yield child
python
def coord_pyramids(coords, zoom_start, zoom_stop): """ generate full pyramid for coords Generate the full pyramid for the list of coords. Note that zoom_stop is exclusive. """ for coord in coords: for child in coord_pyramid(coord, zoom_start, zoom_stop): yield child
generate full pyramid for coords Generate the full pyramid for the list of coords. Note that zoom_stop is exclusive.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1007-L1016
tilezen/tilequeue
tilequeue/command.py
tilequeue_enqueue_full_pyramid_from_toi
def tilequeue_enqueue_full_pyramid_from_toi(cfg, peripherals, args): """enqueue a full pyramid from the z10 toi""" logger = make_logger(cfg, 'enqueue_tiles_of_interest') logger.info('Enqueueing tiles of interest') logger.info('Fetching tiles of interest ...') tiles_of_interest = peripherals.toi.fet...
python
def tilequeue_enqueue_full_pyramid_from_toi(cfg, peripherals, args): """enqueue a full pyramid from the z10 toi""" logger = make_logger(cfg, 'enqueue_tiles_of_interest') logger.info('Enqueueing tiles of interest') logger.info('Fetching tiles of interest ...') tiles_of_interest = peripherals.toi.fet...
enqueue a full pyramid from the z10 toi
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1019-L1066
tilezen/tilequeue
tilequeue/command.py
tilequeue_enqueue_random_pyramids
def tilequeue_enqueue_random_pyramids(cfg, peripherals, args): """enqueue random pyramids""" from tilequeue.stats import RawrTileEnqueueStatsHandler from tilequeue.rawr import make_rawr_enqueuer_from_cfg logger = make_logger(cfg, 'enqueue_random_pyramids') rawr_yaml = cfg.yml.get('rawr') asse...
python
def tilequeue_enqueue_random_pyramids(cfg, peripherals, args): """enqueue random pyramids""" from tilequeue.stats import RawrTileEnqueueStatsHandler from tilequeue.rawr import make_rawr_enqueuer_from_cfg logger = make_logger(cfg, 'enqueue_random_pyramids') rawr_yaml = cfg.yml.get('rawr') asse...
enqueue random pyramids
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1069-L1135
tilezen/tilequeue
tilequeue/command.py
emit_toi_stats
def emit_toi_stats(toi_set, peripherals): """ Calculates new TOI stats and emits them via statsd. """ count_by_zoom = defaultdict(int) total = 0 for coord_int in toi_set: coord = coord_unmarshall_int(coord_int) count_by_zoom[coord.zoom] += 1 total += 1 peripherals.s...
python
def emit_toi_stats(toi_set, peripherals): """ Calculates new TOI stats and emits them via statsd. """ count_by_zoom = defaultdict(int) total = 0 for coord_int in toi_set: coord = coord_unmarshall_int(coord_int) count_by_zoom[coord.zoom] += 1 total += 1 peripherals.s...
Calculates new TOI stats and emits them via statsd.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1177-L1194
tilezen/tilequeue
tilequeue/command.py
tilequeue_load_tiles_of_interest
def tilequeue_load_tiles_of_interest(cfg, peripherals): """ Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest. """ logger = make_logger(cfg, 'load_tiles_of_interest') toi_filename = "toi.txt" logger.info('Load...
python
def tilequeue_load_tiles_of_interest(cfg, peripherals): """ Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest. """ logger = make_logger(cfg, 'load_tiles_of_interest') toi_filename = "toi.txt" logger.info('Load...
Given a newline-delimited file containing tile coordinates in `zoom/column/row` format, load those tiles into the tiles of interest.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1520-L1541
tilezen/tilequeue
tilequeue/command.py
tilequeue_stuck_tiles
def tilequeue_stuck_tiles(cfg, peripherals): """ Check which files exist on s3 but are not in toi. """ store = _make_store(cfg) format = lookup_format_by_extension('zip') layer = 'all' assert peripherals.toi, 'Missing toi' toi = peripherals.toi.fetch_tiles_of_interest() for coord i...
python
def tilequeue_stuck_tiles(cfg, peripherals): """ Check which files exist on s3 but are not in toi. """ store = _make_store(cfg) format = lookup_format_by_extension('zip') layer = 'all' assert peripherals.toi, 'Missing toi' toi = peripherals.toi.fetch_tiles_of_interest() for coord i...
Check which files exist on s3 but are not in toi.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1544-L1558
tilezen/tilequeue
tilequeue/command.py
tilequeue_tile_status
def tilequeue_tile_status(cfg, peripherals, args): """ Report the status of the given tiles in the store, queue and TOI. """ logger = make_logger(cfg, 'tile_status') # friendly warning to avoid confusion when this command outputs nothing # at all when called with no positional arguments. if...
python
def tilequeue_tile_status(cfg, peripherals, args): """ Report the status of the given tiles in the store, queue and TOI. """ logger = make_logger(cfg, 'tile_status') # friendly warning to avoid confusion when this command outputs nothing # at all when called with no positional arguments. if...
Report the status of the given tiles in the store, queue and TOI.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1586-L1636
tilezen/tilequeue
tilequeue/command.py
tilequeue_rawr_enqueue
def tilequeue_rawr_enqueue(cfg, args): """command to take tile expiry path and enqueue for rawr tile generation""" from tilequeue.stats import RawrTileEnqueueStatsHandler from tilequeue.rawr import make_rawr_enqueuer_from_cfg msg_marshall_yaml = cfg.yml.get('message-marshall') assert msg_marshall_y...
python
def tilequeue_rawr_enqueue(cfg, args): """command to take tile expiry path and enqueue for rawr tile generation""" from tilequeue.stats import RawrTileEnqueueStatsHandler from tilequeue.rawr import make_rawr_enqueuer_from_cfg msg_marshall_yaml = cfg.yml.get('message-marshall') assert msg_marshall_y...
command to take tile expiry path and enqueue for rawr tile generation
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1729-L1746
tilezen/tilequeue
tilequeue/command.py
_tilequeue_rawr_setup
def _tilequeue_rawr_setup(cfg): """command to read from rawr queue and generate rawr tiles""" rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' rawr_postgresql_yaml = rawr_yaml.get('postgresql') assert rawr_postgresql_yaml, 'Missing rawr postgresql c...
python
def _tilequeue_rawr_setup(cfg): """command to read from rawr queue and generate rawr tiles""" rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' rawr_postgresql_yaml = rawr_yaml.get('postgresql') assert rawr_postgresql_yaml, 'Missing rawr postgresql c...
command to read from rawr queue and generate rawr tiles
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1749-L1813
tilezen/tilequeue
tilequeue/command.py
tilequeue_rawr_seed_toi
def tilequeue_rawr_seed_toi(cfg, peripherals): """command to read the toi and enqueue the corresponding rawr tiles""" tiles_of_interest = peripherals.toi.fetch_tiles_of_interest() coords = map(coord_unmarshall_int, tiles_of_interest) _tilequeue_rawr_seed(cfg, peripherals, coords)
python
def tilequeue_rawr_seed_toi(cfg, peripherals): """command to read the toi and enqueue the corresponding rawr tiles""" tiles_of_interest = peripherals.toi.fetch_tiles_of_interest() coords = map(coord_unmarshall_int, tiles_of_interest) _tilequeue_rawr_seed(cfg, peripherals, coords)
command to read the toi and enqueue the corresponding rawr tiles
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1925-L1929
tilezen/tilequeue
tilequeue/command.py
tilequeue_rawr_seed_all
def tilequeue_rawr_seed_all(cfg, peripherals): """command to enqueue all the tiles at the group-by zoom""" rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group...
python
def tilequeue_rawr_seed_all(cfg, peripherals): """command to enqueue all the tiles at the group-by zoom""" rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group...
command to enqueue all the tiles at the group-by zoom
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/command.py#L1932-L1951
tilezen/tilequeue
tilequeue/format/geojson.py
encode_single_layer
def encode_single_layer(out, features, zoom): """ Encode a list of (WKB|shapely, property dict, id) features into a GeoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be lon, lats. """ precision = precision_for_zoom(zoom) fs = create_laye...
python
def encode_single_layer(out, features, zoom): """ Encode a list of (WKB|shapely, property dict, id) features into a GeoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be lon, lats. """ precision = precision_for_zoom(zoom) fs = create_laye...
Encode a list of (WKB|shapely, property dict, id) features into a GeoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be lon, lats.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/geojson.py#L56-L67
tilezen/tilequeue
tilequeue/format/geojson.py
encode_multiple_layers
def encode_multiple_layers(out, features_by_layer, zoom): """ features_by_layer should be a dict: layer_name -> feature tuples """ precision = precision_for_zoom(zoom) geojson = {} for layer_name, features in features_by_layer.items(): fs = create_layer_feature_collection(features, preci...
python
def encode_multiple_layers(out, features_by_layer, zoom): """ features_by_layer should be a dict: layer_name -> feature tuples """ precision = precision_for_zoom(zoom) geojson = {} for layer_name, features in features_by_layer.items(): fs = create_layer_feature_collection(features, preci...
features_by_layer should be a dict: layer_name -> feature tuples
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/geojson.py#L70-L79
tilezen/tilequeue
tilequeue/format/topojson.py
update_arc_indexes
def update_arc_indexes(geometry, merged_arcs, old_arcs): """ Updated geometry arc indexes, and add arcs to merged_arcs along the way. Arguments are modified in-place, and nothing is returned. """ if geometry['type'] in ('Point', 'MultiPoint'): return elif geometry['type'] == 'LineStrin...
python
def update_arc_indexes(geometry, merged_arcs, old_arcs): """ Updated geometry arc indexes, and add arcs to merged_arcs along the way. Arguments are modified in-place, and nothing is returned. """ if geometry['type'] in ('Point', 'MultiPoint'): return elif geometry['type'] == 'LineStrin...
Updated geometry arc indexes, and add arcs to merged_arcs along the way. Arguments are modified in-place, and nothing is returned.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/topojson.py#L4-L37
tilezen/tilequeue
tilequeue/format/topojson.py
get_transform
def get_transform(bounds, size=4096): """ Return a TopoJSON transform dictionary and a point-transforming function. Size is the tile size in pixels and sets the implicit output resolution. """ tx, ty = bounds[0], bounds[1] sx, sy = (bounds[2] - bounds[0]) / size, (bounds[3] - bounds[1])...
python
def get_transform(bounds, size=4096): """ Return a TopoJSON transform dictionary and a point-transforming function. Size is the tile size in pixels and sets the implicit output resolution. """ tx, ty = bounds[0], bounds[1] sx, sy = (bounds[2] - bounds[0]) / size, (bounds[3] - bounds[1])...
Return a TopoJSON transform dictionary and a point-transforming function. Size is the tile size in pixels and sets the implicit output resolution.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/topojson.py#L40-L54
tilezen/tilequeue
tilequeue/format/topojson.py
diff_encode
def diff_encode(line, transform): """ Differentially encode a shapely linestring or ring. """ coords = [transform(x, y) for (x, y) in line.coords] pairs = zip(coords[:], coords[1:]) diffs = [(x2 - x1, y2 - y1) for ((x1, y1), (x2, y2)) in pairs] return coords[:1] + [(x, y) for (x, y) in diffs i...
python
def diff_encode(line, transform): """ Differentially encode a shapely linestring or ring. """ coords = [transform(x, y) for (x, y) in line.coords] pairs = zip(coords[:], coords[1:]) diffs = [(x2 - x1, y2 - y1) for ((x1, y1), (x2, y2)) in pairs] return coords[:1] + [(x, y) for (x, y) in diffs i...
Differentially encode a shapely linestring or ring.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/topojson.py#L57-L65
tilezen/tilequeue
tilequeue/format/topojson.py
encode
def encode(file, features_by_layer, bounds, size=4096): """ Encode a dict of layername: (shape, props, id) features into a TopoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be unprojected lon, lats. Bounds are given in geographic c...
python
def encode(file, features_by_layer, bounds, size=4096): """ Encode a dict of layername: (shape, props, id) features into a TopoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be unprojected lon, lats. Bounds are given in geographic c...
Encode a dict of layername: (shape, props, id) features into a TopoJSON stream. If no id is available, pass in None Geometries in the features list are assumed to be unprojected lon, lats. Bounds are given in geographic coordinates as (xmin, ymin, xmax, ymax). Size is...
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/topojson.py#L68-L159
tilezen/tilequeue
tilequeue/query/postgres.py
jinja_filter_bbox_overlaps
def jinja_filter_bbox_overlaps(bounds, geometry_col_name, srid=3857): """ Check whether the boundary of the geometry intersects with the bounding box. Note that the usual meaning of "overlaps" in GIS terminology is that the boundaries of the box and polygon intersect, but not the interiors. This ...
python
def jinja_filter_bbox_overlaps(bounds, geometry_col_name, srid=3857): """ Check whether the boundary of the geometry intersects with the bounding box. Note that the usual meaning of "overlaps" in GIS terminology is that the boundaries of the box and polygon intersect, but not the interiors. This ...
Check whether the boundary of the geometry intersects with the bounding box. Note that the usual meaning of "overlaps" in GIS terminology is that the boundaries of the box and polygon intersect, but not the interiors. This means that if the box or polygon is completely within the other, then st_ove...
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/postgres.py#L117-L146
tilezen/tilequeue
tilequeue/query/postgres.py
make_db_data_fetcher
def make_db_data_fetcher(postgresql_conn_info, template_path, reload_templates, query_cfg, io_pool): """ Returns an object which is callable with the zoom and unpadded bounds and which returns a list of rows. """ sources = parse_source_data(query_cfg) queries_generator ...
python
def make_db_data_fetcher(postgresql_conn_info, template_path, reload_templates, query_cfg, io_pool): """ Returns an object which is callable with the zoom and unpadded bounds and which returns a list of rows. """ sources = parse_source_data(query_cfg) queries_generator ...
Returns an object which is callable with the zoom and unpadded bounds and which returns a list of rows.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/postgres.py#L279-L290
tilezen/tilequeue
tilequeue/metatile.py
make_multi_metatile
def make_multi_metatile(parent, tiles, date_time=None): """ Make a metatile containing a list of tiles all having the same layer, with coordinates relative to the given parent. Set date_time to a 6-tuple of (year, month, day, hour, minute, second) to set the timestamp for members. Otherwise the curr...
python
def make_multi_metatile(parent, tiles, date_time=None): """ Make a metatile containing a list of tiles all having the same layer, with coordinates relative to the given parent. Set date_time to a 6-tuple of (year, month, day, hour, minute, second) to set the timestamp for members. Otherwise the curr...
Make a metatile containing a list of tiles all having the same layer, with coordinates relative to the given parent. Set date_time to a 6-tuple of (year, month, day, hour, minute, second) to set the timestamp for members. Otherwise the current wall clock time is used.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L8-L58
tilezen/tilequeue
tilequeue/metatile.py
common_parent
def common_parent(a, b): """ Find the common parent tile of both a and b. The common parent is the tile at the highest zoom which both a and b can be transformed into by lowering their zoom levels. """ if a.zoom < b.zoom: b = b.zoomTo(a.zoom).container() elif a.zoom > b.zoom: ...
python
def common_parent(a, b): """ Find the common parent tile of both a and b. The common parent is the tile at the highest zoom which both a and b can be transformed into by lowering their zoom levels. """ if a.zoom < b.zoom: b = b.zoomTo(a.zoom).container() elif a.zoom > b.zoom: ...
Find the common parent tile of both a and b. The common parent is the tile at the highest zoom which both a and b can be transformed into by lowering their zoom levels.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L61-L79
tilezen/tilequeue
tilequeue/metatile.py
_parent_tile
def _parent_tile(tiles): """ Find the common parent tile for a sequence of tiles. """ parent = None for t in tiles: if parent is None: parent = t else: parent = common_parent(parent, t) return parent
python
def _parent_tile(tiles): """ Find the common parent tile for a sequence of tiles. """ parent = None for t in tiles: if parent is None: parent = t else: parent = common_parent(parent, t) return parent
Find the common parent tile for a sequence of tiles.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L82-L94
tilezen/tilequeue
tilequeue/metatile.py
make_metatiles
def make_metatiles(size, tiles, date_time=None): """ Group by layers, and make metatiles out of all the tiles which share those properties relative to the "top level" tile which is parent of them all. Provide a 6-tuple date_time to set the timestamp on each tile within the metatile, or leave it as N...
python
def make_metatiles(size, tiles, date_time=None): """ Group by layers, and make metatiles out of all the tiles which share those properties relative to the "top level" tile which is parent of them all. Provide a 6-tuple date_time to set the timestamp on each tile within the metatile, or leave it as N...
Group by layers, and make metatiles out of all the tiles which share those properties relative to the "top level" tile which is parent of them all. Provide a 6-tuple date_time to set the timestamp on each tile within the metatile, or leave it as None to use the current time.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L97-L115
tilezen/tilequeue
tilequeue/metatile.py
extract_metatile
def extract_metatile(io, fmt, offset=None): """ Extract the tile at the given offset (defaults to 0/0/0) and format from the metatile in the file-like object io. """ ext = fmt.extension if offset is None: tile_name = '0/0/0.%s' % ext else: tile_name = '%d/%d/%d.%s' % (offset...
python
def extract_metatile(io, fmt, offset=None): """ Extract the tile at the given offset (defaults to 0/0/0) and format from the metatile in the file-like object io. """ ext = fmt.extension if offset is None: tile_name = '0/0/0.%s' % ext else: tile_name = '%d/%d/%d.%s' % (offset...
Extract the tile at the given offset (defaults to 0/0/0) and format from the metatile in the file-like object io.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L118-L135
tilezen/tilequeue
tilequeue/metatile.py
_metatile_contents_equal
def _metatile_contents_equal(zip_1, zip_2): """ Given two open zip files as arguments, this returns True if the zips both contain the same set of files, having the same names, and each file within the zip is byte-wise identical to the one with the same name in the other zip. """ names_1 = s...
python
def _metatile_contents_equal(zip_1, zip_2): """ Given two open zip files as arguments, this returns True if the zips both contain the same set of files, having the same names, and each file within the zip is byte-wise identical to the one with the same name in the other zip. """ names_1 = s...
Given two open zip files as arguments, this returns True if the zips both contain the same set of files, having the same names, and each file within the zip is byte-wise identical to the one with the same name in the other zip.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L138-L159
tilezen/tilequeue
tilequeue/metatile.py
metatiles_are_equal
def metatiles_are_equal(tile_data_1, tile_data_2): """ Return True if the two tiles are both zipped metatiles and contain the same set of files with the same contents. This ignores the timestamp of the individual files in the zip files, as well as their order or any other metadata. """ try:...
python
def metatiles_are_equal(tile_data_1, tile_data_2): """ Return True if the two tiles are both zipped metatiles and contain the same set of files with the same contents. This ignores the timestamp of the individual files in the zip files, as well as their order or any other metadata. """ try:...
Return True if the two tiles are both zipped metatiles and contain the same set of files with the same contents. This ignores the timestamp of the individual files in the zip files, as well as their order or any other metadata.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/metatile.py#L162-L184
tilezen/tilequeue
tilequeue/log.py
make_coord_dict
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
python
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
helper function to make a dict from a coordinate for logging
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/log.py#L18-L24
tilezen/tilequeue
tilequeue/format/__init__.py
convert_feature_layers_to_dict
def convert_feature_layers_to_dict(feature_layers): """takes a list of 'feature_layer' objects and converts to a dict keyed by the layer name""" features_by_layer = {} for feature_layer in feature_layers: layer_name = feature_layer['name'] features = feature_layer['features'] ...
python
def convert_feature_layers_to_dict(feature_layers): """takes a list of 'feature_layer' objects and converts to a dict keyed by the layer name""" features_by_layer = {} for feature_layer in feature_layers: layer_name = feature_layer['name'] features = feature_layer['features'] ...
takes a list of 'feature_layer' objects and converts to a dict keyed by the layer name
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/__init__.py#L43-L51
tilezen/tilequeue
tilequeue/queue/mapper.py
ZoomRangeAndZoomGroupQueueMapper.group
def group(self, coords): """return CoordGroups that can be used to send to queues Each CoordGroup represents a message that can be sent to a particular queue, stamped with the queue_id. The list of coords, which can be 1, is what should get used for the payload for each queue me...
python
def group(self, coords): """return CoordGroups that can be used to send to queues Each CoordGroup represents a message that can be sent to a particular queue, stamped with the queue_id. The list of coords, which can be 1, is what should get used for the payload for each queue me...
return CoordGroups that can be used to send to queues Each CoordGroup represents a message that can be sent to a particular queue, stamped with the queue_id. The list of coords, which can be 1, is what should get used for the payload for each queue message.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/queue/mapper.py#L74-L122
tilezen/tilequeue
tilequeue/rawr.py
common_parent
def common_parent(coords, parent_zoom): """ Return the common parent for coords Also check that all coords do indeed share the same parent coordinate. """ parent = None for coord in coords: assert parent_zoom <= coord.zoom coord_parent = coord.zoomTo(parent_zoom).container() ...
python
def common_parent(coords, parent_zoom): """ Return the common parent for coords Also check that all coords do indeed share the same parent coordinate. """ parent = None for coord in coords: assert parent_zoom <= coord.zoom coord_parent = coord.zoomTo(parent_zoom).container() ...
Return the common parent for coords Also check that all coords do indeed share the same parent coordinate.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L205-L220
tilezen/tilequeue
tilequeue/rawr.py
convert_coord_object
def convert_coord_object(coord): """Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile""" assert isinstance(coord, Coordinate) coord = coord.container() return Tile(int(coord.zoom), int(coord.column), int(coord.row))
python
def convert_coord_object(coord): """Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile""" assert isinstance(coord, Coordinate) coord = coord.container() return Tile(int(coord.zoom), int(coord.column), int(coord.row))
Convert ModestMaps.Core.Coordinate -> raw_tiles.tile.Tile
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L223-L227
tilezen/tilequeue
tilequeue/rawr.py
unconvert_coord_object
def unconvert_coord_object(tile): """Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate""" assert isinstance(tile, Tile) return Coordinate(zoom=tile.z, column=tile.x, row=tile.y)
python
def unconvert_coord_object(tile): """Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate""" assert isinstance(tile, Tile) return Coordinate(zoom=tile.z, column=tile.x, row=tile.y)
Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L230-L233
tilezen/tilequeue
tilequeue/rawr.py
make_rawr_zip_payload
def make_rawr_zip_payload(rawr_tile, date_time=None): """make a zip file from the rawr tile formatted data""" if date_time is None: date_time = gmtime()[0:6] buf = StringIO() with zipfile.ZipFile(buf, mode='w') as z: for fmt_data in rawr_tile.all_formatted_data: zip_info = z...
python
def make_rawr_zip_payload(rawr_tile, date_time=None): """make a zip file from the rawr tile formatted data""" if date_time is None: date_time = gmtime()[0:6] buf = StringIO() with zipfile.ZipFile(buf, mode='w') as z: for fmt_data in rawr_tile.all_formatted_data: zip_info = z...
make a zip file from the rawr tile formatted data
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L529-L539
tilezen/tilequeue
tilequeue/rawr.py
unpack_rawr_zip_payload
def unpack_rawr_zip_payload(table_sources, payload): """unpack a zipfile and turn it into a callable "tables" object.""" # the io we get from S3 is streaming, so we can't seek on it, but zipfile # seems to require that. so we buffer it all in memory. RAWR tiles are # generally up to around 100MB in size...
python
def unpack_rawr_zip_payload(table_sources, payload): """unpack a zipfile and turn it into a callable "tables" object.""" # the io we get from S3 is streaming, so we can't seek on it, but zipfile # seems to require that. so we buffer it all in memory. RAWR tiles are # generally up to around 100MB in size...
unpack a zipfile and turn it into a callable "tables" object.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L542-L561
tilezen/tilequeue
tilequeue/rawr.py
SqsQueue.send
def send(self, payloads, logger, num_tries=5): """ Enqueue payloads to the SQS queue, retrying failed messages with exponential backoff. """ from time import sleep backoff_interval = 1 backoff_factor = 2 for try_counter in xrange(0, num_tries): ...
python
def send(self, payloads, logger, num_tries=5): """ Enqueue payloads to the SQS queue, retrying failed messages with exponential backoff. """ from time import sleep backoff_interval = 1 backoff_factor = 2 for try_counter in xrange(0, num_tries): ...
Enqueue payloads to the SQS queue, retrying failed messages with exponential backoff.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L61-L104
tilezen/tilequeue
tilequeue/rawr.py
SqsQueue.read
def read(self): """read a single message from the queue""" resp = self.sqs_client.receive_message( QueueUrl=self.queue_url, MaxNumberOfMessages=1, AttributeNames=('SentTimestamp',), WaitTimeSeconds=self.recv_wait_time_seconds, ) if resp['Re...
python
def read(self): """read a single message from the queue""" resp = self.sqs_client.receive_message( QueueUrl=self.queue_url, MaxNumberOfMessages=1, AttributeNames=('SentTimestamp',), WaitTimeSeconds=self.recv_wait_time_seconds, ) if resp['Re...
read a single message from the queue
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L106-L127
tilezen/tilequeue
tilequeue/rawr.py
SqsQueue.done
def done(self, msg_handle): """acknowledge completion of message""" self.sqs_client.delete_message( QueueUrl=self.queue_url, ReceiptHandle=msg_handle.handle, )
python
def done(self, msg_handle): """acknowledge completion of message""" self.sqs_client.delete_message( QueueUrl=self.queue_url, ReceiptHandle=msg_handle.handle, )
acknowledge completion of message
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L129-L134
tilezen/tilequeue
tilequeue/rawr.py
RawrToiIntersector.tiles_of_interest
def tiles_of_interest(self): """conditionally get the toi from s3""" # also return back whether the response was cached # useful for metrics is_cached = False get_options = dict( Bucket=self.bucket, Key=self.key, ) if self.etag: ...
python
def tiles_of_interest(self): """conditionally get the toi from s3""" # also return back whether the response was cached # useful for metrics is_cached = False get_options = dict( Bucket=self.bucket, Key=self.key, ) if self.etag: ...
conditionally get the toi from s3
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/rawr.py#L259-L302
tilezen/tilequeue
tilequeue/worker.py
_ack_coord_handle
def _ack_coord_handle( coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler): """share code for acknowledging a coordinate""" # returns tuple of (handle, error), either of which can be None track_result = msg_tracker.done(coord_handle) queue_han...
python
def _ack_coord_handle( coord, coord_handle, queue_mapper, msg_tracker, timing_state, tile_proc_logger, stats_handler): """share code for acknowledging a coordinate""" # returns tuple of (handle, error), either of which can be None track_result = msg_tracker.done(coord_handle) queue_han...
share code for acknowledging a coordinate
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/worker.py#L91-L144
tilezen/tilequeue
tilequeue/query/rawr.py
_snapping_round
def _snapping_round(num, eps, resolution): """ Return num snapped to within eps of an integer, or int(resolution(num)). """ rounded = round(num) delta = abs(num - rounded) if delta < eps: return int(rounded) else: return int(resolution(num))
python
def _snapping_round(num, eps, resolution): """ Return num snapped to within eps of an integer, or int(resolution(num)). """ rounded = round(num) delta = abs(num - rounded) if delta < eps: return int(rounded) else: return int(resolution(num))
Return num snapped to within eps of an integer, or int(resolution(num)).
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/rawr.py#L229-L239
tilezen/tilequeue
tilequeue/query/rawr.py
_explode_lines
def _explode_lines(shape): """ Return a list of LineStrings which make up the shape. """ if shape.geom_type == 'LineString': return [shape] elif shape.geom_type == 'MultiLineString': return shape.geoms elif shape.geom_type == 'GeometryCollection': lines = [] fo...
python
def _explode_lines(shape): """ Return a list of LineStrings which make up the shape. """ if shape.geom_type == 'LineString': return [shape] elif shape.geom_type == 'MultiLineString': return shape.geoms elif shape.geom_type == 'GeometryCollection': lines = [] fo...
Return a list of LineStrings which make up the shape.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/rawr.py#L581-L598
tilezen/tilequeue
tilequeue/query/rawr.py
_lines_only
def _lines_only(shape): """ Extract the lines (LineString, MultiLineString) from any geometry. We expect the input to be mostly lines, such as the result of an intersection between a line and a polygon. The main idea is to remove points, and any other geometry which might throw a wrench in the works...
python
def _lines_only(shape): """ Extract the lines (LineString, MultiLineString) from any geometry. We expect the input to be mostly lines, such as the result of an intersection between a line and a polygon. The main idea is to remove points, and any other geometry which might throw a wrench in the works...
Extract the lines (LineString, MultiLineString) from any geometry. We expect the input to be mostly lines, such as the result of an intersection between a line and a polygon. The main idea is to remove points, and any other geometry which might throw a wrench in the works.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/rawr.py#L601-L613
tilezen/tilequeue
tilequeue/query/rawr.py
_orient
def _orient(shape): """ The Shapely version of the orient function appears to only work on Polygons, and fails on MultiPolygons. This is a quick wrapper to allow orienting of either. """ assert shape.geom_type in ('Polygon', 'MultiPolygon') if shape.geom_type == 'Polygon': return o...
python
def _orient(shape): """ The Shapely version of the orient function appears to only work on Polygons, and fails on MultiPolygons. This is a quick wrapper to allow orienting of either. """ assert shape.geom_type in ('Polygon', 'MultiPolygon') if shape.geom_type == 'Polygon': return o...
The Shapely version of the orient function appears to only work on Polygons, and fails on MultiPolygons. This is a quick wrapper to allow orienting of either.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/query/rawr.py#L616-L632
tilezen/tilequeue
tilequeue/format/OSciMap4/GeomEncoder.py
GeomEncoder.parseGeometry
def parseGeometry(self, geometry): """ A factory method for creating objects of the correct OpenGIS type. """ self.coordinates = [] self.index = [] self.position = 0 self.lastX = 0 self.lastY = 0 self.isPoly = False self.isPoint...
python
def parseGeometry(self, geometry): """ A factory method for creating objects of the correct OpenGIS type. """ self.coordinates = [] self.index = [] self.position = 0 self.lastX = 0 self.lastY = 0 self.isPoly = False self.isPoint...
A factory method for creating objects of the correct OpenGIS type.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/OSciMap4/GeomEncoder.py#L123-L145
tilezen/tilequeue
tilequeue/format/OSciMap4/GeomEncoder.py
GeomEncoder._dispatchNextType
def _dispatchNextType(self,reader): """ Read a type id from the binary stream (reader) and call the correct method to parse it. """ # Need to check endianess here! endianness = reader.unpack_byte() if endianness == 0: reader.setEndianness('XDR') ...
python
def _dispatchNextType(self,reader): """ Read a type id from the binary stream (reader) and call the correct method to parse it. """ # Need to check endianess here! endianness = reader.unpack_byte() if endianness == 0: reader.setEndianness('XDR') ...
Read a type id from the binary stream (reader) and call the correct method to parse it.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/format/OSciMap4/GeomEncoder.py#L148-L187
tilezen/tilequeue
tilequeue/transform.py
calc_buffered_bounds
def calc_buffered_bounds( format, bounds, meters_per_pixel_dim, layer_name, geometry_type, buffer_cfg): """ Calculate the buffered bounds per format per layer based on config. """ if not buffer_cfg: return bounds format_buffer_cfg = buffer_cfg.get(format.extension) if f...
python
def calc_buffered_bounds( format, bounds, meters_per_pixel_dim, layer_name, geometry_type, buffer_cfg): """ Calculate the buffered bounds per format per layer based on config. """ if not buffer_cfg: return bounds format_buffer_cfg = buffer_cfg.get(format.extension) if f...
Calculate the buffered bounds per format per layer based on config.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/transform.py#L64-L97
tilezen/tilequeue
tilequeue/transform.py
_intersect_multipolygon
def _intersect_multipolygon(shape, tile_bounds, clip_bounds): """ Return the parts of the MultiPolygon shape which overlap the tile_bounds, each clipped to the clip_bounds. This can be used to extract only the parts of a multipolygon which are actually visible in the tile, while keeping those parts ...
python
def _intersect_multipolygon(shape, tile_bounds, clip_bounds): """ Return the parts of the MultiPolygon shape which overlap the tile_bounds, each clipped to the clip_bounds. This can be used to extract only the parts of a multipolygon which are actually visible in the tile, while keeping those parts ...
Return the parts of the MultiPolygon shape which overlap the tile_bounds, each clipped to the clip_bounds. This can be used to extract only the parts of a multipolygon which are actually visible in the tile, while keeping those parts which extend beyond the tile clipped to avoid huge polygons.
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/transform.py#L100-L127
tilezen/tilequeue
tilequeue/transform.py
_clip_shape
def _clip_shape(shape, buffer_padded_bounds, is_clipped, clip_factor): """ Return the shape clipped to a clip_factor expansion of buffer_padded_bounds if is_clipped is True. Otherwise return the original shape, or None if the shape does not intersect buffer_padded_bounds at all. This is used to red...
python
def _clip_shape(shape, buffer_padded_bounds, is_clipped, clip_factor): """ Return the shape clipped to a clip_factor expansion of buffer_padded_bounds if is_clipped is True. Otherwise return the original shape, or None if the shape does not intersect buffer_padded_bounds at all. This is used to red...
Return the shape clipped to a clip_factor expansion of buffer_padded_bounds if is_clipped is True. Otherwise return the original shape, or None if the shape does not intersect buffer_padded_bounds at all. This is used to reduce the size of the geometries which are encoded in the tiles by removing thing...
https://github.com/tilezen/tilequeue/blob/d7b9484ab92e246eb2773949c784ebb37c731e28/tilequeue/transform.py#L130-L162
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/handlers.py
BasicIDTokenHandler.now
def now(self): """ Capture time. """ if self._now is None: # Compute the current time only once per instance self._now = datetime.utcnow() return self._now
python
def now(self): """ Capture time. """ if self._now is None: # Compute the current time only once per instance self._now = datetime.utcnow() return self._now
Capture time.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/handlers.py#L83-L88
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/handlers.py
BasicIDTokenHandler.claim_exp
def claim_exp(self, data): """ Required expiration time. """ expiration = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30) expires = self.now + timedelta(seconds=expiration) return timegm(expires.utctimetuple())
python
def claim_exp(self, data): """ Required expiration time. """ expiration = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30) expires = self.now + timedelta(seconds=expiration) return timegm(expires.utctimetuple())
Required expiration time.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/handlers.py#L111-L115
edx/edx-oauth2-provider
edx_oauth2_provider/management/commands/create_oauth2_client.py
Command._clean_required_args
def _clean_required_args(self, url, redirect_uri, client_type): """ Validate and clean the command's arguments. Arguments: url (str): Client's application URL. redirect_uri (str): Client application's OAuth2 callback URI. client_type (str): Client's type, ind...
python
def _clean_required_args(self, url, redirect_uri, client_type): """ Validate and clean the command's arguments. Arguments: url (str): Client's application URL. redirect_uri (str): Client application's OAuth2 callback URI. client_type (str): Client's type, ind...
Validate and clean the command's arguments. Arguments: url (str): Client's application URL. redirect_uri (str): Client application's OAuth2 callback URI. client_type (str): Client's type, indicating whether the Client application is capable of maintaining the...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/management/commands/create_oauth2_client.py#L106-L141
edx/edx-oauth2-provider
edx_oauth2_provider/management/commands/create_oauth2_client.py
Command._parse_options
def _parse_options(self, options): """Parse the command's options. Arguments: options (dict): Options with which the command was called. Raises: CommandError, if a user matching the provided username does not exist. """ for key in ('username', 'client_na...
python
def _parse_options(self, options): """Parse the command's options. Arguments: options (dict): Options with which the command was called. Raises: CommandError, if a user matching the provided username does not exist. """ for key in ('username', 'client_na...
Parse the command's options. Arguments: options (dict): Options with which the command was called. Raises: CommandError, if a user matching the provided username does not exist.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/management/commands/create_oauth2_client.py#L143-L177
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
id_token
def id_token(access_token, nonce=None, claims_request=None): """ Returns data required for an OpenID Connect ID Token according to: - http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: access_token (:class:`AccessToken`): Associated OAuth2 access token. nonce (str...
python
def id_token(access_token, nonce=None, claims_request=None): """ Returns data required for an OpenID Connect ID Token according to: - http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: access_token (:class:`AccessToken`): Associated OAuth2 access token. nonce (str...
Returns data required for an OpenID Connect ID Token according to: - http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: access_token (:class:`AccessToken`): Associated OAuth2 access token. nonce (str): Optional nonce to protect against replay attacks. claims_reque...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L59-L99
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
userinfo
def userinfo(access_token, scope_request=None, claims_request=None): """ Returns data required for an OpenID Connect UserInfo response, according to: http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse Supports scope and claims request parameter as described in: - http://openid...
python
def userinfo(access_token, scope_request=None, claims_request=None): """ Returns data required for an OpenID Connect UserInfo response, according to: http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse Supports scope and claims request parameter as described in: - http://openid...
Returns data required for an OpenID Connect UserInfo response, according to: http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse Supports scope and claims request parameter as described in: - http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims - http://openid.net/specs...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L102-L152
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
IDToken.encode
def encode(self, secret, algorithm='HS256'): """ Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the ...
python
def encode(self, secret, algorithm='HS256'): """ Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the ...
Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the OpenID Connect claims. secret (str): Secret used to e...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L39-L56
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.access_token_response_data
def access_token_response_data(self, access_token, response_type=None, nonce=''): """ Return `access_token` fields for OAuth2, and add `id_token` fields for OpenID Connect according to the `access_token` scope. """ # Clear the scope for requests that do not use OpenID Connect. ...
python
def access_token_response_data(self, access_token, response_type=None, nonce=''): """ Return `access_token` fields for OAuth2, and add `id_token` fields for OpenID Connect according to the `access_token` scope. """ # Clear the scope for requests that do not use OpenID Connect. ...
Return `access_token` fields for OAuth2, and add `id_token` fields for OpenID Connect according to the `access_token` scope.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L110-L145
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.get_id_token
def get_id_token(self, access_token, nonce): """ Return an ID token for the given Access Token. """ claims_string = self.request.POST.get('claims') claims_request = json.loads(claims_string) if claims_string else {} return oidc.id_token(access_token, nonce, claims_request)
python
def get_id_token(self, access_token, nonce): """ Return an ID token for the given Access Token. """ claims_string = self.request.POST.get('claims') claims_request = json.loads(claims_string) if claims_string else {} return oidc.id_token(access_token, nonce, claims_request)
Return an ID token for the given Access Token.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L147-L153
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.encode_id_token
def encode_id_token(self, id_token): """ Return encoded ID token. """ # Encode the ID token using the `client_secret`. # # TODO: Using the `client_secret` is not ideal, since it is transmitted # over the wire in some authentication flows. A better alternative i...
python
def encode_id_token(self, id_token): """ Return encoded ID token. """ # Encode the ID token using the `client_secret`. # # TODO: Using the `client_secret` is not ideal, since it is transmitted # over the wire in some authentication flows. A better alternative i...
Return encoded ID token.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L155-L171
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
UserInfoView.get
def get(self, request, *_args, **_kwargs): """ Respond to a UserInfo request. Two optional query parameters are accepted, scope and claims. See the references above for more details. """ access_token = self.access_token scope_string = request.GET.get('scope') ...
python
def get(self, request, *_args, **_kwargs): """ Respond to a UserInfo request. Two optional query parameters are accepted, scope and claims. See the references above for more details. """ access_token = self.access_token scope_string = request.GET.get('scope') ...
Respond to a UserInfo request. Two optional query parameters are accepted, scope and claims. See the references above for more details.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L244-L273
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
UserInfoView.userinfo_claims
def userinfo_claims(self, access_token, scope_request, claims_request): """ Return the claims for the requested parameters. """ id_token = oidc.userinfo(access_token, scope_request, claims_request) return id_token.claims
python
def userinfo_claims(self, access_token, scope_request, claims_request): """ Return the claims for the requested parameters. """ id_token = oidc.userinfo(access_token, scope_request, claims_request) return id_token.claims
Return the claims for the requested parameters.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L275-L278
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
collect
def collect(handlers, access_token, scope_request=None, claims_request=None): """ Collect all the claims values from the `handlers`. Arguments: handlers (list): List of claim :class:`Handler` classes. access_token (:class:AccessToken): Associated access token. scope_request (list): List o...
python
def collect(handlers, access_token, scope_request=None, claims_request=None): """ Collect all the claims values from the `handlers`. Arguments: handlers (list): List of claim :class:`Handler` classes. access_token (:class:AccessToken): Associated access token. scope_request (list): List o...
Collect all the claims values from the `handlers`. Arguments: handlers (list): List of claim :class:`Handler` classes. access_token (:class:AccessToken): Associated access token. scope_request (list): List of requested scopes. claims_request (dict): Dictionary with only the relevant section...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L19-L81
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_scopes
def _collect_scopes(handlers, scopes, user, client): """ Get a set of all the authorized scopes according to the handlers. """ results = set() data = {'user': user, 'client': client} def visitor(scope_name, func): claim_names = func(data) # If the claim_names is None, it means that the...
python
def _collect_scopes(handlers, scopes, user, client): """ Get a set of all the authorized scopes according to the handlers. """ results = set() data = {'user': user, 'client': client} def visitor(scope_name, func): claim_names = func(data) # If the claim_names is None, it means that the...
Get a set of all the authorized scopes according to the handlers.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L84-L98
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_names
def _collect_names(handlers, scopes, user, client): """ Get the names of the claims supported by the handlers for the requested scope. """ results = set() data = {'user': user, 'client': client} def visitor(_scope_name, func): claim_names = func(data) # If the claim_names is None, it ...
python
def _collect_names(handlers, scopes, user, client): """ Get the names of the claims supported by the handlers for the requested scope. """ results = set() data = {'user': user, 'client': client} def visitor(_scope_name, func): claim_names = func(data) # If the claim_names is None, it ...
Get the names of the claims supported by the handlers for the requested scope.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L101-L116
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_values
def _collect_values(handlers, names, user, client, values): """ Get the values from the handlers of the requested claims. """ results = {} def visitor(claim_name, func): data = {'user': user, 'client': client} data.update(values.get(claim_name) or {}) claim_value = func(data) ...
python
def _collect_values(handlers, names, user, client, values): """ Get the values from the handlers of the requested claims. """ results = {} def visitor(claim_name, func): data = {'user': user, 'client': client} data.update(values.get(claim_name) or {}) claim_value = func(data) ...
Get the values from the handlers of the requested claims.
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L119-L135
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_validate_claim_request
def _validate_claim_request(claims, ignore_errors=False): """ Validates a claim request section (`userinfo` or `id_token`) according to section 5.5 of the OpenID Connect specification: - http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter Returns a copy of the claim request with o...
python
def _validate_claim_request(claims, ignore_errors=False): """ Validates a claim request section (`userinfo` or `id_token`) according to section 5.5 of the OpenID Connect specification: - http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter Returns a copy of the claim request with o...
Validates a claim request section (`userinfo` or `id_token`) according to section 5.5 of the OpenID Connect specification: - http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter Returns a copy of the claim request with only the valid fields and values. Raises ValueError is the claim r...
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L138-L164
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_validate_claim_values
def _validate_claim_values(name, value, ignore_errors): """ Helper for `validate_claim_request` """ results = {'essential': False} for key, value in value.iteritems(): if key in CLAIM_REQUEST_FIELDS: results[key] = value else: if not ignore_errors: msg...
python
def _validate_claim_values(name, value, ignore_errors): """ Helper for `validate_claim_request` """ results = {'essential': False} for key, value in value.iteritems(): if key in CLAIM_REQUEST_FIELDS: results[key] = value else: if not ignore_errors: msg...
Helper for `validate_claim_request`
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L167-L177
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_visit_handlers
def _visit_handlers(handlers, visitor, prefix, suffixes): """ Use visitor partern to collect information from handlers """ results = [] for handler in handlers: for suffix in suffixes: func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None) if func: ...
python
def _visit_handlers(handlers, visitor, prefix, suffixes): """ Use visitor partern to collect information from handlers """ results = [] for handler in handlers: for suffix in suffixes: func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None) if func: ...
Use visitor partern to collect information from handlers
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L180-L190
mardiros/pyshop
pyshop/views/base.py
CreateView.update_model
def update_model(self, model): """ trivial implementation for simple data in the form, using the model prefix. """ for k, v in self.parse_form().items(): setattr(model, k, v)
python
def update_model(self, model): """ trivial implementation for simple data in the form, using the model prefix. """ for k, v in self.parse_form().items(): setattr(model, k, v)
trivial implementation for simple data in the form, using the model prefix.
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/views/base.py#L114-L120
mardiros/pyshop
pyshop/helpers/i18n.py
locale_negotiator
def locale_negotiator(request): """Locale negotiator base on the `Accept-Language` header""" locale = 'en' if request.accept_language: locale = request.accept_language.best_match(LANGUAGES) locale = LANGUAGES.get(locale, 'en') return locale
python
def locale_negotiator(request): """Locale negotiator base on the `Accept-Language` header""" locale = 'en' if request.accept_language: locale = request.accept_language.best_match(LANGUAGES) locale = LANGUAGES.get(locale, 'en') return locale
Locale negotiator base on the `Accept-Language` header
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/helpers/i18n.py#L16-L22
mardiros/pyshop
pyshop/__init__.py
main
def main(global_config, **settings): """ Get a PyShop WSGI application configured with settings. """ if sys.version_info[0] < 3: reload(sys) sys.setdefaultencoding('utf-8') settings = dict(settings) # Scoping sessions for Pyramid ensure session are commit/rollback # after th...
python
def main(global_config, **settings): """ Get a PyShop WSGI application configured with settings. """ if sys.version_info[0] < 3: reload(sys) sys.setdefaultencoding('utf-8') settings = dict(settings) # Scoping sessions for Pyramid ensure session are commit/rollback # after th...
Get a PyShop WSGI application configured with settings.
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/__init__.py#L19-L45
mardiros/pyshop
pyshop/models.py
Group.by_name
def by_name(cls, session, name): """ Get a package from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the group :type name: `unicode :return: package instance :rtype: :class:`pyshop.mode...
python
def by_name(cls, session, name): """ Get a package from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the group :type name: `unicode :return: package instance :rtype: :class:`pyshop.mode...
Get a package from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the group :type name: `unicode :return: package instance :rtype: :class:`pyshop.models.Group`
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L113-L126
mardiros/pyshop
pyshop/models.py
User.by_login
def by_login(cls, session, login, local=True): """ Get a user from a given login. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: the user login :type login: unicode :return: the associated user :rtype: :class...
python
def by_login(cls, session, login, local=True): """ Get a user from a given login. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: the user login :type login: unicode :return: the associated user :rtype: :class...
Get a user from a given login. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: the user login :type login: unicode :return: the associated user :rtype: :class:`pyshop.models.User`
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L184-L202
mardiros/pyshop
pyshop/models.py
User.by_credentials
def by_credentials(cls, session, login, password): """ Get a user from given credentials :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: username :type login: unicode :param password: user password :type passw...
python
def by_credentials(cls, session, login, password): """ Get a user from given credentials :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: username :type login: unicode :param password: user password :type passw...
Get a user from given credentials :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: username :type login: unicode :param password: user password :type password: unicode :return: associated user :rtype: :class:`...
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L205-L225
mardiros/pyshop
pyshop/models.py
User.by_ldap_credentials
def by_ldap_credentials(cls, session, login, password, settings): """if possible try to contact the LDAP for authentification if success and login don't exist localy create one and return it :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param lo...
python
def by_ldap_credentials(cls, session, login, password, settings): """if possible try to contact the LDAP for authentification if success and login don't exist localy create one and return it :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param lo...
if possible try to contact the LDAP for authentification if success and login don't exist localy create one and return it :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param login: username :type login: unicode :param password: user pas...
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L228-L347
mardiros/pyshop
pyshop/models.py
User.get_locals
def get_locals(cls, session, **kwargs): """ Get all local users. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :return: local users :rtype: generator of :class:`pyshop.models.User` """ return cls.find(session, ...
python
def get_locals(cls, session, **kwargs): """ Get all local users. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :return: local users :rtype: generator of :class:`pyshop.models.User` """ return cls.find(session, ...
Get all local users. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :return: local users :rtype: generator of :class:`pyshop.models.User`
https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L350-L363