sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _parse_authorization(cls, response, uri=None): """ Parse an authorization resource. """ links = _parse_header_links(response) try: new_cert_uri = links[u'next'][u'url'] except KeyError: raise errors.ClientError('"next" link missing') re...
Parse an authorization resource.
entailment
def _check_authorization(cls, authzr, identifier): """ Check that the authorization we got is the one we expected. """ if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return authzr
Check that the authorization we got is the one we expected.
entailment
def answer_challenge(self, challenge_body, response): """ Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challeng...
Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challenge. :return: The updated challenge resource. :rtype: Defer...
entailment
def _parse_challenge(cls, response): """ Parse a challenge resource. """ links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') return ( response...
Parse a challenge resource.
entailment
def _check_challenge(cls, challenge, challenge_body): """ Check that the challenge resource we got is the one we expected. """ if challenge.uri != challenge_body.uri: raise errors.UnexpectedUpdate(challenge.uri) return challenge
Check that the challenge resource we got is the one we expected.
entailment
def poll(self, authzr): """ Update an authorization from the server (usually to check its status). """ action = LOG_ACME_POLL_AUTHORIZATION(authorization=authzr) with action.context(): return ( DeferredContext(self._client.get(authzr.uri)) ...
Update an authorization from the server (usually to check its status).
entailment
def retry_after(cls, response, default=5, _now=time.time): """ Parse the Retry-After value from a response. """ val = response.headers.getRawHeaders(b'retry-after', [default])[0] try: return int(val) except ValueError: return http.stringToDatetime(...
Parse the Retry-After value from a response.
entailment
def request_issuance(self, csr): """ Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes...
Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes. .. seealso:: `txacme.util.csr_for_names` ...
entailment
def _parse_certificate(cls, response): """ Parse a response containing a certificate resource. """ links = _parse_header_links(response) try: cert_chain_uri = links[u'up'][u'url'] except KeyError: cert_chain_uri = None return ( ...
Parse a response containing a certificate resource.
entailment
def fetch_chain(self, certr, max_length=10): """ Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. ...
Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. :rtype: Deferred[List[`acme.messages.CertificateResource`...
entailment
def _wrap_in_jws(self, nonce, obj): """ Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data """ with LOG_J...
Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data
entailment
def _check_response(cls, response, content_type=JSON_CONTENT_TYPE): """ Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Typ...
Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Type does not match, :exc:`ClientError` is raised. :raises .ServerErro...
entailment
def _send_request(self, method, url, *args, **kwargs): """ Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response. """ action = LOG_JWS_REQUEST(url=url) ...
Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response.
entailment
def head(self, url, *args, **kwargs): """ Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to. """ with LOG_JWS_HEAD().context():...
Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to.
entailment
def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): """ Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP ...
Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP Problem (draft-ietf-appsawg-http-problem-00). :raises acme.errors.ClientEr...
entailment
def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. """ nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] ...
Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified.
entailment
def _get_nonce(self, url): """ Get a nonce to use in a request, removing it from the nonces on hand. """ action = LOG_JWS_GET_NONCE() if len(self._nonces) > 0: with action: nonce = self._nonces.pop() action.add_success_fields(nonce=nonc...
Get a nonce to use in a request, removing it from the nonces on hand.
entailment
def _post(self, url, obj, content_type, **kwargs): """ POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected conten...
POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the response. :raises txacme.client.ServerError: If ...
entailment
def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): """ POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload o...
POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the respo...
entailment
def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """ thread = Thread(*a, **kw) thread.daemon = True return thread
Create a `threading.Thread`, but always set ``daemon``.
entailment
def _defer_to_worker(deliver, worker, work, *args, **kwargs): """ Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. """ deferred = Deferred() def wrapped_work(): try: result = work(*args, **kwargs) except BaseException: ...
Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread.
entailment
def _split_zone(server_name, zone_name): """ Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix. """ server_name = server_name.rstrip(u'.') zone_name = zone_name.rstrip(u'.') if not (server_name == zone_nam...
Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix.
entailment
def _get_existing(driver, zone_name, server_name, validation): """ Get existing validation records. """ if zone_name is None: zones = sorted( (z for z in driver.list_zones() if server_name.rstrip(u'.') .endswith(u'.' + z.domain.rstrip(u'.')))...
Get existing validation records.
entailment
def _validation(response): """ Get the validation value for a challenge response. """ h = hashlib.sha256(response.key_authorization.encode("utf-8")) return b64encode(h.digest()).decode()
Get the validation value for a challenge response.
entailment
def load_or_create_client_key(pem_path): """ Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be created will be a 2048-bit RSA key. :type pem_path: ``twisted.python.filepath.FilePath`` :param pem_path: The certificate directory to ...
Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be created will be a 2048-bit RSA key. :type pem_path: ``twisted.python.filepath.FilePath`` :param pem_path: The certificate directory to use, as with the endpoint.
entailment
def _parse(reactor, directory, pemdir, *args, **kwargs): """ Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to us...
Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to use.
entailment
def lazyread(f, delimiter): """ Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param ...
Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param delimiter: Delimiter on which to split u...
entailment
def generate_private_key(key_type): """ Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa``. """ if key_type == u'rsa': return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_b...
Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa``.
entailment
def generate_tls_sni_01_cert(server_name, key_type=u'rsa', _generate_private_key=None): """ Generate a certificate/key pair for responding to a tls-sni-01 challenge. :param str server_name: The SAN the certificate should have. :param str key_type: The type of key to generat...
Generate a certificate/key pair for responding to a tls-sni-01 challenge. :param str server_name: The SAN the certificate should have. :param str key_type: The type of key to generate; usually not necessary. :rtype: ``Tuple[`~cryptography.x509.Certificate`, PrivateKey]`` :return: A tuple of the certif...
entailment
def tap(f): """ "Tap" a Deferred callback chain with a function whose return value is ignored. """ @wraps(f) def _cb(res, *a, **kw): d = maybeDeferred(f, res, *a, **kw) d.addCallback(lambda ignored: res) return d return _cb
"Tap" a Deferred callback chain with a function whose return value is ignored.
entailment
def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR. """ try: return x509.load_der_x509_csr( decode_b64jose(b64der), default_backend()) ex...
Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR.
entailment
def csr_for_names(names, key): """ Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certifica...
Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certificate. :param key: A Cryptography private ...
entailment
def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """ code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
async wrapper is required to avoid await calls raising a SyntaxError
entailment
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part ...
Determine the URL corresponding to Python object
entailment
def layers_to_solr(self, layers): """ Sync n layers in Solr. """ layers_dict_list = [] layers_success_ids = [] layers_errors_ids = [] for layer in layers: layer_dict, message = layer2dict(layer) if not layer_dict: layers_e...
Sync n layers in Solr.
entailment
def layer_to_solr(self, layer): """ Sync a layer in Solr. """ success = True message = 'Synced layer id %s to Solr' % layer.id layer_dict, message = layer2dict(layer) if not layer_dict: success = False else: layer_json = json.dumps...
Sync a layer in Solr.
entailment
def clear_solr(self, catalog="hypermap"): """Clear all indexes in the solr core""" solr_url = "{0}/solr/{1}".format(SEARCH_URL, catalog) solr = pysolr.Solr(solr_url, timeout=60) solr.delete(q='*:*') LOGGER.debug('Solr core cleared')
Clear all indexes in the solr core
entailment
def update_schema(self, catalog="hypermap"): """ set the mapping in solr. :param catalog: core :return: """ schema_url = "{0}/solr/{1}/schema".format(SEARCH_URL, catalog) print schema_url # create a special type to draw better heatmaps. location_r...
set the mapping in solr. :param catalog: core :return:
entailment
def create_layer_from_metadata_xml(resourcetype, xml, monitor=False, service=None, catalog=None): """ Create a layer / keyword list from a metadata record if it does not already exist. """ from models import gen_anytext, Layer if resourcetype == 'http://www.opengis.net/cat/csw/2.0.2': # Dublin cor...
Create a layer / keyword list from a metadata record if it does not already exist.
entailment
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is...
Create a service from an endpoint if it does not already exists.
entailment
def create_services_from_endpoint(url, catalog, greedy_opt=True): """ Generate service/services from an endpoint. WMS, WMTS, TMS endpoints correspond to a single service. ESRI, CSW endpoints corrispond to many services. :return: imported, message """ # this variable will collect any excepti...
Generate service/services from an endpoint. WMS, WMTS, TMS endpoints correspond to a single service. ESRI, CSW endpoints corrispond to many services. :return: imported, message
entailment
def service_url_parse(url): """ Function that parses from url the service and folder of services. """ endpoint = get_sanitized_endpoint(url) url_split_list = url.split(endpoint + '/') if len(url_split_list) != 0: url_split_list = url_split_list[1].split('/') else: raise Excep...
Function that parses from url the service and folder of services.
entailment
def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """ lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
Given coordinates in spherical mercator, return a lon,lat tuple.
entailment
def get_wms_version_negotiate(url, timeout=10): """ OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService """ try: LOGGER.debug('Trying a WMS 1.3.0 GetCapabilities request') return WebMapService(url, version='1.3.0', timeout=timeout) except Exceptio...
OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService
entailment
def get_sanitized_endpoint(url): """ Sanitize an endpoint, as removing unneeded parameters """ # sanitize esri sanitized_url = url.rstrip() esri_string = '/rest/services' if esri_string in url: match = re.search(esri_string, sanitized_url) sanitized_url = url[0:(match.start(0...
Sanitize an endpoint, as removing unneeded parameters
entailment
def get_esri_service_name(url): """ A method to get a service name from an esri endpoint. For example: http://example.com/arcgis/rest/services/myservice/mylayer/MapServer/?f=json Will return: myservice/mylayer """ result = re.search('rest/services/(.*)/[MapServer|ImageServer]', url) if resul...
A method to get a service name from an esri endpoint. For example: http://example.com/arcgis/rest/services/myservice/mylayer/MapServer/?f=json Will return: myservice/mylayer
entailment
def get_esri_extent(esriobj): """ Get the extent of an ESRI resource """ extent = None srs = None if 'fullExtent' in esriobj._json_struct: extent = esriobj._json_struct['fullExtent'] if 'extent' in esriobj._json_struct: extent = esriobj._json_struct['extent'] try: ...
Get the extent of an ESRI resource
entailment
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list of strings """ minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \ % (minx, miny, minx, max...
Return OGC WKT Polygon of a simple bbox list of strings
entailment
def get_solr_date(pydate, is_negative): """ Returns a date in a valid Solr format from a string. """ # check if date is valid and then set it to solr format YYYY-MM-DDThh:mm:ssZ try: if isinstance(pydate, datetime.datetime): solr_date = '%sZ' % pydate.isoformat()[0:19] ...
Returns a date in a valid Solr format from a string.
entailment
def get_date(layer): """ Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat. """ date = None sign = '+' date_type = 1 layer_dates = layer.get_layer_dates() # we index the first date! if layer_dates: ...
Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat.
entailment
def layer2dict(layer): """ Return a json representation for a layer. """ category = None username = None # bbox must be valid before proceeding if not layer.has_valid_bbox(): message = 'Layer id: %s has a not valid bbox' % layer.id return None, message # we can proceed...
Return a json representation for a layer.
entailment
def detect_metadata_url_scheme(url): """detect whether a url is a Service type that HHypermap supports""" scheme = None url_lower = url.lower() if any(x in url_lower for x in ['wms', 'service=wms']): scheme = 'OGC:WMS' if any(x in url_lower for x in ['wmts', 'service=wmts']): schem...
detect whether a url is a Service type that HHypermap supports
entailment
def serialize_checks(check_set): """ Serialize a check_set for raphael """ check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, ...
Serialize a check_set for raphael
entailment
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
A page with number of services and layers faceted on domains.
entailment
def tasks_runner(request): """ A page that let the admin to run global tasks. """ # server info cached_layers_number = 0 cached_layers = cache.get('layers') if cached_layers: cached_layers_number = len(cached_layers) cached_deleted_layers_number = 0 cached_deleted_layers = ...
A page that let the admin to run global tasks.
entailment
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """ layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url o...
Get Layer with matching catalog and uuid
entailment
def parse_datetime(date_str): """ Parses a date string to date object. for BCE dates, only supports the year part. """ is_common_era = True date_str_parts = date_str.split("-") if date_str_parts and date_str_parts[0] == '': is_common_era = False # for now, only support BCE ye...
Parses a date string to date object. for BCE dates, only supports the year part.
entailment
def parse_solr_time_range_as_pair(time_filter): """ :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: (2013-03-01, 2013-05-01T00:00:00) """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, time_filter) if matcher: return matcher.group(1), matcher.group(2) ...
:param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: (2013-03-01, 2013-05-01T00:00:00)
entailment
def parse_datetime_range(time_filter): """ Parse the url param to python objects. From what time range to divide by a.time.gap into intervals. Defaults to q.time and otherwise 90 days. Validate in API: re.search("\\[(.*) TO (.*)\\]", value) :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]...
Parse the url param to python objects. From what time range to divide by a.time.gap into intervals. Defaults to q.time and otherwise 90 days. Validate in API: re.search("\\[(.*) TO (.*)\\]", value) :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: datetime.datetime(2013, 3, 1, 0, 0), ...
entailment
def parse_ISO8601(time_gap): """ P1D to (1, ("DAYS", isodate.Duration(days=1)). P1Y to (1, ("YEARS", isodate.Duration(years=1)). :param time_gap: ISO8601 string. :return: tuple with quantity and unit of time. """ matcher = None if time_gap.count("T"): units = { "H": ...
P1D to (1, ("DAYS", isodate.Duration(days=1)). P1Y to (1, ("YEARS", isodate.Duration(years=1)). :param time_gap: ISO8601 string. :return: tuple with quantity and unit of time.
entailment
def compute_gap(start, end, time_limit): """ Compute a gap that seems reasonable, considering natural time units and limit. # TODO: make it to be reasonable. # TODO: make it to be small unit of time sensitive. :param start: datetime :param end: datetime :param time_limit: gaps count :ret...
Compute a gap that seems reasonable, considering natural time units and limit. # TODO: make it to be reasonable. # TODO: make it to be small unit of time sensitive. :param start: datetime :param end: datetime :param time_limit: gaps count :return: solr's format duration.
entailment
def gap_to_sorl(time_gap): """ P1D to +1DAY :param time_gap: :return: solr's format duration. """ quantity, unit = parse_ISO8601(time_gap) if unit[0] == "WEEKS": return "+{0}DAYS".format(quantity * 7) else: return "+{0}{1}".format(quantity, unit[0])
P1D to +1DAY :param time_gap: :return: solr's format duration.
entailment
def request_time_facet(field, time_filter, time_gap, time_limit=100): """ time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is ...
time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is a soft maximum; less will usually be returned. A suggested value is 100. N...
entailment
def parse_solr_geo_range_as_pair(geo_box_str): """ :param geo_box_str: [-90,-180 TO 90,180] :return: ("-90,-180", "90,180") """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, geo_box_str) if matcher: return matcher.group(1), matcher.group(2) else: raise Excep...
:param geo_box_str: [-90,-180 TO 90,180] :return: ("-90,-180", "90,180")
entailment
def parse_geo_box(geo_box_str): """ parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return: """ from_point_str, to_point_str = parse_solr_geo_range_as_pair(geo_box_str) from_point = parse_lat_lon(from_point_str) to_point = parse_lat_lon(to_point_str) recta...
parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return:
entailment
def request_heatmap_facet(field, hm_filter, hm_grid_level, hm_limit): """ heatmap facet query builder :param field: map the query to this field. :param hm_filter: From what region to plot the heatmap. Defaults to q.geo or otherwise the world. :param hm_grid_level: To explicitly specify the grid leve...
heatmap facet query builder :param field: map the query to this field. :param hm_filter: From what region to plot the heatmap. Defaults to q.geo or otherwise the world. :param hm_grid_level: To explicitly specify the grid level, e.g. to let a user ask for greater or courser resolution than the most rece...
entailment
def asterisk_to_min_max(field, time_filter, search_engine_endpoint, actual_params=None): """ traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param sear...
traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param search_engine_endpoint: solr core :param actual_params: (not implemented) to merge with other params....
entailment
def get_service(raw_xml): """ Set a service object based on the XML metadata <dct:references scheme="OGC:WMS">http://ngamaps.geointapps.org/arcgis /services/RIO/Rio_Foundation_Transportation/MapServer/WMSServer </dct:references> :param instance: :return: Layer """ from pycsw...
Set a service object based on the XML metadata <dct:references scheme="OGC:WMS">http://ngamaps.geointapps.org/arcgis /services/RIO/Rio_Foundation_Transportation/MapServer/WMSServer </dct:references> :param instance: :return: Layer
entailment
def query_ids(self, ids): """ Query by list of identifiers """ results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all() if len(results) == 0: # try services results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all() return...
Query by list of identifiers
entailment
def query_domain(self, domain, typenames, domainquerytype='list', count=False): """ Query by property domain values """ objects = self._get_repo_filter(Layer.objects) if domainquerytype == 'range': return [tuple(objects.aggregate(Min(domain), Max(domain)).values())]...
Query by property domain values
entailment
def query_insert(self, direction='max'): """ Query to get latest (default) or earliest update to repository """ if direction == 'min': return Layer.objects.aggregate( Min('last_updated'))['last_updated__min'].strftime('%Y-%m-%dT%H:%M:%SZ') return self....
Query to get latest (default) or earliest update to repository
entailment
def query_source(self, source): """ Query by source """ return self._get_repo_filter(Layer.objects).filter(url=source)
Query by source
entailment
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """ # run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in ...
Query records from underlying repository
entailment
def insert(self, resourcetype, source, insert_date=None): """ Insert a record into the repository """ caller = inspect.stack()[1][3] if caller == 'transaction': # insert of Layer hhclass = 'Layer' source = resourcetype resourcetype = resourc...
Insert a record into the repository
entailment
def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'): """ Insert or update a record in the repository """ keywords = [] if self.filter is not None: catalog = Catalog.objects.get(id=int(self.filter.split()[-1])) try: ...
Insert or update a record in the repository
entailment
def delete(self, constraint): """ Delete a record from the repository """ results = self._get_repo_filter(Service.objects).extra(where=[constraint['where']], params=constraint['values']).all() deleted = len(results) ...
Delete a record from the repository
entailment
def _get_repo_filter(self, query): """ Apply repository wide side filter / mask query """ if self.filter is not None: return query.extra(where=[self.filter]) return query
Apply repository wide side filter / mask query
entailment
def to_meshcode(lat, lon, level): """緯度経度から指定次の地域メッシュコードを算出する。 Args: lat: 世界測地系の緯度(度単位) lon: 世界測地系の経度(度単位) level: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 ...
緯度経度から指定次の地域メッシュコードを算出する。 Args: lat: 世界測地系の緯度(度単位) lon: 世界測地系の経度(度単位) level: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
entailment
def to_meshlevel(meshcode): """メッシュコードから次数を算出する。 Args: meshcode: メッシュコード Return: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
メッシュコードから次数を算出する。 Args: meshcode: メッシュコード Return: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 5倍(5km四方):5000 ...
entailment
def to_meshpoint(meshcode, lat_multiplier, lon_multiplier): """地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 5倍(5km四方):5000 4倍(4km四方):4000 2.5倍(...
entailment
def check(func): """ Check the permissions, http method and login state. """ def iCheck(request, *args, **kwargs): if not request.method == "POST": return HttpResponseBadRequest("Must be POST request.") follow = func(request, *args, **kwargs) if request.is_ajax(): ...
Check the permissions, http method and login state.
entailment
def register(model, field_name=None, related_name=None, lookup_method_name='get_follows'): """ This registers any model class to be follow-able. """ if model in registry: return registry.append(model) if not field_name: field_name = 'target_%s' % model._meta.module_nam...
This registers any model class to be follow-able.
entailment
def follow(user, obj): """ Make a user follow an object """ follow, created = Follow.objects.get_or_create(user, obj) return follow
Make a user follow an object
entailment
def unfollow(user, obj): """ Make a user unfollow an object """ try: follow = Follow.objects.get_follows(obj).get(user=user) follow.delete() return follow except Follow.DoesNotExist: pass
Make a user unfollow an object
entailment
def toggle(user, obj): """ Toggles a follow status. Useful function if you don't want to perform follow checks but just toggle it on / off. """ if Follow.objects.is_following(user, obj): return unfollow(user, obj) return follow(user, obj)
Toggles a follow status. Useful function if you don't want to perform follow checks but just toggle it on / off.
entailment
def validate_q_time(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *] Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *] """ if value: try: range = utils.parse_datetime_r...
Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *] Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *]
entailment
def validate_q_geo(self, value): """ Would be for example: [-90,-180 TO 90,180] """ if value: try: rectangle = utils.parse_geo_box(value) return "[{0},{1} TO {2},{3}]".format( rectangle.bounds[0], rectang...
Would be for example: [-90,-180 TO 90,180]
entailment
def validate_a_time_filter(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *] """ if value: try: utils.parse_datetime_range(value) except Exception as e: raise serializers.ValidationError(e.m...
Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *]
entailment
def fname(self, model_or_obj_or_qs): """ Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``. """ if isinstance(model_or_obj_or_qs, QuerySet): _, fname = model_map[model_or_obj_or_qs.model] else: cls = model_or_obj_or_qs if inspe...
Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.
entailment
def create(self, user, obj, **kwargs): """ Create a new follow link between a user and an object of a registered model type. """ follow = Follow(user=user) follow.target = obj follow.save() return follow
Create a new follow link between a user and an object of a registered model type.
entailment
def get_or_create(self, user, obj, **kwargs): """ Almost the same as `FollowManager.objects.create` - behaves the same as the normal `get_or_create` methods in django though. Returns a tuple with the `Follow` and either `True` or `False` """ if not self.is_following(...
Almost the same as `FollowManager.objects.create` - behaves the same as the normal `get_or_create` methods in django though. Returns a tuple with the `Follow` and either `True` or `False`
entailment
def is_following(self, user, obj): """ Returns `True` or `False` """ if isinstance(user, AnonymousUser): return False return 0 < self.get_follows(obj).filter(user=user).count()
Returns `True` or `False`
entailment
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
Returns all the followers of a model, an object or a queryset.
entailment
def create_event_regressors(self, event_times_indices, covariates = None, durations = None): """create_event_regressors creates the part of the design matrix corresponding to one event type. :param event_times_indices: indices in the resampled data, on which the events occurred. :type ...
create_event_regressors creates the part of the design matrix corresponding to one event type. :param event_times_indices: indices in the resampled data, on which the events occurred. :type event_times_indices: numpy array, (nr_events) :param covariates: covariates belonging to thi...
entailment
def create_design_matrix(self, demean = False, intercept = True): """create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1]) """ self.design_matrix = np....
create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1])
entailment
def add_continuous_regressors_to_design_matrix(self, regressors): """add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments...
add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments of specific events. For instance, in fMRI analysis this allows us to add car...
entailment
def regress(self, method = 'lstsq'): """regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables ...
regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables 'betas' (nr_betas x nr_signals) and 'residuals' ...
entailment
def ridge_regress(self, cv = 20, alphas = None ): """perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data a...
perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data are not prenormalized. :param cv: cross-validate...
entailment
def betas_for_cov(self, covariate = '0'): """betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string """ # find the index in the designmatrix of the current covariate this...
betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string
entailment
def betas_for_events(self): """betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size), which holds the outcome betas per event type,in the order generated by self.covariates.keys() """ self.betas_per_event_type = np.ze...
betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size), which holds the outcome betas per event type,in the order generated by self.covariates.keys()
entailment