repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.predict_from_design_matrix
def predict_from_design_matrix(self, design_matrix): """predict_from_design_matrix predicts signals given a design matrix. :param design_matrix: design matrix from which to predict a signal. :type design_matrix: numpy array, (nr_samples x betas.shape) :returns: predicted sig...
python
def predict_from_design_matrix(self, design_matrix): """predict_from_design_matrix predicts signals given a design matrix. :param design_matrix: design matrix from which to predict a signal. :type design_matrix: numpy array, (nr_samples x betas.shape) :returns: predicted sig...
[ "def", "predict_from_design_matrix", "(", "self", ",", "design_matrix", ")", ":", "# check if we have already run the regression - which is necessary", "assert", "hasattr", "(", "self", ",", "'betas'", ")", ",", "'no betas found, please run regression before prediction'", "assert...
predict_from_design_matrix predicts signals given a design matrix. :param design_matrix: design matrix from which to predict a signal. :type design_matrix: numpy array, (nr_samples x betas.shape) :returns: predicted signal(s) :rtype: numpy array (nr_signals x nr_samples...
[ "predict_from_design_matrix", "predicts", "signals", "given", "a", "design", "matrix", "." ]
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L280-L298
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.calculate_rsq
def calculate_rsq(self): """calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero. """ assert hasattr(self, 'betas'), 'no betas found, please run ...
python
def calculate_rsq(self): """calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero. """ assert hasattr(self, 'betas'), 'no betas found, please run ...
[ "def", "calculate_rsq", "(", "self", ")", ":", "assert", "hasattr", "(", "self", ",", "'betas'", ")", ",", "'no betas found, please run regression before rsq'", "explained_times", "=", "self", ".", "design_matrix", ".", "sum", "(", "axis", "=", "0", ")", "!=", ...
calculate_rsq calculates coefficient of determination, or r-squared, defined here as 1.0 - SS_res / SS_tot. rsq is only calculated for those timepoints in the data for which the design matrix is non-zero.
[ "calculate_rsq", "calculates", "coefficient", "of", "determination", "or", "r", "-", "squared", "defined", "here", "as", "1", ".", "0", "-", "SS_res", "/", "SS_tot", ".", "rsq", "is", "only", "calculated", "for", "those", "timepoints", "in", "the", "data", ...
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L300-L310
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.bootstrap_on_residuals
def bootstrap_on_residuals(self, nr_repetitions = 1000): """bootstrap_on_residuals bootstraps, by shuffling the residuals. bootstrap_on_residuals should only be used on single-channel data, as otherwise the memory load might increase too much. This uses the lstsq backend regression for a single-pass fit across ...
python
def bootstrap_on_residuals(self, nr_repetitions = 1000): """bootstrap_on_residuals bootstraps, by shuffling the residuals. bootstrap_on_residuals should only be used on single-channel data, as otherwise the memory load might increase too much. This uses the lstsq backend regression for a single-pass fit across ...
[ "def", "bootstrap_on_residuals", "(", "self", ",", "nr_repetitions", "=", "1000", ")", ":", "assert", "self", ".", "resampled_signal", ".", "shape", "[", "0", "]", "==", "1", ",", "'signal input into bootstrap_on_residuals cannot contain signals from multiple channels at ...
bootstrap_on_residuals bootstraps, by shuffling the residuals. bootstrap_on_residuals should only be used on single-channel data, as otherwise the memory load might increase too much. This uses the lstsq backend regression for a single-pass fit across repetitions. Please note that shuffling the residuals may change the...
[ "bootstrap_on_residuals", "bootstraps", "by", "shuffling", "the", "residuals", ".", "bootstrap_on_residuals", "should", "only", "be", "used", "on", "single", "-", "channel", "data", "as", "otherwise", "the", "memory", "load", "might", "increase", "too", "much", "....
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L312-L337
cga-harvard/Hypermap-Registry
hypermap/context_processors.py
resource_urls
def resource_urls(request): """Global values to pass to templates""" url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__version__, SITE_URL=settings.SITE_URL.rstrip('/'), SEARCH_TYPE=settings.SEARCH_TYPE, SEARCH_URL=se...
python
def resource_urls(request): """Global values to pass to templates""" url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__version__, SITE_URL=settings.SITE_URL.rstrip('/'), SEARCH_TYPE=settings.SEARCH_TYPE, SEARCH_URL=se...
[ "def", "resource_urls", "(", "request", ")", ":", "url_parsed", "=", "urlparse", "(", "settings", ".", "SEARCH_URL", ")", "defaults", "=", "dict", "(", "APP_NAME", "=", "__description__", ",", "APP_VERSION", "=", "__version__", ",", "SITE_URL", "=", "settings"...
Global values to pass to templates
[ "Global", "values", "to", "pass", "to", "templates" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/context_processors.py#L7-L19
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
index_cached_layers
def index_cached_layers(self): """ Index and unindex all layers in the Django cache (Index all layers who have been checked). """ from hypermap.aggregator.models import Layer if SEARCH_TYPE == 'solr': from hypermap.aggregator.solr import SolrHypermap solrobject = SolrHypermap() ...
python
def index_cached_layers(self): """ Index and unindex all layers in the Django cache (Index all layers who have been checked). """ from hypermap.aggregator.models import Layer if SEARCH_TYPE == 'solr': from hypermap.aggregator.solr import SolrHypermap solrobject = SolrHypermap() ...
[ "def", "index_cached_layers", "(", "self", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Layer", "if", "SEARCH_TYPE", "==", "'solr'", ":", "from", "hypermap", ".", "aggregator", ".", "solr", "import", "SolrHypermap", "solrobject", ...
Index and unindex all layers in the Django cache (Index all layers who have been checked).
[ "Index", "and", "unindex", "all", "layers", "in", "the", "Django", "cache", "(", "Index", "all", "layers", "who", "have", "been", "checked", ")", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L94-L177
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
remove_service_checks
def remove_service_checks(self, service_id): """ Remove all checks from a service. """ from hypermap.aggregator.models import Service service = Service.objects.get(id=service_id) service.check_set.all().delete() layer_to_process = service.layer_set.all() for layer in layer_to_process: ...
python
def remove_service_checks(self, service_id): """ Remove all checks from a service. """ from hypermap.aggregator.models import Service service = Service.objects.get(id=service_id) service.check_set.all().delete() layer_to_process = service.layer_set.all() for layer in layer_to_process: ...
[ "def", "remove_service_checks", "(", "self", ",", "service_id", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Service", "service", "=", "Service", ".", "objects", ".", "get", "(", "id", "=", "service_id", ")", "service", ".", "...
Remove all checks from a service.
[ "Remove", "all", "checks", "from", "a", "service", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L195-L205
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
index_service
def index_service(self, service_id): """ Index a service in search engine. """ from hypermap.aggregator.models import Service service = Service.objects.get(id=service_id) if not service.is_valid: LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % servi...
python
def index_service(self, service_id): """ Index a service in search engine. """ from hypermap.aggregator.models import Service service = Service.objects.get(id=service_id) if not service.is_valid: LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % servi...
[ "def", "index_service", "(", "self", ",", "service_id", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Service", "service", "=", "Service", ".", "objects", ".", "get", "(", "id", "=", "service_id", ")", "if", "not", "service", ...
Index a service in search engine.
[ "Index", "a", "service", "in", "search", "engine", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L209-L228
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
index_layer
def index_layer(self, layer_id, use_cache=False): """ Index a layer in the search backend. If cache is set, append it to the list, if it isn't send the transaction right away. cache needs memcached to be available. """ from hypermap.aggregator.models import Layer layer = Layer.objects.get(i...
python
def index_layer(self, layer_id, use_cache=False): """ Index a layer in the search backend. If cache is set, append it to the list, if it isn't send the transaction right away. cache needs memcached to be available. """ from hypermap.aggregator.models import Layer layer = Layer.objects.get(i...
[ "def", "index_layer", "(", "self", ",", "layer_id", ",", "use_cache", "=", "False", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Layer", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "id", "=", "layer_id", ")", "...
Index a layer in the search backend. If cache is set, append it to the list, if it isn't send the transaction right away. cache needs memcached to be available.
[ "Index", "a", "layer", "in", "the", "search", "backend", ".", "If", "cache", "is", "set", "append", "it", "to", "the", "list", "if", "it", "isn", "t", "send", "the", "transaction", "right", "away", ".", "cache", "needs", "memcached", "to", "be", "avail...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L232-L291
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
unindex_layers_with_issues
def unindex_layers_with_issues(self, use_cache=False): """ Remove the index for layers in search backend, which are linked to an issue. """ from hypermap.aggregator.models import Issue, Layer, Service from django.contrib.contenttypes.models import ContentType layer_type = ContentType.objects.ge...
python
def unindex_layers_with_issues(self, use_cache=False): """ Remove the index for layers in search backend, which are linked to an issue. """ from hypermap.aggregator.models import Issue, Layer, Service from django.contrib.contenttypes.models import ContentType layer_type = ContentType.objects.ge...
[ "def", "unindex_layers_with_issues", "(", "self", ",", "use_cache", "=", "False", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Issue", ",", "Layer", ",", "Service", "from", "django", ".", "contrib", ".", "contenttypes", ".", "mo...
Remove the index for layers in search backend, which are linked to an issue.
[ "Remove", "the", "index", "for", "layers", "in", "search", "backend", "which", "are", "linked", "to", "an", "issue", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L295-L310
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
unindex_layer
def unindex_layer(self, layer_id, use_cache=False): """ Remove the index for a layer in the search backend. If cache is set, append it to the list of removed layers, if it isn't send the transaction right away. """ from hypermap.aggregator.models import Layer layer = Layer.objects.get(id=layer_...
python
def unindex_layer(self, layer_id, use_cache=False): """ Remove the index for a layer in the search backend. If cache is set, append it to the list of removed layers, if it isn't send the transaction right away. """ from hypermap.aggregator.models import Layer layer = Layer.objects.get(id=layer_...
[ "def", "unindex_layer", "(", "self", ",", "layer_id", ",", "use_cache", "=", "False", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Layer", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "id", "=", "layer_id", ")", ...
Remove the index for a layer in the search backend. If cache is set, append it to the list of removed layers, if it isn't send the transaction right away.
[ "Remove", "the", "index", "for", "a", "layer", "in", "the", "search", "backend", ".", "If", "cache", "is", "set", "append", "it", "to", "the", "list", "of", "removed", "layers", "if", "it", "isn", "t", "send", "the", "transaction", "right", "away", "."...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L314-L343
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
index_all_layers
def index_all_layers(self): """ Index all layers in search engine. """ from hypermap.aggregator.models import Layer if not settings.REGISTRY_SKIP_CELERY: layers_cache = set(Layer.objects.filter(is_valid=True).values_list('id', flat=True)) deleted_layers_cache = set(Layer.objects.fil...
python
def index_all_layers(self): """ Index all layers in search engine. """ from hypermap.aggregator.models import Layer if not settings.REGISTRY_SKIP_CELERY: layers_cache = set(Layer.objects.filter(is_valid=True).values_list('id', flat=True)) deleted_layers_cache = set(Layer.objects.fil...
[ "def", "index_all_layers", "(", "self", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Layer", "if", "not", "settings", ".", "REGISTRY_SKIP_CELERY", ":", "layers_cache", "=", "set", "(", "Layer", ".", "objects", ".", "filter", "("...
Index all layers in search engine.
[ "Index", "all", "layers", "in", "search", "engine", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L347-L360
cga-harvard/Hypermap-Registry
hypermap/aggregator/tasks.py
update_last_wm_layers
def update_last_wm_layers(self, service_id, num_layers=10): """ Update and index the last added and deleted layers (num_layers) in WorldMap service. """ from hypermap.aggregator.models import Service LOGGER.debug( 'Updating the index the last %s added and %s deleted layers in WorldMap servi...
python
def update_last_wm_layers(self, service_id, num_layers=10): """ Update and index the last added and deleted layers (num_layers) in WorldMap service. """ from hypermap.aggregator.models import Service LOGGER.debug( 'Updating the index the last %s added and %s deleted layers in WorldMap servi...
[ "def", "update_last_wm_layers", "(", "self", ",", "service_id", ",", "num_layers", "=", "10", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Service", "LOGGER", ".", "debug", "(", "'Updating the index the last %s added and %s deleted layers...
Update and index the last added and deleted layers (num_layers) in WorldMap service.
[ "Update", "and", "index", "the", "last", "added", "and", "deleted", "layers", "(", "num_layers", ")", "in", "WorldMap", "service", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/tasks.py#L364-L399
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
bbox2wktpolygon
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list """ try: minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) except: LOGGER.debug("Invalid bbox, setting it to a zero POLYGON") minx = 0 ...
python
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list """ try: minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) except: LOGGER.debug("Invalid bbox, setting it to a zero POLYGON") minx = 0 ...
[ "def", "bbox2wktpolygon", "(", "bbox", ")", ":", "try", ":", "minx", "=", "float", "(", "bbox", "[", "0", "]", ")", "miny", "=", "float", "(", "bbox", "[", "1", "]", ")", "maxx", "=", "float", "(", "bbox", "[", "2", "]", ")", "maxy", "=", "fl...
Return OGC WKT Polygon of a simple bbox list
[ "Return", "OGC", "WKT", "Polygon", "of", "a", "simple", "bbox", "list" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L975-L994
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
create_metadata_record
def create_metadata_record(**kwargs): """ Create a csw:Record XML document from harvested metadata """ if 'srs' in kwargs: srs = kwargs['srs'] else: srs = '4326' modified = '%sZ' % datetime.datetime.utcnow().isoformat().split('.')[0] nsmap = Namespaces().get_namespaces(['c...
python
def create_metadata_record(**kwargs): """ Create a csw:Record XML document from harvested metadata """ if 'srs' in kwargs: srs = kwargs['srs'] else: srs = '4326' modified = '%sZ' % datetime.datetime.utcnow().isoformat().split('.')[0] nsmap = Namespaces().get_namespaces(['c...
[ "def", "create_metadata_record", "(", "*", "*", "kwargs", ")", ":", "if", "'srs'", "in", "kwargs", ":", "srs", "=", "kwargs", "[", "'srs'", "]", "else", ":", "srs", "=", "'4326'", "modified", "=", "'%sZ'", "%", "datetime", ".", "datetime", ".", "utcnow...
Create a csw:Record XML document from harvested metadata
[ "Create", "a", "csw", ":", "Record", "XML", "document", "from", "harvested", "metadata" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L997-L1042
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
gen_anytext
def gen_anytext(*args): """ Convenience function to create bag of words for anytext property """ bag = [] for term in args: if term is not None: if isinstance(term, list): for term2 in term: if term2 is not None: bag.a...
python
def gen_anytext(*args): """ Convenience function to create bag of words for anytext property """ bag = [] for term in args: if term is not None: if isinstance(term, list): for term2 in term: if term2 is not None: bag.a...
[ "def", "gen_anytext", "(", "*", "args", ")", ":", "bag", "=", "[", "]", "for", "term", "in", "args", ":", "if", "term", "is", "not", "None", ":", "if", "isinstance", "(", "term", ",", "list", ")", ":", "for", "term2", "in", "term", ":", "if", "...
Convenience function to create bag of words for anytext property
[ "Convenience", "function", "to", "create", "bag", "of", "words", "for", "anytext", "property" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1045-L1060
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
update_layers_wmts
def update_layers_wmts(service): """ Update layers for an OGC:WMTS service. Sample endpoint: http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml """ try: wmts = WebMapTileService(service.url) # set srs # WMTS is always in 4326 srs, created = Spatia...
python
def update_layers_wmts(service): """ Update layers for an OGC:WMTS service. Sample endpoint: http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml """ try: wmts = WebMapTileService(service.url) # set srs # WMTS is always in 4326 srs, created = Spatia...
[ "def", "update_layers_wmts", "(", "service", ")", ":", "try", ":", "wmts", "=", "WebMapTileService", "(", "service", ".", "url", ")", "# set srs", "# WMTS is always in 4326", "srs", ",", "created", "=", "SpatialReferenceSystem", ".", "objects", ".", "get_or_create...
Update layers for an OGC:WMTS service. Sample endpoint: http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml
[ "Update", "layers", "for", "an", "OGC", ":", "WMTS", "service", ".", "Sample", "endpoint", ":", "http", ":", "//", "map1", ".", "vis", ".", "earthdata", ".", "nasa", ".", "gov", "/", "wmts", "-", "geo", "/", "1", ".", "0", ".", "0", "/", "WMTSCap...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1156-L1235
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
update_layers_geonode_wm
def update_layers_geonode_wm(service, num_layers=None): """ Update layers for a WorldMap instance. Sample endpoint: http://localhost:8000/ """ wm_api_url = urlparse.urljoin(service.url, 'worldmap/api/2.8/layer/?format=json') if num_layers: total = num_layers else: response =...
python
def update_layers_geonode_wm(service, num_layers=None): """ Update layers for a WorldMap instance. Sample endpoint: http://localhost:8000/ """ wm_api_url = urlparse.urljoin(service.url, 'worldmap/api/2.8/layer/?format=json') if num_layers: total = num_layers else: response =...
[ "def", "update_layers_geonode_wm", "(", "service", ",", "num_layers", "=", "None", ")", ":", "wm_api_url", "=", "urlparse", ".", "urljoin", "(", "service", ".", "url", ",", "'worldmap/api/2.8/layer/?format=json'", ")", "if", "num_layers", ":", "total", "=", "num...
Update layers for a WorldMap instance. Sample endpoint: http://localhost:8000/
[ "Update", "layers", "for", "a", "WorldMap", "instance", ".", "Sample", "endpoint", ":", "http", ":", "//", "localhost", ":", "8000", "/" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1238-L1390
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
update_layers_warper
def update_layers_warper(service): """ Update layers for a Warper service. Sample endpoint: http://warp.worldmap.harvard.edu/maps """ params = {'field': 'title', 'query': '', 'show_warped': '1', 'format': 'json'} headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} re...
python
def update_layers_warper(service): """ Update layers for a Warper service. Sample endpoint: http://warp.worldmap.harvard.edu/maps """ params = {'field': 'title', 'query': '', 'show_warped': '1', 'format': 'json'} headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} re...
[ "def", "update_layers_warper", "(", "service", ")", ":", "params", "=", "{", "'field'", ":", "'title'", ",", "'query'", ":", "''", ",", "'show_warped'", ":", "'1'", ",", "'format'", ":", "'json'", "}", "headers", "=", "{", "'Content-Type'", ":", "'applicat...
Update layers for a Warper service. Sample endpoint: http://warp.worldmap.harvard.edu/maps
[ "Update", "layers", "for", "a", "Warper", "service", ".", "Sample", "endpoint", ":", "http", ":", "//", "warp", ".", "worldmap", ".", "harvard", ".", "edu", "/", "maps" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1541-L1632
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
update_layers_esri_mapserver
def update_layers_esri_mapserver(service, greedy_opt=False): """ Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json """ try: esri_service = ArcMapService(service.url) # set srs # both m...
python
def update_layers_esri_mapserver(service, greedy_opt=False): """ Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json """ try: esri_service = ArcMapService(service.url) # set srs # both m...
[ "def", "update_layers_esri_mapserver", "(", "service", ",", "greedy_opt", "=", "False", ")", ":", "try", ":", "esri_service", "=", "ArcMapService", "(", "service", ".", "url", ")", "# set srs", "# both mapserver and imageserver exposes just one srs at the service level", ...
Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json
[ "Update", "layers", "for", "an", "ESRI", "REST", "MapServer", ".", "Sample", "endpoint", ":", "https", ":", "//", "gis", ".", "ngdc", ".", "noaa", ".", "gov", "/", "arcgis", "/", "rest", "/", "services", "/", "SampleWorldCities", "/", "MapServer", "/", ...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1635-L1749
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
update_layers_esri_imageserver
def update_layers_esri_imageserver(service): """ Update layers for an ESRI REST ImageServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/bag_bathymetry/ImageServer/?f=json """ try: esri_service = ArcImageService(service.url) # set srs # both mapserver and ...
python
def update_layers_esri_imageserver(service): """ Update layers for an ESRI REST ImageServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/bag_bathymetry/ImageServer/?f=json """ try: esri_service = ArcImageService(service.url) # set srs # both mapserver and ...
[ "def", "update_layers_esri_imageserver", "(", "service", ")", ":", "try", ":", "esri_service", "=", "ArcImageService", "(", "service", ".", "url", ")", "# set srs", "# both mapserver and imageserver exposes just one srs at the service level", "# not sure if other ones are support...
Update layers for an ESRI REST ImageServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/bag_bathymetry/ImageServer/?f=json
[ "Update", "layers", "for", "an", "ESRI", "REST", "ImageServer", ".", "Sample", "endpoint", ":", "https", ":", "//", "gis", ".", "ngdc", ".", "noaa", ".", "gov", "/", "arcgis", "/", "rest", "/", "services", "/", "bag_bathymetry", "/", "ImageServer", "/", ...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1752-L1813
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
endpointlist_post_save
def endpointlist_post_save(instance, *args, **kwargs): """ Used to process the lines of the endpoint list. """ with open(instance.upload.file.name, mode='rb') as f: lines = f.readlines() for url in lines: if len(url) > 255: LOGGER.debug('Skipping this endpoint, as it is m...
python
def endpointlist_post_save(instance, *args, **kwargs): """ Used to process the lines of the endpoint list. """ with open(instance.upload.file.name, mode='rb') as f: lines = f.readlines() for url in lines: if len(url) > 255: LOGGER.debug('Skipping this endpoint, as it is m...
[ "def", "endpointlist_post_save", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "instance", ".", "upload", ".", "file", ".", "name", ",", "mode", "=", "'rb'", ")", "as", "f", ":", "lines", "=", "f", ".", ...
Used to process the lines of the endpoint list.
[ "Used", "to", "process", "the", "lines", "of", "the", "endpoint", "list", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1818-L1835
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
service_pre_save
def service_pre_save(instance, *args, **kwargs): """ Used to do a service full check when saving it. """ # check if service is unique # we cannot use unique_together as it relies on a combination of fields # from different models (service, resource) exists = Service.objects.filter(url=insta...
python
def service_pre_save(instance, *args, **kwargs): """ Used to do a service full check when saving it. """ # check if service is unique # we cannot use unique_together as it relies on a combination of fields # from different models (service, resource) exists = Service.objects.filter(url=insta...
[ "def", "service_pre_save", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check if service is unique", "# we cannot use unique_together as it relies on a combination of fields", "# from different models (service, resource)", "exists", "=", "Service", "...
Used to do a service full check when saving it.
[ "Used", "to", "do", "a", "service", "full", "check", "when", "saving", "it", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1851-L1868
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
service_post_save
def service_post_save(instance, *args, **kwargs): """ Used to do a service full check when saving it. """ # check service if instance.is_monitored and settings.REGISTRY_SKIP_CELERY: check_service(instance.id) elif instance.is_monitored: check_service.delay(instance.id)
python
def service_post_save(instance, *args, **kwargs): """ Used to do a service full check when saving it. """ # check service if instance.is_monitored and settings.REGISTRY_SKIP_CELERY: check_service(instance.id) elif instance.is_monitored: check_service.delay(instance.id)
[ "def", "service_post_save", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check service", "if", "instance", ".", "is_monitored", "and", "settings", ".", "REGISTRY_SKIP_CELERY", ":", "check_service", "(", "instance", ".", "id", ")", ...
Used to do a service full check when saving it.
[ "Used", "to", "do", "a", "service", "full", "check", "when", "saving", "it", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1871-L1880
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
layer_pre_save
def layer_pre_save(instance, *args, **kwargs): """ Used to check layer validity. """ is_valid = True # we do not need to check validity for WM layers if not instance.service.type == 'Hypermap:WorldMap': # 0. a layer is invalid if its service its invalid as well if not instance...
python
def layer_pre_save(instance, *args, **kwargs): """ Used to check layer validity. """ is_valid = True # we do not need to check validity for WM layers if not instance.service.type == 'Hypermap:WorldMap': # 0. a layer is invalid if its service its invalid as well if not instance...
[ "def", "layer_pre_save", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "is_valid", "=", "True", "# we do not need to check validity for WM layers", "if", "not", "instance", ".", "service", ".", "type", "==", "'Hypermap:WorldMap'", ":", "#...
Used to check layer validity.
[ "Used", "to", "check", "layer", "validity", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1883-L1905
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
layer_post_save
def layer_post_save(instance, *args, **kwargs): """ Used to do a layer full check when saving it. """ if instance.is_monitored and instance.service.is_monitored: # index and monitor if not settings.REGISTRY_SKIP_CELERY: check_layer.delay(instance.id) else: check_...
python
def layer_post_save(instance, *args, **kwargs): """ Used to do a layer full check when saving it. """ if instance.is_monitored and instance.service.is_monitored: # index and monitor if not settings.REGISTRY_SKIP_CELERY: check_layer.delay(instance.id) else: check_...
[ "def", "layer_post_save", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "is_monitored", "and", "instance", ".", "service", ".", "is_monitored", ":", "# index and monitor", "if", "not", "settings", ".", "REGISTRY...
Used to do a layer full check when saving it.
[ "Used", "to", "do", "a", "layer", "full", "check", "when", "saving", "it", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1908-L1918
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
issue_post_delete
def issue_post_delete(instance, *args, **kwargs): """ Used to do reindex layers/services when a issue is removed form them. """ LOGGER.debug('Re-adding layer/service to search engine index') if isinstance(instance.content_object, Service): if not settings.REGISTRY_SKIP_CELERY: in...
python
def issue_post_delete(instance, *args, **kwargs): """ Used to do reindex layers/services when a issue is removed form them. """ LOGGER.debug('Re-adding layer/service to search engine index') if isinstance(instance.content_object, Service): if not settings.REGISTRY_SKIP_CELERY: in...
[ "def", "issue_post_delete", "(", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "'Re-adding layer/service to search engine index'", ")", "if", "isinstance", "(", "instance", ".", "content_object", ",", "Service", ")...
Used to do reindex layers/services when a issue is removed form them.
[ "Used", "to", "do", "reindex", "layers", "/", "services", "when", "a", "issue", "is", "removed", "form", "them", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L1921-L1935
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Resource.get_checks_admin_reliability_warning_url
def get_checks_admin_reliability_warning_url(self): """ When service Realiability is going down users should go to the the check history to find problem causes. :return: admin url with check list for this instance """ # TODO: cache this. path = self.get_checks_adm...
python
def get_checks_admin_reliability_warning_url(self): """ When service Realiability is going down users should go to the the check history to find problem causes. :return: admin url with check list for this instance """ # TODO: cache this. path = self.get_checks_adm...
[ "def", "get_checks_admin_reliability_warning_url", "(", "self", ")", ":", "# TODO: cache this.", "path", "=", "self", ".", "get_checks_admin_url", "(", ")", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ")", "params", "=", ...
When service Realiability is going down users should go to the the check history to find problem causes. :return: admin url with check list for this instance
[ "When", "service", "Realiability", "is", "going", "down", "users", "should", "go", "to", "the", "the", "check", "history", "to", "find", "problem", "causes", ".", ":", "return", ":", "admin", "url", "with", "check", "list", "for", "this", "instance" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L261-L275
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Service.update_layers
def update_layers(self): """ Update layers for a service. """ signals.post_save.disconnect(layer_post_save, sender=Layer) try: LOGGER.debug('Updating layers for service id %s' % self.id) if self.type == 'OGC:WMS': update_layers_wms(self) ...
python
def update_layers(self): """ Update layers for a service. """ signals.post_save.disconnect(layer_post_save, sender=Layer) try: LOGGER.debug('Updating layers for service id %s' % self.id) if self.type == 'OGC:WMS': update_layers_wms(self) ...
[ "def", "update_layers", "(", "self", ")", ":", "signals", ".", "post_save", ".", "disconnect", "(", "layer_post_save", ",", "sender", "=", "Layer", ")", "try", ":", "LOGGER", ".", "debug", "(", "'Updating layers for service id %s'", "%", "self", ".", "id", "...
Update layers for a service.
[ "Update", "layers", "for", "a", "service", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L309-L336
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Service.check_available
def check_available(self): """ Check for availability of a service and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking service id %s' % self.id) try: title = None ...
python
def check_available(self): """ Check for availability of a service and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking service id %s' % self.id) try: title = None ...
[ "def", "check_available", "(", "self", ")", ":", "success", "=", "True", "start_time", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "message", "=", "''", "LOGGER", ".", "debug", "(", "'Checking service id %s'", "%", "self", ".", "id", ")", ...
Check for availability of a service and provide run metrics.
[ "Check", "for", "availability", "of", "a", "service", "and", "provide", "run", "metrics", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L338-L453
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Service.update_validity
def update_validity(self): """ Update validity of a service. """ # WM is always valid if self.type == 'Hypermap:WorldMap': return signals.post_save.disconnect(service_post_save, sender=Service) try: # some service now must be considered...
python
def update_validity(self): """ Update validity of a service. """ # WM is always valid if self.type == 'Hypermap:WorldMap': return signals.post_save.disconnect(service_post_save, sender=Service) try: # some service now must be considered...
[ "def", "update_validity", "(", "self", ")", ":", "# WM is always valid", "if", "self", ".", "type", "==", "'Hypermap:WorldMap'", ":", "return", "signals", ".", "post_save", ".", "disconnect", "(", "service_post_save", ",", "sender", "=", "Service", ")", "try", ...
Update validity of a service.
[ "Update", "validity", "of", "a", "service", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L455-L497
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Catalog.get_search_url
def get_search_url(self): """ resolve the search url no matter if local or remote. :return: url or exception """ if self.is_remote: return self.url return reverse('search_api', args=[self.slug])
python
def get_search_url(self): """ resolve the search url no matter if local or remote. :return: url or exception """ if self.is_remote: return self.url return reverse('search_api', args=[self.slug])
[ "def", "get_search_url", "(", "self", ")", ":", "if", "self", ".", "is_remote", ":", "return", "self", ".", "url", "return", "reverse", "(", "'search_api'", ",", "args", "=", "[", "self", ".", "slug", "]", ")" ]
resolve the search url no matter if local or remote. :return: url or exception
[ "resolve", "the", "search", "url", "no", "matter", "if", "local", "or", "remote", ".", ":", "return", ":", "url", "or", "exception" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L525-L534
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Layer.get_url_endpoint
def get_url_endpoint(self): """ Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint. """ endpoint = self.url if self.type not in ('Hypermap:WorldMap',): endpoint = 'registry/%s/l...
python
def get_url_endpoint(self): """ Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint. """ endpoint = self.url if self.type not in ('Hypermap:WorldMap',): endpoint = 'registry/%s/l...
[ "def", "get_url_endpoint", "(", "self", ")", ":", "endpoint", "=", "self", ".", "url", "if", "self", ".", "type", "not", "in", "(", "'Hypermap:WorldMap'", ",", ")", ":", "endpoint", "=", "'registry/%s/layer/%s/map/wmts/1.0.0/WMTSCapabilities.xml'", "%", "(", "se...
Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint.
[ "Returns", "the", "Hypermap", "endpoint", "for", "a", "layer", ".", "This", "endpoint", "will", "be", "the", "WMTS", "MapProxy", "endpoint", "only", "for", "WM", "we", "use", "the", "original", "endpoint", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L573-L584
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Layer.check_available
def check_available(self): """ Check for availability of a layer and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking layer id %s' % self.id) signals.post_save.disconnect(layer_post_save, ...
python
def check_available(self): """ Check for availability of a layer and provide run metrics. """ success = True start_time = datetime.datetime.utcnow() message = '' LOGGER.debug('Checking layer id %s' % self.id) signals.post_save.disconnect(layer_post_save, ...
[ "def", "check_available", "(", "self", ")", ":", "success", "=", "True", "start_time", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "message", "=", "''", "LOGGER", ".", "debug", "(", "'Checking layer id %s'", "%", "self", ".", "id", ")", "s...
Check for availability of a layer and provide run metrics.
[ "Check", "for", "availability", "of", "a", "layer", "and", "provide", "run", "metrics", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L800-L837
cga-harvard/Hypermap-Registry
hypermap/aggregator/models.py
Layer.registry_tags
def registry_tags(self, query_string='{http://gis.harvard.edu/HHypermap/registry/0.1}property'): """ Get extra metadata tagged with a registry keyword. For example: <registry:property name="nomination/serviceOwner" value="True"/> <registry:property name="nominator/name" v...
python
def registry_tags(self, query_string='{http://gis.harvard.edu/HHypermap/registry/0.1}property'): """ Get extra metadata tagged with a registry keyword. For example: <registry:property name="nomination/serviceOwner" value="True"/> <registry:property name="nominator/name" v...
[ "def", "registry_tags", "(", "self", ",", "query_string", "=", "'{http://gis.harvard.edu/HHypermap/registry/0.1}property'", ")", ":", "from", "pycsw", ".", "core", ".", "etree", "import", "etree", "parsed", "=", "etree", ".", "fromstring", "(", "self", ".", "xml",...
Get extra metadata tagged with a registry keyword. For example: <registry:property name="nomination/serviceOwner" value="True"/> <registry:property name="nominator/name" value="Random Person"/> <registry:property name="nominator/email" value="contact@example.com"/> ...
[ "Get", "extra", "metadata", "tagged", "with", "a", "registry", "keyword", ".", "For", "example", ":", "<registry", ":", "property", "name", "=", "nomination", "/", "serviceOwner", "value", "=", "True", "/", ">", "<registry", ":", "property", "name", "=", "...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/models.py#L839-L879
sethmlarson/trytravis
trytravis.py
_input_github_repo
def _input_github_repo(url=None): """ Grabs input from the user and saves it as their trytravis target repo """ if url is None: url = user_input('Input the URL of the GitHub repository ' 'to use as a `trytravis` repository: ') url = url.strip() http_match = _HTTPS_RE...
python
def _input_github_repo(url=None): """ Grabs input from the user and saves it as their trytravis target repo """ if url is None: url = user_input('Input the URL of the GitHub repository ' 'to use as a `trytravis` repository: ') url = url.strip() http_match = _HTTPS_RE...
[ "def", "_input_github_repo", "(", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "user_input", "(", "'Input the URL of the GitHub repository '", "'to use as a `trytravis` repository: '", ")", "url", "=", "url", ".", "strip", "(", ")", ...
Grabs input from the user and saves it as their trytravis target repo
[ "Grabs", "input", "from", "the", "user", "and", "saves", "it", "as", "their", "trytravis", "target", "repo" ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L86-L125
sethmlarson/trytravis
trytravis.py
_load_github_repo
def _load_github_repo(): """ Loads the GitHub repository from the users config. """ if 'TRAVIS' in os.environ: raise RuntimeError('Detected that we are running in Travis. ' 'Stopping to prevent infinite loops.') try: with open(os.path.join(config_dir, 'repo'), 'r')...
python
def _load_github_repo(): """ Loads the GitHub repository from the users config. """ if 'TRAVIS' in os.environ: raise RuntimeError('Detected that we are running in Travis. ' 'Stopping to prevent infinite loops.') try: with open(os.path.join(config_dir, 'repo'), 'r')...
[ "def", "_load_github_repo", "(", ")", ":", "if", "'TRAVIS'", "in", "os", ".", "environ", ":", "raise", "RuntimeError", "(", "'Detected that we are running in Travis. '", "'Stopping to prevent infinite loops.'", ")", "try", ":", "with", "open", "(", "os", ".", "path"...
Loads the GitHub repository from the users config.
[ "Loads", "the", "GitHub", "repository", "from", "the", "users", "config", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L128-L138
sethmlarson/trytravis
trytravis.py
_submit_changes_to_github_repo
def _submit_changes_to_github_repo(path, url): """ Temporarily commits local changes and submits them to the GitHub repository that the user has specified. Then reverts the changes to the git repository if a commit was necessary. """ try: repo = git.Repo(path) except Exception: r...
python
def _submit_changes_to_github_repo(path, url): """ Temporarily commits local changes and submits them to the GitHub repository that the user has specified. Then reverts the changes to the git repository if a commit was necessary. """ try: repo = git.Repo(path) except Exception: r...
[ "def", "_submit_changes_to_github_repo", "(", "path", ",", "url", ")", ":", "try", ":", "repo", "=", "git", ".", "Repo", "(", "path", ")", "except", "Exception", ":", "raise", "RuntimeError", "(", "'Couldn\\'t locate a repository at `%s`.'", "%", "path", ")", ...
Temporarily commits local changes and submits them to the GitHub repository that the user has specified. Then reverts the changes to the git repository if a commit was necessary.
[ "Temporarily", "commits", "local", "changes", "and", "submits", "them", "to", "the", "GitHub", "repository", "that", "the", "user", "has", "specified", ".", "Then", "reverts", "the", "changes", "to", "the", "git", "repository", "if", "a", "commit", "was", "n...
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L141-L185
sethmlarson/trytravis
trytravis.py
_wait_for_travis_build
def _wait_for_travis_build(url, commit, committed_at): """ Waits for a Travis build to appear with the given commit SHA """ print('Waiting for a Travis build to appear ' 'for `%s` after `%s`...' % (commit, committed_at)) import requests slug = _slug_from_url(url) start_time = time.time() ...
python
def _wait_for_travis_build(url, commit, committed_at): """ Waits for a Travis build to appear with the given commit SHA """ print('Waiting for a Travis build to appear ' 'for `%s` after `%s`...' % (commit, committed_at)) import requests slug = _slug_from_url(url) start_time = time.time() ...
[ "def", "_wait_for_travis_build", "(", "url", ",", "commit", ",", "committed_at", ")", ":", "print", "(", "'Waiting for a Travis build to appear '", "'for `%s` after `%s`...'", "%", "(", "commit", ",", "committed_at", ")", ")", "import", "requests", "slug", "=", "_sl...
Waits for a Travis build to appear with the given commit SHA
[ "Waits", "for", "a", "Travis", "build", "to", "appear", "with", "the", "given", "commit", "SHA" ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L188-L234
sethmlarson/trytravis
trytravis.py
_watch_travis_build
def _watch_travis_build(build_id): """ Watches and progressively outputs information about a given Travis build """ import requests try: build_size = None # type: int running = True while running: with requests.get('https://api.travis-ci.org/builds/%d' % build_id, ...
python
def _watch_travis_build(build_id): """ Watches and progressively outputs information about a given Travis build """ import requests try: build_size = None # type: int running = True while running: with requests.get('https://api.travis-ci.org/builds/%d' % build_id, ...
[ "def", "_watch_travis_build", "(", "build_id", ")", ":", "import", "requests", "try", ":", "build_size", "=", "None", "# type: int", "running", "=", "True", "while", "running", ":", "with", "requests", ".", "get", "(", "'https://api.travis-ci.org/builds/%d'", "%",...
Watches and progressively outputs information about a given Travis build
[ "Watches", "and", "progressively", "outputs", "information", "about", "a", "given", "Travis", "build" ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L237-L286
sethmlarson/trytravis
trytravis.py
_travis_job_state
def _travis_job_state(state): """ Converts a Travis state into a state character, color, and whether it's still running or a stopped state. """ if state in [None, 'queued', 'created', 'received']: return colorama.Fore.YELLOW, '*', True elif state in ['started', 'running']: return coloram...
python
def _travis_job_state(state): """ Converts a Travis state into a state character, color, and whether it's still running or a stopped state. """ if state in [None, 'queued', 'created', 'received']: return colorama.Fore.YELLOW, '*', True elif state in ['started', 'running']: return coloram...
[ "def", "_travis_job_state", "(", "state", ")", ":", "if", "state", "in", "[", "None", ",", "'queued'", ",", "'created'", ",", "'received'", "]", ":", "return", "colorama", ".", "Fore", ".", "YELLOW", ",", "'*'", ",", "True", "elif", "state", "in", "[",...
Converts a Travis state into a state character, color, and whether it's still running or a stopped state.
[ "Converts", "a", "Travis", "state", "into", "a", "state", "character", "color", "and", "whether", "it", "s", "still", "running", "or", "a", "stopped", "state", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L289-L305
sethmlarson/trytravis
trytravis.py
_slug_from_url
def _slug_from_url(url): """ Parses a project slug out of either an HTTPS or SSH URL. """ http_match = _HTTPS_REGEX.match(url) ssh_match = _SSH_REGEX.match(url) if not http_match and not ssh_match: raise RuntimeError('Could not parse the URL (`%s`) ' 'for your reposito...
python
def _slug_from_url(url): """ Parses a project slug out of either an HTTPS or SSH URL. """ http_match = _HTTPS_REGEX.match(url) ssh_match = _SSH_REGEX.match(url) if not http_match and not ssh_match: raise RuntimeError('Could not parse the URL (`%s`) ' 'for your reposito...
[ "def", "_slug_from_url", "(", "url", ")", ":", "http_match", "=", "_HTTPS_REGEX", ".", "match", "(", "url", ")", "ssh_match", "=", "_SSH_REGEX", ".", "match", "(", "url", ")", "if", "not", "http_match", "and", "not", "ssh_match", ":", "raise", "RuntimeErro...
Parses a project slug out of either an HTTPS or SSH URL.
[ "Parses", "a", "project", "slug", "out", "of", "either", "an", "HTTPS", "or", "SSH", "URL", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L308-L318
sethmlarson/trytravis
trytravis.py
_version_string
def _version_string(): """ Gets the output for `trytravis --version`. """ platform_system = platform.system() if platform_system == 'Linux': os_name, os_version, _ = platform.dist() else: os_name = platform_system os_version = platform.version() python_version = platform.pyth...
python
def _version_string(): """ Gets the output for `trytravis --version`. """ platform_system = platform.system() if platform_system == 'Linux': os_name, os_version, _ = platform.dist() else: os_name = platform_system os_version = platform.version() python_version = platform.pyth...
[ "def", "_version_string", "(", ")", ":", "platform_system", "=", "platform", ".", "system", "(", ")", "if", "platform_system", "==", "'Linux'", ":", "os_name", ",", "os_version", ",", "_", "=", "platform", ".", "dist", "(", ")", "else", ":", "os_name", "...
Gets the output for `trytravis --version`.
[ "Gets", "the", "output", "for", "trytravis", "--", "version", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L321-L333
sethmlarson/trytravis
trytravis.py
_main
def _main(argv): """ Function that acts just like main() except doesn't catch exceptions. """ repo_input_argv = len(argv) == 2 and argv[0] in ['--repo', '-r', '-R'] # We only support a single argv parameter. if len(argv) > 1 and not repo_input_argv: _main(['--help']) # Parse the comman...
python
def _main(argv): """ Function that acts just like main() except doesn't catch exceptions. """ repo_input_argv = len(argv) == 2 and argv[0] in ['--repo', '-r', '-R'] # We only support a single argv parameter. if len(argv) > 1 and not repo_input_argv: _main(['--help']) # Parse the comman...
[ "def", "_main", "(", "argv", ")", ":", "repo_input_argv", "=", "len", "(", "argv", ")", "==", "2", "and", "argv", "[", "0", "]", "in", "[", "'--repo'", ",", "'-r'", ",", "'-R'", "]", "# We only support a single argv parameter.", "if", "len", "(", "argv",...
Function that acts just like main() except doesn't catch exceptions.
[ "Function", "that", "acts", "just", "like", "main", "()", "except", "doesn", "t", "catch", "exceptions", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L343-L388
sethmlarson/trytravis
trytravis.py
main
def main(argv=None): # pragma: no coverage """ Main entry point when the user runs the `trytravis` command. """ try: colorama.init() if argv is None: argv = sys.argv[1:] _main(argv) except RuntimeError as e: print(colorama.Fore.RED + 'ERROR: ' + str...
python
def main(argv=None): # pragma: no coverage """ Main entry point when the user runs the `trytravis` command. """ try: colorama.init() if argv is None: argv = sys.argv[1:] _main(argv) except RuntimeError as e: print(colorama.Fore.RED + 'ERROR: ' + str...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# pragma: no coverage", "try", ":", "colorama", ".", "init", "(", ")", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "_main", "(", "argv", ")", "except", ...
Main entry point when the user runs the `trytravis` command.
[ "Main", "entry", "point", "when", "the", "user", "runs", "the", "trytravis", "command", "." ]
train
https://github.com/sethmlarson/trytravis/blob/d92ed708fe71d8db93a6df8077d23ee39ec0364e/trytravis.py#L391-L403
cga-harvard/Hypermap-Registry
hypermap/search/views.py
csw_global_dispatch
def csw_global_dispatch(request, url=None, catalog_id=None): """pycsw wrapper""" if request.user.is_authenticated(): # turn on CSW-T settings.REGISTRY_PYCSW['manager']['transactions'] = 'true' env = request.META.copy() # TODO: remove this workaround # HH should be able to pass env['wsgi....
python
def csw_global_dispatch(request, url=None, catalog_id=None): """pycsw wrapper""" if request.user.is_authenticated(): # turn on CSW-T settings.REGISTRY_PYCSW['manager']['transactions'] = 'true' env = request.META.copy() # TODO: remove this workaround # HH should be able to pass env['wsgi....
[ "def", "csw_global_dispatch", "(", "request", ",", "url", "=", "None", ",", "catalog_id", "=", "None", ")", ":", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "# turn on CSW-T", "settings", ".", "REGISTRY_PYCSW", "[", "'manager'", "]"...
pycsw wrapper
[ "pycsw", "wrapper" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/views.py#L19-L59
cga-harvard/Hypermap-Registry
hypermap/search/views.py
csw_global_dispatch_by_catalog
def csw_global_dispatch_by_catalog(request, catalog_slug): """pycsw wrapper for catalogs""" catalog = get_object_or_404(Catalog, slug=catalog_slug) if catalog: # define catalog specific settings url = settings.SITE_URL.rstrip('/') + request.path.rstrip('/') return csw_global_dispatch(requ...
python
def csw_global_dispatch_by_catalog(request, catalog_slug): """pycsw wrapper for catalogs""" catalog = get_object_or_404(Catalog, slug=catalog_slug) if catalog: # define catalog specific settings url = settings.SITE_URL.rstrip('/') + request.path.rstrip('/') return csw_global_dispatch(requ...
[ "def", "csw_global_dispatch_by_catalog", "(", "request", ",", "catalog_slug", ")", ":", "catalog", "=", "get_object_or_404", "(", "Catalog", ",", "slug", "=", "catalog_slug", ")", "if", "catalog", ":", "# define catalog specific settings", "url", "=", "settings", "....
pycsw wrapper for catalogs
[ "pycsw", "wrapper", "for", "catalogs" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/views.py#L63-L70
cga-harvard/Hypermap-Registry
hypermap/search/views.py
opensearch_dispatch
def opensearch_dispatch(request): """OpenSearch wrapper""" ctx = { 'shortname': settings.REGISTRY_PYCSW['metadata:main']['identification_title'], 'description': settings.REGISTRY_PYCSW['metadata:main']['identification_abstract'], 'developer': settings.REGISTRY_PYCSW['metadata:main']['co...
python
def opensearch_dispatch(request): """OpenSearch wrapper""" ctx = { 'shortname': settings.REGISTRY_PYCSW['metadata:main']['identification_title'], 'description': settings.REGISTRY_PYCSW['metadata:main']['identification_abstract'], 'developer': settings.REGISTRY_PYCSW['metadata:main']['co...
[ "def", "opensearch_dispatch", "(", "request", ")", ":", "ctx", "=", "{", "'shortname'", ":", "settings", ".", "REGISTRY_PYCSW", "[", "'metadata:main'", "]", "[", "'identification_title'", "]", ",", "'description'", ":", "settings", ".", "REGISTRY_PYCSW", "[", "'...
OpenSearch wrapper
[ "OpenSearch", "wrapper" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/views.py#L73-L87
cga-harvard/Hypermap-Registry
hypermap/aggregator/elasticsearch_client.py
ESHypermap.good_coords
def good_coords(coords): """ passed a string array """ if (len(coords) != 4): return False for coord in coords[0:3]: try: num = float(coord) if (math.isnan(num)): return False if (math.isinf(num)): ...
python
def good_coords(coords): """ passed a string array """ if (len(coords) != 4): return False for coord in coords[0:3]: try: num = float(coord) if (math.isnan(num)): return False if (math.isinf(num)): ...
[ "def", "good_coords", "(", "coords", ")", ":", "if", "(", "len", "(", "coords", ")", "!=", "4", ")", ":", "return", "False", "for", "coord", "in", "coords", "[", "0", ":", "3", "]", ":", "try", ":", "num", "=", "float", "(", "coord", ")", "if",...
passed a string array
[ "passed", "a", "string", "array" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/elasticsearch_client.py#L36-L49
cga-harvard/Hypermap-Registry
hypermap/aggregator/elasticsearch_client.py
ESHypermap.clear_es
def clear_es(): """Clear all indexes in the es core""" # TODO: should receive a catalog slug. ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404]) LOGGER.debug('Elasticsearch: Index cleared')
python
def clear_es(): """Clear all indexes in the es core""" # TODO: should receive a catalog slug. ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404]) LOGGER.debug('Elasticsearch: Index cleared')
[ "def", "clear_es", "(", ")", ":", "# TODO: should receive a catalog slug.", "ESHypermap", ".", "es", ".", "indices", ".", "delete", "(", "ESHypermap", ".", "index_name", ",", "ignore", "=", "[", "400", ",", "404", "]", ")", "LOGGER", ".", "debug", "(", "'E...
Clear all indexes in the es core
[ "Clear", "all", "indexes", "in", "the", "es", "core" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/elasticsearch_client.py#L221-L225
cga-harvard/Hypermap-Registry
hypermap/aggregator/elasticsearch_client.py
ESHypermap.create_indices
def create_indices(catalog_slug): """Create ES core indices """ # TODO: enable auto_create_index in the ES nodes to make this implicit. # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation # http://support.searchly.com/customer/en/portal/quest...
python
def create_indices(catalog_slug): """Create ES core indices """ # TODO: enable auto_create_index in the ES nodes to make this implicit. # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation # http://support.searchly.com/customer/en/portal/quest...
[ "def", "create_indices", "(", "catalog_slug", ")", ":", "# TODO: enable auto_create_index in the ES nodes to make this implicit.", "# https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation", "# http://support.searchly.com/customer/en/portal/questions/", "# ...
Create ES core indices
[ "Create", "ES", "core", "indices" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/elasticsearch_client.py#L228-L247
cga-harvard/Hypermap-Registry
pavement.py
kill_process
def kill_process(procname, scriptname): """kill WSGI processes that may be running in development""" # from http://stackoverflow.com/a/2940878 import signal import subprocess p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.decode().sp...
python
def kill_process(procname, scriptname): """kill WSGI processes that may be running in development""" # from http://stackoverflow.com/a/2940878 import signal import subprocess p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.decode().sp...
[ "def", "kill_process", "(", "procname", ",", "scriptname", ")", ":", "# from http://stackoverflow.com/a/2940878", "import", "signal", "import", "subprocess", "p", "=", "subprocess", ".", "Popen", "(", "[", "'ps'", ",", "'aux'", "]", ",", "stdout", "=", "subproce...
kill WSGI processes that may be running in development
[ "kill", "WSGI", "processes", "that", "may", "be", "running", "in", "development" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/pavement.py#L50-L64
cga-harvard/Hypermap-Registry
hypermap/aggregator/populate_database.py
populate_initial_services
def populate_initial_services(): """ Populate a fresh installed Hypermap instances with basic services. """ services_list = ( ( 'Harvard WorldMap', 'Harvard WorldMap open source web geospatial platform', 'Hypermap:WorldMap', 'http://worldmap.harvar...
python
def populate_initial_services(): """ Populate a fresh installed Hypermap instances with basic services. """ services_list = ( ( 'Harvard WorldMap', 'Harvard WorldMap open source web geospatial platform', 'Hypermap:WorldMap', 'http://worldmap.harvar...
[ "def", "populate_initial_services", "(", ")", ":", "services_list", "=", "(", "(", "'Harvard WorldMap'", ",", "'Harvard WorldMap open source web geospatial platform'", ",", "'Hypermap:WorldMap'", ",", "'http://worldmap.harvard.edu'", ")", ",", "(", "'NYPL MapWarper'", ",", ...
Populate a fresh installed Hypermap instances with basic services.
[ "Populate", "a", "fresh", "installed", "Hypermap", "instances", "with", "basic", "services", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/populate_database.py#L10-L65
cga-harvard/Hypermap-Registry
hypermap/search_api/views.py
elasticsearch
def elasticsearch(serializer, catalog): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: """ search_engine_endpoint = "{0}/{1}/_search".format(SEARCH_URL, catalog.slug) q_text = serializer.validated_data.get("q_text") ...
python
def elasticsearch(serializer, catalog): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: """ search_engine_endpoint = "{0}/{1}/_search".format(SEARCH_URL, catalog.slug) q_text = serializer.validated_data.get("q_text") ...
[ "def", "elasticsearch", "(", "serializer", ",", "catalog", ")", ":", "search_engine_endpoint", "=", "\"{0}/{1}/_search\"", ".", "format", "(", "SEARCH_URL", ",", "catalog", ".", "slug", ")", "q_text", "=", "serializer", ".", "validated_data", ".", "get", "(", ...
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return:
[ "https", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "_the_search_api", ".", "html", ":", "param", "serializer", ":", ":", "return", ":" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/views.py#L32-L361
cga-harvard/Hypermap-Registry
hypermap/search_api/views.py
solr
def solr(serializer): """ Search on solr endpoint :param serializer: :return: """ search_engine_endpoint = serializer.validated_data.get("search_engine_endpoint") q_time = serializer.validated_data.get("q_time") q_geo = serializer.validated_data.get("q_geo") q_text = serializer.valid...
python
def solr(serializer): """ Search on solr endpoint :param serializer: :return: """ search_engine_endpoint = serializer.validated_data.get("search_engine_endpoint") q_time = serializer.validated_data.get("q_time") q_geo = serializer.validated_data.get("q_geo") q_text = serializer.valid...
[ "def", "solr", "(", "serializer", ")", ":", "search_engine_endpoint", "=", "serializer", ".", "validated_data", ".", "get", "(", "\"search_engine_endpoint\"", ")", "q_time", "=", "serializer", ".", "validated_data", ".", "get", "(", "\"q_time\"", ")", "q_geo", "...
Search on solr endpoint :param serializer: :return:
[ "Search", "on", "solr", "endpoint", ":", "param", "serializer", ":", ":", "return", ":" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/views.py#L364-L573
cga-harvard/Hypermap-Registry
hypermap/search_api/views.py
parse_get_params
def parse_get_params(request): """ parse all url get params that contains dots in a representation of serializer field names, for example: d.docs.limit to d_docs_limit. that makes compatible an actual API client with django-rest-framework serializers. :param request: :return: QueryDict with ...
python
def parse_get_params(request): """ parse all url get params that contains dots in a representation of serializer field names, for example: d.docs.limit to d_docs_limit. that makes compatible an actual API client with django-rest-framework serializers. :param request: :return: QueryDict with ...
[ "def", "parse_get_params", "(", "request", ")", ":", "get", "=", "request", ".", "GET", ".", "copy", "(", ")", "new_get", "=", "request", ".", "GET", ".", "copy", "(", ")", "for", "key", "in", "get", ".", "iterkeys", "(", ")", ":", "if", "key", "...
parse all url get params that contains dots in a representation of serializer field names, for example: d.docs.limit to d_docs_limit. that makes compatible an actual API client with django-rest-framework serializers. :param request: :return: QueryDict with parsed get params.
[ "parse", "all", "url", "get", "params", "that", "contains", "dots", "in", "a", "representation", "of", "serializer", "field", "names", "for", "example", ":", "d", ".", "docs", ".", "limit", "to", "d_docs_limit", ".", "that", "makes", "compatible", "an", "a...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/views.py#L576-L594
konikvranik/pyCEC
pycec/tcp.py
main
def main(): """For testing purpose""" tcp_adapter = TcpAdapter("192.168.1.3", name="HASS", activate_source=False) hdmi_network = HDMINetwork(tcp_adapter) hdmi_network.start() while True: for d in hdmi_network.devices: _LOGGER.info("Device: %s", d) time.sleep(7)
python
def main(): """For testing purpose""" tcp_adapter = TcpAdapter("192.168.1.3", name="HASS", activate_source=False) hdmi_network = HDMINetwork(tcp_adapter) hdmi_network.start() while True: for d in hdmi_network.devices: _LOGGER.info("Device: %s", d) time.sleep(7)
[ "def", "main", "(", ")", ":", "tcp_adapter", "=", "TcpAdapter", "(", "\"192.168.1.3\"", ",", "name", "=", "\"HASS\"", ",", "activate_source", "=", "False", ")", "hdmi_network", "=", "HDMINetwork", "(", "tcp_adapter", ")", "hdmi_network", ".", "start", "(", "...
For testing purpose
[ "For", "testing", "purpose" ]
train
https://github.com/konikvranik/pyCEC/blob/acf42a842d8a912ed68d63d8d6b653e6c405b29b/pycec/tcp.py#L143-L152
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
compare_hexdigests
def compare_hexdigests( digest1, digest2 ): """Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different""" # convert to 32-tuple of unsighed two-byte INTs digest1 = tuple([int(digest1[i:i+2],16) for i in range(0,63,2)]) digest2 = tuple([int(di...
python
def compare_hexdigests( digest1, digest2 ): """Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different""" # convert to 32-tuple of unsighed two-byte INTs digest1 = tuple([int(digest1[i:i+2],16) for i in range(0,63,2)]) digest2 = tuple([int(di...
[ "def", "compare_hexdigests", "(", "digest1", ",", "digest2", ")", ":", "# convert to 32-tuple of unsighed two-byte INTs", "digest1", "=", "tuple", "(", "[", "int", "(", "digest1", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "for", "i", "in", "range"...
Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different
[ "Compute", "difference", "in", "bits", "between", "digest1", "and", "digest2", "returns", "-", "127", "to", "128", ";", "128", "is", "the", "same", "-", "127", "is", "different" ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L196-L205
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
Nilsimsa.tran3
def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
python
def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
[ "def", "tran3", "(", "self", ",", "a", ",", "b", ",", "c", ",", "n", ")", ":", "return", "(", "(", "(", "TRAN", "[", "(", "a", "+", "n", ")", "&", "255", "]", "^", "TRAN", "[", "b", "]", "*", "(", "n", "+", "n", "+", "1", ")", ")", ...
Get accumulator for a transition n between chars a, b, c.
[ "Get", "accumulator", "for", "a", "transition", "n", "between", "chars", "a", "b", "c", "." ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L117-L119
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
Nilsimsa.update
def update(self, data): """Add data to running digest, increasing the accumulators for 0-8 triplets formed by this char and the previous 0-3 chars.""" for character in data: if PY3: ch = character else: ch = ord(character) se...
python
def update(self, data): """Add data to running digest, increasing the accumulators for 0-8 triplets formed by this char and the previous 0-3 chars.""" for character in data: if PY3: ch = character else: ch = ord(character) se...
[ "def", "update", "(", "self", ",", "data", ")", ":", "for", "character", "in", "data", ":", "if", "PY3", ":", "ch", "=", "character", "else", ":", "ch", "=", "ord", "(", "character", ")", "self", ".", "count", "+=", "1", "# incr accumulators for triple...
Add data to running digest, increasing the accumulators for 0-8 triplets formed by this char and the previous 0-3 chars.
[ "Add", "data", "to", "running", "digest", "increasing", "the", "accumulators", "for", "0", "-", "8", "triplets", "formed", "by", "this", "char", "and", "the", "previous", "0", "-", "3", "chars", "." ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L121-L145
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
Nilsimsa.digest
def digest(self): """Get digest of data seen thus far as a list of bytes.""" total = 0 # number of triplets seen if self.count == 3: # 3 chars = 1 triplet total = 1 elif self.count == 4: # 4 chars = 4 triplets ...
python
def digest(self): """Get digest of data seen thus far as a list of bytes.""" total = 0 # number of triplets seen if self.count == 3: # 3 chars = 1 triplet total = 1 elif self.count == 4: # 4 chars = 4 triplets ...
[ "def", "digest", "(", "self", ")", ":", "total", "=", "0", "# number of triplets seen", "if", "self", ".", "count", "==", "3", ":", "# 3 chars = 1 triplet", "total", "=", "1", "elif", "self", ".", "count", "==", "4", ":", "# 4 chars = 4 triplets", "total", ...
Get digest of data seen thus far as a list of bytes.
[ "Get", "digest", "of", "data", "seen", "thus", "far", "as", "a", "list", "of", "bytes", "." ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L147-L164
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
Nilsimsa.from_file
def from_file(self, filename): """Update running digest with content of named file.""" f = open(filename, 'rb') while True: data = f.read(10480) if not data: break self.update(data) f.close()
python
def from_file(self, filename): """Update running digest with content of named file.""" f = open(filename, 'rb') while True: data = f.read(10480) if not data: break self.update(data) f.close()
[ "def", "from_file", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'rb'", ")", "while", "True", ":", "data", "=", "f", ".", "read", "(", "10480", ")", "if", "not", "data", ":", "break", "self", ".", "update", "("...
Update running digest with content of named file.
[ "Update", "running", "digest", "with", "content", "of", "named", "file", "." ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L174-L182
diffeo/py-nilsimsa
nilsimsa/deprecated/_deprecated_nilsimsa.py
Nilsimsa.compare
def compare(self, otherdigest, ishex=False): """Compute difference in bits between own digest and another. returns -127 to 128; 128 is the same, -127 is different""" bits = 0 myd = self.digest() if ishex: # convert to 32-tuple of unsighed two-byte INTs ...
python
def compare(self, otherdigest, ishex=False): """Compute difference in bits between own digest and another. returns -127 to 128; 128 is the same, -127 is different""" bits = 0 myd = self.digest() if ishex: # convert to 32-tuple of unsighed two-byte INTs ...
[ "def", "compare", "(", "self", ",", "otherdigest", ",", "ishex", "=", "False", ")", ":", "bits", "=", "0", "myd", "=", "self", ".", "digest", "(", ")", "if", "ishex", ":", "# convert to 32-tuple of unsighed two-byte INTs", "otherdigest", "=", "tuple", "(", ...
Compute difference in bits between own digest and another. returns -127 to 128; 128 is the same, -127 is different
[ "Compute", "difference", "in", "bits", "between", "own", "digest", "and", "another", ".", "returns", "-", "127", "to", "128", ";", "128", "is", "the", "same", "-", "127", "is", "different" ]
train
https://github.com/diffeo/py-nilsimsa/blob/c652f4bbfd836f7aebf292dcea676cc925ec315a/nilsimsa/deprecated/_deprecated_nilsimsa.py#L184-L194
CloudGenix/sdk-python
cloudgenix/__init__.py
jdout
def jdout(api_response): """ JD Output function. Does quick pretty printing of a CloudGenix Response body. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** A CloudGenix-attribute extended `requests.Response` object **Returns:** Prett...
python
def jdout(api_response): """ JD Output function. Does quick pretty printing of a CloudGenix Response body. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** A CloudGenix-attribute extended `requests.Response` object **Returns:** Prett...
[ "def", "jdout", "(", "api_response", ")", ":", "try", ":", "# attempt to output the cgx_content. should always be a Dict if it exists.", "output", "=", "json", ".", "dumps", "(", "api_response", ".", "cgx_content", ",", "indent", "=", "4", ")", "except", "(", "TypeE...
JD Output function. Does quick pretty printing of a CloudGenix Response body. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** A CloudGenix-attribute extended `requests.Response` object **Returns:** Pretty-formatted text of the Response body
[ "JD", "Output", "function", ".", "Does", "quick", "pretty", "printing", "of", "a", "CloudGenix", "Response", "body", ".", "This", "function", "returns", "a", "string", "instead", "of", "directly", "printing", "content", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L159-L180
CloudGenix/sdk-python
cloudgenix/__init__.py
jdout_detailed
def jdout_detailed(api_response, sensitive=False): """ JD Output Detailed function. Meant for quick DETAILED pretty-printing of CloudGenix Request and Response objects for troubleshooting. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** ...
python
def jdout_detailed(api_response, sensitive=False): """ JD Output Detailed function. Meant for quick DETAILED pretty-printing of CloudGenix Request and Response objects for troubleshooting. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** ...
[ "def", "jdout_detailed", "(", "api_response", ",", "sensitive", "=", "False", ")", ":", "try", ":", "# try to be super verbose.", "output", "=", "\"REQUEST: {0} {1}\\n\"", ".", "format", "(", "api_response", ".", "request", ".", "method", ",", "api_response", ".",...
JD Output Detailed function. Meant for quick DETAILED pretty-printing of CloudGenix Request and Response objects for troubleshooting. This function returns a string instead of directly printing content. **Parameters:** - **api_response:** A CloudGenix-attribute extended `requests.Response` object ...
[ "JD", "Output", "Detailed", "function", ".", "Meant", "for", "quick", "DETAILED", "pretty", "-", "printing", "of", "CloudGenix", "Request", "and", "Response", "objects", "for", "troubleshooting", ".", "This", "function", "returns", "a", "string", "instead", "of"...
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L201-L266
CloudGenix/sdk-python
cloudgenix/__init__.py
API.notify_for_new_version
def notify_for_new_version(self): """ Check for a new version of the SDK on API constructor instantiation. If new version found, print Notification to STDERR. On failure of this check, fail silently. **Returns:** No item returned, directly prints notification to `sys.stderr`. ...
python
def notify_for_new_version(self): """ Check for a new version of the SDK on API constructor instantiation. If new version found, print Notification to STDERR. On failure of this check, fail silently. **Returns:** No item returned, directly prints notification to `sys.stderr`. ...
[ "def", "notify_for_new_version", "(", "self", ")", ":", "# broad exception clause, if this fails for any reason just return.", "try", ":", "recommend_update", "=", "False", "update_check_resp", "=", "requests", ".", "get", "(", "self", ".", "update_info_url", ",", "timeou...
Check for a new version of the SDK on API constructor instantiation. If new version found, print Notification to STDERR. On failure of this check, fail silently. **Returns:** No item returned, directly prints notification to `sys.stderr`.
[ "Check", "for", "a", "new", "version", "of", "the", "SDK", "on", "API", "constructor", "instantiation", ".", "If", "new", "version", "found", "print", "Notification", "to", "STDERR", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L446-L503
CloudGenix/sdk-python
cloudgenix/__init__.py
API.ssl_verify
def ssl_verify(self, ssl_verify): """ Modify ssl verification settings **Parameters:** - ssl_verify: - True: Verify using builtin BYTE_CA_BUNDLE. - False: No SSL Verification. - Str: Full path to a x509 PEM CA File or bundle. **Returns:...
python
def ssl_verify(self, ssl_verify): """ Modify ssl verification settings **Parameters:** - ssl_verify: - True: Verify using builtin BYTE_CA_BUNDLE. - False: No SSL Verification. - Str: Full path to a x509 PEM CA File or bundle. **Returns:...
[ "def", "ssl_verify", "(", "self", ",", "ssl_verify", ")", ":", "self", ".", "verify", "=", "ssl_verify", "# if verify true/false, set ca_verify_file appropriately", "if", "isinstance", "(", "self", ".", "verify", ",", "bool", ")", ":", "if", "self", ".", "verify...
Modify ssl verification settings **Parameters:** - ssl_verify: - True: Verify using builtin BYTE_CA_BUNDLE. - False: No SSL Verification. - Str: Full path to a x509 PEM CA File or bundle. **Returns:** Mutates API object in place, no return.
[ "Modify", "ssl", "verification", "settings" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L505-L546
CloudGenix/sdk-python
cloudgenix/__init__.py
API.modify_rest_retry
def modify_rest_retry(self, total=8, connect=None, read=None, redirect=None, status=None, method_whitelist=urllib3.util.retry.Retry.DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0.705883, raise_on_redirect=True, raise_on_status=True, ...
python
def modify_rest_retry(self, total=8, connect=None, read=None, redirect=None, status=None, method_whitelist=urllib3.util.retry.Retry.DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0.705883, raise_on_redirect=True, raise_on_status=True, ...
[ "def", "modify_rest_retry", "(", "self", ",", "total", "=", "8", ",", "connect", "=", "None", ",", "read", "=", "None", ",", "redirect", "=", "None", ",", "status", "=", "None", ",", "method_whitelist", "=", "urllib3", ".", "util", ".", "retry", ".", ...
Modify retry parameters for the SDK's rest call object. Parameters are directly from and passed directly to `urllib3.util.retry.Retry`, and get applied directly to the underlying `requests.Session` object. Default retry with total=8 and backoff_factor=0.705883: - Try 1, 0 delay (0 tot...
[ "Modify", "retry", "parameters", "for", "the", "SDK", "s", "rest", "call", "object", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L548-L604
CloudGenix/sdk-python
cloudgenix/__init__.py
API.view_rest_retry
def view_rest_retry(self, url=None): """ View current rest retry settings in the `requests.Session()` object **Parameters:** - **url:** URL to use to determine retry methods for. Defaults to 'https://' **Returns:** Dict, Key header, value is header value. """ ...
python
def view_rest_retry(self, url=None): """ View current rest retry settings in the `requests.Session()` object **Parameters:** - **url:** URL to use to determine retry methods for. Defaults to 'https://' **Returns:** Dict, Key header, value is header value. """ ...
[ "def", "view_rest_retry", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "\"https://\"", "return", "vars", "(", "self", ".", "_session", ".", "get_adapter", "(", "url", ")", ".", "max_retries", ")" ]
View current rest retry settings in the `requests.Session()` object **Parameters:** - **url:** URL to use to determine retry methods for. Defaults to 'https://' **Returns:** Dict, Key header, value is header value.
[ "View", "current", "rest", "retry", "settings", "in", "the", "requests", ".", "Session", "()", "object" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L606-L618
CloudGenix/sdk-python
cloudgenix/__init__.py
API.view_cookies
def view_cookies(self): """ View current cookies in the `requests.Session()` object **Returns:** List of Dicts, one cookie per Dict. """ return_list = [] for cookie in self._session.cookies: return_list.append(vars(cookie)) return return_list
python
def view_cookies(self): """ View current cookies in the `requests.Session()` object **Returns:** List of Dicts, one cookie per Dict. """ return_list = [] for cookie in self._session.cookies: return_list.append(vars(cookie)) return return_list
[ "def", "view_cookies", "(", "self", ")", ":", "return_list", "=", "[", "]", "for", "cookie", "in", "self", ".", "_session", ".", "cookies", ":", "return_list", ".", "append", "(", "vars", "(", "cookie", ")", ")", "return", "return_list" ]
View current cookies in the `requests.Session()` object **Returns:** List of Dicts, one cookie per Dict.
[ "View", "current", "cookies", "in", "the", "requests", ".", "Session", "()", "object" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L662-L672
CloudGenix/sdk-python
cloudgenix/__init__.py
API.set_debug
def set_debug(self, debuglevel): """ Change the debug level of the API **Returns:** No item returned. """ if isinstance(debuglevel, int): self._debuglevel = debuglevel if self._debuglevel == 1: logging.basicConfig(level=logging.INFO, ...
python
def set_debug(self, debuglevel): """ Change the debug level of the API **Returns:** No item returned. """ if isinstance(debuglevel, int): self._debuglevel = debuglevel if self._debuglevel == 1: logging.basicConfig(level=logging.INFO, ...
[ "def", "set_debug", "(", "self", ",", "debuglevel", ")", ":", "if", "isinstance", "(", "debuglevel", ",", "int", ")", ":", "self", ".", "_debuglevel", "=", "debuglevel", "if", "self", ".", "_debuglevel", "==", "1", ":", "logging", ".", "basicConfig", "("...
Change the debug level of the API **Returns:** No item returned.
[ "Change", "the", "debug", "level", "of", "the", "API" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L674-L708
CloudGenix/sdk-python
cloudgenix/__init__.py
API._subclass_container
def _subclass_container(self): """ Call subclasses via function to allow passing parent namespace to subclasses. **Returns:** dict with subclass references. """ _parent_class = self class GetWrapper(Get): def __init__(self): self._parent_cla...
python
def _subclass_container(self): """ Call subclasses via function to allow passing parent namespace to subclasses. **Returns:** dict with subclass references. """ _parent_class = self class GetWrapper(Get): def __init__(self): self._parent_cla...
[ "def", "_subclass_container", "(", "self", ")", ":", "_parent_class", "=", "self", "class", "GetWrapper", "(", "Get", ")", ":", "def", "__init__", "(", "self", ")", ":", "self", ".", "_parent_class", "=", "_parent_class", "class", "PostWrapper", "(", "Post",...
Call subclasses via function to allow passing parent namespace to subclasses. **Returns:** dict with subclass references.
[ "Call", "subclasses", "via", "function", "to", "allow", "passing", "parent", "namespace", "to", "subclasses", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L710-L753
CloudGenix/sdk-python
cloudgenix/__init__.py
API.rest_call
def rest_call(self, url, method, data=None, sensitive=False, timeout=None, content_json=True, retry=None, max_retry=None, retry_sleep=None): """ Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the...
python
def rest_call(self, url, method, data=None, sensitive=False, timeout=None, content_json=True, retry=None, max_retry=None, retry_sleep=None): """ Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the...
[ "def", "rest_call", "(", "self", ",", "url", ",", "method", ",", "data", "=", "None", ",", "sensitive", "=", "False", ",", "timeout", "=", "None", ",", "content_json", "=", "True", ",", "retry", "=", "None", ",", "max_retry", "=", "None", ",", "retry...
Generic REST call worker function **Parameters:** - **url:** URL for the REST call - **method:** METHOD for the REST call - **data:** Optional DATA for the call (for POST/PUT/etc.) - **sensitive:** Flag if content request/response should be hidden from logging functions...
[ "Generic", "REST", "call", "worker", "function" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L755-L890
CloudGenix/sdk-python
cloudgenix/__init__.py
API._cleanup_ca_temp_file
def _cleanup_ca_temp_file(self): """ Function to clean up ca temp file for requests. **Returns:** Removes TEMP ca file, no return """ if os.name == 'nt': if isinstance(self.ca_verify_filename, (binary_type, text_type)): # windows requires file to be c...
python
def _cleanup_ca_temp_file(self): """ Function to clean up ca temp file for requests. **Returns:** Removes TEMP ca file, no return """ if os.name == 'nt': if isinstance(self.ca_verify_filename, (binary_type, text_type)): # windows requires file to be c...
[ "def", "_cleanup_ca_temp_file", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "if", "isinstance", "(", "self", ".", "ca_verify_filename", ",", "(", "binary_type", ",", "text_type", ")", ")", ":", "# windows requires file to be closed for acc...
Function to clean up ca temp file for requests. **Returns:** Removes TEMP ca file, no return
[ "Function", "to", "clean", "up", "ca", "temp", "file", "for", "requests", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L892-L904
CloudGenix/sdk-python
cloudgenix/__init__.py
API.parse_auth_token
def parse_auth_token(self, auth_token): """ Break auth_token up into it's constituent values. **Parameters:** - **auth_token:** Auth_token string **Returns:** dict with Auth Token constituents """ # remove the random security key value from the front of the a...
python
def parse_auth_token(self, auth_token): """ Break auth_token up into it's constituent values. **Parameters:** - **auth_token:** Auth_token string **Returns:** dict with Auth Token constituents """ # remove the random security key value from the front of the a...
[ "def", "parse_auth_token", "(", "self", ",", "auth_token", ")", ":", "# remove the random security key value from the front of the auth_token", "auth_token_cleaned", "=", "auth_token", ".", "split", "(", "'-'", ",", "1", ")", "[", "1", "]", "# URL Decode the Auth Token", ...
Break auth_token up into it's constituent values. **Parameters:** - **auth_token:** Auth_token string **Returns:** dict with Auth Token constituents
[ "Break", "auth_token", "up", "into", "it", "s", "constituent", "values", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L906-L931
CloudGenix/sdk-python
cloudgenix/__init__.py
API.update_region_to_controller
def update_region_to_controller(self, region): """ Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates the ...
python
def update_region_to_controller(self, region): """ Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates the ...
[ "def", "update_region_to_controller", "(", "self", ",", "region", ")", ":", "# default region position in a list", "region_position", "=", "1", "# Check for a global \"ignore region\" flag", "if", "self", ".", "ignore_region", ":", "# bypass", "api_logger", ".", "debug", ...
Update the controller string with dynamic region info. Controller string should end up as `<name[-env]>.<region>.cloudgenix.com` **Parameters:** - **region:** region string. **Returns:** No return value, mutates the controller in the class namespace
[ "Update", "the", "controller", "string", "with", "dynamic", "region", "info", ".", "Controller", "string", "should", "end", "up", "as", "<name", "[", "-", "env", "]", ">", ".", "<region", ">", ".", "cloudgenix", ".", "com" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L933-L997
CloudGenix/sdk-python
cloudgenix/__init__.py
API.parse_region
def parse_region(self, login_response): """ Return region from a successful login response. **Parameters:** - **login_response:** requests.Response from a successful login. **Returns:** region name. """ auth_token = login_response.cgx_content['x_auth_token'] ...
python
def parse_region(self, login_response): """ Return region from a successful login response. **Parameters:** - **login_response:** requests.Response from a successful login. **Returns:** region name. """ auth_token = login_response.cgx_content['x_auth_token'] ...
[ "def", "parse_region", "(", "self", ",", "login_response", ")", ":", "auth_token", "=", "login_response", ".", "cgx_content", "[", "'x_auth_token'", "]", "auth_token_dict", "=", "self", ".", "parse_auth_token", "(", "auth_token", ")", "auth_region", "=", "auth_tok...
Return region from a successful login response. **Parameters:** - **login_response:** requests.Response from a successful login. **Returns:** region name.
[ "Return", "region", "from", "a", "successful", "login", "response", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L999-L1012
CloudGenix/sdk-python
cloudgenix/__init__.py
API.reparse_login_cookie_after_region_update
def reparse_login_cookie_after_region_update(self, login_response): """ Sometimes, login cookie gets sent with region info instead of api.cloudgenix.com. This function re-parses the original login request and applies cookies to the session if they now match the new region. **Parameters:...
python
def reparse_login_cookie_after_region_update(self, login_response): """ Sometimes, login cookie gets sent with region info instead of api.cloudgenix.com. This function re-parses the original login request and applies cookies to the session if they now match the new region. **Parameters:...
[ "def", "reparse_login_cookie_after_region_update", "(", "self", ",", "login_response", ")", ":", "login_url", "=", "login_response", ".", "request", ".", "url", "api_logger", ".", "debug", "(", "\"ORIGINAL REQUEST URL = %s\"", ",", "login_url", ")", "# replace old contr...
Sometimes, login cookie gets sent with region info instead of api.cloudgenix.com. This function re-parses the original login request and applies cookies to the session if they now match the new region. **Parameters:** - **login_response:** requests.Response from a non-region login. ...
[ "Sometimes", "login", "cookie", "gets", "sent", "with", "region", "info", "instead", "of", "api", ".", "cloudgenix", ".", "com", ".", "This", "function", "re", "-", "parses", "the", "original", "login", "request", "and", "applies", "cookies", "to", "the", ...
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L1014-L1038
CloudGenix/sdk-python
cloudgenix/__init__.py
API._catch_nonjson_streamresponse
def _catch_nonjson_streamresponse(rawresponse): """ Validate a streamed response is JSON. Return a Python dictionary either way. **Parameters:** - **rawresponse:** Streamed Response from Requests. **Returns:** Dictionary """ # attempt to load response for re...
python
def _catch_nonjson_streamresponse(rawresponse): """ Validate a streamed response is JSON. Return a Python dictionary either way. **Parameters:** - **rawresponse:** Streamed Response from Requests. **Returns:** Dictionary """ # attempt to load response for re...
[ "def", "_catch_nonjson_streamresponse", "(", "rawresponse", ")", ":", "# attempt to load response for return.", "try", ":", "response", "=", "json", ".", "loads", "(", "rawresponse", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "if", "rawresponse", ...
Validate a streamed response is JSON. Return a Python dictionary either way. **Parameters:** - **rawresponse:** Streamed Response from Requests. **Returns:** Dictionary
[ "Validate", "a", "streamed", "response", "is", "JSON", ".", "Return", "a", "Python", "dictionary", "either", "way", "." ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L1041-L1069
CloudGenix/sdk-python
cloudgenix/__init__.py
API.url_decode
def url_decode(url): """ URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLENCODED string """ return re.compile('%([0-9a-fA-F]{2})', re.M).sub(lambda m: chr(int(m.group(1), 16)), url)
python
def url_decode(url): """ URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLENCODED string """ return re.compile('%([0-9a-fA-F]{2})', re.M).sub(lambda m: chr(int(m.group(1), 16)), url)
[ "def", "url_decode", "(", "url", ")", ":", "return", "re", ".", "compile", "(", "'%([0-9a-fA-F]{2})'", ",", "re", ".", "M", ")", ".", "sub", "(", "lambda", "m", ":", "chr", "(", "int", "(", "m", ".", "group", "(", "1", ")", ",", "16", ")", ")",...
URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLENCODED string
[ "URL", "Decode", "function", "using", "REGEX" ]
train
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/__init__.py#L1072-L1082
deplicate/deplicate
duplicate/utils/fs/nt.py
blksize
def blksize(path): """ Get optimal file system buffer size (in bytes) for I/O calls. """ diskfreespace = win32file.GetDiskFreeSpace dirname = os.path.dirname(fullpath(path)) try: cluster_sectors, sector_size = diskfreespace(dirname)[:2] size = cluster_sectors * sector_size e...
python
def blksize(path): """ Get optimal file system buffer size (in bytes) for I/O calls. """ diskfreespace = win32file.GetDiskFreeSpace dirname = os.path.dirname(fullpath(path)) try: cluster_sectors, sector_size = diskfreespace(dirname)[:2] size = cluster_sectors * sector_size e...
[ "def", "blksize", "(", "path", ")", ":", "diskfreespace", "=", "win32file", ".", "GetDiskFreeSpace", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "fullpath", "(", "path", ")", ")", "try", ":", "cluster_sectors", ",", "sector_size", "=", "diskfre...
Get optimal file system buffer size (in bytes) for I/O calls.
[ "Get", "optimal", "file", "system", "buffer", "size", "(", "in", "bytes", ")", "for", "I", "/", "O", "calls", "." ]
train
https://github.com/deplicate/deplicate/blob/9975502571d1d024a990f5cb304d01b63c0d7717/duplicate/utils/fs/nt.py#L28-L44
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.gravatar
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False): """Pass email hash, return Gravatar URL. You can get email hash like this:: import hashlib avatar_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest() Visit htt...
python
def gravatar(hash, size=100, rating='g', default='identicon', include_extension=False, force_default=False): """Pass email hash, return Gravatar URL. You can get email hash like this:: import hashlib avatar_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest() Visit htt...
[ "def", "gravatar", "(", "hash", ",", "size", "=", "100", ",", "rating", "=", "'g'", ",", "default", "=", "'identicon'", ",", "include_extension", "=", "False", ",", "force_default", "=", "False", ")", ":", "if", "include_extension", ":", "hash", "+=", "'...
Pass email hash, return Gravatar URL. You can get email hash like this:: import hashlib avatar_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest() Visit https://en.gravatar.com/site/implement/images/ for more information. :param hash: The email hash used to generate ...
[ "Pass", "email", "hash", "return", "Gravatar", "URL", ".", "You", "can", "get", "email", "hash", "like", "this", "::" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L27-L50
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.social_media
def social_media(username, platform='twitter', size='medium'): """Return avatar URL at social media. Visit https://avatars.io for more information. :param username: The username of the social media. :param platform: One of facebook, instagram, twitter, gravatar. :param size: The...
python
def social_media(username, platform='twitter', size='medium'): """Return avatar URL at social media. Visit https://avatars.io for more information. :param username: The username of the social media. :param platform: One of facebook, instagram, twitter, gravatar. :param size: The...
[ "def", "social_media", "(", "username", ",", "platform", "=", "'twitter'", ",", "size", "=", "'medium'", ")", ":", "return", "'https://avatars.io/{platform}/{username}/{size}'", ".", "format", "(", "platform", "=", "platform", ",", "username", "=", "username", ","...
Return avatar URL at social media. Visit https://avatars.io for more information. :param username: The username of the social media. :param platform: One of facebook, instagram, twitter, gravatar. :param size: The size of avatar, one of small, medium and large.
[ "Return", "avatar", "URL", "at", "social", "media", ".", "Visit", "https", ":", "//", "avatars", ".", "io", "for", "more", "information", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L63-L72
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.jcrop_css
def jcrop_css(css_url=None): """Load jcrop css file. :param css_url: The custom CSS URL. """ if css_url is None: if current_app.config['AVATARS_SERVE_LOCAL']: css_url = url_for('avatars.static', filename='jcrop/css/jquery.Jcrop.min.css') else: ...
python
def jcrop_css(css_url=None): """Load jcrop css file. :param css_url: The custom CSS URL. """ if css_url is None: if current_app.config['AVATARS_SERVE_LOCAL']: css_url = url_for('avatars.static', filename='jcrop/css/jquery.Jcrop.min.css') else: ...
[ "def", "jcrop_css", "(", "css_url", "=", "None", ")", ":", "if", "css_url", "is", "None", ":", "if", "current_app", ".", "config", "[", "'AVATARS_SERVE_LOCAL'", "]", ":", "css_url", "=", "url_for", "(", "'avatars.static'", ",", "filename", "=", "'jcrop/css/j...
Load jcrop css file. :param css_url: The custom CSS URL.
[ "Load", "jcrop", "css", "file", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L84-L94
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.jcrop_js
def jcrop_js(js_url=None, with_jquery=True): """Load jcrop Javascript file. :param js_url: The custom JavaScript URL. :param with_jquery: Include jQuery or not, default to ``True``. """ serve_local = current_app.config['AVATARS_SERVE_LOCAL'] if js_url is None: ...
python
def jcrop_js(js_url=None, with_jquery=True): """Load jcrop Javascript file. :param js_url: The custom JavaScript URL. :param with_jquery: Include jQuery or not, default to ``True``. """ serve_local = current_app.config['AVATARS_SERVE_LOCAL'] if js_url is None: ...
[ "def", "jcrop_js", "(", "js_url", "=", "None", ",", "with_jquery", "=", "True", ")", ":", "serve_local", "=", "current_app", ".", "config", "[", "'AVATARS_SERVE_LOCAL'", "]", "if", "js_url", "is", "None", ":", "if", "serve_local", ":", "js_url", "=", "url_...
Load jcrop Javascript file. :param js_url: The custom JavaScript URL. :param with_jquery: Include jQuery or not, default to ``True``.
[ "Load", "jcrop", "Javascript", "file", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L97-L119
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.crop_box
def crop_box(endpoint=None, filename=None): """Create a crop box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop. """ crop_size = current_app.config['AVATARS_CROP_BASE_WIDTH'] ...
python
def crop_box(endpoint=None, filename=None): """Create a crop box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop. """ crop_size = current_app.config['AVATARS_CROP_BASE_WIDTH'] ...
[ "def", "crop_box", "(", "endpoint", "=", "None", ",", "filename", "=", "None", ")", ":", "crop_size", "=", "current_app", ".", "config", "[", "'AVATARS_CROP_BASE_WIDTH'", "]", "if", "endpoint", "is", "None", "or", "filename", "is", "None", ":", "url", "=",...
Create a crop box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop.
[ "Create", "a", "crop", "box", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L122-L134
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.preview_box
def preview_box(endpoint=None, filename=None): """Create a preview box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop. """ preview_size = current_app.config['AVATARS_CROP_PREVIEW_SIZE'...
python
def preview_box(endpoint=None, filename=None): """Create a preview box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop. """ preview_size = current_app.config['AVATARS_CROP_PREVIEW_SIZE'...
[ "def", "preview_box", "(", "endpoint", "=", "None", ",", "filename", "=", "None", ")", ":", "preview_size", "=", "current_app", ".", "config", "[", "'AVATARS_CROP_PREVIEW_SIZE'", "]", "or", "current_app", ".", "config", "[", "'AVATARS_SIZE_TUPLE'", "]", "[", "...
Create a preview box. :param endpoint: The endpoint of view function that serve avatar image file. :param filename: The filename of the image that need to be crop.
[ "Create", "a", "preview", "box", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L137-L154
greyli/flask-avatars
flask_avatars/__init__.py
_Avatars.init_jcrop
def init_jcrop(min_size=None): """Initialize jcrop. :param min_size: The minimal size of crop area. """ init_x = current_app.config['AVATARS_CROP_INIT_POS'][0] init_y = current_app.config['AVATARS_CROP_INIT_POS'][1] init_size = current_app.config['AVATARS_CROP_INIT_SIZE'...
python
def init_jcrop(min_size=None): """Initialize jcrop. :param min_size: The minimal size of crop area. """ init_x = current_app.config['AVATARS_CROP_INIT_POS'][0] init_y = current_app.config['AVATARS_CROP_INIT_POS'][1] init_size = current_app.config['AVATARS_CROP_INIT_SIZE'...
[ "def", "init_jcrop", "(", "min_size", "=", "None", ")", ":", "init_x", "=", "current_app", ".", "config", "[", "'AVATARS_CROP_INIT_POS'", "]", "[", "0", "]", "init_y", "=", "current_app", ".", "config", "[", "'AVATARS_CROP_INIT_POS'", "]", "[", "1", "]", "...
Initialize jcrop. :param min_size: The minimal size of crop area.
[ "Initialize", "jcrop", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L157-L226
greyli/flask-avatars
flask_avatars/__init__.py
Avatars.resize_avatar
def resize_avatar(self, img, base_width): """Resize an avatar. :param img: The image that needs to be resize. :param base_width: The width of output image. """ w_percent = (base_width / float(img.size[0])) h_size = int((float(img.size[1]) * float(w_percent))) img...
python
def resize_avatar(self, img, base_width): """Resize an avatar. :param img: The image that needs to be resize. :param base_width: The width of output image. """ w_percent = (base_width / float(img.size[0])) h_size = int((float(img.size[1]) * float(w_percent))) img...
[ "def", "resize_avatar", "(", "self", ",", "img", ",", "base_width", ")", ":", "w_percent", "=", "(", "base_width", "/", "float", "(", "img", ".", "size", "[", "0", "]", ")", ")", "h_size", "=", "int", "(", "(", "float", "(", "img", ".", "size", "...
Resize an avatar. :param img: The image that needs to be resize. :param base_width: The width of output image.
[ "Resize", "an", "avatar", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L278-L287
greyli/flask-avatars
flask_avatars/__init__.py
Avatars.save_avatar
def save_avatar(self, image): """Save an avatar as raw image, return new filename. :param image: The image that needs to be saved. """ path = current_app.config['AVATARS_SAVE_PATH'] filename = uuid4().hex + '_raw.png' image.save(os.path.join(path, filename)) retu...
python
def save_avatar(self, image): """Save an avatar as raw image, return new filename. :param image: The image that needs to be saved. """ path = current_app.config['AVATARS_SAVE_PATH'] filename = uuid4().hex + '_raw.png' image.save(os.path.join(path, filename)) retu...
[ "def", "save_avatar", "(", "self", ",", "image", ")", ":", "path", "=", "current_app", ".", "config", "[", "'AVATARS_SAVE_PATH'", "]", "filename", "=", "uuid4", "(", ")", ".", "hex", "+", "'_raw.png'", "image", ".", "save", "(", "os", ".", "path", ".",...
Save an avatar as raw image, return new filename. :param image: The image that needs to be saved.
[ "Save", "an", "avatar", "as", "raw", "image", "return", "new", "filename", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L289-L297
greyli/flask-avatars
flask_avatars/__init__.py
Avatars.crop_avatar
def crop_avatar(self, filename, x, y, w, h): """Crop avatar with given size, return a list of file name: [filename_s, filename_m, filename_l]. :param filename: The raw image's filename. :param x: The x-pos to start crop. :param y: The y-pos to start crop. :param w: The crop widt...
python
def crop_avatar(self, filename, x, y, w, h): """Crop avatar with given size, return a list of file name: [filename_s, filename_m, filename_l]. :param filename: The raw image's filename. :param x: The x-pos to start crop. :param y: The y-pos to start crop. :param w: The crop widt...
[ "def", "crop_avatar", "(", "self", ",", "filename", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "x", "=", "int", "(", "x", ")", "y", "=", "int", "(", "y", ")", "w", "=", "int", "(", "w", ")", "h", "=", "int", "(", "h", ")", "sizes...
Crop avatar with given size, return a list of file name: [filename_s, filename_m, filename_l]. :param filename: The raw image's filename. :param x: The x-pos to start crop. :param y: The y-pos to start crop. :param w: The crop width. :param h: The crop height.
[ "Crop", "avatar", "with", "given", "size", "return", "a", "list", "of", "file", "name", ":", "[", "filename_s", "filename_m", "filename_l", "]", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/__init__.py#L299-L349
greyli/flask-avatars
flask_avatars/identicon.py
Identicon.get_image
def get_image(self, string, width, height, pad=0): """ Byte representation of a PNG image """ hex_digest_byte_list = self._string_to_byte_list(string) matrix = self._create_matrix(hex_digest_byte_list) return self._create_image(matrix, width, height, pad)
python
def get_image(self, string, width, height, pad=0): """ Byte representation of a PNG image """ hex_digest_byte_list = self._string_to_byte_list(string) matrix = self._create_matrix(hex_digest_byte_list) return self._create_image(matrix, width, height, pad)
[ "def", "get_image", "(", "self", ",", "string", ",", "width", ",", "height", ",", "pad", "=", "0", ")", ":", "hex_digest_byte_list", "=", "self", ".", "_string_to_byte_list", "(", "string", ")", "matrix", "=", "self", ".", "_create_matrix", "(", "hex_diges...
Byte representation of a PNG image
[ "Byte", "representation", "of", "a", "PNG", "image" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L72-L78
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._get_pastel_colour
def _get_pastel_colour(self, lighten=127): """ Create a pastel colour hex colour string """ def r(): return random.randint(0, 128) + lighten return r(), r(), r()
python
def _get_pastel_colour(self, lighten=127): """ Create a pastel colour hex colour string """ def r(): return random.randint(0, 128) + lighten return r(), r(), r()
[ "def", "_get_pastel_colour", "(", "self", ",", "lighten", "=", "127", ")", ":", "def", "r", "(", ")", ":", "return", "random", ".", "randint", "(", "0", ",", "128", ")", "+", "lighten", "return", "r", "(", ")", ",", "r", "(", ")", ",", "r", "("...
Create a pastel colour hex colour string
[ "Create", "a", "pastel", "colour", "hex", "colour", "string" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L87-L93
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._luminance
def _luminance(self, rgb): """ Determine the liminanace of an RGB colour """ a = [] for v in rgb: v = v / float(255) if v < 0.03928: result = v / 12.92 else: result = math.pow(((v + 0.055) / 1.055), 2.4) ...
python
def _luminance(self, rgb): """ Determine the liminanace of an RGB colour """ a = [] for v in rgb: v = v / float(255) if v < 0.03928: result = v / 12.92 else: result = math.pow(((v + 0.055) / 1.055), 2.4) ...
[ "def", "_luminance", "(", "self", ",", "rgb", ")", ":", "a", "=", "[", "]", "for", "v", "in", "rgb", ":", "v", "=", "v", "/", "float", "(", "255", ")", "if", "v", "<", "0.03928", ":", "result", "=", "v", "/", "12.92", "else", ":", "result", ...
Determine the liminanace of an RGB colour
[ "Determine", "the", "liminanace", "of", "an", "RGB", "colour" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L95-L108
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._string_to_byte_list
def _string_to_byte_list(self, data): """ Creates a hex digest of the input string given to create the image, if it's not already hexadecimal Returns: Length 16 list of rgb value range integers (each representing a byte of the hex digest) """ byte...
python
def _string_to_byte_list(self, data): """ Creates a hex digest of the input string given to create the image, if it's not already hexadecimal Returns: Length 16 list of rgb value range integers (each representing a byte of the hex digest) """ byte...
[ "def", "_string_to_byte_list", "(", "self", ",", "data", ")", ":", "bytes_length", "=", "16", "m", "=", "self", ".", "digest", "(", ")", "m", ".", "update", "(", "str", ".", "encode", "(", "data", ")", ")", "hex_digest", "=", "m", ".", "hexdigest", ...
Creates a hex digest of the input string given to create the image, if it's not already hexadecimal Returns: Length 16 list of rgb value range integers (each representing a byte of the hex digest)
[ "Creates", "a", "hex", "digest", "of", "the", "input", "string", "given", "to", "create", "the", "image", "if", "it", "s", "not", "already", "hexadecimal" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L110-L126
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._bit_is_one
def _bit_is_one(self, n, hash_bytes): """ Check if the n (index) of hash_bytes is 1 or 0. """ scale = 16 # hexadecimal if not hash_bytes[int(n / (scale / 2))] >> int( (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1: return False return True
python
def _bit_is_one(self, n, hash_bytes): """ Check if the n (index) of hash_bytes is 1 or 0. """ scale = 16 # hexadecimal if not hash_bytes[int(n / (scale / 2))] >> int( (scale / 2) - ((n % (scale / 2)) + 1)) & 1 == 1: return False return True
[ "def", "_bit_is_one", "(", "self", ",", "n", ",", "hash_bytes", ")", ":", "scale", "=", "16", "# hexadecimal", "if", "not", "hash_bytes", "[", "int", "(", "n", "/", "(", "scale", "/", "2", ")", ")", "]", ">>", "int", "(", "(", "scale", "/", "2", ...
Check if the n (index) of hash_bytes is 1 or 0.
[ "Check", "if", "the", "n", "(", "index", ")", "of", "hash_bytes", "is", "1", "or", "0", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L128-L138
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._create_image
def _create_image(self, matrix, width, height, pad): """ Generates a PNG byte list """ image = Image.new("RGB", (width + (pad * 2), height + (pad * 2)), self.bg_colour) image_draw = ImageDraw.Draw(image) # Calculate the block width and ...
python
def _create_image(self, matrix, width, height, pad): """ Generates a PNG byte list """ image = Image.new("RGB", (width + (pad * 2), height + (pad * 2)), self.bg_colour) image_draw = ImageDraw.Draw(image) # Calculate the block width and ...
[ "def", "_create_image", "(", "self", ",", "matrix", ",", "width", ",", "height", ",", "pad", ")", ":", "image", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "(", "width", "+", "(", "pad", "*", "2", ")", ",", "height", "+", "(", "pad", "*", "2...
Generates a PNG byte list
[ "Generates", "a", "PNG", "byte", "list" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L140-L167
greyli/flask-avatars
flask_avatars/identicon.py
Identicon._create_matrix
def _create_matrix(self, byte_list): """ This matrix decides which blocks should be filled fg/bg colour True for fg_colour False for bg_colour hash_bytes - array of hash bytes values. RGB range values in each slot Returns: List representation of the matrix ...
python
def _create_matrix(self, byte_list): """ This matrix decides which blocks should be filled fg/bg colour True for fg_colour False for bg_colour hash_bytes - array of hash bytes values. RGB range values in each slot Returns: List representation of the matrix ...
[ "def", "_create_matrix", "(", "self", ",", "byte_list", ")", ":", "# Number of rows * cols halfed and rounded", "# in order to fill opposite side", "cells", "=", "int", "(", "self", ".", "rows", "*", "self", ".", "cols", "/", "2", "+", "self", ".", "cols", "%", ...
This matrix decides which blocks should be filled fg/bg colour True for fg_colour False for bg_colour hash_bytes - array of hash bytes values. RGB range values in each slot Returns: List representation of the matrix [[True, True, True, True], [False,...
[ "This", "matrix", "decides", "which", "blocks", "should", "be", "filled", "fg", "/", "bg", "colour", "True", "for", "fg_colour", "False", "for", "bg_colour" ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L169-L203
greyli/flask-avatars
flask_avatars/identicon.py
Identicon.generate
def generate(self, text): """Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l]. :param text: The text used to generate image. """ sizes = current_app.config['AVATARS_SIZE_TUPLE'] path = current_app.config['AVATARS_SAVE_PATH'] suf...
python
def generate(self, text): """Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l]. :param text: The text used to generate image. """ sizes = current_app.config['AVATARS_SIZE_TUPLE'] path = current_app.config['AVATARS_SAVE_PATH'] suf...
[ "def", "generate", "(", "self", ",", "text", ")", ":", "sizes", "=", "current_app", ".", "config", "[", "'AVATARS_SIZE_TUPLE'", "]", "path", "=", "current_app", ".", "config", "[", "'AVATARS_SAVE_PATH'", "]", "suffix", "=", "{", "sizes", "[", "0", "]", "...
Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l]. :param text: The text used to generate image.
[ "Generate", "and", "save", "avatars", "return", "a", "list", "of", "file", "name", ":", "[", "filename_s", "filename_m", "filename_l", "]", "." ]
train
https://github.com/greyli/flask-avatars/blob/13eca90342349c58962fef0ec541edcb1b009c70/flask_avatars/identicon.py#L205-L221
rbuffat/pyepw
pyepw/epw.py
Location.read
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.city = None else: self.city = vals[i] i += 1 if len(vals[i]) == 0: self.stat...
python
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.city = None else: self.city = vals[i] i += 1 if len(vals[i]) == 0: self.stat...
[ "def", "read", "(", "self", ",", "vals", ")", ":", "i", "=", "0", "if", "len", "(", "vals", "[", "i", "]", ")", "==", "0", ":", "self", ".", "city", "=", "None", "else", ":", "self", ".", "city", "=", "vals", "[", "i", "]", "i", "+=", "1"...
Read values. Args: vals (list): list of strings representing values
[ "Read", "values", "." ]
train
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L35-L87
rbuffat/pyepw
pyepw/epw.py
Location.city
def city(self, value=None): """Corresponds to IDD Field `city` Args: value (str): value for IDD Field `city` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `...
python
def city(self, value=None): """Corresponds to IDD Field `city` Args: value (str): value for IDD Field `city` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `...
[ "def", "city", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "str", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type str '", "...
Corresponds to IDD Field `city` Args: value (str): value for IDD Field `city` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
[ "Corresponds", "to", "IDD", "Field", "city" ]
train
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L100-L122