idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
21,400 | def discover_thread ( callback , timeout = 5 , include_invisible = False , interface_addr = None ) : thread = StoppableThread ( target = _discover_thread , args = ( callback , timeout , include_invisible , interface_addr ) ) thread . start ( ) return thread | Return a started thread with a discovery callback . |
21,401 | def by_name ( name ) : devices = discover ( all_households = True ) for device in ( devices or [ ] ) : if device . player_name == name : return device return None | Return a device by name . |
21,402 | def get_trainer ( name ) : name = name . lower ( ) return int ( hashlib . md5 ( name . encode ( 'utf-8' ) ) . hexdigest ( ) , 16 ) % 10 ** 8 | return the unique id for a trainer determined by the md5 sum |
21,403 | def scale_image ( image , new_width ) : ( original_width , original_height ) = image . size aspect_ratio = original_height / float ( original_width ) new_height = int ( aspect_ratio * new_width ) new_image = image . resize ( ( new_width * 2 , new_height ) ) return new_image | Resizes an image preserving the aspect ratio . |
21,404 | def map_pixels_to_ascii_chars ( image , range_width = 25 ) : pixels_in_image = list ( image . getdata ( ) ) pixels_to_chars = [ ASCII_CHARS [ pixel_value / range_width ] for pixel_value in pixels_in_image ] return "" . join ( pixels_to_chars ) | Maps each pixel to an ascii char based on the range in which it lies . |
21,405 | def load_steps ( working_dir = None , steps_dir = None , step_file = None , step_list = None ) : if steps_dir is not None : step_files = glob . glob ( os . path . join ( steps_dir , '*.cwl' ) ) elif step_file is not None : step_files = [ step_file ] elif step_list is not None : step_files = [ ] for path in step_list : ... | Return a dictionary containing Steps read from file . |
21,406 | def load_yaml ( filename ) : with open ( filename ) as myfile : content = myfile . read ( ) if "win" in sys . platform : content = content . replace ( "\\" , "/" ) return yaml . safe_load ( content ) | Return object in yaml file . |
21,407 | def sort_loading_order ( step_files ) : tools = [ ] workflows = [ ] workflows_with_subworkflows = [ ] for f in step_files : if f . startswith ( 'http://' ) or f . startswith ( 'https://' ) : tools . append ( f ) else : obj = load_yaml ( f ) if obj . get ( 'class' , '' ) == 'Workflow' : if 'requirements' in obj . keys (... | Sort step files into correct loading order . |
21,408 | def load_cwl ( fname ) : logger . debug ( 'Loading CWL file "{}"' . format ( fname ) ) if legacy_cwltool : try : ( document_loader , workflowobj , uri ) = fetch_document ( fname ) ( document_loader , _ , processobj , metadata , uri ) = validate_document ( document_loader , workflowobj , uri ) except TypeError : from cw... | Load and validate CWL file using cwltool |
21,409 | def set_input ( self , p_name , value ) : name = self . python_names . get ( p_name ) if p_name is None or name not in self . get_input_names ( ) : raise ValueError ( 'Invalid input "{}"' . format ( p_name ) ) self . step_inputs [ name ] = value | Set a Step s input variable to a certain value . |
21,410 | def output_reference ( self , name ) : if name not in self . output_names : raise ValueError ( 'Invalid output "{}"' . format ( name ) ) return Reference ( step_name = self . name_in_workflow , output_name = name ) | Return a reference to the given output for use in an input of a next Step . |
21,411 | def _input_optional ( inp ) : if 'default' in inp . keys ( ) : return True typ = inp . get ( 'type' ) if isinstance ( typ , six . string_types ) : return typ . endswith ( '?' ) elif isinstance ( typ , dict ) : return False elif isinstance ( typ , list ) : return bool ( u'null' in typ ) else : raise ValueError ( 'Invali... | Returns True if a step input parameter is optional . |
21,412 | def to_obj ( self , wd = False , pack = False , relpath = None ) : obj = CommentedMap ( ) if pack : obj [ 'run' ] = self . orig elif relpath is not None : if self . from_url : obj [ 'run' ] = self . run else : obj [ 'run' ] = os . path . relpath ( self . run , relpath ) elif wd : if self . from_url : obj [ 'run' ] = se... | Return the step as an dict that can be written to a yaml file . |
21,413 | def list_inputs ( self ) : doc = [ ] for inp , typ in self . input_types . items ( ) : if isinstance ( typ , six . string_types ) : typ = "'{}'" . format ( typ ) doc . append ( '{}: {}' . format ( inp , typ ) ) return '\n' . join ( doc ) | Return a string listing all the Step s input names and their types . |
21,414 | def load ( self , steps_dir = None , step_file = None , step_list = None ) : self . _closed ( ) self . steps_library . load ( steps_dir = steps_dir , step_file = step_file , step_list = step_list ) | Load CWL steps into the WorkflowGenerator s steps library . |
21,415 | def _has_requirements ( self ) : self . _closed ( ) return any ( [ self . has_workflow_step , self . has_scatter_requirement , self . has_multiple_inputs ] ) | Returns True if the workflow needs a requirements section . |
21,416 | def inputs ( self , name ) : self . _closed ( ) step = self . _get_step ( name , make_copy = False ) return step . list_inputs ( ) | List input names and types of a step in the steps library . |
21,417 | def _add_step ( self , step ) : self . _closed ( ) self . has_workflow_step = self . has_workflow_step or step . is_workflow self . wf_steps [ step . name_in_workflow ] = step | Add a step to the workflow . |
21,418 | def add_input ( self , ** kwargs ) : self . _closed ( ) def _get_item ( args ) : if not args : raise ValueError ( "No parameter specified." ) item = args . popitem ( ) if args : raise ValueError ( "Too many parameters, not clear what to do " "with {}" . format ( kwargs ) ) return item symbols = None input_dict = Commen... | Add workflow input . |
21,419 | def add_outputs ( self , ** kwargs ) : self . _closed ( ) for name , source_name in kwargs . items ( ) : obj = { } obj [ 'outputSource' ] = source_name obj [ 'type' ] = self . step_output_types [ source_name ] self . wf_outputs [ name ] = obj | Add workflow outputs . |
21,420 | def _get_step ( self , name , make_copy = True ) : self . _closed ( ) s = self . steps_library . get_step ( name ) if s is None : msg = '"{}" not found in steps library. Please check your ' 'spelling or load additional steps' raise ValueError ( msg . format ( name ) ) if make_copy : s = copy . deepcopy ( s ) return s | Return step from steps library . |
21,421 | def to_obj ( self , wd = False , pack = False , relpath = None ) : self . _closed ( ) obj = CommentedMap ( ) obj [ 'cwlVersion' ] = 'v1.0' obj [ 'class' ] = 'Workflow' try : obj [ 'doc' ] = self . documentation except ( AttributeError , ValueError ) : pass try : obj [ 'label' ] = self . label except ( AttributeError , ... | Return the created workflow as a dict . |
21,422 | def to_script ( self , wf_name = 'wf' ) : self . _closed ( ) script = [ ] params = [ ] returns = [ ] for name , typ in self . wf_inputs . items ( ) : params . append ( '{}=\'{}\'' . format ( name , typ ) ) returns . append ( name ) script . append ( '{} = {}.add_inputs({})' . format ( ', ' . join ( returns ) , wf_name ... | Generated and print the scriptcwl script for the currunt workflow . |
21,423 | def _types_match ( type1 , type2 ) : if isinstance ( type1 , six . string_types ) and isinstance ( type2 , six . string_types ) : type1 = type1 . rstrip ( '?' ) type2 = type2 . rstrip ( '?' ) if type1 != type2 : return False return True | Returns False only if it can show that no value of type1 can possibly match type2 . |
21,424 | def validate ( self ) : ( fd , tmpfile ) = tempfile . mkstemp ( ) os . close ( fd ) try : self . save ( tmpfile , mode = 'abs' , validate = False ) document_loader , processobj , metadata , uri = load_cwl ( tmpfile ) finally : os . remove ( tmpfile ) | Validate workflow object . |
21,425 | def save ( self , fname , mode = None , validate = True , encoding = 'utf-8' , wd = False , inline = False , relative = False , pack = False ) : self . _closed ( ) if mode is None : mode = 'abs' if pack : mode = 'pack' elif wd : mode = 'wd' elif relative : mode = 'rel' msg = 'Using deprecated save method. Please save t... | Save the workflow to file . |
21,426 | def str_presenter ( dmpr , data ) : if is_multiline ( data ) : return dmpr . represent_scalar ( 'tag:yaml.org,2002:str' , data , style = '|' ) return dmpr . represent_scalar ( 'tag:yaml.org,2002:str' , data ) | Return correct str_presenter to write multiple lines to a yaml field . |
21,427 | def build_grad_matrices ( V , points ) : mesh = V . mesh ( ) bbt = BoundingBoxTree ( ) bbt . build ( mesh ) dofmap = V . dofmap ( ) el = V . element ( ) rows = [ ] cols = [ ] datax = [ ] datay = [ ] for i , xy in enumerate ( points ) : cell_id = bbt . compute_first_entity_collision ( Point ( * xy ) ) cell = Cell ( mesh... | Build the sparse m - by - n matrices that map a coefficient set for a function in V to the values of dx and dy at a number m of points . |
21,428 | def apply_M ( self , ax , ay ) : jac = numpy . array ( [ [ self . dx . dot ( ax ) , self . dy . dot ( ax ) ] , [ self . dx . dot ( ay ) , self . dy . dot ( ay ) ] ] ) M = numpy . einsum ( "ijl,jkl->ikl" , jac , self . J ) a = ( M [ 0 , 0 ] + M [ 1 , 1 ] ) / 2 b = ( M [ 0 , 0 ] - M [ 1 , 1 ] ) / 2 c = ( M [ 1 , 0 ] + M ... | Linear operator that converts ax ay to abcd . |
21,429 | def cost_min2 ( self , alpha ) : n = self . V . dim ( ) ax = alpha [ : n ] ay = alpha [ n : ] q2 , r2 = self . get_q2_r2 ( ax , ay ) Lax = self . L * ax Lay = self . L * ay out = [ 0.5 * numpy . dot ( Lax , Lax ) , 0.5 * numpy . dot ( Lay , Lay ) , 0.5 * numpy . dot ( q2 - 1 , q2 - 1 ) , 0.5 * numpy . dot ( r2 , r2 ) ,... | Residual formulation Hessian is a low - rank update of the identity . |
21,430 | def delta ( a , b ) : diff = a - b return numpy . einsum ( "i...,i...->..." , diff , diff ) | Computes the distances between two colors or color sets . The shape of a and b must be equal . |
21,431 | def plot_flat_gamut ( xy_to_2d = lambda xy : xy , axes_labels = ( "x" , "y" ) , plot_rgb_triangle = True , fill_horseshoe = True , plot_planckian_locus = True , ) : observer = observers . cie_1931_2 ( ) _plot_monochromatic ( observer , xy_to_2d , fill_horseshoe = fill_horseshoe ) if plot_rgb_triangle : _plot_rgb_triang... | Show a flat color gamut by default xy . There exists a chroma gamut for all color models which transform lines in XYZ to lines and hence have a natural decomposition into lightness and chroma components . Also the flat gamut is the same for every lightness value . Examples for color models with this property are CIELUV... |
21,432 | def _get_xy_tree ( xy , degree ) : x , y = xy tree = [ numpy . array ( [ numpy . ones ( x . shape , dtype = int ) ] ) ] for d in range ( degree ) : tree . append ( numpy . concatenate ( [ tree [ - 1 ] * x , [ tree [ - 1 ] [ - 1 ] * y ] ] ) ) return tree | Evaluates the entire tree of 2d mononomials . |
21,433 | def spectrum_to_xyz100 ( spectrum , observer ) : lambda_o , data_o = observer lambda_s , data_s = spectrum lmbda = numpy . sort ( numpy . unique ( numpy . concatenate ( [ lambda_o , lambda_s ] ) ) ) assert lmbda [ 0 ] < 361e-9 assert lmbda [ - 1 ] > 829e-9 idata_o = numpy . array ( [ numpy . interp ( lmbda , lambda_o ,... | Computes the tristimulus values XYZ from a given spectrum for a given observer via |
21,434 | def d ( nominal_temperature ) : tcp = 1.4388e-2 / 1.4380e-2 * nominal_temperature if 4000 <= tcp <= 7000 : xd = ( ( - 4.6070e9 / tcp + 2.9678e6 ) / tcp + 0.09911e3 ) / tcp + 0.244063 else : assert 7000 < tcp <= 25000 xd = ( ( - 2.0064e9 / tcp + 1.9018e6 ) / tcp + 0.24748e3 ) / tcp + 0.237040 yd = ( - 3.000 * xd + 2.870... | CIE D - series illuminants . |
21,435 | 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 illuminant E are weighted equally with a relative spectral power of 100 . 0 . |
21,436 | 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 of a and the first of b . |
21,437 | 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 ) if filter == 'rock' : mask = ( l == 31 ) elif filter == 'rock+ice' : mask = np . logical_or ( ( l == 31 ) , ( ... | Generate raster mask for specified NLCD LULC filter |
21,438 | 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 < 0.0 or bareground_thresh > 100.0 : sys . exi... | Generate raster mask for exposed bare ground from global bareground data |
21,439 | 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 ) if dem_dt >= datetime ( 2003 , 9 , 30 ) and dem_dt < datetime ( 2010 , 1 , 1 ) : snodas_url_str ... | Function to fetch and process SNODAS snow depth products for input datetime |
21,440 | 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 ) ct = osr . CoordinateTransformation ( geom_dup ... | Helper function to identify MODIS tiles that intersect input geometry |
21,441 | def get_modscag_fn_list ( dem_dt , tile_list = ( 'h08v04' , 'h09v04' , 'h10v04' , 'h08v05' , 'h09v05' ) , pad_days = 7 ) : import re import requests from bs4 import BeautifulSoup auth = iolib . get_auth ( ) pad_days = timedelta ( days = pad_days ) dt_list = timelib . dt_range ( dem_dt - pad_days , dem_dt + pad_days + t... | Function to fetch and process MODSCAG fractional snow cover products for input datetime |
21,442 | def proc_modscag ( fn_list , extent = None , t_srs = None ) : 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 . splitext ( os . path . split ( fn_list [ - 1 ] ) [ 1 ] ) [ 0 ] + ... | Process the MODSCAG products for full date range create composites and reproject |
21,443 | 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 len_accum = 0 for x in value : len_accum += self . _value_length ( x , t ) return len_accum | Given an integer or list of them convert it to an array of bytes . |
21,444 | 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 ) if 'symbol' in matched : self . _parse_cmd ( matched ) elif 'filename' in ma... | Parse a line in a TileBus file |
21,445 | 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." , variable = var ) if len ( self . variables [ "ModuleName" ] ) > 6 : raise DataError ... | Validate that all information has been filled in |
21,446 | 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 ( key , val ) if not self . valid : self . _validate_information ( ) mib . set_api_ver... | Create a TileBus Block based on the information in this descriptor |
21,447 | 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 async wrapper" , adapter ) adapter = AsynchronousModernWrapper ( adapter ,... | Add a device adapter to this aggregating adapter . |
21,448 | 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 . |
21,449 | 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 [ : successful ] : await adapter . stop ( ) raise | Start all adapters managed by this device adapter . |
21,450 | 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 ( ) : connstring = "adapter/{0}/{1}" . format ( adapter_id , devinfo [ 'connection_string' ] ) if dev is None : dev = copy . d... | Unify all visible devices across all connected adapters |
21,451 | async def probe ( self ) : for adapter in self . adapters : if adapter . get_config ( 'probe_supported' , False ) : await adapter . probe ( ) | Probe for devices . |
21,452 | 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 . |
21,453 | 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 ) conn_string = self . _translate_conn_string ( adapter_id , co... | Handle an event received from an adapter . |
21,454 | 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 : continue if now > dev [ 'expires' ] : to_remove . append ( adapter_id ) local_conn = "adapter/%d/%s" % ( adapter_... | Periodic callback to remove expired devices from visible_devices . |
21,455 | 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' raise SCons . Errors . UserError ( m % ( key , val ) ) | Validator to check if Path is a directory . |
21,456 | 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 |
21,457 | async def _reset_vector ( self ) : self . _logger . debug ( "sensor_graph subsystem task starting" ) self . initialized . set ( ) while True : stream , reading = await self . _inputs . get ( ) try : await process_graph_input ( self . graph , stream , reading , self . _executor ) self . process_streamers ( ) except : se... | Background task to initialize this system in the event loop . |
21,458 | 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 isinstance ( encoded_stream , DataStream ) : stream = encoded_stream encoded_stream = stream . encod... | Process or drop a graph input . |
21,459 | 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 ) find_type = None try : exact = streamer . walker . seek ( value , targ... | Complex logic for actually seeking a streamer to a reading_id . |
21,460 | 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 <= old_ack and not force : return _pack_sgerror ( SensorGraphError . OLD_ACK... | Acknowledge a streamer value as received from the remote side . |
21,461 | 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 . |
21,462 | def process_streamers ( self ) : in_progress = self . _stream_manager . in_progress ( ) triggered = self . graph . check_streamers ( blacklist = in_progress ) for streamer in triggered : self . _stream_manager . process_streamer ( streamer , callback = self . _handle_streamer_finished ) | Check if any streamers should be handed to the stream manager . |
21,463 | 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 . _stream_manager . in_progress ( ) : return _pack_sgerror ( SensorGr... | Pass a streamer to the stream manager if it has data . |
21,464 | 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 . |
21,465 | 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 . |
21,466 | 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_sgerror ( SensorGraphError . INVALID_NODE_STREAM ) try : self . graph . add_node ( node_string... | Add a node to the sensor_graph using a binary node descriptor . |
21,467 | 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 ( ) return Error . NO_ERROR except ResourceUsageError : return _p... | Add a streamer to the sensor_graph using a binary streamer descriptor . |
21,468 | 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 . streamers [ index ] ) ] | Inspect the streamer at the given index . |
21,469 | def inspect_node ( self , index ) : if index >= len ( self . graph . nodes ) : raise RPCErrorCode ( 6 ) return create_binary_descriptor ( str ( self . graph . nodes [ index ] ) ) | Inspect the graph node at the given index . |
21,470 | 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_time , info . last_error , highest_ack , info . last_status , info . att... | Query the status of the streamer at the given index . |
21,471 | 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 . |
21,472 | 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 . |
21,473 | 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 . |
21,474 | 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 . |
21,475 | 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 shared_data [ 1 ] = return_value done . set ( ) callback = _callback workitem = WorkItem ( value , callb... | Dispatch an item to the workqueue and optionally wait . |
21,476 | 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 : exc = tp if exc . __traceback__ is not tb : raise exc . with_traceback ( tb ) raise... | raise_ implementation from future . utils |
21,477 | def flush ( self ) : done = threading . Event ( ) def _callback ( ) : done . set ( ) self . defer ( _callback ) done . wait ( ) | Synchronously wait until this work item is processed . |
21,478 | def direct_dispatch ( self , arg , callback ) : try : self . _current_callbacks . appendleft ( callback ) exc_info = None retval = None retval = self . _routine ( arg ) except : exc_info = sys . exc_info ( ) finally : self . _current_callbacks . popleft ( ) if callback is not None and retval is not self . STILL_PENDING... | Directly dispatch a work item . |
21,479 | 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 . |
21,480 | 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 . |
21,481 | 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 ( '-nologo' ) env [ 'WIXLIGHTCOM' ] = "$WIXLIGHT $WIXLIGHTFLA... | Add Builders and construction variables for WiX to an Environment . |
21,482 | 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 : data = parse_exp . parseString ( desc ) time = 0 if '... | Create a new stimulus from a description string . |
21,483 | 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 ArgumentError ( "You must supply either an int connection id or a string internal id to _get_connection_state" , i... | Get the connection id . |
21,484 | 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 try : data = table [ key ] except KeyError : return None return data | Get the data for a connection by either conn_id or internal_id |
21,485 | 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 ArgumentError ( "You must supply either an int connection id or a string internal id to _get_connection_state"... | Get a connection s state by either conn_id or internal_id |
21,486 | 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 , 'Connection attempt timed out' ) elif data [ 'state' ] == self . Disconnecting : self . f... | Check if any operations in progress need to be timed out |
21,487 | 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 . |
21,488 | 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 = False ) self . _actions . put ( action ) | Finish an operation on a connection . |
21,489 | 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 connection whose state is not InProgress, conn_key=%s" , str ( conn_... | Finish an attempted operation . |
21,490 | 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 ] = out [ - 1 ] + line . lstrip ( ) else : out . append ( line ) line_continues_a_comment = len ... | Standardize an input TeX - file contents . |
21,491 | def scan_recurse ( self , node , path = ( ) ) : path_dict = dict ( list ( path ) ) queue = [ ] queue . extend ( self . scan ( node ) ) seen = { } nodes = [ ] source_dir = node . get_dir ( ) while queue : include = queue . pop ( ) inc_type , inc_subdir , inc_filename = include try : if seen [ inc_filename ] == 1 : conti... | do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does |
21,492 | 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 : ] : caller = callee + caller [ : 3 ] try : entry = cal... | Trace caller stack and save info into global dicts which are printed automatically at the end of SCons execution . |
21,493 | 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 = prepare_lines ( ih2 ) import difflib result = list ( difflib . uni... | Diff 2 IntelHex objects and produce unified diff output for their hex dumps . |
21,494 | def _decode_record ( self , s , line = 0 ) : s = s . rstrip ( '\r\n' ) if not s : return if s [ 0 ] == ':' : try : bin = array ( 'B' , unhexlify ( asbytes ( s [ 1 : ] ) ) ) except ( TypeError , ValueError ) : raise HexRecordError ( line = line ) length = len ( bin ) if length < 5 : raise HexRecordError ( line = line ) ... | Decode one record of HEX file . |
21,495 | 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 . _decode_record try : for s in fobj : line += 1 decode ( s , line ) except _EndOfFile : pass finally : if fclose : fclose ( ) | Load hex file into internal buffer . This is not necessary if object was initialized with source set . This will overwrite addresses if object was already initialized . |
21,496 | 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 . frombytes ( array ( 'B' , asbytes ( fread ( ) ) ) , offset = offset ) finally : if fclose : fclose ( ) | Load bin file into internal buffer . Not needed if source set in constructor . This will overwrite addresses without warning if object was already initialized . |
21,497 | 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 instead' % format ) | Load data file into internal buffer . Preferred wrapper over loadbin or loadhex . |
21,498 | def _get_start_end ( self , start = None , end = None , size = None ) : if ( start , end ) == ( None , None ) and self . _buf == { } : raise EmptyIntelHexError if size is not None : if None not in ( start , end ) : raise ValueError ( "tobinarray: you can't use start,end and size" " arguments in the same time" ) if ( st... | Return default values for start and end if they are None . If this IntelHex object is empty then it s error to invoke this method with both start and end as None . |
21,499 | def tobinarray ( self , start = None , end = None , pad = _DEPRECATED , size = None ) : if not isinstance ( pad , _DeprecatedParam ) : print ( "IntelHex.tobinarray: 'pad' parameter is deprecated." ) if pad is not None : print ( "Please, use IntelHex.padding attribute instead." ) else : print ( "Please, don't pass it ex... | Convert this object to binary form as array . If start and end unspecified they will be inferred from the data . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.