code stringlengths 1 18.2k |
|---|
inferred positions, resetting all values to 0 is intended. record[:] = [0, 0, 0, 0] return result # first element of the line; sink column (0th element) is always # the absolute value, so always use the provided value sourced from # the original mapping_line; the source column (3rd element) is # never reset, so if a pr... |
the segment. # accumulate the current record first record[0] += segment[0] if len(segment) == 1: # Mark the termination, as 1-tuple determines the end of the # previous symbol and denote that whatever follows are not # in any previous source files. So if it isn't recorded, # make note of this if it wasn't done already.... |
(idx 1 and # 2), regenerate it too. Finally, if the column offsets differ # between source and sink, regenerate. if len(segment) == 5 or regen_next or segment[1] or segment[2] or ( record[0] != record[3]): result.append(regenerate(segment)) regen_next = len(segment) == 5 # must return the consumed/omitted values. retur... |
def write( stream_fragments, stream, normalize=True, book=None, sources=None, names=None, mappings=None): """ Given an iterable of stream fragments, write it to the stream object by using its write method. Returns a 3-tuple, where the first element is the mapping, second element is the list of sources and the third bei... |
normalize flag is currently NOT supported. If multiple sets of outputs are to be produced, the recommended method is to chain all the stream fragments together before passing in. Advanced usage arguments book A Book instance; if none is provided an instance will be created from the default_book constructor. The Bookkee... |
line of the string; None if not present - Original starting column fo the line; None if not present - Original string that this fragment represents (i.e. for the case where this string fragment was an identifier but got mangled into an alternative form); use None if this was not the case. - The source of the fragment. ... |
def push_line(): mappings.append([]) book.keeper._sink_column = 0 if names is None: names = Names() if sources is None: sources = Names() if book is None: book = default_book() if not isinstance(mappings, list): # note that mappings = [] # finalize initial states; the most recent list (mappings[-1]) # is the current li... |
and that an implied source colno/linecol were # provided (i.e. value of 0), and that the string is empty, # it can be safely skipped, since it is an implied and # unmapped indentation if lineno is None or colno is None: mappings[-1].append((book.keeper.sink_column,)) else: name_id = names.update(original_name) # this i... |
not calculate and assume # the value to be written is unchanged. source_line = 0 # if the provided colno is to be inferred, calculate it # based on the previous line length plus the previous # real source column value, otherwise standard value # for tracking. # the reason for using the previous lengths is simply # due ... |
book.keeper.source_column, name_id )) else: mappings[-1].append(( book.keeper.sink_column, source_id, source_line, book.keeper.source_column )) # doing this last to update the position for the next line # or chunk for the relative values based on what was added if line[-1:] in '\r\n': # Note: this HAS to be an edge cas... |
not lines[-1]: logger.warning( 'text in the generated document at line %d may be ' 'mapped incorrectly due to trailing newline character ' 'in provided text fragment.', len(mappings) ) logger.info( 'text in stream fragments should not have trailing ' 'characters after a new line, they should be split ' 'off into a sepa... |
that use case while also # supporting the default normalize flag due to the complex # tracking of all the existing values... mappings = normalize_mappings(mappings) list_sources = [ INVALID_SOURCE if s == NotImplemented else s for s in sources ] or [INVALID_SOURCE] return mappings, list_sources, list(names) |
def encode_sourcemap(filename, mappings, sources, names=[]): """ Take a filename, mappings and names produced from the write function and sources. As the write function currently does not handle the tracking of source filenames, the sources should be a list of one element with the original filename. Arguments filename ... |
as its first element. Returns a dict which can be JSON encoded into a sourcemap file. Example usage: >>> from io import StringIO >>> from calmjs.parse import es5 >>> from calmjs.parse.unparsers.es5 import pretty_printer >>> from calmjs.parse.sourcemap import write, encode_sourcemap >>> program = es5(u"var i = 'hello';"... |
def write_sourcemap( mappings, sources, names, output_stream, sourcemap_stream, normalize_paths=True, source_mapping_url=NotImplemented): """ Write out the mappings, sources and names (generally produced by the write function) to the provided sourcemap_stream, and write the sourceMappingURL to the output_stream. Argume... |
as an attribute by the output_stream object so that the correct character set will be used for the base64 encoded JSON serialized string. normalize_paths If set to True, absolute paths found will be turned into relative paths with relation from the stream being written to, and the path separator used will become a '/' ... |
be missing if using StringIO; fall back to # default_encoding encoding = getattr(output_stream, 'encoding', None) or default_encoding output_stream.writelines([ '\n//# sourceMappingURL=data:application/json;base64;charset=', encoding, ',', base64.b64encode( encoded_sourcemap.encode(encoding)).decode('ascii'), ]) else: ... |
def update(self, name): """ Query a name for the relative index value to be added into the source map name field (optional 5th element). """ if name is None: return if name not in self._names: # add the name if it isn't already tracked self._names[name] = len(self._names) result = self._names[name] - self._current self... |
def repr_compat(s): """ Since Python 2 is annoying with unicode literals, and that we are enforcing the usage of unicode, this ensures the repr doesn't spew out the unicode literal prefix. """ if unicode and isinstance(s, unicode): return repr(s)[1:] else: return repr(s) |
def generate_tab_names(name): """ Return the names to lextab and yacctab modules for the given module name. Typical usage should be like so:: >>> lextab, yacctab = generate_tab_names(__name__) """ package_name, module_name = name.rsplit('.', 1) version = ply_dist.version.replace( '.', '_') if ply_dist is not None else ... |
def normrelpath(base, target): """ This function takes the base and target arguments as paths, and returns an equivalent relative path from base to the target, if both provided paths are absolute. """ if not all(map(isabs, [base, target])): return target return relpath(normpath(target), dirname(normpath(base))) |
def permute_graph(G, order): '''Reorder the graph's vertices, returning a copy of the input graph. order : integer array-like, some permutation of range(G.num_vertices()). ''' adj = G.matrix('dense') adj = adj[np.ix_(order, order)] return Graph.from_adj_matrix(adj) |
def laplacian_reordering(G): '''Reorder vertices using the eigenvector of the graph Laplacian corresponding to the first positive eigenvalue.''' L = G.laplacian() vals, vecs = np.linalg.eigh(L) min_positive_idx = np.argmax(vals == vals[vals>0].min()) vec = vecs[:, min_positive_idx] return permute_graph(G, np.argsort(ve... |
def node_centroid_hill_climbing(G, relax=1, num_centerings=20, verbose=False): '''Iterative reordering method based on alternating rounds of node-centering and hill-climbing search.''' # Initialize order with BFS from a random start node. order = _breadth_first_order(G) for it in range(num_centerings): B = permute_grap... |
def add_column_xsd(self, tb, column, attrs): """ Add the XSD for a column to tb (a TreeBuilder) """ if column.nullable: attrs['minOccurs'] = str(0) attrs['nillable'] = 'true' for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES): if isinstance(column.type, cls): attrs['type'] = xsd_type with tag(tb, 'xsd:element', ... |
else: with tag(tb, 'xsd:element', attrs) as tb: with tag(tb, 'xsd:simpleType') as tb: with tag(tb, 'xsd:restriction', {'base': 'xsd:decimal'}) as tb: if column.type.scale is not None: with tag(tb, 'xsd:fractionDigits', {'value': str(column.type.scale)}) \ as tb: pass if column.type.precision is not None: precision = co... |
def add_column_property_xsd(self, tb, column_property): """ Add the XSD for a column property to the ``TreeBuilder``. """ if len(column_property.columns) != 1: raise NotImplementedError # pragma: no cover column = column_property.columns[0] if column.primary_key and not self.include_primary_keys: return if column.forei... |
def add_class_properties_xsd(self, tb, cls): """ Add the XSD for the class properties to the ``TreeBuilder``. And call the user ``sequence_callback``. """ for p in class_mapper(cls).iterate_properties: if isinstance(p, ColumnProperty): self.add_column_property_xsd(tb, p) if self.sequence_callback: self.sequence_callbac... |
def get_class_xsd(self, io, cls): """ Returns the XSD for a mapped class. """ attrs = {} attrs['xmlns:gml'] = 'http://www.opengis.net/gml' attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema' tb = TreeBuilder() with tag(tb, 'xsd:schema', attrs) as tb: with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb: wi... |
def load_db_from_url(url="https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"): """ Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo in the OpenExoplanetCatalogue GitHub group. The database is loaded from the url in memory :param u... |
def searchPlanet(self, name): """ Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even just 1214. :param name: the name of the planet to search :return: dictionary of results as planetname -> planet object """ searchName = compactString(name) returnDict = {} for altnam... |
def transitingPlanets(self): """ Returns a list of transiting planet objects """ transitingPlanets = [] for planet in self.planets: try: if planet.isTransiting: transitingPlanets.append(planet) except KeyError: # No 'discoverymethod' tag - this also filters Solar System planets pass return transitingPlanets |
def _generatePlanetSearchDict(self): """ Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form (lowercase, no spaces and dashes) """ planetNameDict = {} for planet in self.planets: name = planet.name altnames = planet.params['altnames'] altnames.append(name) # as w... |
def _loadDatabase(self, databaseLocation, stream=False): """ Loads the database from a given file path in the class :param databaseLocation: the location on disk or the stream object :param stream: if true treats the databaseLocation as a stream object """ # Initialise Database self.systems = [] self.binaries = [] self... |
the system if not root.tag == 'system': raise LoadDataBaseError('file {0} does not contain a valid system - could be an error with your version' ' of the catalogue'.format(filename)) self._loadSystem(root) |
def generate_slug(self, model_instance): """Returns a unique slug.""" queryset = model_instance.__class__._default_manager.all() # Only count slugs that match current length to prevent issues # when pre-existing slugs are a different length. lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length} if queryset.fi... |
def south_field_triple(self): """Returns a suitable description of this field for South.""" # We'll just introspect the _actual_ field. from south.modelsinspector import introspector field_class = '%s.%s' % (self.__module__, self.__class__.__name__) args, kwargs = introspector(self) kwargs.update({ 'length': repr(self.... |
def create(cls, session, record, endpoint_override=None, out_type=None, **add_params): """Create an object on HelpScout. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be created. endpoint_override (str, optional): Override the default endpoint using this. ... |
def delete(cls, session, record, endpoint_override=None, out_type=None): """Delete a record. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be deleted. endpoint_override (str, optional): Override the default endpoint using this. out_type (helpscout.BaseMode... |
def get(cls, session, record_id, endpoint_override=None): """Return a specific record. Args: session (requests.sessions.Session): Authenticated session. record_id (int): The ID of the record to get. endpoint_override (str, optional): Override the default endpoint using this. Returns: helpscout.BaseModel: A record singl... |
def list(cls, session, endpoint_override=None, data=None): """Return records in a mailbox. Args: session (requests.sessions.Session): Authenticated session. endpoint_override (str, optional): Override the default endpoint using this. data (dict, optional): Data to provide as request parameters. Returns: RequestPaginato... |
def search(cls, session, queries, out_type): """Search for a record given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will... |
def update(cls, session, record): """Update a record. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be updated. Returns: helpscout.BaseModel: Freshly updated record. """ cls._check_implements('update') data = record.to_api() del data['id'] data['reload'] =... |
def simple_integrate(ts, peak_list, base_ts=None, intname='simple'): """ Integrate each peak naively; without regard to overlap. This is used as the terminal step by most of the other integrators. """ peaks = [] for hints in peak_list: t0, t1 = hints['t0'], hints['t1'] hints['int'] = intname pk_ts = ts.twin((t0, t1)) i... |
def drop_integrate(ts, peak_list): """ Resolves overlap by breaking at the minimum value. """ peaks = [] for _, pks in _get_windows(peak_list): temp_pks = [] pks = sorted(pks, key=lambda p: p['t0']) if 'y0' in pks[0] and 'y1' in pks[-1]: y0, y1 = pks[0]['y0'], pks[-1]['y1'] else: y0 = ts.get_point(pks[0]['t0']) y1 = ts... |
p in temp_pks if t0 <= p['t1']] if len(overlap_pks) > 0: # find the last of the overlapping peaks overlap_pk = max(overlap_pks, key=lambda p: p['t0']) # get the section of trace and find the lowest point over_ts = ts.twin((t0, overlap_pk['t1'])) min_t = over_ts.index[over_ts.values.argmin()] # delete the existing overl... |
def _integrate_mpwrap(ts_and_pks, integrate, fopts): """ Take a zipped timeseries and peaks found in it and integrate it to return peaks. Used to allow multiprocessing support. """ ts, tpks = ts_and_pks pks = integrate(ts, tpks, **fopts) # for p in pks: # p.info['mz'] = str(ts.name) return pks |
def get_bytes(num_bytes): """ Returns a random string of num_bytes length. """ # Is this the way to do it? #s = c_ubyte() # Or this? s = create_string_buffer(num_bytes) # Used to keep track of status. 1 = success, 0 = error. ok = c_int() # Provider? hProv = c_ulong() ok = windll.Advapi32.CryptAcquireContextA(byref(hPro... |
def get_long(): """ Generates a random long. The length of said long varies by platform. """ # The C long type to populate. pbRandomData = c_ulong() # Determine the byte size of this machine's long type. size_of_long = wintypes.DWORD(sizeof(pbRandomData)) # Used to keep track of status. 1 = success, 0 = error. ok = c_i... |
def annotate(*args, **kwargs): """Set function annotations (on Python2 and 3).""" def decorator(f): if not hasattr(f, '__annotations__'): f.__annotations__ = kwargs.copy() else: f.__annotations__.update(kwargs) if args: if len(args) != 1: raise ValueError('annotate supports only a single argument.') f.__annotations__['... |
def auto_instantiate(*classes): """Creates a decorator that will instantiate objects based on function parameter annotations. The decorator will check every argument passed into ``f``. If ``f`` has an annotation for the specified parameter and the annotation is found in ``classes``, the parameter value passed in will b... |
which auto-instantiation should be performed. If empty, perform for all. :note: When dealing with data, it is almost always more convenient to use the :func:`~data.decorators.data` decorator instead. """ def decorator(f): # collect our argspec sig = signature(f) @wraps(f) def _(*args, **kwargs): bvals = sig.bind(*args,... |
def data(*argnames): """Designate an argument as a :class:`~data.Data` argument. Works by combining calls to :func:`~data.decorators.auto_instantiate` and :func:~data.decorators.annotate` on the named arguments. Example: .. code-block:: python class Foo(object): @data('bar') def meth(self, foo, bar): pass Inside ``meth... |
def ratioTerminatorToStar(H_p, R_p, R_s): # TODO add into planet class r"""Calculates the ratio of the terminator to the star assuming 5 scale heights large. If you dont know all of the input try :py:func:`calcRatioTerminatorToStar` .. math:: \Delta F = \frac{10 H R_p + 25 H^2}{R_\star^2} Where :math:`\Delta F` is the ... |
def SNRPlanet(SNRStar, starPlanetFlux, Nobs, pixPerbin, NVisits=1): r""" Calculate the Signal to Noise Ratio of the planet atmosphere .. math:: \text{SNR}_\text{planet} = \text{SNR}_\text{star} \times \Delta F \times \sqrt{N_\text{obs}} \times \sqrt{N_\text{pixPerbin}} \times \sqrt{N_\text{visits}} Where :math:`\text{S... |
def transitDurationCircular(P, R_s, R_p, a, i): r"""Estimation of the primary transit time. Assumes a circular orbit. .. math:: T_\text{dur} = \frac{P}{\pi}\sin^{-1} \left[\frac{R_\star}{a}\frac{\sqrt{(1+k)^2 + b^2}}{\sin{a}} \right] Where :math:`T_\text{dur}` transit duration, P orbital period, :math:`R_\star` radius ... |
def estimateStellarTemperature(M_s): """Estimates stellar temperature using the main sequence relationship T ~ 5800*M^0.65 (Cox 2000). """ # TODO improve with more x and k values from Cox 2000 try: temp = (5800 * aq.K * float(M_s.rescale(aq.M_s) ** 0.65)).rescale(aq.K) except AttributeError: temp = np.nan return temp |
def estimateDistance(m, M, Av=0.0): """ estimate the distance to star based on the absolute magnitude, apparent magnitude and the absorption / extinction. :param m: apparent magnitude :param M: absolute magnitude :param Av: absorbtion / extinction :return: d (distance to object) in parsecs """ try: m = float(m) # basic... |
def _createAbsMagEstimationDict(): """ loads magnitude_estimation.dat which is from http://xoomer.virgilio.it/hrtrace/Sk.htm on 24/01/2014 and based on Schmid-Kaler (1982) creates a dict in the form [Classletter][ClassNumber][List of values for each L Class] """ magnitude_estimation_filepath = resource_filename( __name... |
'IV': 1, 'III': 2, 'II': 3, 'Ib': 4, 'Iab': 5, 'Ia': 6, 'Ia0': 7} return absMagDict, LClassRef |
def estimateAbsoluteMagnitude(spectralType): """Uses the spectral type to lookup an approximate absolute magnitude for the star. """ from .astroclasses import SpectralType specType = SpectralType(spectralType) if specType.classLetter == '': return np.nan elif specType.classNumber == '': specType.classNumber = 5 # appro... |
def is_remote_allowed(remote): """ Check if `remote` is allowed to make a CORS request. """ if settings.debug: return True if not remote: return False for domain_pattern in settings.node['cors_whitelist_domains']: if domain_pattern.match(remote): return True return False |
def endpoint(url, methods=['GET']): """ Returns a decorator which when applied a function, causes that function to serve `url` and only allows the HTTP methods in `methods` """ def decorator(function, methods=methods): # Always allow OPTIONS since CORS requests will need it. methods = set(methods) methods.add('OPTIONS'... |
* (time.time() - start_time)) }) headers = [] remote_origin = environment.get('HTTP_ORIGIN') if req_method == 'OPTIONS': # This is a CORS preflight request so check that the remote domain is # allowed and respond with appropriate CORS headers. # http://www.html5rocks.com/static/images/cors_server_flowchart.png if is_re... |
- start_time)) }) # All responses are JSON. headers.append(('Content-Type', 'application/json')) if remote_origin: headers.append(('Access-Control-Allow-Origin', remote_origin)) response = function(environment, start_response, headers) if not isinstance(response, types.GeneratorType): response[TOOK_FIELD] = '%fms' % (1... |
def generate_challenges(self, num, root_seed): """ Generate the specified number of hash challenges. :param num: The number of hash challenges we want to generate. :param root_seed: Some value that we use to generate our seeds from. """ # Generate a series of seeds seeds = self.generate_seeds(num, root_seed, self.secre... |
def meet_challenge(self, challenge): """ Get the SHA256 hash of a specific file block plus the provided seed. The default block size is one tenth of the file. If the file is larger than 10KB, 1KB is used as the block size. :param challenge: challenge as a `Challenge <heartbeat.Challenge>` object """ chunk_size = min(10... |
def generate_seeds(num, root_seed, secret): """ Deterministically generate list of seeds from a root seed. :param num: Numbers of seeds to generate as int :param root_seed: Seed to start off with. :return: seed values as a list of length num """ # Generate a starting seed from the root if num < 0: raise HeartbeatError(... |
def pick_blocks(self, num, root_seed): """ Pick a set of positions to start reading blocks from the file that challenges are created for. This is a deterministic operation. Positions are guaranteed to be within the bounds of the file. :param num: Number of blocks to pick :param root_seed: Seed with which begin picking ... |
def check_answer(self, hash_answer): """ Check if the returned hash is in our challenges list. :param hash_answer: Hash that we compare to our list of challenges :return: boolean indicating if answer is correct, True, or not, False """ for challenge in self.challenges: if challenge.response == hash_answer: # If we don'... |
def _load_apis(self): """Find available APIs and set instances property auth proxies.""" helpscout = __import__('helpscout.apis') for class_name in helpscout.apis.__all__: if not class_name.startswith('_'): cls = getattr(helpscout.apis, class_name) api = AuthProxy(self.session, cls) setattr(self, class_name, api) self.... |
def slice_time(begin, end=None, duration=datetime.timedelta(days=2)): """ :param begin: datetime :param end: datetime :param duration: timedelta :return: a generator for a set of timeslices of the given duration """ duration_ms = int(duration.total_seconds() * 1000) previous = int(unix_time(begin) * 1000) next = previo... |
def make_response(response): """Make response tuple Potential features to be added - Parameters validation """ if isinstance(response, unicode) or \ isinstance(response, str): response = (response, 'text/html') return response |
def on_notify_load_status(self, webkitView, *args, **kwargs): """Callback function when the page was loaded completely FYI, this function will be called after $(document).ready() in jQuery """ status = webkitView.get_load_status() if status == status.FINISHED: if self.debug is True: print 'Load finished' |
def _init_ui(self): """Initial the first UI page. - load html from '/' endpoint - if <title> is defined, use as windows title """ (content, mimetype) = make_response(self._url_map_to_function('/')) try: beautifulsoup = BeautifulSoup(content) self.window.set_title(beautifulsoup.find('title').string) except: pass if self... |
def fft(ts): """ Perform a fast-fourier transform on a Trace """ t_step = ts.index[1] - ts.index[0] oc = np.abs(np.fft.fftshift(np.fft.fft(ts.values))) / len(ts.values) t = np.fft.fftshift(np.fft.fftfreq(len(oc), d=t_step)) return Trace(oc, t) |
def movingaverage(arr, window): """ Calculates the moving average ("rolling mean") of an array of a certain window size. """ m = np.ones(int(window)) / int(window) return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect') |
def loads(ast_str): """ Create a Trace from a suitably compressed string. """ data = zlib.decompress(ast_str) li = struct.unpack('<L', data[0:4])[0] lt = struct.unpack('<L', data[4:8])[0] n = data[8:8 + li].decode('utf-8') t = np.fromstring(data[8 + li:8 + li + lt]) d = np.fromstring(data[8 + li + lt:]) return Trace(d,... |
def dumps(asts): """ Create a compressed string from an Trace. """ d = asts.values.tostring() t = asts.index.values.astype(float).tostring() lt = struct.pack('<L', len(t)) i = asts.name.encode('utf-8') li = struct.pack('<L', len(i)) try: # python 2 return buffer(zlib.compress(li + lt + i + t + d)) except NameError: # p... |
def ts_func(f): """ This wraps a function that would normally only accept an array and allows it to operate on a DataFrame. Useful for applying numpy functions to DataFrames. """ def wrap_func(df, *args): # TODO: should vectorize to apply over all columns? return Chromatogram(f(df.values, *args), df.index, df.columns) ... |
def desaturate(c, k=0): """ Utility function to desaturate a color c by an amount k. """ from matplotlib.colors import ColorConverter c = ColorConverter().to_rgb(c) intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] return [intensity * k + i * (1 - k) for i in c] |
def find_spectrum_match(spec, spec_lib, method='euclidian'): """ Find spectrum in spec_lib most similar to spec. """ # filter out any points with abundance below 1 % # spec[spec / np.sum(spec) < 0.01] = 0 # normalize everything to sum to 1 spec = spec / np.max(spec) if method == 'dot': d1 = (spec_lib * lil_matrix(spec)... |
def get_command(self, ctx, name): """Get a callable command object.""" if name not in self.daemon_class.list_actions(): return None # The context object is a Daemon object daemon = ctx.obj def subcommand(debug=False): """Call a daemonocle action.""" if daemon.detach and debug: daemon.detach = False daemon.do_action(nam... |
def load(self, path=None): ''' Load configuration (from configuration files). Parameters ---------- path : ~pathlib.Path or None Path to configuration file, which must exist; or path to directory containing a configuration file; or None. Returns ------- ~typing.Dict[str, ~typing.Dict[str, str]] The configuration as a d... |
paths.append(path) # Prepend file sys root to abs paths paths = [(path_._root / str(x)[1:] if x.is_absolute() else x) for x in paths] if path: path = paths[-1] # Passed path must exist if not path.exists(): raise ValueError('Expected configuration file at {}'.format(path)) # Configure parser config_parser = ConfigParse... |
def cli_help_message(self, description): ''' Get a user friendly help message that can be dropped in a `click.Command`\ 's epilog. Parameters ---------- description : str Description of the configuration file to include in the message. Returns ------- str A help message that uses :py:mod:`click`\ 's help formatting con... |
def start(self): """ Start the application, initializing your components. """ current_pedalboard = self.controller(CurrentController).pedalboard if current_pedalboard is None: self.log('Not exists any current pedalboard.') self.log('Use CurrentController to set the current pedalboard') else: self.log('Load current peda... |
def stop(self): """ Stop the application, closing your components. """ for component in self.components: component.close() self.log('Stopping component - {}', component.__class__.__name__) for controller in self.controllers.values(): controller.close() self.log('Stopping controller - {}', controller.__class__.__name__)... |
def get_seconds(value, scale): """Convert time scale dict to seconds Given a dictionary with keys for scale and value, convert value into seconds based on scale. """ scales = { 'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 * 24, 'weeks': lambda x: x *... |
def _get_col_epsg(mapped_class, geom_attr): """Get the EPSG code associated with a geometry attribute. Arguments: geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is the name of the geometry attribute as defined in the mapped class. """ col = class_map... |
def create_geom_filter(request, mapped_class, geom_attr): """Create MapFish geometry filter based on the request params. Either a box or within or geometry filter, depending on the request params. Additional named arguments are passed to the spatial filter. Arguments: request the request. mapped_class the SQLAlchemy ma... |
shape = Point(float(request.params['lon']), float(request.params['lat'])) elif 'geometry' in request.params: shape = loads(request.params['geometry'], object_hook=GeoJSON.to_instance) shape = asShape(shape) if shape is None: return None column_epsg = _get_col_epsg(mapped_class, geom_attr) geom_attr = getattr(mapped_cla... |
def create_attr_filter(request, mapped_class): """Create an ``and_`` SQLAlchemy filter (a ClauseList object) based on the request params (``queryable``, ``eq``, ``ne``, ...). Arguments: request the request. mapped_class the SQLAlchemy mapped class. """ mapping = { 'eq': '__eq__', 'ne': '__ne__', 'lt': '__lt__', 'lte': ... |
def create_filter(request, mapped_class, geom_attr, **kwargs): """ Create MapFish default filter based on the request params. Arguments: request the request. mapped_class the SQLAlchemy mapped class. geom_attr the key of the geometry property as defined in the SQLAlchemy mapper. If you use ``declarative_base`` this is ... |
def _filter_attrs(self, feature, request): """ Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters. """ if 'attrs' in request.params: attrs = request.params['attrs'].split(',') props = feature.properties new_props = {} for name in attrs: if ... |
def _get_order_by(self, request): """ Return an SA order_by """ attr = request.params.get('sort', request.params.get('order_by')) if attr is None or not hasattr(self.mapped_class, attr): return None if request.params.get('dir', '').upper() == 'DESC': return desc(getattr(self.mapped_class, attr)) else: return asc(getatt... |
def _query(self, request, filter=None): """ Build a query based on the filter and the request params, and send the query to the database. """ limit = None offset = None if 'maxfeatures' in request.params: limit = int(request.params['maxfeatures']) if 'limit' in request.params: limit = int(request.params['limit']) if 'o... |
def count(self, request, filter=None): """ Return the number of records matching the given filter. """ if filter is None: filter = create_filter(request, self.mapped_class, self.geom_attr) query = self.Session().query(self.mapped_class) if filter is not None: query = query.filter(filter) return query.count() |
def read(self, request, filter=None, id=None): """ Build a query based on the filter or the idenfier, send the query to the database, and return a Feature or a FeatureCollection. """ ret = None if id is not None: o = self.Session().query(self.mapped_class).get(id) if o is None: return HTTPNotFound() # FIXME: we return ... |
def create(self, request): """ Read the GeoJSON feature collection from the request body and create new objects in the database. """ if self.readonly: return HTTPMethodNotAllowed(headers={'Allow': 'GET, HEAD'}) collection = loads(request.body, object_hook=GeoJSON.to_instance) if not isinstance(collection, FeatureCollec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.