Search is not available for this dataset
text
stringlengths
75
104k
def frombytes(data, size, bandtype=gdal.GDT_Byte): """Returns an in-memory raster initialized from a pixel buffer. Arguments: data -- byte buffer of raw pixel data size -- two or three-tuple of (xsize, ysize, bandcount) bandtype -- band data type """ r = ImageDriver('MEM').raster('', size, ...
def project(self, coords): """Convert image pixel/line coordinates to georeferenced x/y, return a generator of two-tuples. Arguments: coords -- input coordinates as iterable containing two-tuples/lists such as ((0, 0), (10, 10)) """ geotransform = self.tuple ...
def transform(self, coords): """Transform from projection coordinates (Xp,Yp) space to pixel/line (P,L) raster space, based on the provided geotransformation. Arguments: coords -- input coordinates as iterable containing two-tuples/lists such as ((-120, 38), (-121, 39)) ...
def copy(self, source, dest): """Returns a copied Raster instance. Arguments: source -- the source Raster instance or filepath as str dest -- destination filepath as str """ if not self.copyable: raise IOError('Driver does not support raster copying') ...
def Create(self, *args, **kwargs): """Calls Driver.Create() with optionally provided creation options as dict, or falls back to driver specific defaults. """ if not self.writable: raise IOError('Driver does not support raster creation') options = kwargs.pop('options',...
def options(self): """Returns a dict of driver specific raster creation options. See GDAL format docs at http://www.gdal.org/formats_list.html """ if self._options is None: try: elem = ET.fromstring( self.info.get('DMD_CREATIONOPTIONLIST',...
def raster(self, path, size, bandtype=gdal.GDT_Byte): """Returns a new Raster instance. gdal.Driver.Create() does not support all formats. Arguments: path -- file object or path as str size -- two or three-tuple of (xsize, ysize, bandcount) bandtype -- GDAL pixel data t...
def SetGeoTransform(self, affine): """Sets the affine transformation. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: affine -- AffineTransform or six-tuple of geotransformation values """ if isinstance(affine, collections.Sequence): ...
def array(self, envelope=()): """Returns an NDArray, optionally subset by spatial envelope. Keyword args: envelope -- coordinate extent tuple or Envelope """ args = () if envelope: args = self.get_offset(envelope) return self.ds.ReadAsArray(*args)
def envelope(self): """Returns the minimum bounding rectangle as a tuple of min X, min Y, max X, max Y. """ if self._envelope is None: origin = self.affine.origin ur_x = origin[0] + self.ds.RasterXSize * self.affine.scale[0] ll_y = origin[1] + self.ds....
def get_offset(self, envelope): """Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size). Arguments: envelope -- coordinate extent tuple or Envelope """ if isinstance(envelope, collections.Sequence): envelope = Envelope(envelope) if not (self.en...
def driver(self): """Returns the underlying ImageDriver instance.""" if self._driver is None: self._driver = ImageDriver(self.ds.GetDriver()) return self._driver
def new(self, size=(), affine=None): """Derive new Raster instances. Keyword args: size -- tuple of image size (width, height) affine -- AffineTransform or six-tuple of geotransformation values """ size = size or self.size + (len(self),) band = self.ds.GetRasterB...
def masked_array(self, geometry=None): """Returns a MaskedArray using nodata values. Keyword args: geometry -- any geometry, envelope, or coordinate extent tuple """ if geometry is None: return self._masked_array() geom = transform(geometry, self.sref) ...
def nodata(self): """Returns read only property for band nodata value, assuming single band rasters for now. """ if self._nodata is None: self._nodata = self[0].GetNoDataValue() return self._nodata
def ReadRaster(self, *args, **kwargs): """Returns raster data bytes for partial or full extent. Overrides gdal.Dataset.ReadRaster() with the full raster size by default. """ args = args or (0, 0, self.ds.RasterXSize, self.ds.RasterYSize) return self.ds.ReadRaster(*args, ...
def resample(self, size, interpolation=gdalconst.GRA_NearestNeighbour): """Returns a new instance resampled to provided size. Arguments: size -- tuple of x,y image dimensions """ # Find the scaling factor for pixel size. factors = (size[0] / float(self.RasterXSize), ...
def save(self, to, driver=None): """Save this instance to the path and format provided. Arguments: to -- output path as str, file, or MemFileIO instance Keyword args: driver -- GDAL driver name as string or ImageDriver """ path = getattr(to, 'name', to) i...
def SetProjection(self, sref): """Sets the spatial reference. Intercepts the gdal.Dataset call to ensure use as a property setter. Arguments: sref -- SpatialReference or any format supported by the constructor """ if not hasattr(sref, 'ExportToWkt'): sref = ...
def shape(self): """Returns a tuple of row, column, (band count if multidimensional).""" shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount) return shp[:2] if shp[2] <= 1 else shp
def warp(self, to_sref, dest=None, interpolation=gdalconst.GRA_NearestNeighbour): """Returns a new reprojected instance. Arguments: to_sref -- spatial reference as a proj4 or wkt string, or a SpatialReference Keyword args: dest -- filepath as str interpolation --...
def calc_chunklen(alph_len): ''' computes the ideal conversion ratio for the given alphabet. A ratio is considered ideal when the number of bits in one output encoding chunk that don't add up to one input encoding chunk is minimal. ''' binlen, enclen = min([ (i, i*8 / m...
def lookup_alphabet(charset): ''' retrieves a named charset or treats the input as a custom alphabet and use that ''' if charset in PRESETS: return PRESETS[charset] if len(charset) < 16: _logger.warning('very small alphabet in use, possibly a failed lookup?') return charset
def _encode_chunk(self, data, index): ''' gets a chunk from the input data, converts it to a number and encodes that number ''' chunk = self._get_chunk(data, index) return self._encode_long(self._chunk_to_long(chunk))
def _encode_long(self, val): ''' encodes an integer of 8*self.chunklen[0] bits using the specified alphabet ''' return ''.join([ self.alphabet[(val//len(self.alphabet)**i) % len(self.alphabet)] for i in reversed(range(self.chunklen[1])) ...
def _chunk_to_long(self, chunk): ''' parses a chunk of bytes to integer using big-endian representation ''' return sum([ 256**(self.chunklen[0]-1-i) * ord_byte(chunk[i]) for i in range(self.chunklen[0]) ])
def _get_chunk(self, data, index): ''' partition the data into chunks and retrieve the chunk at the given index ''' return data[index*self.chunklen[0]:(index+1)*self.chunklen[0]]
def memoize(func): """Cache result of function call.""" cache = {} @wraps(func) def inner(filename): if filename not in cache: cache[filename] = func(filename) return cache[filename] return inner
def _regexp(filename): """Get a list of patterns from a file and make a regular expression.""" lines = _get_resource_content(filename).decode('utf-8').splitlines() return re.compile('|'.join(lines))
def normalize_date_format(date): ''' Dates can be defined in many ways, but zipline use aware datetime objects only. Plus, the software work with utc timezone so we convert it. ''' if isinstance(date, int): # This is probably epoch time date = time.strftime('%Y-%m-%d %H:%M:%S', ...
def _detect_timezone(): ''' Get timezone as set by the system ''' default_timezone = 'America/New_York' locale_code = locale.getdefaultlocale() return default_timezone if not locale_code[0] else \ str(pytz.country_timezones[locale_code[0][-2:]][0])
def api_url(full_version, resource): ''' >>> # Harmonize api endpoints >>> # __version__ should be like major.minor.fix >>> from my_app import __version__ >>> api_url(__version__, '/some/endpoint') /v0/some/endpoint ''' return '/v{}/{}'.format(dna.utils.Version(full_version).major, resou...
def api_doc(full_version, resource, method='GET', **kwargs): ''' >>> # Wrap api endpoints with more details >>> api_doc('/resource', secure=True, key='value') GET /resource?secure=true&key=value ''' doc = '{} {}'.format(method, api_url(full_version, resource)) params = '&'.join(['{}={}'.form...
def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to...
def activate_pdb_hook(): ''' Catch exceptions with a prompt for post-mortem analyzis''' def debug_exception(type_exception, value, tb): import pdb pdb.post_mortem(tb) import sys sys.excepthook = debug_exception
def emphasis(obj, align=True): ''' Clearer data printing ''' if isinstance(obj, dict): if align: pretty_msg = os.linesep.join( ["%25s: %s" % (k, obj[k]) for k in sorted(obj.keys())]) else: pretty_msg = json.dumps(obj, indent=4, sort_keys=True) else: ...
def listcoins(self): ''' Use this function to list all coins with their data which are available on cryptocoincharts. Usage: http://api.cryptocoincharts.info/listCoins ''' url = self.API_PATH + 'listCoins' json_data = json.loads(self._getdata(url)) ...
def tradingpair(self, pair): ''' Use this function to query price and volume data for ONE trading pair. A list with all coin currencies can be found by using the listcoins method. A example pair: currency1_currency2 = "doge_btc" Usage: http://api.cryptocoincharts.info/tradingPai...
def tradingpairs(self, pairs): ''' Use this function to query price and volume data for MANY trading pairs. Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...] A example pair: currency1_currency2 = "doge_btc" ...
def _getdata(self, url, data = ""): ''' Wrapper method ''' request = Request(url) if data != "": request = Request(url, urlencode(data)) try: response = urlopen(request) except HTTPError as e: print('The Se...
async def handle_jobs(job_handler, host, port, *, loop): """ Connects to the remote master and continuously receives calls, executes them, then returns a response until interrupted. """ try: try: reader, writer = await asyncio.open_connection(host, port, loop=loop) exce...
def worker_main(job_handler, host, port): """ Starts an asyncio event loop to connect to the master and run jobs. """ loop = asyncio.new_event_loop() asyncio.set_event_loop(None) loop.run_until_complete(handle_jobs(job_handler, host, port, loop=loop)) loop.close()
def run_worker_pool(job_handler, host="localhost", port=48484, *, max_workers=None): """ Runs a pool of workers which connect to a remote HighFive master and begin executing calls. """ if max_workers is None: max_workers = multiprocessing.cpu_count() processes = [...
def classification(self, classification): """ Sets the classification of this CompanyDetailCompany. Classification of Company :param classification: The classification of this CompanyDetailCompany. :type: str """ allowed_values = ["Public Limited Indian Non-Gover...
def _send_message(self, msg): """Add message to queue and start processing the queue.""" LWLink.the_queue.put_nowait(msg) if LWLink.thread is None or not LWLink.thread.isAlive(): LWLink.thread = Thread(target=self._send_queue) LWLink.thread.start()
def turn_on_light(self, device_id, name): """Create the message to turn light on.""" msg = "!%sFdP32|Turn On|%s" % (device_id, name) self._send_message(msg)
def turn_on_switch(self, device_id, name): """Create the message to turn switch on.""" msg = "!%sF1|Turn On|%s" % (device_id, name) self._send_message(msg)
def turn_on_with_brightness(self, device_id, name, brightness): """Scale brightness from 0..255 to 1..32.""" brightness_value = round((brightness * 31) / 255) + 1 # F1 = Light on and F0 = light off. FdP[0..32] is brightness. 32 is # full. We want that when turning the light on. m...
def turn_off(self, device_id, name): """Create the message to turn light or switch off.""" msg = "!%sF0|Turn Off|%s" % (device_id, name) self._send_message(msg)
def _send_queue(self): """If the queue is not empty, process the queue.""" while not LWLink.the_queue.empty(): self._send_reliable_message(LWLink.the_queue.get_nowait())
def _send_reliable_message(self, msg): """Send msg to LightwaveRF hub.""" result = False max_retries = 15 trans_id = next(LWLink.transaction_id) msg = "%d,%s" % (trans_id, msg) try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \ as...
def create_adapter(cmph, ffi, obj): """ Generates a wrapped adapter for the given object Parameters ---------- obj : list, buffer, array, or file Raises ------ ValueError If presented with an object that cannot be adapted Returns ------- CMPH capable adapter """ ...
def nature(self, nature): """ Sets the nature of this YearlyFinancials. Nature of the balancesheet :param nature: The nature of this YearlyFinancials. :type: str """ allowed_values = ["STANDALONE"] if nature not in allowed_values: raise ValueE...
def computed_displaywidth(): '''Figure out a reasonable default with. Use os.environ['COLUMNS'] if possible, and failing that use 80. ''' try: width = int(os.environ['COLUMNS']) except (KeyError, ValueError): width = get_terminal_size().columns return width or 80
def columnize(array, displaywidth=80, colsep = ' ', arrange_vertical=True, ljust=True, lineprefix='', opts={}): """Return a list of strings as a compact set of columns arranged horizontally or vertically. For example, for a line width of 4 characters (arranged vertically): ...
def generate_hash(data, algorithm='chd_ph', hash_fns=(), chd_keys_per_bin=1, chd_load_factor=None, fch_bits_per_key=None, num_graph_vertices=None, brz_memory_size=8, brz_temp_dir=None, brz_max_keys_per_bucket=128, bdz_precomputed_rank=7, chd_avg_ke...
def load_hash(existing_mph): """ Load a Minimal Perfect Hash (MPH) Given an input stream, this will load a minimal perfect hash Parameters ---------- existing_mph : file_like, string An input stream that is file like, and able to load a preexisting MPH, or the filename represent...
def save(self, output): """ Persist the Minimal Perfect Hash (MPH) to a stream Parameters ---------- output : file_like The stream to use to persist the MPH Raises ------ IOError If there is an issue accessing or manipulating the ...
def lookup(self, key): """ Generate hash code for a key from the Minimal Perfect Hash (MPH) Parameters ---------- Key : object The item to generate a key for, this works best for keys that are strings, or can be transformed fairly directly into bytes ...
def update_(self, sct_dict, conf_arg=True): """Update values of configuration section with dict. Args: sct_dict (dict): dict indexed with option names. Undefined options are discarded. conf_arg (bool): if True, only options that can be set in a config ...
def reset_(self): """Restore default values of options in this section.""" for opt, meta in self.defaults_(): self[opt] = meta.default
def from_dict_(cls, conf_dict): """Use a dictionary to create a :class:`ConfigurationManager`. Args: conf_dict (dict of dict of :class:`ConfOpt`): the first level of keys should be the section names. The second level should be the option names. The values are...
def set_config_files_(self, *config_files): """Set the list of config files. Args: config_files (pathlike): path of config files, given in the order of reading. """ self._config_files = tuple(pathlib.Path(path) for path in config_files)
def opt_vals_(self): """Iterator over sections, option names, and option values. This iterator is also implemented at the section level. The two loops produce the same output:: for sct, opt, val in conf.opt_vals_(): print(sct, opt, val) for sct in conf....
def defaults_(self): """Iterator over sections, option names, and option metadata. This iterator is also implemented at the section level. The two loops produce the same output:: for sct, opt, meta in conf.defaults_(): print(sct, opt, meta.default) for ...
def create_config_(self, index=0, update=False): """Create config file. Create config file in :attr:`config_files_[index]`. Parameters: index(int): index of config file. update (bool): if set to True and :attr:`config_files_` already exists, its content ...
def update_(self, conf_dict, conf_arg=True): """Update values of configuration options with dict. Args: conf_dict (dict): dict of dict indexed with section and option names. conf_arg (bool): if True, only options that can be set in a config file a...
def read_config_(self, cfile): """Read a config file and set config values accordingly. Returns: dict: content of config file. """ if not cfile.exists(): return {} try: conf_dict = toml.load(str(cfile)) except toml.TomlDecodeError: ...
def read_configs_(self): """Read config files and set config values accordingly. Returns: (dict, list, list): respectively content of files, list of missing/empty files and list of files for which a parsing error arised. """ if not self.config_files_:...
def _lookup_version(module_file): """ For the given module file (usually found by: from package import __file__ as module_file in the caller, return the location of the current RELEASE-VERSION file and the file itself. """ version_dir = path.abspath(path.dirname(module_file)) v...
def _names(section, option): """List of cli strings for a given option.""" meta = section.def_[option] action = meta.cmd_kwargs.get('action') if action is internal.Switch: names = ['-{}'.format(option), '+{}'.format(option)] if meta.shortname is not None: names.append('-{}'.f...
def sections_list(self, cmd=None): """List of config sections used by a command. Args: cmd (str): command name, set to ``None`` or ``''`` for the bare command. Returns: list of str: list of configuration sections used by that command. """ ...
def _cmd_opts_solver(self, cmd_name): """Scan options related to one command and enrich _opt_cmds.""" sections = self.sections_list(cmd_name) cmd_dict = self._opt_cmds[cmd_name] if cmd_name else self._opt_bare for sct in reversed(sections): for opt, opt_meta in self._conf[sct...
def _add_options_to_parser(self, opts_dict, parser): """Add options to a parser.""" store_bool = ('store_true', 'store_false') for opt, sct in opts_dict.items(): meta = self._conf[sct].def_[opt] kwargs = copy.deepcopy(meta.cmd_kwargs) action = kwargs.get('acti...
def _build_parser(self): """Build command line argument parser. Returns: :class:`argparse.ArgumentParser`: the command line argument parser. You probably won't need to use it directly. To parse command line arguments and update the :class:`ConfigurationManager` insta...
def parse_args(self, arglist=None): """Parse arguments and update options accordingly. Args: arglist (list of str): list of arguments to parse. If set to None, ``sys.argv[1:]`` is used. Returns: :class:`Namespace`: the argument namespace returned by the ...
def _zsh_comp_command(self, zcf, cmd, grouping, add_help=True): """Write zsh _arguments compdef for a given command. Args: zcf (file): zsh compdef file. cmd (str): command name, set to None or '' for bare command. grouping (bool): group options (zsh>=5.4). ...
def zsh_complete(self, path, cmd, *cmds, sourceable=False): """Write zsh compdef script. Args: path (path-like): desired path of the compdef script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. ...
def _bash_comp_command(self, cmd, add_help=True): """Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings. ...
def bash_complete(self, path, cmd, *cmds): """Write bash complete script. Args: path (path-like): desired path of the complete script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. """ path...
def zsh_version(): """Try to guess zsh version, return (0, 0) on failure.""" try: out = subprocess.check_output(shlex.split('zsh --version')) except (FileNotFoundError, subprocess.CalledProcessError): return (0, 0) match = re.search(br'[0-9]+\.[0-9]+', out) return tuple(map(int, matc...
async def start_master(host="", port=48484, *, loop=None): """ Starts a new HighFive master at the given host and port, and returns it. """ loop = loop if loop is not None else asyncio.get_event_loop() manager = jobs.JobManager(loop=loop) workers = set() server = await loop.create_server( ...
def connection_made(self, transport): """ Called when a remote worker connection has been found. Finishes setting up the protocol object. """ if self._manager.is_closed(): logger.debug("worker tried to connect while manager was closed") return lo...
def data_received(self, data): """ Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer, it removed and sent to line_received(). """ self._buffer.extend(data) while True: ...
def line_received(self, line): """ Called when a complete line is found from the remote worker. Decodes a response object from the line, then passes it to the worker object. """ response = json.loads(line.decode("utf-8")) self._worker.response_received(response)
def connection_lost(self, exc): """ Called when the connection to the remote worker is broken. Closes the worker. """ logger.debug("worker connection lost") self._worker.close() self._workers.remove(self._worker)
def _job_loaded(self, job): """ Called when a job has been found for the worker to run. Sends the job's RPC to the remote worker. """ logger.debug("worker {} found a job".format(id(self))) if self._closed: self._manager.return_job(job) return ...
def response_received(self, response): """ Called when a response to a job RPC has been received. Decodes the response and finalizes the result, then reports the result to the job manager. """ if self._closed: return assert self._job is not None ...
def close(self): """ Closes the worker. No more jobs will be handled by the worker, and any running job is immediately returned to the job manager. """ if self._closed: return self._closed = True if self._job is not None: self._manager.r...
def run(self, job_list): """ Runs a job set which consists of the jobs in an iterable job list. """ if self._closed: raise RuntimeError("master is closed") return self._manager.add_job_set(job_list)
def close(self): """ Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled. """ if self._closed: return self._closed = True self._server.close() self._manager.close() for worker in se...
def _change(self): """ Called when a state change has occurred. Waiters are notified that a change has occurred. """ for waiter in self._waiters: if not waiter.done(): waiter.set_result(None) self._waiters = []
def add(self, result): """ Adds a new result. """ assert not self._complete self._results.append(result) self._change()
async def wait_changed(self): """ Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed, this method returns immediately. """ if not self.is_complete(): wai...
def _load_job(self): """ If there is still a job in the job iterator, loads it and increments the active job count. """ try: next_job = next(self._jobs) except StopIteration: self._on_deck = None else: if not isinstance(next_jo...
def _done(self): """ Marks the job set as completed, and notifies all waiting tasks. """ self._results.complete() waiters = self._waiters for waiter in waiters: waiter.set_result(None) self._manager.job_set_done(self)
def get_job(self): """ Gets a job from the job set if one is queued. The jobs_available() method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available, an IndexError is raised. """ if len(self._return...
def add_result(self, result): """ Adds the result of a completed job to the result list, then decrements the active job count. If the job set is already complete, the result is simply discarded instead. """ if self._active_jobs == 0: return self._res...
def cancel(self): """ Cancels the job set. The job set is immediately finished, and all queued jobs are discarded. """ if self._active_jobs == 0: return self._jobs = iter(()) self._on_deck = None self._return_queue.clear() self._activ...
async def wait_done(self): """ Waits until the job set is finished. Returns immediately if the job set is already finished. """ if self._active_jobs > 0: future = self._loop.create_future() self._waiters.append(future) await future