sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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... | 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... | entailment |
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 ... | 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. | entailment |
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 ... | 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... | entailment |
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... | Global values to pass to templates | entailment |
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()
... | Index and unindex all layers in the Django cache (Index all layers who have been checked). | entailment |
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:
... | Remove all checks from a service. | entailment |
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... | Index a service in search engine. | entailment |
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... | 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. | entailment |
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... | Remove the index for layers in search backend, which are linked to an issue. | entailment |
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_... | 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. | entailment |
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... | Index all layers in search engine. | entailment |
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... | Update and index the last added and deleted layers (num_layers) in WorldMap service. | entailment |
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
... | Return OGC WKT Polygon of a simple bbox list | entailment |
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... | Create a csw:Record XML document from harvested metadata | entailment |
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... | Convenience function to create bag of words for anytext property | entailment |
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... | Update layers for an OGC:WMTS service.
Sample endpoint: http://map1.vis.earthdata.nasa.gov/wmts-geo/1.0.0/WMTSCapabilities.xml | entailment |
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 =... | Update layers for a WorldMap instance.
Sample endpoint: http://localhost:8000/ | entailment |
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... | Update layers for a Warper service.
Sample endpoint: http://warp.worldmap.harvard.edu/maps | entailment |
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... | Update layers for an ESRI REST MapServer.
Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json | entailment |
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 ... | Update layers for an ESRI REST ImageServer.
Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/bag_bathymetry/ImageServer/?f=json | entailment |
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... | Used to process the lines of the endpoint list. | entailment |
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... | Used to do a service full check when saving it. | entailment |
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) | Used to do a service full check when saving it. | entailment |
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... | Used to check layer validity. | entailment |
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_... | Used to do a layer full check when saving it. | entailment |
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... | Used to do reindex layers/services when a issue is removed form them. | entailment |
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... | 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 | entailment |
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)
... | Update layers for a service. | entailment |
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
... | Check for availability of a service and provide run metrics. | entailment |
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... | Update validity of a service. | entailment |
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]) | resolve the search url no matter if local or remote.
:return: url or exception | entailment |
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... | Returns the Hypermap endpoint for a layer.
This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original endpoint. | entailment |
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, ... | Check for availability of a layer and provide run metrics. | entailment |
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... | 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"/>
... | entailment |
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... | Grabs input from the user and saves
it as their trytravis target repo | entailment |
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')... | Loads the GitHub repository from the users config. | entailment |
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... | 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. | entailment |
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()
... | Waits for a Travis build to appear with the given commit SHA | entailment |
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,
... | Watches and progressively outputs information
about a given Travis build | entailment |
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... | Converts a Travis state into a state character, color,
and whether it's still running or a stopped state. | entailment |
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... | Parses a project slug out of either an HTTPS or SSH URL. | entailment |
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... | Gets the output for `trytravis --version`. | entailment |
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... | Function that acts just like main() except
doesn't catch exceptions. | entailment |
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... | Main entry point when the user runs the `trytravis` command. | entailment |
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.... | pycsw wrapper | entailment |
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... | pycsw wrapper for catalogs | entailment |
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... | OpenSearch wrapper | entailment |
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)):
... | passed a string array | entailment |
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') | Clear all indexes in the es core | entailment |
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... | Create ES core indices | entailment |
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... | kill WSGI processes that may be running in development | entailment |
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... | Populate a fresh installed Hypermap instances with basic services. | entailment |
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")
... | https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html
:param serializer:
:return: | entailment |
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... | Search on solr endpoint
:param serializer:
:return: | entailment |
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 ... | 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. | entailment |
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) | For testing purpose | entailment |
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... | Compute difference in bits between digest1 and digest2
returns -127 to 128; 128 is the same, -127 is different | entailment |
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) | Get accumulator for a transition n between chars a, b, c. | entailment |
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... | Add data to running digest, increasing the accumulators for 0-8
triplets formed by this char and the previous 0-3 chars. | entailment |
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
... | Get digest of data seen thus far as a list of bytes. | entailment |
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() | Update running digest with content of named file. | entailment |
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
... | Compute difference in bits between own digest and another.
returns -127 to 128; 128 is the same, -127 is different | entailment |
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... | 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 | entailment |
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:** ... | 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
... | entailment |
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`.
... | 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`. | entailment |
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:... | 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. | entailment |
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,
... | 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... | entailment |
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.
"""
... | 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. | entailment |
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 | View current cookies in the `requests.Session()` object
**Returns:** List of Dicts, one cookie per Dict. | entailment |
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,
... | Change the debug level of the API
**Returns:** No item returned. | entailment |
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... | Call subclasses via function to allow passing parent namespace to subclasses.
**Returns:** dict with subclass references. | entailment |
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... | 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... | entailment |
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... | Function to clean up ca temp file for requests.
**Returns:** Removes TEMP ca file, no return | entailment |
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... | Break auth_token up into it's constituent values.
**Parameters:**
- **auth_token:** Auth_token string
**Returns:** dict with Auth Token constituents | entailment |
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 ... | 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 | entailment |
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']
... | Return region from a successful login response.
**Parameters:**
- **login_response:** requests.Response from a successful login.
**Returns:** region name. | entailment |
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:... | 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.
... | entailment |
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... | Validate a streamed response is JSON. Return a Python dictionary either way.
**Parameters:**
- **rawresponse:** Streamed Response from Requests.
**Returns:** Dictionary | entailment |
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) | URL Decode function using REGEX
**Parameters:**
- **url:** URLENCODED text string
**Returns:** Non URLENCODED string | entailment |
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... | Get optimal file system buffer size (in bytes) for I/O calls. | entailment |
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... | 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 ... | entailment |
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... | 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. | entailment |
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:
... | Load jcrop css file.
:param css_url: The custom CSS URL. | entailment |
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:
... | Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``. | entailment |
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']
... | 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. | entailment |
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'... | 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. | entailment |
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'... | Initialize jcrop.
:param min_size: The minimal size of crop area. | entailment |
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... | Resize an avatar.
:param img: The image that needs to be resize.
:param base_width: The width of output image. | entailment |
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... | Save an avatar as raw image, return new filename.
:param image: The image that needs to be saved. | entailment |
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... | 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. | entailment |
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) | Byte representation of a PNG image | entailment |
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() | Create a pastel colour hex colour string | entailment |
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)
... | Determine the liminanace of an RGB colour | entailment |
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... | 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) | entailment |
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 | Check if the n (index) of hash_bytes is 1 or 0. | entailment |
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 ... | Generates a PNG byte list | entailment |
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
... | 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,... | entailment |
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... | Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l].
:param text: The text used to generate image. | entailment |
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... | Read values.
Args:
vals (list): list of strings representing values | entailment |
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 `... | 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 | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.