text
stringlengths
81
112k
Used to do a service full check when saving it. 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: ...
Used to check layer validity. 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 ...
Used to do a layer full check when saving it. 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.dela...
Used to do reindex layers/services when a issue is removed form them. 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,...
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 def get_checks_admin_reliability_warning_url(self): """ When service Realiability is going down users should go to the th...
Update layers for a service. 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': ...
Check for availability of a service and provide run metrics. 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'...
Update validity of a service. 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...
resolve the search url no matter if local or remote. :return: url or exception 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...
Returns the Hypermap endpoint for a layer. This endpoint will be the WMTS MapProxy endpoint, only for WM we use the original 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 orig...
Check for availability of a layer and provide run metrics. 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...
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"/> ...
Grabs input from the user and saves it as their trytravis target 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 ...
Loads the GitHub repository from the users config. 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: ...
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. def _submit_changes_to_github_repo(path, url): """ Temporarily commits local changes and submits them to the GitHub repo...
Waits for a Travis build to appear with the given commit SHA 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...
Watches and progressively outputs information about a given 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: ...
Converts a Travis state into a state character, color, and whether it's still running or a stopped 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']: ...
Parses a project slug out of either an HTTPS or SSH 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 ...
Gets the output for `trytravis --version`. 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....
Function that acts just like main() except doesn't catch exceptions. 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 ...
Main entry point when the user runs the `trytravis` command. 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: ...
pycsw wrapper 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 ...
pycsw wrapper for catalogs 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('/') ret...
OpenSearch wrapper 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[...
passed a string array 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 (m...
Clear all indexes in the es core 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')
Create ES core 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/...
kill WSGI processes that may be running in development 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...
Populate a fresh installed Hypermap instances with basic 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', ...
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: def elasticsearch(serializer, catalog): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html :param serializer: :return: """ search_engin...
Search on solr endpoint :param serializer: :return: 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 = seriali...
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. def parse_get_params(re...
For testing purpose 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) ti...
Compute difference in bits between digest1 and digest2 returns -127 to 128; 128 is the same, -127 is different 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 ...
Get accumulator for a transition n between chars a, b, c. 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)
Add data to running digest, increasing the accumulators for 0-8 triplets formed by this char and the previous 0-3 chars. 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 chara...
Get digest of data seen thus far as a list of bytes. 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...
Update running digest with content of named 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.c...
Compute difference in bits between own digest and another. returns -127 to 128; 128 is the same, -127 is different 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""" ...
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 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 ...
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): """ ...
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. def ssl_ve...
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...
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): """ View current rest ...
View current cookies in the `requests.Session()` object **Returns:** List of Dicts, one cookie per Dict. def view_cookies(self): """ View current cookies in the `requests.Session()` object **Returns:** List of Dicts, one cookie per Dict. """ return_list = [] fo...
Change the debug level of the API **Returns:** No item returned. 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._debugl...
Call subclasses via function to allow passing parent namespace to subclasses. **Returns:** dict with subclass references. def _subclass_container(self): """ Call subclasses via function to allow passing parent namespace to subclasses. **Returns:** dict with subclass references. ...
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...
Function to clean up ca temp file for requests. **Returns:** Removes TEMP ca file, no return 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 isinsta...
Break auth_token up into it's constituent values. **Parameters:** - **auth_token:** Auth_token string **Returns:** dict with Auth Token constituents def parse_auth_token(self, auth_token): """ Break auth_token up into it's constituent values. **Parameters:** ...
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 def update_region_to_controller(...
Return region from a successful login response. **Parameters:** - **login_response:** requests.Response from a successful login. **Returns:** region name. def parse_region(self, login_response): """ Return region from a successful login response. **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. ...
Validate a streamed response is JSON. Return a Python dictionary either way. **Parameters:** - **rawresponse:** Streamed Response from Requests. **Returns:** Dictionary def _catch_nonjson_streamresponse(rawresponse): """ Validate a streamed response is JSON. Return a Pytho...
URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLENCODED string def url_decode(url): """ URL Decode function using REGEX **Parameters:** - **url:** URLENCODED text string **Returns:** Non URLE...
Get optimal file system buffer size (in bytes) for I/O calls. 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(d...
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 ...
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. def social_media(usernam...
Load jcrop css file. :param css_url: The custom CSS URL. 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...
Load jcrop Javascript file. :param js_url: The custom JavaScript URL. :param with_jquery: Include jQuery or not, default to ``True``. def jcrop_js(js_url=None, with_jquery=True): """Load jcrop Javascript file. :param js_url: The custom JavaScript URL. :param with_jquery: Inclu...
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. def crop_box(endpoint=None, filename=None): """Create a crop box. :param endpoint: The endpoint of view function that serve ...
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. def preview_box(endpoint=None, filename=None): """Create a preview box. :param endpoint: The endpoint of view function th...
Initialize jcrop. :param min_size: The minimal size of crop area. 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_I...
Resize an avatar. :param img: The image that needs to be resize. :param base_width: The width of output image. 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. ""...
Save an avatar as raw image, return new filename. :param image: The image that needs to be saved. 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...
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. def crop_avatar(s...
Byte representation of a PNG 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...
Create a pastel colour hex colour string 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()
Determine the liminanace of an RGB colour 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 = ma...
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) def _string_to_byte_list(self, data): """ Creates a hex digest of...
Check if the n (index) of hash_bytes is 1 or 0. 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 ==...
Generates a PNG byte list 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) # Cal...
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,...
Generate and save avatars, return a list of file name: [filename_s, filename_m, filename_l]. :param text: The text used to generate image. 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 ge...
Read values. Args: vals (list): list of strings representing values 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: ...
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 def city(s...
Corresponds to IDD Field `state_province_region` Args: value (str): value for IDD Field `state_province_region` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value...
Corresponds to IDD Field `country` Args: value (str): value for IDD Field `country` 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 def ...
Corresponds to IDD Field `source` Args: value (str): value for IDD Field `source` 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 def so...
Corresponds to IDD Field `wmo` usually a 6 digit field. Used as alpha in EnergyPlus. Args: value (str): value for IDD Field `wmo` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
Corresponds to IDD Field `latitude` + is North, - is South, degree minutes represented in decimal (i.e. 30 minutes is .5) Args: value (float): value for IDD Field `latitude` Unit: deg Default value: 0.0 value >= -90.0 value <=...
Corresponds to IDD Field `longitude` - is West, + is East, degree minutes represented in decimal (i.e. 30 minutes is .5) Args: value (float): value for IDD Field `longitude` Unit: deg Default value: 0.0 value >= -180.0 value <...
Corresponds to IDD Field `timezone` Time relative to GMT. Args: value (float): value for IDD Field `timezone` Unit: hr - not on standard units list??? Default value: 0.0 value >= -12.0 value <= 12.0 if `value` is None i...
Corresponds to IDD Field `elevation` Args: value (float): value for IDD Field `elevation` Unit: m Default value: 0.0 value >= -1000.0 value < 9999.9 if `value` is None it will not be checked against the ...
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be expor...
Read values. Args: vals (list): list of strings representing values def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 if len(vals[i]) == 0: self.title_of_design_condition = None ...
Corresponds to IDD Field `title_of_design_condition` Args: value (str): value for IDD Field `title_of_design_condition` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: i...
Corresponds to IDD Field `unkown_field` Empty field in data. Args: value (str): value for IDD Field `unkown_field` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `va...
Corresponds to IDD Field `design_stat_heating` Args: value (str): value for IDD Field `design_stat_heating` Accepted values are: - Heating Default value: Heating if `value` is None it will not be checked against the ...
Corresponds to IDD Field `coldestmonth` Args: value (int): value for IDD Field `coldestmonth` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and is assumed to be a missing value Rais...
Corresponds to IDD Field `db996` Dry-bulb temperature corresponding to 99.6% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `db996` Unit: C if `value` is None it will not be checked against the ...
Corresponds to IDD Field `db990` Dry-bulb temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `db990` Unit: C if `value` is None it will not be checked against the ...
Corresponds to IDD Field `dp996` Dew-point temperature corresponding to 99.6% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `dp996` Unit: C if `value` is None it will not be checked against the ...
Corresponds to IDD Field `hr_dp996` humidity ratio, calculated at standard atmospheric pressure at elevation of station, corresponding to Dew-point temperature corresponding to 99.6% annual cumulative frequency of occurrence (cold conditions) Args: value (float): val...
Corresponds to IDD Field `db_dp996` mean coincident drybulb temperature corresponding to Dew-point temperature corresponding to 99.6% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `db_dp996` Unit: C ...
Corresponds to IDD Field `dp990` Dew-point temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `dp990` Unit: C if `value` is None it will not be checked against the ...
Corresponds to IDD Field `hr_dp990` humidity ratio, calculated at standard atmospheric pressure at elevation of station, corresponding to Dew-point temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): val...
Corresponds to IDD Field `db_dp990` mean coincident drybulb temperature corresponding to Dew-point temperature corresponding to 90.0% annual cumulative frequency of occurrence (cold conditions) Args: value (float): value for IDD Field `db_dp990` Unit: C ...