Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def d(nominal_temperature): # From CIE 15:2004. Colorimetry, 3rd edition, 2004 (page 69, note 5): # # The method required to calculate the values for the relative spectral # power distributions of illuminants D50, D55, D65, and D75, in Table T.1 # is...
[ "CIE D-series illuminants.\n\n The technical report `Colorimetry, 3rd edition, 2004` gives the data for\n D50, D55, and D65 explicitly, but also explains how it's computed for S0,\n S1, S2. Values are given at 5nm resolution in the document, but really\n every other value is just interpolated. Hence, on...
Please provide a description of the function:def e(): lmbda = 1.0e-9 * numpy.arange(300, 831) data = numpy.full(lmbda.shape, 100.0) return lmbda, data
[ "This is a hypothetical reference radiator. All wavelengths in CIE\n illuminant E are weighted equally with a relative spectral power of 100.0.\n " ]
Please provide a description of the function:def to_xyz100(self, data, description): rgb_c = compute_to(data, description, self) # Step 6: Calculate R, G and B # rgb = (rgb_c.T / self.D_RGB).T # Step 7: Calculate X, Y and Z # xyz = self.solve_M16(rgb) return dot(...
[ "Input: J or Q; C, M or s; H or h\n " ]
Please provide a description of the function:def dot(a, b): b = numpy.asarray(b) return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])
[ "Take arrays `a` and `b` and form the dot product between the last axis\n of `a` and the first of `b`.\n " ]
Please provide a description of the function:def solve(A, x): # https://stackoverflow.com/a/48387507/353337 x = numpy.asarray(x) return numpy.linalg.solve(A, x.reshape(x.shape[0], -1)).reshape(x.shape)
[ "Solves a linear equation system with a matrix of shape (n, n) and an\n array of shape (n, ...). The output has the same shape as the second\n argument.\n " ]
Please provide a description of the function:def to_xyz100(self, data, description): # Steps 1-5 rgb_ = compute_to(data, description, self) # Step 6: Calculate RC, GC and BC # rgb_c = dot(self.M_cat02, solve(self.M_hpe, rgb_)) # # Step 7: Calculate R, G and B ...
[ "Input: J or Q; C, M or s; H or h\n " ]
Please provide a description of the function:def main(): parser = getparser() args = parser.parse_args() fn = args.fn sitename = args.sitename #User-specified output extent #Note: not checked, untested if args.extent is not None: extent = (args.extent).split() else: exte...
[ "\n ICESat-1 filters\n " ]
Please provide a description of the function:def get_nlcd_fn(): #This is original filename, which requires ~17 GB #nlcd_fn = os.path.join(datadir, 'nlcd_2011_landcover_2011_edition_2014_10_10/nlcd_2011_landcover_2011_edition_2014_10_10.img') #get_nlcd.sh now creates a compressed GTiff, which is 1.1 GB ...
[ "Calls external shell script `get_nlcd.sh` to fetch:\n\n 2011 Land Use Land Cover (nlcd) grids, 30 m\n \n http://www.mrlc.gov/nlcd11_leg.php\n " ]
Please provide a description of the function:def get_bareground_fn(): bg_fn = os.path.join(datadir, 'bare2010/bare2010.vrt') if not os.path.exists(bg_fn): cmd = ['get_bareground.sh',] sys.exit("Missing bareground data source. If already downloaded, specify correct datadir. If not, run `%s` ...
[ "Calls external shell script `get_bareground.sh` to fetch:\n\n ~2010 global bare ground, 30 m\n\n Note: unzipped file size is 64 GB! Original products are uncompressed, and tiles are available globally (including empty data over ocean)\n\n The shell script will compress all downloaded tiles using lossless ...
Please provide a description of the function:def get_glacier_poly(): #rgi_fn = os.path.join(datadir, 'rgi50/regions/rgi50_merge.shp') #Update to rgi60, should have this returned from get_rgi.sh rgi_fn = os.path.join(datadir, 'rgi60/regions/rgi60_merge.shp') if not os.path.exists(rgi_fn): cm...
[ "Calls external shell script `get_rgi.sh` to fetch:\n\n Randolph Glacier Inventory (RGI) glacier outline shapefiles \n\n Full RGI database: rgi50.zip is 410 MB\n\n The shell script will unzip and merge regional shp into single global shp\n \n http://www.glims.org/RGI/\n " ]
Please provide a description of the function:def get_icemask(ds, glac_shp_fn=None): print("Masking glaciers") if glac_shp_fn is None: glac_shp_fn = get_glacier_poly() if not os.path.exists(glac_shp_fn): print("Unable to locate glacier shp: %s" % glac_shp_fn) else: print("Fo...
[ "Generate glacier polygon raster mask for input Dataset res/extent\n " ]
Please provide a description of the function:def get_nlcd_mask(nlcd_ds, filter='not_forest', out_fn=None): print("Loading NLCD LULC") b = nlcd_ds.GetRasterBand(1) l = b.ReadAsArray() print("Filtering NLCD LULC with: %s" % filter) #Original nlcd products have nan as ndv #12 - ice ...
[ "Generate raster mask for specified NLCD LULC filter\n " ]
Please provide a description of the function:def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None): print("Loading bareground") b = bareground_ds.GetRasterBand(1) l = b.ReadAsArray() print("Masking pixels with <%0.1f%% bare ground" % bareground_thresh) if bareground_thresh <...
[ "Generate raster mask for exposed bare ground from global bareground data\n " ]
Please provide a description of the function:def get_snodas_ds(dem_dt, code=1036): import tarfile import gzip snodas_ds = None snodas_url_str = None outdir = os.path.join(datadir, 'snodas') if not os.path.exists(outdir): os.makedirs(outdir) #Note: unmasked products (beyond CON...
[ "Function to fetch and process SNODAS snow depth products for input datetime\n\n http://nsidc.org/data/docs/noaa/g02158_snodas_snow_cover_model/index.html\n\n Product codes:\n 1036 is snow depth\n 1034 is SWE\n\n filename format: us_ssmv11036tS__T0001TTNATS2015042205HP001.Hdr\n\n " ]
Please provide a description of the function:def get_modis_tile_list(ds): from demcoreg import modis_grid modis_dict = {} for key in modis_grid.modis_dict: modis_dict[key] = ogr.CreateGeometryFromWkt(modis_grid.modis_dict[key]) geom = geolib.ds_geom(ds) geom_dup = geolib.geom_dup(geom) ...
[ "Helper function to identify MODIS tiles that intersect input geometry\n\n modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox)\n\n See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html\n " ]
Please provide a description of the function:def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7): #Could also use global MODIS 500 m snowcover grids, 8 day #http://nsidc.org/data/docs/daac/modis_v5/mod10a2_modis_terra_snow_8-day_global_500m_grid.gd.htm...
[ "Function to fetch and process MODSCAG fractional snow cover products for input datetime\n\n Products are tiled in MODIS sinusoidal projection\n\n example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif\n\n " ]
Please provide a description of the function:def proc_modscag(fn_list, extent=None, t_srs=None): #Use cubic spline here for improve upsampling ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline') stack_fn = os.path.splitext(fn_list[0])[0] + '_' + os.path....
[ "Process the MODSCAG products for full date range, create composites and reproject\n " ]
Please provide a description of the function:def apply_xy_shift(ds, dx, dy, createcopy=True): print("X shift: ", dx) print("Y shift: ", dy) #Update geotransform gt_orig = ds.GetGeoTransform() gt_shift = np.copy(gt_orig) gt_shift[0] += dx gt_shift[3] += dy print("Original geotr...
[ "\n Apply horizontal shift to GDAL dataset GeoTransform\n \n Returns:\n GDAL Dataset copy with updated GeoTransform\n " ]
Please provide a description of the function:def compute_offset_sad(dem1, dem2, pad=(9,9), plot=False): #This defines the search window size #Use half-pixel stride? #Note: stride is not properly implemented #stride = 1 #ref = dem1[::stride,::stride] #kernel = dem2[pad[0]:-pad[0]:stride, pa...
[ "Compute subpixel horizontal offset between input rasters using sum of absolute differences (SAD) method\n ", " \n diff_med = np.ma.median(diff)\n diff_mad = malib.mad(diff)\n diff_madr = (diff_med - mad, diff_med + mad)\n diff = np.ma.masked_outside(diff, diff_madr)...
Please provide a description of the function:def compute_offset_ncc(dem1, dem2, pad=(9,9), prefilter=False, plot=False): #Apply edge detection filter up front - improves results when input DEMs are same resolution if prefilter: print("Applying LoG edge-detection filter to DEMs") sigma = 1...
[ "Compute horizontal offset between input rasters using normalized cross-correlation (NCC) method\n " ]
Please provide a description of the function:def compute_offset_nuth(dh, slope, aspect, min_count=100, remove_outliers=True, plot=True): import scipy.optimize as optimization if dh.count() < min_count: sys.exit("Not enough dh samples") if slope.count() < min_count: sys.exit("Not enough...
[ "Compute horizontal offset between input rasters using Nuth and Kaab [2011] (nuth) method\n ", "\n #Mask bins in grid directions, can potentially contain biased stats\n #Especially true for SGM algorithm\n #badbins = [0, 90, 180, 270, 360]\n badbins = [0, 45, 90, 135, 180, 225, 270, 315, 360]\n ...
Please provide a description of the function:def find_first_peak(corr): ind = corr.argmax() s = corr.shape[1] i = ind // s j = ind % s return i, j, corr.max()
[ "\n Find row and column indices of the first correlation peak.\n \n Parameters\n ----------\n corr : np.ndarray\n the correlation map\n \n Returns\n -------\n i : int\n the row index of the correlation peak\n \n j : int\n the column index of the correlat...
Please provide a description of the function:def find_subpixel_peak_position(corr, subpixel_method='gaussian'): # initialization default_peak_position = (corr.shape[0]/2,corr.shape[1]/2) # the peak locations peak1_i, peak1_j, dummy = find_first_peak(corr) try: # the peak and its n...
[ "\n Find subpixel approximation of the correlation peak.\n \n This function returns a subpixels approximation of the correlation\n peak by using one of the several methods available. If requested, \n the function also returns the signal to noise ratio level evaluated \n from the correlation map.\n...
Please provide a description of the function:def main(): #filenames = !ls *align/*reference-DEM.tif #run ~/src/demtools/error_analysis.py $filenames.s if len(sys.argv) < 1: sys.exit('No input files provided') fn_list = sys.argv[1:] n_samp = len(fn_list) error_dict_list = [] for fn...
[ "\n #ECEF translations\n #key = 'Translation vector (ECEF meters)'\n key = 'Translation vector (Cartesian, meters)'\n #key = 'Translation vector (meters)'\n val = np.array([e[key] for e in error_dict_list])\n #make_plot3d(val[:,0], val[:,1], val[:,2], title=key)\n ce90 = geolib.CE90(val[:,0], v...
Please provide a description of the function:def _value_length(self, value, t): if isinstance(value, int): fmt = '<%s' % (type_codes[t]) output = struct.pack(fmt, value) return len(output) elif isinstance(value, str): return len(value) + 1 # Acc...
[ "Given an integer or list of them, convert it to an array of bytes." ]
Please provide a description of the function:def _parse_line(self, line_no, line): try: matched = statement.parseString(line) except ParseException as exc: raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line) ...
[ "Parse a line in a TileBus file\n\n Args:\n line_no (int): The line number for printing useful error messages\n line (string): The line that we are trying to parse\n " ]
Please provide a description of the function:def _validate_information(self): needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"] for var in needed_variables: if var not in self.variables: raise DataError("Needed variable was not defined in mib file.",...
[ "Validate that all information has been filled in" ]
Please provide a description of the function:def get_block(self, config_only=False): mib = TBBlock() for cid, config in self.configs.items(): mib.add_config(cid, config) if not config_only: for key, val in self.commands.items(): mib.add_command...
[ "Create a TileBus Block based on the information in this descriptor" ]
Please provide a description of the function:def add_adapter(self, adapter): if self._started: raise InternalError("New adapters cannot be added after start() is called") if isinstance(adapter, DeviceAdapter): self._logger.warning("Wrapping legacy device adapter %s in ...
[ "Add a device adapter to this aggregating adapter." ]
Please provide a description of the function:def get_config(self, name, default=_MISSING): val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exist and no default".format(name)) return val
[ "Get a configuration setting from this DeviceAdapter.\n\n See :meth:`AbstractDeviceAdapter.get_config`.\n " ]
Please provide a description of the function:async def start(self): successful = 0 try: for adapter in self.adapters: await adapter.start() successful += 1 self._started = True except: for adapter in self.adapters[:s...
[ "Start all adapters managed by this device adapter.\n\n If there is an error starting one or more adapters, this method will\n stop any adapters that we successfully started and raise an exception.\n " ]
Please provide a description of the function:def visible_devices(self): devs = {} for device_id, adapters in self._devices.items(): dev = None max_signal = None best_adapter = None for adapter_id, devinfo in adapters.items(): co...
[ "Unify all visible devices across all connected adapters\n\n Returns:\n dict: A dictionary mapping UUIDs to device information dictionaries\n " ]
Please provide a description of the function:async def connect(self, conn_id, connection_string): if connection_string.startswith('device/'): adapter_id, local_conn = self._find_best_adapter(connection_string, conn_id) translate_conn = True elif connection_string.starts...
[ "Connect to a device.\n\n See :meth:`AbstractDeviceAdapter.connect`.\n " ]
Please provide a description of the function:async def disconnect(self, conn_id): adapter_id = self._get_property(conn_id, 'adapter') await self.adapters[adapter_id].disconnect(conn_id) self._teardown_connection(conn_id)
[ "Disconnect from a connected device.\n\n See :meth:`AbstractDeviceAdapter.disconnect`.\n " ]
Please provide a description of the function:async def open_interface(self, conn_id, interface): adapter_id = self._get_property(conn_id, 'adapter') await self.adapters[adapter_id].open_interface(conn_id, interface)
[ "Open an interface on an IOTile device.\n\n See :meth:`AbstractDeviceAdapter.open_interface`.\n " ]
Please provide a description of the function:async def close_interface(self, conn_id, interface): adapter_id = self._get_property(conn_id, 'adapter') await self.adapters[adapter_id].close_interface(conn_id, interface)
[ "Close an interface on this IOTile device.\n\n See :meth:`AbstractDeviceAdapter.close_interface`.\n " ]
Please provide a description of the function:async def probe(self): for adapter in self.adapters: if adapter.get_config('probe_supported', False): await adapter.probe()
[ "Probe for devices.\n\n This method will probe all adapters that can probe and will send a\n notification for all devices that we have seen from all adapters.\n\n See :meth:`AbstractDeviceAdapter.probe`.\n " ]
Please provide a description of the function:async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payload, timeout)
[ "Send an RPC to a device.\n\n See :meth:`AbstractDeviceAdapter.send_rpc`.\n " ]
Please provide a description of the function:async def debug(self, conn_id, name, cmd_args): adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].debug(conn_id, name, cmd_args)
[ "Send a debug command to a device.\n\n See :meth:`AbstractDeviceAdapter.debug`.\n " ]
Please provide a description of the function:async def send_script(self, conn_id, data): adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_script(conn_id, data)
[ "Send a script to a device.\n\n See :meth:`AbstractDeviceAdapter.send_script`.\n " ]
Please provide a description of the function:async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, event...
[ "Handle an event received from an adapter." ]
Please provide a description of the function:def _device_expiry_callback(self): expired = 0 for adapters in self._devices.values(): to_remove = [] now = monotonic() for adapter_id, dev in adapters.items(): if 'expires' not in dev: ...
[ "Periodic callback to remove expired devices from visible_devices." ]
Please provide a description of the function:def PathIsDir(self, key, val, env): if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' ...
[ "Validator to check if Path is a directory." ]
Please provide a description of the function:def PathExists(self, key, val, env): if not os.path.exists(val): m = 'Path for option %s does not exist: %s' raise SCons.Errors.UserError(m % (key, val))
[ "Validator to check if Path exists" ]
Please provide a description of the function:async def process_graph_input(graph, stream, value, rpc_executor): graph.sensor_log.push(stream, value) # FIXME: This should be specified in our device model if stream.important: associated_output = stream.associated_stream() graph.sensor_l...
[ "Process an input through this sensor graph.\n\n The tick information in value should be correct and is transfered\n to all results produced by nodes acting on this tick. This coroutine\n is an asyncio compatible version of SensorGraph.process_input()\n\n Args:\n stream (DataStream): The stream ...
Please provide a description of the function:def clear_to_reset(self, config_vars): super(SensorGraphSubsystem, self).clear_to_reset(config_vars) self.graph.clear() if not self.persisted_exists: return for node in self.persisted_nodes: self.graph.add_...
[ "Clear all volatile information across a reset.\n\n The reset behavior is that:\n - any persisted sensor_graph is loaded\n - if there is a persisted graph found, enabled is set to True\n - if there is a persisted graph found, reset readings are pushed\n into it.\n " ]
Please provide a description of the function:def process_input(self, encoded_stream, value): if not self.enabled: return if isinstance(encoded_stream, str): stream = DataStream.FromString(encoded_stream) encoded_stream = stream.encode() elif isinsta...
[ "Process or drop a graph input.\n\n This method asynchronously queued an item to be processed by the\n sensorgraph worker task in _reset_vector. It must be called from\n inside the emulation loop and returns immediately before the input is\n processed.\n " ]
Please provide a description of the function:def _seek_streamer(self, index, value): highest_id = self._rsl.highest_stored_id() streamer = self.graph.streamers[index] if not streamer.walker.buffered: return _pack_sgerror(SensorLogError.CANNOT_USE_UNBUFFERED_STREAM) ...
[ "Complex logic for actually seeking a streamer to a reading_id.\n\n This routine hides all of the gnarly logic of the various edge cases.\n In particular, the behavior depends on whether the reading id is found,\n and if it is found, whether it belongs to the indicated streamer or not.\n\n ...
Please provide a description of the function:def acknowledge_streamer(self, index, ack, force): if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) old_ack = self.streamer_acks.get(index, 0) if ack != 0: if ack ...
[ "Acknowledge a streamer value as received from the remote side." ]
Please provide a description of the function:def _handle_streamer_finished(self, index, succeeded, highest_ack): self._logger.debug("Rolling back streamer %d after streaming, highest ack from streaming subsystem was %d", index, highest_ack) self.acknowledge_streamer(index, highest_ack, False)
[ "Callback when a streamer finishes processing." ]
Please provide a description of the function:def process_streamers(self): # Check for any triggered streamers and pass them to stream manager in_progress = self._stream_manager.in_progress() triggered = self.graph.check_streamers(blacklist=in_progress) for streamer in triggere...
[ "Check if any streamers should be handed to the stream manager." ]
Please provide a description of the function:def trigger_streamer(self, index): self._logger.debug("trigger_streamer RPC called on streamer %d", index) if index >= len(self.graph.streamers): return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED) if index in self._s...
[ "Pass a streamer to the stream manager if it has data." ]
Please provide a description of the function:def persist(self): self.persisted_nodes = self.graph.dump_nodes() self.persisted_streamers = self.graph.dump_streamers() self.persisted_exists = True self.persisted_constants = self._sensor_log.dump_constants()
[ "Trigger saving the current sensorgraph to persistent storage." ]
Please provide a description of the function:def reset(self): self.persisted_exists = False self.persisted_nodes = [] self.persisted_streamers = [] self.persisted_constants = [] self.graph.clear() self.streamer_status = {}
[ "Clear the sensorgraph from RAM and flash." ]
Please provide a description of the function:def add_node(self, binary_descriptor): try: node_string = parse_binary_descriptor(binary_descriptor) except: self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor) return _pack_sgerr...
[ "Add a node to the sensor_graph using a binary node descriptor.\n\n Args:\n binary_descriptor (bytes): An encoded binary node descriptor.\n\n Returns:\n int: A packed error code.\n " ]
Please provide a description of the function:def add_streamer(self, binary_descriptor): streamer = streamer_descriptor.parse_binary_descriptor(binary_descriptor) try: self.graph.add_streamer(streamer) self.streamer_status[len(self.graph.streamers) - 1] = StreamerStatus...
[ "Add a streamer to the sensor_graph using a binary streamer descriptor.\n\n Args:\n binary_descriptor (bytes): An encoded binary streamer descriptor.\n\n Returns:\n int: A packed error code\n " ]
Please provide a description of the function:def inspect_streamer(self, index): if index >= len(self.graph.streamers): return [_pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED), b'\0'*14] return [Error.NO_ERROR, streamer_descriptor.create_binary_descriptor(self.graph.streamer...
[ "Inspect the streamer at the given index." ]
Please provide a description of the function:def inspect_node(self, index): if index >= len(self.graph.nodes): raise RPCErrorCode(6) #FIXME: use actual error code here for UNKNOWN_ERROR status return create_binary_descriptor(str(self.graph.nodes[index]))
[ "Inspect the graph node at the given index." ]
Please provide a description of the function:def query_streamer(self, index): if index >= len(self.graph.streamers): return None info = self.streamer_status[index] highest_ack = self.streamer_acks.get(index, 0) return [info.last_attempt_time, info.last_success_tim...
[ "Query the status of the streamer at the given index." ]
Please provide a description of the function:def sg_set_online(self, online): self.sensor_graph.enabled = bool(online) return [Error.NO_ERROR]
[ "Set the sensor-graph online/offline." ]
Please provide a description of the function:def sg_graph_input(self, value, stream_id): self.sensor_graph.process_input(stream_id, value) return [Error.NO_ERROR]
[ "\"Present a graph input to the sensor_graph subsystem." ]
Please provide a description of the function:def sg_add_streamer(self, desc): if len(desc) == 13: desc += b'\0' err = self.sensor_graph.add_streamer(desc) return [err]
[ "Add a graph streamer using a binary descriptor." ]
Please provide a description of the function:def sg_seek_streamer(self, index, force, value): force = bool(force) err = self.sensor_graph.acknowledge_streamer(index, value, force) return [err]
[ "Ackowledge a streamer." ]
Please provide a description of the function:def sg_query_streamer(self, index): resp = self.sensor_graph.query_streamer(index) if resp is None: return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))] return [struct.pack("<LLLLBBBx", *resp)]
[ "Query the current status of a streamer." ]
Please provide a description of the function:def dispatch(self, value, callback=None): done = None if callback is None: done = threading.Event() shared_data = [None, None] def _callback(exc_info, return_value): shared_data[0] = exc_info ...
[ "Dispatch an item to the workqueue and optionally wait.\n\n This is the only way to add work to the background work queue. Unless\n you also pass a callback object, this method will synchronously wait\n for the work to finish and return the result. If the work raises an\n exception, the ...
Please provide a description of the function:def future_raise(self, tp, value=None, tb=None): if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not have a separate value") if value is not None: exc = tp(value) else: ...
[ "raise_ implementation from future.utils" ]
Please provide a description of the function:def flush(self): done = threading.Event() def _callback(): done.set() self.defer(_callback) done.wait()
[ "Synchronously wait until this work item is processed.\n\n This has the effect of waiting until all work items queued before this\n method has been called have finished.\n " ]
Please provide a description of the function:def wait_until_idle(self): done = threading.Event() def _callback(): done.set() self.defer_until_idle(_callback) done.wait()
[ "Block the calling thread until the work queue is (temporarily) empty.\n\n See the detailed discussion under defer_until_idle() for restrictions\n and expected use cases for this method.\n\n This routine will block the calling thread.\n " ]
Please provide a description of the function:def direct_dispatch(self, arg, callback): try: self._current_callbacks.appendleft(callback) exc_info = None retval = None retval = self._routine(arg) except: # pylint:disable=bare-except;We need to ...
[ "Directly dispatch a work item.\n\n This method MUST only be called from inside of another work item and\n will synchronously invoke the work item as if it was passed to\n dispatch(). Calling this method from any other thread has undefined\n consequences since it will be unsynchronized ...
Please provide a description of the function:def run(self): idle_watchers = [] while True: try: if self._work_queue.empty() and len(idle_watchers) > 0: for watcher in idle_watchers: try: watche...
[ "The target routine called to start thread activity." ]
Please provide a description of the function:def stop(self, timeout=None, force=False): self.signal_stop() self.wait_stopped(timeout, force)
[ "Stop the worker thread and synchronously wait for it to finish.\n\n Args:\n timeout (float): The maximum time to wait for the thread to stop\n before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError\n is not raised and the thread is just marked a...
Please provide a description of the function:def wait_stopped(self, timeout=None, force=False): self.join(timeout) if self.is_alive() and force is False: raise TimeoutExpiredError("Error waiting for background thread to exit", timeout=timeout)
[ "Wait for the thread to stop.\n\n You must have previously called signal_stop or this function will\n hang.\n\n Args:\n\n timeout (float): The maximum time to wait for the thread to stop\n before raising a TimeoutExpiredError. If force is True,\n Timeou...
Please provide a description of the function:def generate(env): if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nolog...
[ "Add Builders and construction variables for WiX to an Environment." ]
Please provide a description of the function:def FromString(cls, desc): if language.stream is None: language.get_language() parse_exp = Optional(time_interval('time') - Literal(':').suppress()) - language.stream('stream') - Literal('=').suppress() - number('value') try: ...
[ "Create a new stimulus from a description string.\n\n The string must have the format:\n\n [time: ][system ]input X = Y\n where X and Y are integers. The time, if given must\n be a time_interval, which is an integer followed by a\n time unit such as second(s), minute(s), etc.\n\n...
Please provide a description of the function:def get_connection_id(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentErr...
[ "Get the connection id.\n\n Args:\n conn_or_int_id (int, string): The external integer connection id or\n and internal string connection id\n\n Returns:\n dict: The context data associated with that connection or None if it cannot\n be found.\n\n ...
Please provide a description of the function:def _get_connection(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: return None ...
[ "Get the data for a connection by either conn_id or internal_id\n\n Args:\n conn_or_int_id (int, string): The external integer connection id or\n and internal string connection id\n\n Returns:\n dict: The context data associated with that connection or None if it c...
Please provide a description of the function:def _get_connection_state(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: raise Argumen...
[ "Get a connection's state by either conn_id or internal_id\n\n This routine must only be called from the internal worker thread.\n\n Args:\n conn_or_int_id (int, string): The external integer connection id or\n and internal string connection id\n " ]
Please provide a description of the function:def _check_timeouts(self): for conn_id, data in self._connections.items(): if 'timeout' in data and data['timeout'].expired: if data['state'] == self.Connecting: self.finish_connection(conn_id, False, 'Connect...
[ "Check if any operations in progress need to be timed out\n\n Adds the corresponding finish action that fails the request due to a\n timeout.\n " ]
Please provide a description of the function:def _begin_connection_action(self, action): conn_id = action.data['connection_id'] int_id = action.data['internal_id'] callback = action.data['callback'] # Make sure we are not reusing an id that is currently connected to something ...
[ "Begin a connection attempt\n\n Args:\n action (ConnectionAction): the action object describing what we are\n connecting to\n " ]
Please provide a description of the function:def _finish_connection_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.Connecting: print("Invalid finish_connection action on a connection whose...
[ "Finish a connection attempt\n\n Args:\n action (ConnectionAction): the action object describing what we are\n connecting to and what the result of the operation was\n " ]
Please provide a description of the function:def unexpected_disconnect(self, conn_or_internal_id): data = { 'id': conn_or_internal_id } action = ConnectionAction('force_disconnect', data, sync=False) self._actions.put(action)
[ "Notify that there was an unexpected disconnection of the device.\n\n Any in progress operations are canceled cleanly and the device is transitioned\n to a disconnected state.\n\n Args:\n conn_or_internal_id (string, int): Either an integer connection id or a string\n ...
Please provide a description of the function:def begin_disconnection(self, conn_or_internal_id, callback, timeout): data = { 'id': conn_or_internal_id, 'callback': callback } action = ConnectionAction('begin_disconnection', data, timeout=timeout, sync=False) ...
[ "Begin a disconnection attempt\n\n Args:\n conn_or_internal_id (string, int): Either an integer connection id or a string\n internal_id\n callback (callable): Callback to call when this disconnection attempt either\n succeeds or fails\n timeout (...
Please provide a description of the function:def _force_disconnect_action(self, action): conn_key = action.data['id'] if self._get_connection_state(conn_key) == self.Disconnected: return data = self._get_connection(conn_key) # If there are any operations in progre...
[ "Forcibly disconnect a device.\n\n Args:\n action (ConnectionAction): the action object describing what we are\n forcibly disconnecting\n " ]
Please provide a description of the function:def _begin_disconnection_action(self, action): conn_key = action.data['id'] callback = action.data['callback'] if self._get_connection_state(conn_key) != self.Idle: callback(conn_key, self.id, False, 'Cannot start disconnection,...
[ "Begin a disconnection attempt\n\n Args:\n action (ConnectionAction): the action object describing what we are\n connecting to and what the result of the operation was\n " ]
Please provide a description of the function:def _finish_disconnection_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.Disconnecting: self._logger.error("Invalid finish_disconnection action...
[ "Finish a disconnection attempt\n\n There are two possible outcomes:\n - if we were successful at disconnecting, we transition to disconnected\n - if we failed at disconnecting, we transition back to idle\n\n Args:\n action (ConnectionAction): the action object describing what...
Please provide a description of the function:def finish_operation(self, conn_or_internal_id, success, *args): data = { 'id': conn_or_internal_id, 'success': success, 'callback_args': args } action = ConnectionAction('finish_operation', data, sync=Fa...
[ "Finish an operation on a connection.\n\n Args:\n conn_or_internal_id (string, int): Either an integer connection id or a string\n internal_id\n success (bool): Whether the operation was successful\n failure_reason (string): Optional reason why the operation fa...
Please provide a description of the function:def _finish_operation_action(self, action): success = action.data['success'] conn_key = action.data['id'] if self._get_connection_state(conn_key) != self.InProgress: self._logger.error("Invalid finish_operation action on a conne...
[ "Finish an attempted operation.\n\n Args:\n action (ConnectionAction): the action object describing the result\n of the operation that we are finishing\n " ]
Please provide a description of the function:def canonical_text(self, text): out = [] line_continues_a_comment = False for line in text.splitlines(): line,comment = self.comment_re.findall(line)[0] if line_continues_a_comment == True: out[-1] = ou...
[ "Standardize an input TeX-file contents.\n\n Currently:\n * removes comments, unwrapping comment-wrapped lines.\n " ]
Please provide a description of the function:def scan_recurse(self, node, path=()): path_dict = dict(list(path)) queue = [] queue.extend( self.scan(node) ) seen = {} # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pat...
[ " do a recursive scan of the top level target file\n This lets us search for included files based on the\n directory of the main file just as latex does", "which lets\n # us keep the sort order constant regardless of whether the file\n # is actually found in a Repository or locally." ]
Please provide a description of the function:def caller_trace(back=0): global caller_bases, caller_dicts import traceback tb = traceback.extract_stack(limit=3+back) tb.reverse() callee = tb[1][:3] caller_bases[callee] = caller_bases.get(callee, 0) + 1 for caller in tb[2:]: calle...
[ "\n Trace caller stack and save info into global dicts, which\n are printed automatically at the end of SCons execution.\n " ]
Please provide a description of the function:def Trace(msg, file=None, mode='w', tstamp=None): global TraceDefault global TimeStampDefault global PreviousTime if file is None: file = TraceDefault else: TraceDefault = file if tstamp is None: tstamp = TimeStampDefault ...
[ "Write a trace message to a file. Whenever a file is specified,\n it becomes the default for the next call to Trace()." ]
Please provide a description of the function:def verify(self, obj): if isinstance(obj, str): raise ValidationError("Object was not a list", reason="a string was passed instead of a list", object=obj) out_obj = [] if self._min_length is not None and len(obj) < self._min_len...
[ "Verify that the object conforms to this verifier's schema\n\n Args:\n obj (object): A python object to verify\n\n Raises:\n ValidationError: If there is a problem verifying the dictionary, a\n ValidationError is thrown with at least the reason key set indicating\n...
Please provide a description of the function:def hex2bin(fin, fout, start=None, end=None, size=None, pad=None): try: h = IntelHex(fin) except HexReaderError: e = sys.exc_info()[1] # current exception txt = "ERROR: bad HEX file: %s" % str(e) print(txt) return 1 ...
[ "Hex-to-Bin convertor engine.\n @return 0 if all OK\n\n @param fin input hex file (filename or file-like object)\n @param fout output bin file (filename or file-like object)\n @param start start of address range (optional)\n @param end end of address range (inclusive; optional)...
Please provide a description of the function:def bin2hex(fin, fout, offset=0): h = IntelHex() try: h.loadbin(fin, offset) except IOError: e = sys.exc_info()[1] # current exception txt = 'ERROR: unable to load bin file:', str(e) print(txt) return 1 try: ...
[ "Simple bin-to-hex convertor.\n @return 0 if all OK\n\n @param fin input bin file (filename or file-like object)\n @param fout output hex file (filename or file-like object)\n @param offset starting address offset for loading bin\n " ]
Please provide a description of the function:def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3): def prepare_lines(ih): sio = StringIO() ih.dump(sio) dump = sio.getvalue() lines = dump.splitlines() return lines a = prepare_lines(ih1) b = pre...
[ "Diff 2 IntelHex objects and produce unified diff output for their\n hex dumps.\n\n @param ih1 first IntelHex object to compare\n @param ih2 second IntelHex object to compare\n @param tofile file-like object to write output\n @param name1 name of the first hex file to show in t...
Please provide a description of the function:def _get_file_and_addr_range(s, _support_drive_letter=None): if _support_drive_letter is None: _support_drive_letter = (os.name == 'nt') drive = '' if _support_drive_letter: if s[1:2] == ':' and s[0].upper() in ''.join([chr(i) for i in range_...
[ "Special method for hexmerge.py script to split file notation\n into 3 parts: (filename, start, end)\n\n @raise _BadFileNotation when string cannot be safely split.\n " ]
Please provide a description of the function:def _decode_record(self, s, line=0): '''Decode one record of HEX file. @param s line with HEX record. @param line line number (for error messages). @raise EndOfFile if EOF record encountered. ''' s = s.rstrip('\...
[]
Please provide a description of the function:def loadhex(self, fobj): if getattr(fobj, "read", None) is None: fobj = open(fobj, "r") fclose = fobj.close else: fclose = None self._offset = 0 line = 0 try: decode = self._de...
[ "Load hex file into internal buffer. This is not necessary\n if object was initialized with source set. This will overwrite\n addresses if object was already initialized.\n\n @param fobj file name or file-like object\n " ]
Please provide a description of the function:def loadbin(self, fobj, offset=0): fread = getattr(fobj, "read", None) if fread is None: f = open(fobj, "rb") fread = f.read fclose = f.close else: fclose = None try: self.f...
[ "Load bin file into internal buffer. Not needed if source set in\n constructor. This will overwrite addresses without warning\n if object was already initialized.\n\n @param fobj file name or file-like object\n @param offset starting address offset\n " ]
Please provide a description of the function:def loadfile(self, fobj, format): if format == "hex": self.loadhex(fobj) elif format == "bin": self.loadbin(fobj) else: raise ValueError('format should be either "hex" or "bin";' ' got %r in...
[ "Load data file into internal buffer. Preferred wrapper over\n loadbin or loadhex.\n\n @param fobj file name or file-like object\n @param format file format (\"hex\" or \"bin\")\n " ]