code stringlengths 1 18.2k |
|---|
is not None: return childAndSegments return None |
def indirect(self, interface): """ Create a L{VirtualHostWrapper} so it can have the first chance to handle web requests. """ if interface is IResource: siteStore = self.store.parent if self.store.parent is None: siteStore = self.store return VirtualHostWrapper( siteStore, IWebViewer(self.store), self) return self |
def subdomain(self, hostname): """ Determine of which known domain the given hostname is a subdomain. @return: A two-tuple giving the subdomain part and the domain part or C{None} if the domain is not a subdomain of any known domain. """ hostname = hostname.split(":")[0] for domain in getDomainNames(self.siteStore): if... |
def locateChild(self, context, segments): """ Delegate dispatch to a sharing resource if the request is for a user subdomain, otherwise fall back to the wrapped resource's C{locateChild} implementation. """ request = IRequest(context) hostname = request.getHeader('host') info = self.subdomain(hostname) if info is not N... |
def _webTranslator(store, fallback): """ Discover a web translator based on an Axiom store and a specified default. Prefer the specified default. This is an implementation detail of various initializers in this module which require an L{IWebTranslator} provider. Some of those initializers did not previously require a w... |
def resort(self, columnName): """ Re-sort the table. @param columnName: the name of the column to sort by. This is a string because it is passed from the browser. """ csc = self.currentSortColumn newSortColumn = self.columns[columnName] if newSortColumn is None: raise Unsortable('column %r has no sort attribute' % (col... |
def inequalityQuery(self, constraint, count, isAscending): """ Perform a query to obtain some rows from the table represented by this model, at the behest of a networked client. @param constraint: an additional constraint to apply to the query. @type constraint: L{axiom.iaxiom.IComparison}. @param count: the maximum nu... |
def rowsAfterValue(self, value, count): """ Retrieve some rows at or after a given sort-column value. @param value: Starting value in the index for the current sort column at which to start returning results. Rows with a column value for the current sort column which is greater than or equal to this value will be retur... |
pyvalue, count, True) return self.constructRows(query) |
def rowsAfterRow(self, rowObject, count): """ Wrapper around L{rowsAfterItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to uniquely identify a row. @param count: an i... |
def rowsBeforeRow(self, rowObject, count): """ Wrapper around L{rowsBeforeItem} which accepts the web ID for a item instead of the item itself. @param rowObject: a dictionary mapping strings to column values, sent from the client. One of those column values must be C{__id__} to uniquely identify a row. @param count: an... |
def _toComparableValue(self, value): """ Trivial wrapper which takes into account the possibility that our sort column might not have defined the C{toComparableValue} method. This can probably serve as a good generic template for some infrastructure to deal with arbitrarily-potentially-missing methods from certain vers... |
since " "Mantissa 0.6.6.", DeprecationWarning, filename, lineno) return value |
def rowsBeforeValue(self, value, count): """ Retrieve display data for rows with sort-column values less than the given value. @type value: Some type compatible with the current sort column. @param value: Starting value in the index for the current sort column at which to start returning results. Rows with a column val... |
def rowsBeforeItem(self, item, count): """ The inverse of rowsAfterItem. @param item: then L{Item} to request rows before. @type item: this L{InequalityModel}'s L{itemType} attribute. @param count: The maximum number of rows to return. @type count: L{int} @return: A list of row data, ordered by the current sort column,... |
def requestRowRange(self, rangeBegin, rangeEnd): """ Retrieve display data for the given range of rows. @type rangeBegin: C{int} @param rangeBegin: The index of the first row to retrieve. @type rangeEnd: C{int} @param rangeEnd: The index of the last row to retrieve. @return: A C{list} of C{dict}s giving row data. """ r... |
def getTableMetadata(self): """ Retrieve a description of the various properties of this scrolltable. @return: A sequence containing 5 elements. They are, in order, a list of the names of the columns present, a mapping of column names to two-tuples of their type and a boolean indicating their sortability, the total num... |
def constructRows(self, items): """ Build row objects that are serializable using Athena for sending to the client. @param items: an iterable of objects compatible with my columns' C{extractValue} methods. @return: a list of dictionaries, where each dictionary has a string key for each column name in my list of columns... |
def _getColumnList(self): """ Get a list of serializable objects that describe the interesting columns on our item type. Columns which report having no type will be treated as having the type I{text}. @rtype: C{list} of C{dict} """ columnList = [] for columnName in self.columnNames: column = self.columns[columnName] ty... |
def getInitialArguments(self): """ Return the constructor arguments required for the JavaScript client class, Mantissa.ScrollTable.ScrollTable. @return: a 3-tuple of:: - The unicode attribute ID of my current sort column - A list of dictionaries with 'name' and 'type' keys which are strings describing the name and type... |
def printChannelColRow(campaign, ra, dec): """Prints the channel, col, row for a given campaign and coordinate.""" fovobj = fields.getKeplerFov(campaign) ch, col, row = fovobj.getChannelColRow(ra, dec) print("Position in C{}: channel {}, col {:.0f}, row {:.0f}.".format(campaign, int(ch), col, row)) |
def findCampaigns(ra, dec): """Returns a list of the campaigns that cover a given position. Parameters ---------- ra, dec : float, float Position in decimal degrees (J2000). Returns ------- campaigns : list of int A list of the campaigns that cover the given position. """ # Temporary disable the logger to avoid the pre... |
def findCampaignsByName(target): """Returns a list of the campaigns that cover a given target. Parameters ---------- target : str Name of the celestial object. Returns ------- campaigns : list of int A list of the campaigns that cover the given target name. ra, dec : float, float Resolved coordinates in decimal degrees... |
target "{0}".'.format(target)) # Find the campaigns with visibility return findCampaigns(crd.ra.deg, crd.dec.deg), crd.ra.deg, crd.dec.deg |
def K2findCampaigns_main(args=None): """Exposes K2findCampaigns to the command line.""" parser = argparse.ArgumentParser( description="Check if a celestial coordinate is " "(or was) observable by any past or future " "observing campaign of NASA's K2 mission.") parser.add_argument('ra', nargs=1, type=float, help="Right ... |
dec) # Make a context plot if the user requested so if args.plot: save_context_plots(ra, dec, "Your object") |
def K2findCampaigns_byname_main(args=None): """Exposes K2findCampaigns to the command line.""" parser = argparse.ArgumentParser( description="Check if a target is " "(or was) observable by any past or future " "observing campaign of NASA's K2 mission.") parser.add_argument('name', nargs=1, type=str, help="Name of the o... |
campaigns {0}.".format(campaigns) + Highlight.END) else: print(Highlight.RED + "Sorry, {} is not on silicon " "during any K2 campaign.".format(targetname) + Highlight.END) # Print the pixel positions for c in campaigns: printChannelColRow(c, ra, dec) # Make a context plot if the user requested so if args.plot: save_con... |
def K2findCampaigns_csv_main(args=None): """Exposes K2findCampaigns-csv to the command line.""" parser = argparse.ArgumentParser( description="Check which objects listed in a CSV table " "are (or were) observable by NASA's K2 mission.") parser.add_argument('input_filename', nargs=1, type=str, help="Path to a comma-sepa... |
open(output_fn, "w") for target in names: try: campaigns, ra, dec = findCampaignsByName(target) except ValueError: campaigns = [] output.write("{0}, {1}\n".format(target, campaigns)) output.flush() output.close() |
def mock_import(do_not_mock=None, **mock_kwargs): """ Mocks import statements by ignoring ImportErrors and replacing the missing module with a Mock. :param str|unicode|list[str|unicode] do_not_mock: names of modules that should exists, and an ImportError could be raised for. :param mock_kwargs: kwargs for MagicMock obj... |
def request(self, url, params=None, data=None, method='GET'): """ Perform an HTTP request and return the response body as a decoded JSON value :param str url: the URL to make the request of. If ``url`` begins with a forward slash, :attr:`endpoint` is prepended to it; otherwise, ``url`` is treated as an absolute URL. :p... |
:param str method: the HTTP method to use: ``"GET"``, ``"POST"``, ``"PUT"``, or ``"DELETE"`` (case-insensitive); default: ``"GET"`` :return: a decoded JSON value, or `None` if no data was returned :rtype: `list` or `dict` (depending on the request) or `None` :raises ValueError: if ``method`` is an invalid value :raises... |
= self.session.put(url, **attrs) elif method == 'DELETE': r = self.session.delete(url, **attrs) else: raise ValueError('Unrecognized HTTP method: ' + repr(method)) self.last_response = r self.last_meta = None if not r.ok: raise DOAPIError(r) if r.text.strip(): # Even when returning "no content", the API can still retur... |
def last_rate_limit(self): """ A `dict` of the rate limit information returned in the most recent response, or `None` if no requests have been made yet. The `dict` consists of all headers whose names begin with ``"RateLimit"`` (case insensitive). The DigitalOcean API specifies the following rate limit headers: :var str... |
def paginate(self, url, key, params=None): """ Fetch a sequence of paginated resources from the API endpoint. The initial request to ``url`` and all subsequent requests must respond with a JSON object; the field specified by ``key`` must be a list, whose elements will be yielded, and the next request will be made to th... |
may be included to override the default :attr:`per_page` setting. :rtype: generator of decoded JSON values :raises ValueError: if a response body is not an object or ``key`` is not one of its keys :raises DOAPIError: if the API endpoint replies with an error """ if params is None: params = {} if self.per_page is not No... |
def fetch_all_droplets(self, tag_name=None): r""" Returns a generator that yields all of the droplets belonging to the account .. versionchanged:: 0.2.0 ``tag_name`` parameter added :param tag_name: if non-`None`, only droplets with the given tag are returned :type tag_name: string or `Tag` :rtype: generator of `Drople... |
def create_droplet(self, name, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs): """ Create a new droplet. All fields other than ``name``, ``image``, ``size``, and ``region`` are optional and will be omitted from the API request if not specified. The return... |
:type size: string or `Size` :param region: the slug or `Region` object representing the region in which to create the droplet :type region: string or `Region` :param iterable ssh_keys: an iterable of SSH key resource IDs, SSH key fingerprints, and/or `SSHKey` objects specifying the public keys to add to the new drople... |
data = { "name": name, "image": image.id if isinstance(image, Image) else image, "size": str(size), "region": str(region), } if ssh_keys is not None: data["ssh_keys"] = [k._id if isinstance(k, SSHKey) else k for k in ssh_keys] if backups is not None: data["backups"] = backups if ipv6 is not None: data["ipv6"] = ipv6 if... |
def create_multiple_droplets(self, names, image, size, region, ssh_keys=None, backups=None, ipv6=None, private_networking=None, user_data=None, **kwargs): r""" Create multiple new droplets at once with the same image, size, etc., differing only in name. All fields other than ``names``, ``image``, ``size``, and ``region... |
string, or `Image` :param size: the slug or `Size` object representing the size of the new droplets :type size: string or `Size` :param region: the slug or `Region` object representing the region in which to create the droplets :type region: string or `Region` :param iterable ssh_keys: an iterable of SSH key resource I... |
the new droplet resources :rtype: list of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error """ data = { "names": names, "image": image.id if isinstance(image, Image) else image, "size": str(size), "region": str(region), } if ssh_keys is not None: data["ssh_keys"] = [k._id if isinstance(k, SSHK... |
def fetch_all_droplet_neighbors(self): r""" Returns a generator of all sets of multiple droplets that are running on the same physical hardware :rtype: generator of lists of `Droplet`\ s :raises DOAPIError: if the API endpoint replies with an error """ for hood in self.paginate('/v2/reports/droplet_neighbors', 'neighbo... |
def wait_droplets(self, droplets, status=None, locked=None, wait_interval=None, wait_time=None): r""" Poll the server periodically until all droplets in ``droplets`` have reached some final state, yielding each `Droplet`'s final value when it's done. If ``status`` is non-`None`, ``wait_droplets`` will wait for each dro... |
:param iterable droplets: an iterable of `Droplet`\ s and/or other values that are acceptable arguments to :meth:`fetch_droplet` :param status: When non-`None`, the desired value for the ``status`` field of each `Droplet`, which should be one of `Droplet.STATUS_ACTIVE`, `Droplet.STATUS_ARCHIVE`, `Droplet.STATUS_NEW`, a... |
if not specified or `None` :rtype: generator of `Droplet`\ s :raises TypeError: if both or neither of ``status`` & ``locked`` are defined :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exceeded """ if (status is None) == (locked is None): ### TODO: Is TypeErr... |
def wait_actions(self, actions, wait_interval=None, wait_time=None): r""" Poll the server periodically until all actions in ``actions`` have either completed or errored out, yielding each `Action`'s final value as it ends. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any remaining in-progress actions)... |
indefinitely; defaults to :attr:`wait_time` if not specified or `None` :rtype: generator of `Action`\ s :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exceeded """ return self._wait(map(self._action, actions), "done", True, wait_interval, wait_time) |
def wait_actions_on_objects(self, objects, wait_interval=None, wait_time=None): """ .. versionadded:: 0.2.0 Poll the server periodically until the most recent action on each resource in ``objects`` has finished, yielding each resource's final state when the corresponding action is done. If ``wait_time`` is exceeded, a ... |
not specified or `None` :rtype: generator of objects :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exceeded """ acts = [] for o in objects: a = o.fetch_last_action() if a is None: yield o else: acts.append(a) for a in self.wait_actions(acts, wait_interval, w... |
def create_ssh_key(self, name, public_key, **kwargs): """ Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` files :param kwargs: additional fields to inclu... |
def fetch_all_images(self, type=None, private=None): # pylint: disable=redefined-builtin r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: string or None :param boo... |
def create_domain(self, name, ip_address, **kwargs): """ Add a new domain name resource to the account. Note that this method does not actually register a new domain name; it merely configures DigitalOcean's nameservers to provide DNS resolution for the domain. See `How To Set Up a Host Name with DigitalOcean <https://... |
def create_floating_ip(self, droplet_id=None, region=None, **kwargs): """ Create a new floating IP assigned to a droplet or reserved to a region. Either ``droplet_id`` or ``region`` must be specified, but not both. The returned `FloatingIP` object will represent the IP at the moment of creation; if the IP address is su... |
kwargs: additional fields to include in the API request :return: the new floating IP :rtype: FloatingIP :raises TypeError: if both ``droplet_id`` & ``region`` or neither of them are defined :raises DOAPIError: if the API endpoint replies with an error """ if (droplet_id is None) == (region is None): ### TODO: Is TypeEr... |
def create_tag(self, name): """ .. versionadded:: 0.2.0 Add a new tag resource to the account :param str name: the name of the new tag :rtype: Tag :raises DOAPIError: if the API endpoint replies with an error """ return self._tag(self.request('/v2/tags', method='POST', data={ "name": name, })["tag"]) |
def _wait(self, objects, attr, value, wait_interval=None, wait_time=None): r""" Calls the ``fetch`` method of each object in ``objects`` periodically until the ``attr`` attribute of each one equals ``value``, yielding the final state of each object as soon as it satisfies the condition. If ``wait_time`` is exceeded, a ... |
seconds after which the method will raise an error if any objects have not yet completed, or a negative number to wait indefinitely; defaults to :attr:`wait_time` if not specified or `None` :rtype: generator :raises DOAPIError: if the API endpoint replies with an error :raises WaitTimeoutError: if ``wait_time`` is exce... |
= next_objs if not objects: break loop_end = time() time_left = wait_interval - (loop_end - loop_start) if end_time is not None: time_left = min(time_left, end_time - loop_end) if time_left > 0: try: sleep(time_left) except KeyboardInterrupt: for o in objects: yield o return if objects: raise WaitTimeoutError(objects, ... |
def min_tasks_per_node(queue_id): """ This function is used when requesting non exclusive use as the parallel environment might enforce a minimum number of tasks """ parallel_env = queue_id.split(':')[0] queue_name = queue_id.split(':')[1] tasks = 1 pe_tasks = tasks with os.popen('qconf -sp ' + parallel_env) as f: try:... |
def check_shape(meth): """ Decorator for larray magic methods, to ensure that the operand has the same shape as the array. """ @wraps(meth) def wrapped_meth(self, val): if isinstance(val, (larray, numpy.ndarray)): if val.shape != self._shape: raise ValueError("shape mismatch: objects cannot be broadcast to a single sha... |
def partial_shape(addr, full_shape): """ Calculate the size of the sub-array represented by `addr` """ def size(x, max): if isinstance(x, (int, long, numpy.integer)): return None elif isinstance(x, slice): y = min(max, x.stop or max) # slice limits can go past the bounds return 1 + (y - (x.start or 0) - 1) // (x.step o... |
def reverse(func): """Given a function f(a, b), returns f(b, a)""" @wraps(func) def reversed_func(a, b): return func(b, a) reversed_func.__doc__ = "Reversed argument form of %s" % func.__doc__ reversed_func.__name__ = "reversed %s" % func.__name__ return reversed_func |
def _build_ufunc(func): """Return a ufunc that works with lazy arrays""" def larray_compatible_ufunc(x): if isinstance(x, larray): y = deepcopy(x) y.apply(func) return y else: return func(x) return larray_compatible_ufunc |
def is_homogeneous(self): """True if all the elements of the array are the same.""" hom_base = isinstance(self.base_value, (int, long, numpy.integer, float, bool)) \ or type(self.base_value) == self.dtype \ or (isinstance(self.dtype, type) and isinstance(self.base_value, self.dtype)) hom_ops = all(obj.is_homogeneous fo... |
def _partially_evaluate(self, addr, simplify=False): """ Return part of the lazy array. """ if self.is_homogeneous: if simplify: base_val = self.base_value else: base_val = self._homogeneous_array(addr) * self.base_value elif isinstance(self.base_value, (int, long, numpy.integer, float, bool)): base_val = self._homogen... |
base_val = base_val.reshape(partial_shape) elif isinstance(self.base_value, collections.Iterator): raise NotImplementedError("coming soon...") else: raise ValueError("invalid base value for array (%s)" % self.base_value) return self._apply_operations(base_val, addr, simplify=simplify) |
def check_bounds(self, addr): """ Check whether the given address is within the array bounds. """ def is_boolean_array(arr): return hasattr(arr, 'dtype') and arr.dtype == bool def check_axis(x, size): if isinstance(x, (int, long, numpy.integer)): lower = upper = x elif isinstance(x, slice): lower = x.start or 0 upper =... |
or (upper >= size): raise IndexError("Index out of bounds") full_addr = self._full_address(addr) if isinstance(addr, numpy.ndarray) and addr.dtype == bool: if len(addr.shape) > len(self._shape): raise IndexError("Too many indices for array") for xmax, size in zip(addr.shape, self._shape): upper = xmax - 1 if upper >= s... |
def evaluate(self, simplify=False, empty_val=0): """ Return the lazy array as a real NumPy array. If the array is homogeneous and ``simplify`` is ``True``, return a single numerical value. """ # need to catch the situation where a generator-based larray is evaluated a second time if self.is_homogeneous: if simplify: x ... |
isinstance(self.base_value, collections.Iterator): x = numpy.fromiter(self.base_value, dtype=self.dtype or float, count=self.size) if x.shape != self._shape: x = x.reshape(self._shape) else: raise ValueError("invalid base value for array") return self._apply_operations(x, simplify=simplify) |
def is_closest_date_parameter(task, param_name): """ Return the parameter class of param_name on task. """ for name, obj in task.get_params(): if name == param_name: return hasattr(obj, 'use_closest_date') return False |
def delistify(x): """ A basic slug version of a given parameter list. """ if isinstance(x, list): x = [e.replace("'", "") for e in x] return '-'.join(sorted(x)) return x |
def effective_task_id(self): """ Replace date in task id with closest date. """ params = self.param_kwargs if 'date' in params and is_closest_date_parameter(self, 'date'): params['date'] = self.closest() task_id_parts = sorted(['%s=%s' % (k, str(v)) for k, v in params.items()]) return '%s(%s)' % (self.task_family, ', '... |
def taskdir(self): """ Return the directory under which all artefacts are stored. """ return os.path.join(self.BASE, self.TAG, self.task_family) |
def path(self, filename=None, ext='tsv', digest=False, shard=False, encoding='utf-8'): """ Return the path for this class with a certain set of parameters. `ext` sets the extension of the file. If `hash` is true, the filename (w/o extenstion) will be hashed. If `shard` is true, the files are placed in shards, based on ... |
isinstance(val, datetime.date): val = val.strftime('%Y-%m-%d') parts.append('%s-%s' % (name, val)) name = '-'.join(sorted(parts)) if len(name) == 0: name = 'output' if digest: name = hashlib.sha1(name.encode(encoding)).hexdigest() if not ext: filename = '{fn}'.format(ext=ext, fn=name) else: filename = '{fn}.{ext}'.form... |
def run(self): """ Just copy the fixture, so we have some output. """ luigi.LocalTarget(path=self.fixture).copy(self.output().path) |
def get_listeners(self, name): """ Return the callables related to name """ return list(map(lambda listener: listener[0], self.listeners[name])) |
def add_listener(self, name, listener, priority=0): """ Add a new listener to the dispatch """ if name not in self.listeners: self.listeners[name] = [] self.listeners[name].append((listener, priority)) # reorder event self.listeners[name].sort(key=lambda listener: listener[1], reverse=True) |
def dump_etree(data, container=None, nsmap=None, attribs=None): """Convert dictionary to Simple Dublin Core XML as ElementTree. :param data: Dictionary. :param container: Name (include namespace) of container element. :param nsmap: Namespace mapping for lxml. :param attribs: Default attributes for container element. :r... |
def rule_factory(plural, singular): """Element rule factory.""" @rules.rule(plural) def f(path, values): for v in values: if v: elem = etree.Element( '{{http://purl.org/dc/elements/1.1/}}{0}'.format(singular)) elem.text = v yield elem f.__name__ = plural return f |
def startReceivingBoxes(self, sender): """ Start observing log events for stat events to send. """ AMP.startReceivingBoxes(self, sender) log.addObserver(self._emit) |
def stopReceivingBoxes(self, reason): """ Stop observing log events. """ AMP.stopReceivingBoxes(self, reason) log.removeObserver(self._emit) |
def _emit(self, event): """ If the given event is a stat event, send a I{StatUpdate} command. """ if (event.get('interface') is not iaxiom.IStatEvent and 'athena_send_messages' not in event and 'athena_received_messages' not in event): return out = [] for k, v in event.iteritems(): if k in ('system', 'message', 'interf... |
def normalize_filename(filename): """ Remove special characters and shorten if name is too long """ # if the url pointed to a directory then just replace all the special chars filename = re.sub("/|\\|;|:|\?|=", "_", filename) if len(filename) > 150: prefix = hashlib.md5(filename).hexdigest() filename = prefix + filenam... |
def build_local_filename(download_url=None, filename=None, decompress=False): """ Determine which local filename to use based on the file's source URL, an optional desired filename, and whether a compression suffix needs to be removed """ assert download_url or filename, "Either filename or URL must be specified" # if ... |
def compare(file1, file2): """compares the contents of two files, passed in either as open file handles or accessible file paths. Does a simple naive string comparison, so do not use on larger files""" if isinstance(file1, six.string_types): # pragma: no branch file1 = open(file1, 'r', True) if isinstance(file2, six.st... |
def sha1sum(f): """Return the SHA-1 hash of the contents of file `f`, in hex format""" h = hashlib.sha1() fp = open(f, 'rb') while True: block = fp.read(512 * 1024) if not block: break h.update(block) return h.hexdigest() |
def safe_copyfile(src, dest): """safely copy src to dest using a temporary intermediate and then renaming to dest""" fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(dest)) shutil.copyfileobj(open(src, 'rb'), os.fdopen(fd, 'wb')) shutil.copystat(src, tmpname) os.rename(tmpname, dest) |
def sphericalAngSep(ra0, dec0, ra1, dec1, radians=False): """ Compute the spherical angular separation between two points on the sky. //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html NB: For small distances you can probably use sqrt( dDec**2 + cos^2(dec)*dRa) where dDec = dec1 - dec0 and dRa = ra1 - ... |
def sphericalAngSepFast(ra0, dec0, ra1, dec1, radians=False): """A faster (but less accurate) implementation of sphericalAngleSep Taken from http://www.movable-type.co.uk/scripts/latlong.html For additional speed, set wantSquare=True, and the return value is the square of the separation """ if radians==False: ra0 = np.... |
def haversine(x): """Return the haversine of an angle haversine(x) = sin(x/2)**2, where x is an angle in radians """ y = .5*x y = np.sin(y) return y*y |
def addDefaultShareID(store, shareID, priority): """ Add a default share ID to C{store}, pointing to C{shareID} with a priority C{priority}. The highest-priority share ID identifies the share that will be retrieved when a user does not explicitly provide a share ID in their URL (e.g. /host/users/username/). @param shar... |
def getDefaultShareID(store): """ Get the highest-priority default share ID for C{store}. @return: the default share ID, or u'' if one has not been set. @rtype: C{unicode} """ defaultShareID = store.findFirst( _DefaultShareID, sort=_DefaultShareID.priority.desc) if defaultShareID is None: return u'' return defaultShare... |
def linkTo(sharedProxyOrItem): """ Generate the path part of a URL to link to a share item or its proxy. @param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share} @return: a URL object, which when converted to a string will look something like '/users/user@host/shareID'. @rtype: L{nevow.url.URL} @raise: L{Runtim... |
lm.internal: path = ['users', lm.localpart.encode('ascii')] break else: raise RuntimeError( "Shared item is in a user store with no" " internal username -- can't generate a link.") if (sharedProxyOrItem.shareID == getDefaultShareID(userStore)): shareID = sharedProxyOrItem.shareID path.append('') else: shareID = None pa... |
def _storeFromUsername(store, username): """ Find the user store of the user with username C{store} @param store: site-store @type store: L{axiom.store.Store} @param username: the name a user signed up with @type username: C{unicode} @rtype: L{axiom.store.Store} or C{None} """ lm = store.findUnique( userbase.LoginMetho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.