Search is not available for this dataset
text
stringlengths
75
104k
def _connect_deferred(self, deferred): """ Hook up the Deferred that that this will be the result of. Should only be run in Twisted thread, and only called once. """ self._deferred = deferred # Because we use __del__, we need to make sure there are no cycles # i...
def _set_result(self, result): """ Set the result of the EventualResult, if not already set. This can only happen in the reactor thread, either as a result of Deferred firing, or as a result of ResultRegistry.stop(). So, no need for thread-safety. """ if self._re...
def _result(self, timeout=None): """ Return the result, if available. It may take an unknown amount of time to return the result, so a timeout option is provided. If the given number of seconds pass with no result, a TimeoutError will be thrown. If a previous call timed...
def wait(self, timeout=None): """ Return the result, or throw the exception if result is a failure. It may take an unknown amount of time to return the result, so a timeout option is provided. If the given number of seconds pass with no result, a TimeoutError will be thrown. ...
def original_failure(self): """ Return the underlying Failure object, if the result is an error. If no result is yet available, or the result was not an error, None is returned. This method is useful if you want to get the original traceback for an error result. ...
def _startReapingProcesses(self): """ Start a LoopingCall that calls reapAllProcesses. """ lc = LoopingCall(self._reapAllProcesses) lc.clock = self._reactor lc.start(0.1, False)
def _common_setup(self): """ The minimal amount of setup done by both setup() and no_setup(). """ self._started = True self._reactor = self._reactorFactory() self._registry = ResultRegistry() # We want to unblock EventualResult regardless of how the reactor is ...
def setup(self): """ Initialize the crochet library. This starts the reactor in a thread, and connect's Twisted's logs to Python's standard library logging module. This must be called at least once before the library can be used, and can be called multiple times. ...
def _run_in_reactor(self, function, _, args, kwargs): """ Implementation: A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, an EventualResult is returned. """ def runs_in_reactor(result, args, kwargs): ...
def run_in_reactor(self, function): """ A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, an EventualResult is returned. """ result = self._run_in_reactor(function) # Backwards compatibility; use __wrap...
def wait_for_reactor(self, function): """ DEPRECATED, use wait_for(timeout) instead. A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, its result is returned or its exception raised. Deferreds are handled tran...
def wait_for(self, timeout): """ A decorator factory that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, its result is returned or its exception raised. Deferreds are handled transparently. Calls will timeout after the given...
def in_reactor(self, function): """ DEPRECATED, use run_in_reactor. A decorator that ensures the wrapped function runs in the reactor thread. The wrapped function will get the reactor passed in as a first argument, in addition to any arguments it is called with. ...
def _mx(domain): """ Return Deferred that fires with a list of (priority, MX domain) tuples for a given domain. """ def got_records(result): return sorted( [(int(record.payload.preference), str(record.payload.name)) for record in result[0]]) d = lookupMailExchang...
def store(self, deferred_result): """ Store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object. """ self._counter += 1 self._stored[self._counter] = deferred_result return self._counter
def log_errors(self): """ Log errors for all stored EventualResults that have error results. """ for result in self._stored.values(): failure = result.original_failure() if failure is not None: log.err(failure, "Unhandled error in stashed EventualR...
def start_ssh_server(port, username, password, namespace): """ Start an SSH server on the given port, exposing a Python prompt with the given namespace. """ # This is a lot of boilerplate, see http://tm.tl/6429 for a ticket to # provide a utility function that simplifies this. from twisted.i...
def _synced(method, self, args, kwargs): """Underlying synchronized wrapper.""" with self._lock: return method(*args, **kwargs)
def register(self, f, *args, **kwargs): """ Register a function and arguments to be called later. """ self._functions.append(lambda: f(*args, **kwargs))
def register_function(self, function, name=None): """ Register function to be called from EPC client. :type function: callable :arg function: Function to publish. :type name: str :arg name: Name by which function is published. This method returns t...
def get_method(self, name): """ Get registered method callend `name`. """ try: return self.funcs[name] except KeyError: try: return self.instance._get_method(name) except AttributeError: return SimpleXMLRPCServer...
def set_debugger(self, debugger): """ Set debugger to run when an error occurs in published method. You can also set debugger by passing `debugger` argument to the class constructor. :type debugger: {'pdb', 'ipdb', None} :arg debugger: type of debugger. """ ...
def connect(self, socket_or_address): """ Connect to server and start serving registered functions. :type socket_or_address: tuple or socket object :arg socket_or_address: A ``(host, port)`` pair to be passed to `socket.create_connection`, or ...
def main(args=None): """ Quick CLI to serve Python functions in a module. Example usage:: python -m epc.server --allow-dotted-names os Note that only the functions which gets and returns simple built-in types (str, int, float, list, tuple, dict) works. """ import argparse fro...
def print_port(self, stream=sys.stdout): """ Print port this EPC server runs on. As Emacs client reads port number from STDOUT, you need to call this just before calling :meth:`serve_forever`. :type stream: text stream :arg stream: A stream object to write port on. ...
def call(self, name, *args, **kwds): """ Call method connected to this handler. :type name: str :arg name: Method name to call. :type args: list :arg args: Arguments for remote method to call. :type callback: callable :arg callback: A f...
def methods(self, *args, **kwds): """ Request info of callable remote methods. Arguments for :meth:`call` except for `name` can be applied to this function too. """ self.callmanager.methods(self, *args, **kwds)
def call_sync(self, name, args, timeout=None): """ Blocking version of :meth:`call`. :type name: str :arg name: Remote function name to call. :type args: list :arg args: Arguments passed to the remote function. :type timeout: int or None :ar...
def func_call_as_str(name, *args, **kwds): """ Return arguments and keyword arguments as formatted string >>> func_call_as_str('f', 1, 2, a=1) 'f(1, 2, a=1)' """ return '{0}({1})'.format( name, ', '.join(itertools.chain( map('{0!r}'.format, args), map('{...
def newthread(template="EPCThread-{0}", **kwds): """ Instantiate :class:`threading.Thread` with an appropriate name. """ if not isinstance(template, str): template = '{0}.{1}-{{0}}'.format(template.__module__, template.__class__.__name__) return thre...
def callwith(context_manager): """ A decorator to wrap execution of function with a context manager. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwds): with context_manager: return func(*args, **kwds) return wrapper return ...
def _scene_centroid(self): """ Compute image center coordinates :return: Tuple of image center in lat, lon """ ul_lat = self.corner_ul_lat_product ll_lat = self.corner_ll_lat_product ul_lon = self.corner_ul_lon_product ur_lon = self.corner_ur_lon_product l...
def earth_sun_d(dtime): """ Earth-sun distance in AU :param dtime time, e.g. datetime.datetime(2007, 5, 1) :type datetime object :return float(distance from sun to earth in astronomical units) """ doy = int(dtime.strftime('%j')) rad_term = 0.9856 * (doy -...
def reflectance(self, band): """ :param band: An optical band, i.e. 1-5, 7 :return: At satellite reflectance, [-] """ if band == 6: raise ValueError('LT5 reflectance must be other than band 6') rad = self.radiance(band) esun = self.ex_atm_irrad[band...
def albedo(self, model='smith'): """Finds broad-band surface reflectance (albedo) Smith (2010), “The heat budget of the earth’s surface deduced from space” LT5 toa reflectance bands 1, 3, 4, 5, 7 # normalized i.e. 0.356 + 0.130 + 0.373 + 0.085 + 0.07 = 1.014 Sh...
def saturation_mask(self, band, value=255): """ Mask saturated pixels, 1 (True) is saturated. :param band: Image band with dn values, type: array :param value: Maximum (saturated) value, i.e. 255 for 8-bit data, type: int :return: boolean array """ dn = self._get_band('b{...
def ndvi(self): """ Normalized difference vegetation index. :return: NDVI """ red, nir = self.reflectance(3), self.reflectance(4) ndvi = self._divide_zero((nir - red), (nir + red), nan) return ndvi
def lai(self): """ Leaf area index (LAI), or the surface area of leaves to surface area ground. Trezza and Allen, 2014 :param ndvi: normalized difference vegetation index [-] :return: LAI [-] """ ndvi = self.ndvi() lai = 7.0 * (ndvi ** 3) lai = whe...
def land_surface_temp(self): """ Mean values from Allen (2007) :return: """ rp = 0.91 tau = 0.866 rsky = 1.32 epsilon = self.emissivity(approach='tasumi') radiance = self.radiance(6) rc = ((radiance - rp) / tau) - ((1 - epsilon) * rsky) ...
def brightness_temp(self, band, temp_scale='K'): """Calculate brightness temperature of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php T = K2 / log((K1 / L) + 1) and L = ML * Q + AL where: T = At-satellite brightness temperature (degrees kelvin) ...
def reflectance(self, band): """Calculate top of atmosphere reflectance of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php R_raw = MR * Q + AR R = R_raw / cos(Z) = R_raw / sin(E) Z = 90 - E (in degrees) where: ...
def radiance(self, band): """Calculate top of atmosphere radiance of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php L = ML * Q + AL where: L = TOA spectral radiance (Watts / (m2 * srad * mm)) ML = Band-specific multiplica...
def ndsi(self): """ Normalized difference snow index. :return: NDSI """ green, swir1 = self.reflectance(3), self.reflectance(6) ndsi = self._divide_zero((green - swir1), (green + swir1), nan) return ndsi
def whiteness_index(self): """Index of "Whiteness" based on visible bands. Parameters ---------- Output ------ ndarray: whiteness index """ mean_vis = (self.blue + self.green + self.red) / 3 blue_absdiff = np.absolute(self._divide_zer...
def potential_cloud_pixels(self): """Determine potential cloud pixels (PCPs) Combine basic spectral testsr to get a premliminary cloud mask First pass, section 3.1.1 in Zhu and Woodcock 2012 Equation 6 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ...
def temp_water(self): """Use water to mask tirs and find 82.5 pctile Equation 7 and 8 (Zhu and Woodcock, 2012) Parameters ---------- is_water: ndarray, boolean water mask, water is True, land is False swir2: ndarray tirs1: ndarray Output ...
def water_temp_prob(self): """Temperature probability for water Equation 9 (Zhu and Woodcock, 2012) Parameters ---------- water_temp: float 82.5th percentile temperature over water swir2: ndarray tirs1: ndarray Output ------ nda...
def brightness_prob(self, clip=True): """The brightest water may have Band 5 reflectance as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11 Equation 10 (Zhu and Woodcock, 2012) Parameters ---------- nir: ndarray clip: boolean Output ...
def temp_land(self, pcps, water): """Derive high/low percentiles of land temperature Equations 12 an 13 (Zhu and Woodcock, 2012) Parameters ---------- pcps: ndarray potential cloud pixels, boolean water: ndarray water mask, boolean tirs1: n...
def land_temp_prob(self, tlow, thigh): """Temperature-based probability of cloud over land Equation 14 (Zhu and Woodcock, 2012) Parameters ---------- tirs1: ndarray tlow: float Low (17.5 percentile) temperature of land thigh: float High (82...
def variability_prob(self, whiteness): """Use the probability of the spectral variability to identify clouds over land. Equation 15 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ndsi: ndarray whiteness: ndarray Output ------ ...
def land_threshold(self, land_cloud_prob, pcps, water): """Dynamic threshold for determining cloud cutoff Equation 17 (Zhu and Woodcock, 2012) Parameters ---------- land_cloud_prob: ndarray probability of cloud over land pcps: ndarray potential clo...
def potential_cloud_layer(self, pcp, water, tlow, land_cloud_prob, land_threshold, water_cloud_prob, water_threshold=0.5): """Final step of determining potential cloud layer Equation 18 (Zhu and Woodcock, 2012) Saturation (green or red) test is not in the algorithm ...
def potential_snow_layer(self): """Spectral test to determine potential snow Uses the 9.85C (283K) threshold defined in Zhu, Woodcock 2015 Parameters ---------- ndsi: ndarray green: ndarray nir: ndarray tirs1: ndarray Output ------ ...
def cloud_mask(self, min_filter=(3, 3), max_filter=(10, 10), combined=False, cloud_and_shadow=False): """Calculate the potential cloud layer from source data *This is the high level function which ties together all the equations for generating potential clouds* Parameters -------...
def gdal_nodata_mask(pcl, pcsl, tirs_arr): """ Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style uint8 mask """ tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0) return ((~(pcl | pcsl | tirs_mask)) * 2...
def parsemeta(metadataloc): """Parses the metadata from a Landsat image bundle. Arguments: metadataloc: a filename or a directory. Returns metadata dictionary """ # filename or directory? if several fit, use first one and warn if os.path.isdir(metadataloc): me...
def _checkstatus(status, line): """Returns state/status after reading the next line. The status codes are:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE, 3 - END METDADATA GROUP, 4 - END PARSING Permitted Transitions::...
def _transstat(status, grouppath, dictpath, line): """Executes processing steps when reading a line""" if status == 0: raise MTLParseError( "Status should not be '%s' after reading line:\n%s" % (STATUSCODE[status], line)) elif status == 1: currentdict = dictpath[-1] ...
def _postprocess(valuestr): """ Takes value as str, returns str, int, float, date, datetime, or time """ # USGS has started quoting time sometimes. Grr, strip quotes in this case intpattern = re.compile(r'^\-?\d+$') floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$') datedtpattern = '...
def warp_vrt(directory, delete_extra=False, use_band_map=False, overwrite=False, remove_bqa=True, return_profile=False): """ Read in image geometry, resample subsequent images to same grid. The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578 to download ...
def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envname`` and ``.basepyt...
def _setup_no_fallback(parser): """Add the option, --tox-pyenv-no-fallback. If this option is set, do not allow fallback to tox's built-in strategy for looking up python executables if the call to `pyenv which` by this plugin fails. This will allow the error to raise instead of falling back to tox'...
def sendEmail(self, emails, massType='SingleEmailMessage'): """ Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com/us ...
def quote(myitem, elt=True): '''URL encode string''' if elt and '<' in myitem and len(myitem) > 24 and myitem.find(']]>') == -1: return '<![CDATA[%s]]>' % (myitem) else: myitem = myitem.replace('&', '&amp;').\ replace('<', '&lt;').replace(']]>', ']]&gt;') if not elt: ...
def _doPrep(field_dict): """ _doPrep is makes changes in-place. Do some prep work converting python types into formats that Salesforce will accept. This includes converting lists of strings to "apple;orange;pear". Dicts will be converted to embedded objects None or empty list values will be ...
def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an array _doPrep(sObjectsCopy) else: # else this is an array, and each elelment should b...
def sendEmail(self, emails, mass_type='SingleEmailMessage'): """ Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com ...
def queryTypesDescriptions(self, types): """ Given a list of types, construct a dictionary such that each key is a type, and each value is the corresponding sObject for that type. """ types = list(types) if types: types_descs = self.describeSObjects(ty...
def create_token(self): """Create a session protection token for this client. This method generates a session protection token for the cilent, which consists in a hash of the user agent and the IP address. This method can be overriden by subclasses to implement different token generatio...
def clear_session(self, response): """Clear the session. This method is invoked when the session is found to be invalid. Subclasses can override this method to implement a custom session reset. """ session.clear() # if flask-login is installed, we try to clear t...
def haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'): """ Generate heroku-like random names to use in your python applications :param delimiter: Delimiter :param token_length: TokenLength :param token_hex: TokenHex :param token_ch...
def get_parser_class(): """ Returns the parser according to the system platform """ global distro if distro == 'Linux': Parser = parser.LinuxParser if not os.path.exists(Parser.get_command()[0]): Parser = parser.UnixIPParser elif distro in ['Darwin', 'MacOSX']: ...
def default_interface(ifconfig=None, route_output=None): """ Return just the default interface device dictionary. :param ifconfig: For mocking actual command output :param route_output: For mocking actual command output """ global Parser return Parser(ifconfig=ifconfig)._default_interface(r...
def parse(self, ifconfig=None): # noqa: max-complexity=12 """ Parse ifconfig output into self._interfaces. Optional Arguments: ifconfig The data (stdout) from the ifconfig command. Default is to call exec_cmd(self.get_command()). """ ...
def alter(self, interfaces): """ Used to provide the ability to alter the interfaces dictionary before it is returned from self.parse(). Required Arguments: interfaces The interfaces dictionary. Returns: interfaces dict """ # fixup ...
def _default_interface(self, route_output=None): """ :param route_output: For mocking actual output """ if not route_output: out, __, __ = exec_cmd('/sbin/ip route') lines = out.splitlines() else: lines = route_output.split("\n") for l...
def get(self, line_number): """Return the needle positions or None. :param int line_number: the number of the line :rtype: list :return: the needle positions for a specific line specified by :paramref:`line_number` or :obj:`None` if no were given """ if line_nu...
def get_bytes(self, line_number): """Get the bytes representing needle positions or None. :param int line_number: the line number to take the bytes from :rtype: bytes :return: the bytes that represent the message or :obj:`None` if no data is there for the line. Depend...
def get_line_configuration_message(self, line_number): """Return the cnfLine content without id for the line. :param int line_number: the number of the line :rtype: bytes :return: a cnfLine message without id as defined in :ref:`cnfLine` """ if line_number not in self._l...
def read_message_type(file): """Read the message type from a file.""" message_byte = file.read(1) if message_byte == b'': return ConnectionClosed message_number = message_byte[0] return _message_types.get(message_number, UnknownMessage)
def read_end_of_message(self): """Read the b"\\r\\n" at the end of the message.""" read = self._file.read last = read(1) current = read(1) while last != b'' and current != b'' and not \ (last == b'\r' and current == b'\n'): last = current c...
def _init(self): """Read the success byte.""" self._api_version = self._file.read(1)[0] self._firmware_version = FirmwareVersion(*self._file.read(2))
def _init(self): """Read the line number.""" self._line_number = next_line( self._communication.last_requested_line_number, self._file.read(1)[0])
def _init(self): """Read the success byte.""" self._ready = self._file.read(1) self._hall_left = self._file.read(2) self._hall_right = self._file.read(2) self._carriage_type = self._file.read(1)[0] self._carriage_position = self._file.read(1)[0]
def _init(self): """Read the b"\\r\\n" at the end of the message.""" read_values = [] read = self._file.read last = read(1) current = read(1) while last != b'' and current != b'' and not \ (last == b'\r' and current == b'\n'): read_values.appen...
def send(self): """Send this message to the controller.""" self._file.write(self.as_bytes()) self._file.write(b'\r\n')
def init(self, left_end_needle, right_end_needle): """Initialize the StartRequest with start and stop needle. :raises TypeError: if the arguments are not integers :raises ValueError: if the values do not match the :ref:`specification <m4-01>` """ if not isinstance(left...
def content_bytes(self): """Return the start and stop needle.""" get_message = \ self._communication.needle_positions.get_line_configuration_message return get_message(self._line_number)
def sum_all(iterable, start): """Sum up an iterable starting with a start value. In contrast to :func:`sum`, this also works on other types like :class:`lists <list>` and :class:`sets <set>`. """ if hasattr(start, "__add__"): for value in iterable: start += value else: ...
def next_line(last_line, next_line_8bit): """Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return:...
def camel_case_to_under_score(camel_case_name): """Return the underscore name of a camel case name. :param str camel_case_name: a name in camel case such as ``"ACamelCaseName"`` :return: the name using underscores, e.g. ``"a_camel_case_name"`` :rtype: str """ result = [] for letter in...
def _message_received(self, message): """Notify the observers about the received message.""" with self.lock: self._state.receive_message(message) for callable in chain(self._on_message_received, self._on_message): callable(message)
def receive_message(self): """Receive a message from the file.""" with self.lock: assert self.can_receive_messages() message_type = self._read_message_type(self._file) message = message_type(self._file, self) self._message_received(message)
def can_receive_messages(self): """Whether tihs communication is ready to receive messages.] :rtype: bool .. code:: python assert not communication.can_receive_messages() communication.start() assert communication.can_receive_messages() communic...
def stop(self): """Stop the communication with the shield.""" with self.lock: self._message_received(ConnectionClosed(self._file, self))
def send(self, host_message_class, *args): """Send a host message. :param type host_message_class: a subclass of :class:`AYABImterface.communication.host_messages.Message` :param args: additional arguments that shall be passed to the :paramref:`host_message_class` as argumen...
def state(self, new_state): """Set the state.""" with self.lock: self._state.exit() self._state = new_state self._state.enter()
def parallelize(self, seconds_to_wait=2): """Start a parallel thread for receiving messages. If :meth:`start` was no called before, start will be called in the thread. The thread calls :meth:`receive_message` until the :attr:`state` :meth:`~AYABInterface.communication.states.Sta...
def _parallel_receive_loop(self, seconds_to_wait): """Run the receiving in parallel.""" sleep(seconds_to_wait) with self._lock: self._number_of_threads_receiving_messages += 1 try: with self._lock: if self.state.is_waiting_for_start(): ...