signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def encode_sentence ( sentence ) : """Encode a single sentence ."""
tree = etree . Element ( 'sentence' ) encode_infons ( tree , sentence . infons ) etree . SubElement ( tree , 'offset' ) . text = str ( sentence . offset ) if sentence . text : etree . SubElement ( tree , 'text' ) . text = sentence . text for ann in sentence . annotations : tree . append ( encode_annotation ( an...
def fwd ( self , astr_startPath , ** kwargs ) : """Return the files - in - working - directory in treeRecurse compatible format . : return : Return the cwd in treeRecurse compatible format ."""
status = self . cd ( astr_startPath ) [ 'status' ] if status : l = self . lsf ( ) if len ( l ) : lf = [ self . cwd ( ) + '/' + f for f in l ] for entry in lf : self . l_fwd . append ( entry ) return { 'status' : status , 'cwd' : self . cwd ( ) }
def is_authorized ( self , request ) : """Check if the user is authenticated for the given request . The include _ paths and exclude _ paths are first checked . If authentication is required then the Authorization HTTP header is checked against the credentials ."""
if self . _is_request_in_include_path ( request ) : if self . _is_request_in_exclude_path ( request ) : return True else : auth = request . authorization if auth and auth [ 0 ] == 'Basic' : credentials = b64decode ( auth [ 1 ] ) . decode ( 'UTF-8' ) username , pas...
def _process_pair ( first_fn , second_fn , error_protocol ) : """Look at given filenames , decide which is what and try to pair them ."""
ebook = None metadata = None if _is_meta ( first_fn ) and not _is_meta ( second_fn ) : # 1st meta , 2nd data logger . debug ( "Parsed: '%s' as meta, '%s' as data." % ( first_fn , second_fn ) ) metadata , ebook = first_fn , second_fn elif not _is_meta ( first_fn ) and _is_meta ( second_fn ) : # 1st data , 2nd me...
def resolve ( self , year : int = YEAR_ANY ) -> MDate : """Return the date object in the solar / lunar year . : param year : : return :"""
year = year or self . year if year : return self . _resolve ( year ) raise ValueError ( 'Unable resolve the date without a specified year.' )
def on_mouse_wheel ( self , event ) : '''handle mouse wheel zoom changes'''
state = self . state if not state . can_zoom : return mousepos = self . image_coordinates ( event . GetPosition ( ) ) rotation = event . GetWheelRotation ( ) / event . GetWheelDelta ( ) oldzoom = self . zoom if rotation > 0 : self . zoom /= 1.0 / ( 1.1 * rotation ) elif rotation < 0 : self . zoom /= 1.1 * (...
def is_local ( path ) : # type : ( str ) - > bool """Return True if path is within sys . prefix , if we ' re running in a virtualenv . If we ' re not in a virtualenv , all paths are considered " local . " """
if not running_under_virtualenv ( ) : return True return normalize_path ( path ) . startswith ( normalize_path ( sys . prefix ) )
def builtin_lookup ( name ) : """lookup a name into the builtin module return the list of matching statements and the astroid for the builtin module"""
builtin_astroid = MANAGER . ast_from_module ( builtins ) if name == "__dict__" : return builtin_astroid , ( ) try : stmts = builtin_astroid . locals [ name ] except KeyError : stmts = ( ) return builtin_astroid , stmts
def run ( self , directories = None ) : """Finds and runs the specs . Returns a tuple indicating the number of ( succeses , failures , skipped ) >"""
if directories is None : directories = [ os . getcwd ( ) ] total_successes , total_errors , total_skipped = 0 , 0 , 0 for directory in directories : successes , errors , skips = self . execute ( self . find_specs ( directory ) ) total_successes += successes total_errors += errors total_skipped += sk...
def register_image ( kwargs = None , call = None ) : '''Create an ami from a snapshot CLI Example : . . code - block : : bash salt - cloud - f register _ image my - ec2 - config ami _ name = my _ ami description = " my description " root _ device _ name = / dev / xvda snapshot _ id = snap - xxxxx'''
if call != 'function' : log . error ( 'The create_volume function must be called with -f or --function.' ) return False if 'ami_name' not in kwargs : log . error ( 'ami_name must be specified to register an image.' ) return False block_device_mapping = kwargs . get ( 'block_device_mapping' , None ) if n...
def port_id_from_name ( port_name , device_id , nodes ) : """Get the port ID when given a port name : param str port _ name : port name : param str device _ id : device ID : param list nodes : list of nodes from : py : meth : ` generate _ nodes ` : return : port ID : rtype : int"""
port_id = None for node in nodes : if device_id == node [ 'id' ] : for port in node [ 'ports' ] : if port_name == port [ 'name' ] : port_id = port [ 'id' ] break break return port_id
def state_fidelity ( state0 : State , state1 : State ) -> bk . BKTensor : """Return the quantum fidelity between pure states ."""
assert state0 . qubits == state1 . qubits # FIXME tensor = bk . absolute ( bk . inner ( state0 . tensor , state1 . tensor ) ) ** bk . fcast ( 2 ) return tensor
def default_gateway ( ) : '''Populates grains which describe whether a server has a default gateway configured or not . Uses ` ip - 4 route show ` and ` ip - 6 route show ` and greps for a ` default ` at the beginning of any line . Assuming the standard ` default via < ip > ` format for default gateways , it ...
grains = { } ip_bin = salt . utils . path . which ( 'ip' ) if not ip_bin : return { } grains [ 'ip_gw' ] = False grains [ 'ip4_gw' ] = False grains [ 'ip6_gw' ] = False for ip_version in ( '4' , '6' ) : try : out = __salt__ [ 'cmd.run' ] ( [ ip_bin , '-' + ip_version , 'route' , 'show' ] ) for l...
def sparse_surface ( self ) : """Filled cells on the surface of the mesh . Returns voxels : ( n , 3 ) int , filled cells on mesh surface"""
if self . _method == 'ray' : func = voxelize_ray elif self . _method == 'subdivide' : func = voxelize_subdivide else : raise ValueError ( 'voxelization method incorrect' ) voxels , origin = func ( mesh = self . _data [ 'mesh' ] , pitch = self . _data [ 'pitch' ] , max_iter = self . _data [ 'max_iter' ] [ 0 ...
def renumerate_stages ( pipeline ) : """Renumber Pipeline Stage reference IDs to account for dependencies . stage order is defined in the templates . The ` ` refId ` ` field dictates if a stage should be mainline or parallel to other stages . * ` ` master ` ` - A mainline required stage . Other stages depend ...
stages = pipeline [ 'stages' ] main_index = 0 branch_index = 0 previous_refid = '' for stage in stages : current_refid = stage [ 'refId' ] . lower ( ) if current_refid == 'master' : if main_index == 0 : stage [ 'requisiteStageRefIds' ] = [ ] else : stage [ 'requisiteStage...
def combine ( files : List [ str ] , output_file : str , key : str = None , file_attrs : Dict [ str , str ] = None , batch_size : int = 1000 , convert_attrs : bool = False ) -> None : """Combine two or more loom files and save as a new loom file Args : files ( list of str ) : the list of input files ( full path...
if file_attrs is None : file_attrs = { } if len ( files ) == 0 : raise ValueError ( "The input file list was empty" ) copyfile ( files [ 0 ] , output_file ) ds = connect ( output_file ) for a in file_attrs : ds . attrs [ a ] = file_attrs [ a ] if len ( files ) >= 2 : for f in files [ 1 : ] : ds ...
def actual_causation ( ) : """The actual causation example network , consisting of an ` ` OR ` ` and ` ` AND ` ` gate with self - loops ."""
tpm = np . array ( [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] ] ) cm = np . array ( [ [ 1 , 1 ] , [ 1 , 1 ] ] ) return Network ( tpm , cm , node_labels = ( 'OR' , 'AND' ) )
def color_ramp ( number_of_colour ) : """Generate list of color in hexadecimal . This will generate colors using hsl model by playing around with the hue see : https : / / coderwall . com / p / dvsxwg / smoothly - transition - from - green - to - red : param number _ of _ colour : The number of intervals betw...
if number_of_colour < 1 : raise Exception ( 'The number of colours should be > 0' ) colors = [ ] if number_of_colour == 1 : hue_interval = 1 else : hue_interval = 1.0 / ( number_of_colour - 1 ) for i in range ( number_of_colour ) : hue = ( i * hue_interval ) / 3 light = 127.5 saturation = - 1.00...
def _find_missing ( self , data , return_bool = False ) : """Parameters data : pd . DataFrame ( ) Input dataframe . return _ bool : bool Returns pd . DataFrame ( )"""
# This returns the full table with True where the condition is true if return_bool == False : data = self . _find_missing_return_frame ( data ) return data # This returns a bool selector if any of the column is True elif return_bool == "any" : bool_sel = self . _find_missing_return_frame ( data ) . any ( ax...
def resolve_job ( self , name ) : """Attempt to resolve the task name in to a job name . If no job resolver can resolve the task , i . e . they all return None , return None . Keyword arguments : name - - Name of the task to be resolved ."""
for r in self . job_resolvers ( ) : resolved_name = r ( name ) if resolved_name is not None : return resolved_name return None
def split_by_percent ( self , spin_systems_list ) : """Split list of spin systems by specified percentages . : param list spin _ systems _ list : List of spin systems . : return : List of spin systems divided into sub - lists corresponding to specified split percentages . : rtype : : py : class : ` list `"""
chunk_sizes = [ int ( ( i * len ( spin_systems_list ) ) / 100 ) for i in self . plsplit ] if sum ( chunk_sizes ) < len ( spin_systems_list ) : difference = len ( spin_systems_list ) - sum ( chunk_sizes ) chunk_sizes [ chunk_sizes . index ( min ( chunk_sizes ) ) ] += difference assert sum ( chunk_sizes ) == len ...
def _delete ( self , pk ) : """Delete function logic , override to implement diferent logic deletes the record with primary _ key = pk : param pk : record primary key to delete"""
item = self . datamodel . get ( pk , self . _base_filters ) if not item : abort ( 404 ) try : self . pre_delete ( item ) except Exception as e : flash ( str ( e ) , 'danger' ) else : view_menu = security_manager . find_view_menu ( item . get_perm ( ) ) pvs = security_manager . get_session . query ( ...
def _pull_schema_definition ( self , fname ) : """download an ontology definition from the web"""
std_url = urlopen ( self . _ontology_file ) cached_std = open ( fname , "w+" ) cached_std . write ( std_url . read ( ) ) cached_std . close ( )
def _send_upstream ( queue , client , codec , batch_time , batch_size , req_acks , ack_timeout , retry_options , stop_event , log_messages_on_error = ASYNC_LOG_MESSAGES_ON_ERROR , stop_timeout = ASYNC_STOP_TIMEOUT_SECS , codec_compresslevel = None ) : """Private method to manage producing messages asynchronously ...
request_tries = { } while not stop_event . is_set ( ) : try : client . reinit ( ) except Exception as e : log . warn ( 'Async producer failed to connect to brokers; backoff for %s(ms) before retrying' , retry_options . backoff_ms ) time . sleep ( float ( retry_options . backoff_ms ) / 10...
def result_tree_flat ( context , cl , request ) : """Added ' filtered ' param , so the template ' s js knows whether the results have been affected by a GET param or not . Only when the results are not filtered you can drag and sort the tree"""
return { # ' filtered ' : is _ filtered _ cl ( cl , request ) , 'results' : ( th_for_result ( cl , res ) for res in list ( cl . result_list ) ) , }
def _convert_strls ( self , data ) : """Convert columns to StrLs if either very large or in the convert _ strl variable"""
convert_cols = [ col for i , col in enumerate ( data ) if self . typlist [ i ] == 32768 or col in self . _convert_strl ] if convert_cols : ssw = StataStrLWriter ( data , convert_cols ) tab , new_data = ssw . generate_table ( ) data = new_data self . _strl_blob = ssw . generate_blob ( tab ) return data
def getReward ( self ) : """Returns the reward corresponding to the last action performed ."""
t = self . env . market . period # Compute revenue minus costs . totalEarnings = 0.0 for g in self . env . generators : # Compute costs in $ ( not $ / hr ) . costs = g . total_cost ( round ( g . p , 4 ) , self . env . _g0 [ g ] [ "p_cost" ] , self . env . _g0 [ g ] [ "pcost_model" ] ) offbids = [ ob for ob in s...
def markdown_editor ( selector ) : """Enable markdown editor for given textarea . : returns : Editor template context ."""
return dict ( selector = selector , extra_settings = mark_safe ( simplejson . dumps ( dict ( previewParserPath = reverse ( 'django_markdown_preview' ) ) ) ) )
def _get_attribute_tensors ( onnx_model_proto ) : # type : ( ModelProto ) - > Iterable [ TensorProto ] """Create an iterator of tensors from node attributes of an ONNX model ."""
for node in onnx_model_proto . graph . node : for attribute in node . attribute : if attribute . HasField ( "t" ) : yield attribute . t for tensor in attribute . tensors : yield tensor
def _get_object_size ( data , position , obj_end ) : """Validate and return a BSON document ' s size ."""
try : obj_size = _UNPACK_INT ( data [ position : position + 4 ] ) [ 0 ] except struct . error as exc : raise InvalidBSON ( str ( exc ) ) end = position + obj_size - 1 if data [ end : end + 1 ] != b"\x00" : raise InvalidBSON ( "bad eoo" ) if end >= obj_end : raise InvalidBSON ( "invalid object length" ) ...
def send_message ( self , msg ) : """Send any kind of message . Parameters msg : Message object The message to send ."""
assert get_thread_ident ( ) == self . ioloop_thread_id data = str ( msg ) + "\n" # Log all sent messages here so no one else has to . if self . _logger . isEnabledFor ( logging . DEBUG ) : self . _logger . debug ( "Sending to {}: {}" . format ( self . bind_address_string , repr ( data ) ) ) if not self . _connected...
def get_config_input_source_config_source_running_running ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_config = ET . Element ( "get_config" ) config = get_config input = ET . SubElement ( get_config , "input" ) source = ET . SubElement ( input , "source" ) config_source = ET . SubElement ( source , "config-source" ) running = ET . SubElement ( config_source , "running" ) running = ...
def recv ( self ) : """Receives a message from PS and decrypts it and returns a Message"""
LOGGER . debug ( 'Receiving' ) try : message_length = struct . unpack ( '>i' , self . _socket . recv ( 4 ) ) [ 0 ] message_length -= Connection . COMM_LENGTH LOGGER . debug ( 'Length: %i' , message_length ) except socket . timeout : return None comm_status = struct . unpack ( '>i' , self . _socket . rec...
def members ( self ) : """Access the members : returns : twilio . rest . chat . v1 . service . channel . member . MemberList : rtype : twilio . rest . chat . v1 . service . channel . member . MemberList"""
if self . _members is None : self . _members = MemberList ( self . _version , service_sid = self . _solution [ 'service_sid' ] , channel_sid = self . _solution [ 'sid' ] , ) return self . _members
def upload ( self , fileobj , tileset , name = None , patch = False , callback = None , bypass = False ) : """Upload data and create a Mapbox tileset Effectively replicates the Studio upload feature . Returns a Response object , the json ( ) of which returns a dict with upload metadata . Parameters fileob...
tileset = self . _validate_tileset ( tileset ) url = self . stage ( fileobj , callback = callback ) return self . create ( url , tileset , name = name , patch = patch , bypass = bypass )
def truncate ( self , index , chain = - 1 ) : """Tell the traces to truncate themselves at the given index ."""
chain = range ( self . chains ) [ chain ] for name in self . trace_names [ chain ] : self . _traces [ name ] . truncate ( index , chain )
def finalizePrivateLessonRegistration ( sender , ** kwargs ) : '''Once a private lesson registration is finalized , mark the slots that were used to book the private lesson as booked and associate them with the final registration . No need to notify students in this instance because they are already receiving...
finalReg = kwargs . pop ( 'registration' ) for er in finalReg . eventregistration_set . filter ( event__privatelessonevent__isnull = False ) : er . event . finalizeBooking ( eventRegistration = er , notifyStudent = False )
def _set_base_path_env ( ) : # type : ( ) - > None """Sets the environment variable SAGEMAKER _ BASE _ DIR as ~ / sagemaker _ local / { timestamp } / opt / ml Returns : ( bool ) : indicating whe"""
local_config_dir = os . path . join ( os . path . expanduser ( '~' ) , 'sagemaker_local' , 'jobs' , str ( time . time ( ) ) , 'opt' , 'ml' ) logger . info ( 'Setting environment variable SAGEMAKER_BASE_DIR as %s .' % local_config_dir ) os . environ [ BASE_PATH_ENV ] = local_config_dir
def to_dict ( self ) : """Convert to dictionary . : return ( dict ) : A dict mapping from strings to vectors ."""
d = { } for word , idx in self . vocab . iteritems ( ) : d [ word ] = self . array [ idx ] . tolist ( ) return d
def delete_package ( path , packages ) : """Remove downloaded packages"""
if _meta_ . del_all in [ "on" , "ON" ] : for pkg in packages : os . remove ( path + pkg )
def compute_ld ( cur_geno , other_genotypes , r2 = False ) : """Compute LD between a marker and a list of markers . Args : cur _ geno ( Genotypes ) : The genotypes of the marker . other _ genotypes ( list ) : A list of genotypes . Returns : numpy . array : An array containing the r or r * * 2 values betwe...
# Normalizing the current genotypes norm_cur = normalize_genotypes ( cur_geno ) # Normalizing and creating the matrix for the other genotypes norm_others = np . stack ( tuple ( normalize_genotypes ( g ) for g in other_genotypes ) , axis = 1 , ) # Making sure the size is the same assert norm_cur . shape [ 0 ] == norm_ot...
def add_selected ( self , ) : """Create a new reftrack with the selected element and type and add it to the root . : returns : None : rtype : None : raises : NotImplementedError"""
browser = self . shot_browser if self . browser_tabw . currentIndex ( ) == 1 else self . asset_browser selelements = browser . selected_indexes ( 2 ) if not selelements : return seltypes = browser . selected_indexes ( 3 ) if not seltypes : return elementi = selelements [ 0 ] typi = seltypes [ 0 ] if not element...
def publish ( self , request : Request ) -> None : """Dispatches a request . Expects zero or more target handlers : param request : The request to dispatch : return : None ."""
handler_factories = self . _registry . lookup ( request ) for factory in handler_factories : handler = factory ( ) handler . handle ( request )
def padded_to_same_length ( seq1 , seq2 , item = 0 ) : """Return a pair of sequences of the same length by padding the shorter sequence with ` ` item ` ` . The padded sequence is a tuple . The unpadded sequence is returned as - is ."""
len1 , len2 = len ( seq1 ) , len ( seq2 ) if len1 == len2 : return ( seq1 , seq2 ) elif len1 < len2 : return ( cons . ed ( seq1 , yield_n ( len2 - len1 , item ) ) , seq2 ) else : return ( seq1 , cons . ed ( seq2 , yield_n ( len1 - len2 , item ) ) )
def ring_number ( self ) : """The number of the ring that has changed state , with 0 being the first ring . On tablets with only one ring , this method always returns 0. For events not of type : attr : ` ~ libinput . constant . EventType . TABLET _ PAD _ RING ` , this property raises : exc : ` AssertionEr...
if self . type != EventType . TABLET_PAD_RING : raise AttributeError ( _wrong_prop . format ( self . type ) ) return self . _libinput . libinput_event_tablet_pad_get_ring_number ( self . _handle )
def lookup_module_ident ( id , version ) : """Return the ` ` module _ ident ` ` for the given ` ` id ` ` & major and minor version as a tuple ."""
with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( "SELECT module_ident FROM modules " "WHERE uuid = %s " "AND CONCAT_WS('.', major_version, minor_version) = %s" , ( id , version ) ) try : mident = cursor . fetchone ( ) [ 0 ] except ( IndexE...
def on_mouse_press ( self , x , y , buttons , modifiers ) : """Set the start point of the drag ."""
self . view [ 'ball' ] . set_state ( Trackball . STATE_ROTATE ) if ( buttons == pyglet . window . mouse . LEFT ) : ctrl = ( modifiers & pyglet . window . key . MOD_CTRL ) shift = ( modifiers & pyglet . window . key . MOD_SHIFT ) if ( ctrl and shift ) : self . view [ 'ball' ] . set_state ( Trackball ...
def verify_processing_options ( opt , parser ) : """Parses the processing scheme options and verifies that they are reasonable . Parameters opt : object Result of parsing the CLI with OptionParser , or any object with the required attributes . parser : object OptionParser instance ."""
scheme_types = scheme_prefix . values ( ) if opt . processing_scheme . split ( ':' ) [ 0 ] not in scheme_types : parser . error ( "(%s) is not a valid scheme type." )
def train ( self , data , label , batch_size ) : """Description : training for LipNet"""
# pylint : disable = no - member sum_losses = 0 len_losses = 0 with autograd . record ( ) : losses = [ self . loss_fn ( self . net ( X ) , Y ) for X , Y in zip ( data , label ) ] for loss in losses : sum_losses += mx . nd . array ( loss ) . sum ( ) . asscalar ( ) len_losses += len ( loss ) loss . backwa...
def shift_hue ( image , hue ) : """Shifts the hue of an image in HSV format . : param image : PIL Image to perform operation on : param hue : value between 0 and 2.0"""
hue = ( hue - 1.0 ) * 180 img = image . copy ( ) . convert ( "HSV" ) pixels = img . load ( ) for i in range ( img . width ) : for j in range ( img . height ) : h , s , v = pixels [ i , j ] h = abs ( int ( h + hue ) ) if h > 255 : h -= 255 pixels [ i , j ] = ( h , s , v ) ...
def upload_files ( self , container , src_dst_map , content_type = None ) : """Upload multiple files ."""
if not content_type : content_type = "application/octet.stream" url = self . make_url ( container , None , None ) headers = self . _base_headers multi_files = [ ] try : for src_path in src_dst_map : dst_name = src_dst_map [ src_path ] if not dst_name : dst_name = os . path . basename...
def dragdrop ( self , chviewer , uris ) : """Called when a drop operation is performed on a channel viewer . We are called back with a URL and we attempt to ( down ) load it if it names a file ."""
# find out our channel chname = self . get_channel_name ( chviewer ) self . open_uris ( uris , chname = chname ) return True
def _set_show_portindex_interface_info ( self , v , load = False ) : """Setter method for show _ portindex _ interface _ info , mapped from YANG variable / brocade _ fabric _ service _ rpc / show _ portindex _ interface _ info ( rpc ) If this variable is read - only ( config : false ) in the source YANG file , ...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = show_portindex_interface_info . show_portindex_interface_info , is_leaf = True , yang_name = "show-portindex-interface-info" , rest_name = "show-portindex-interface-info" , parent = self , path_helper = self . _path_helper , ...
def binary_construct ( tokens ) : """Construct proper instructions for binary expressions from a sequence of tokens at the same precedence level . For instance , if the tokens represent " 1 + 2 + 3 " , this will return the instruction array " 1 2 add _ op 3 add _ op " . : param tokens : The sequence of toke...
# Initialize the list of instructions we will return with the # left - most element instructions = [ tokens [ 0 ] ] # Now process all the remaining tokens , building up the array we # will return for i in range ( 1 , len ( tokens ) , 2 ) : op , rhs = tokens [ i : i + 2 ] # Add the right - hand side instruct...
def cli ( env , billing_id , datacenter ) : """Adds a load balancer given the id returned from create - options ."""
mgr = SoftLayer . LoadBalancerManager ( env . client ) if not formatting . confirm ( "This action will incur charges on your " "account. Continue?" ) : raise exceptions . CLIAbort ( 'Aborted.' ) mgr . add_local_lb ( billing_id , datacenter = datacenter ) env . fout ( "Load balancer is being created!" )
def _convert_ddb_list_to_list ( conversion_list ) : """Given a dynamodb list , it will return a python list without the dynamodb datatypes Args : conversion _ list ( dict ) : a dynamodb list which includes the datatypes Returns : list : Returns a sanitized list without the dynamodb datatypes"""
ret_list = [ ] for v in conversion_list : for v1 in v : ret_list . append ( v [ v1 ] ) return ret_list
def arc_consistency_3 ( domains , constraints ) : """Makes a CSP problem arc consistent . Ignores any constraint that is not binary ."""
arcs = list ( all_arcs ( constraints ) ) pending_arcs = set ( arcs ) while pending_arcs : x , y = pending_arcs . pop ( ) if revise ( domains , ( x , y ) , constraints ) : if len ( domains [ x ] ) == 0 : return False pending_arcs = pending_arcs . union ( ( x2 , y2 ) for x2 , y2 in arc...
def _shapeletOutput ( self , x , y , beta , shapelets , precalc = True ) : """returns the the numerical values of a set of shapelets at polar coordinates : param shapelets : set of shapelets [ l = , r = , a _ lr = ] : type shapelets : array of size ( n , 3) : param coordPolar : set of coordinates in polar uni...
n = len ( np . atleast_1d ( x ) ) if n <= 1 : values = 0. else : values = np . zeros ( len ( x [ 0 ] ) ) n = 0 k = 0 i = 0 num_n = len ( shapelets ) while i < num_n * ( num_n + 1 ) / 2 : values += self . _function ( x , y , shapelets [ n - k ] [ k ] , beta , n - k , k , precalc = precalc ) k += 1 if...
def handle_resource_not_found ( resource ) : """Set resource state to ERRED and append / create " not found " error message ."""
resource . set_erred ( ) resource . runtime_state = '' message = 'Does not exist at backend.' if message not in resource . error_message : if not resource . error_message : resource . error_message = message else : resource . error_message += ' (%s)' % message resource . save ( ) logger . warnin...
def write_column ( self , column , data , ** keys ) : """Write data to a column in this HDU This HDU must be a table HDU . parameters column : scalar string / integer The column in which to write . Can be the name or number ( 0 offset ) column : ndarray Numerical python array to write . This should matc...
firstrow = keys . get ( 'firstrow' , 0 ) colnum = self . _extract_colnum ( column ) # need it to be contiguous and native byte order . For now , make a # copy . but we may be able to avoid this with some care . if not data . flags [ 'C_CONTIGUOUS' ] : # this always makes a copy data_send = numpy . ascontiguousarray...
def from_sys_requirements ( cls , system_requirements , _type = 'all' ) : """Returns SystemRequirementsDict encapsulating system requirements . It can extract only entrypoints with specific fields ( ' clusterSpec ' , ' instanceType ' , etc ) , depending on the value of _ type ."""
if _type not in ( 'all' , 'clusterSpec' , 'instanceType' ) : raise DXError ( "Expected '_type' to be either 'all', 'clusterSpec', or 'instanceType'" ) if _type == 'all' : return cls ( system_requirements ) extracted = defaultdict ( dict ) for entrypoint , req in system_requirements . items ( ) : if _type in...
def pauli_sum ( * elements : Pauli ) -> Pauli : """Return the sum of elements of the Pauli algebra"""
terms = [ ] key = itemgetter ( 0 ) for term , grp in groupby ( heapq . merge ( * elements , key = key ) , key = key ) : coeff = sum ( g [ 1 ] for g in grp ) if not isclose ( coeff , 0.0 ) : terms . append ( ( term , coeff ) ) return Pauli ( tuple ( terms ) )
def tune ( runner , kernel_options , device_options , tuning_options ) : """Find the best performing kernel configuration in the parameter space : params runner : A runner from kernel _ tuner . runners : type runner : kernel _ tuner . runner : param kernel _ options : A dictionary with all options for the ker...
results = [ ] cache = { } method = tuning_options . method # scale variables in x to make ' eps ' relevant for multiple variables tuning_options [ "scaling" ] = True bounds , x0 , eps = get_bounds_x0_eps ( tuning_options ) kwargs = setup_method_arguments ( method , bounds ) options = setup_method_options ( method , tun...
def set_value ( self , option , value , index = None ) : """Sets the value on the given option . : param option : The name of the option as it appears in the config file : param value : The value that is being applied . If this section is indexed then the value must be a list ( to be applied directly ) or you...
if self . is_indexed and index is None and not isinstance ( value , list ) : raise TypeError ( "Value should be a list when not giving an index in an indexed header" ) self . values [ option ] . set_value ( value = value , index = index ) return self
def setaty ( self , content ) : """Grab the ( aty ) soap - enc : arrayType and attach it to the content for proper array processing later in end ( ) . @ param content : The current content being unmarshalled . @ type content : L { Content } @ return : self @ rtype : L { Encoded }"""
name = 'arrayType' ns = ( None , 'http://schemas.xmlsoap.org/soap/encoding/' ) aty = content . node . get ( name , ns ) if aty is not None : content . aty = aty parts = aty . split ( '[' ) ref = parts [ 0 ] if len ( parts ) == 2 : self . applyaty ( content , ref ) else : pass ...
def map ( requests , prefetch = True , size = None ) : """Concurrently converts a list of Requests to Responses . : param requests : a collection of Request objects . : param prefetch : If False , the content will not be downloaded immediately . : param size : Specifies the number of requests to make at a tim...
if size : pool = Pool ( size ) pool . map ( send , requests ) pool . join ( ) else : jobs = [ gevent . spawn ( send , r ) for r in requests ] gevent . joinall ( jobs ) if prefetch : [ r . response . content for r in requests ] return [ r . response for r in requests ]
def check_key ( data_object , key , cardinal = False ) : """Update the value of an index key by matching values or getting positionals ."""
itype = ( int , np . int32 , np . int64 ) if not isinstance ( key , itype + ( slice , tuple , list , np . ndarray ) ) : raise KeyError ( "Unknown key type {} for key {}" . format ( type ( key ) , key ) ) keys = data_object . index . values if cardinal and data_object . _cardinal is not None : keys = data_object...
def load_fast_format ( filename ) : """Load a reach instance in fast format . As described above , the fast format stores the words and vectors of the Reach instance separately , and is drastically faster than loading from . txt files . Parameters filename : str The filename prefix from which to load . ...
words , unk_index , name , vectors = Reach . _load_fast ( filename ) return Reach ( vectors , words , unk_index = unk_index , name = name )
def ensure_keys ( walk , * keys ) : """Use walk to try to retrieve all keys"""
all_retrieved = True for k in keys : try : walk ( k ) except WalkKeyNotRetrieved : all_retrieved = False return all_retrieved
def is_team_member ( name , team_name , profile = "github" ) : '''Returns True if the github user is in the team with team _ name , or False otherwise . name The name of the user whose membership to check . team _ name The name of the team to check membership in . profile The name of the profile confi...
return name . lower ( ) in list_team_members ( team_name , profile = profile )
def ignore_broken_pipe ( ) : """If a shellish program has redirected stdio it is subject to erroneous " ignored " exceptions during the interpretor shutdown . This essentially beats the interpretor to the punch by closing them early and ignoring any broken pipe exceptions ."""
for f in sys . stdin , sys . stdout , sys . stderr : try : f . close ( ) except BrokenPipeError : pass
def update_current_state ( self , wid , key , value ) : '''Update current state with a ( possibly new ) value associated with key If the key does not represent an existing entry , then ignore it'''
cscoll = self . current_state ( ) c_state = cscoll . get ( wid , { } ) if key in c_state : current_value = c_state . get ( key , None ) if current_value != value : c_state [ key ] = value setattr ( self , '_current_state_hydrated_changed' , True )
def send_to_delivery_stream ( events , stream_name ) : """Sends a list of events to a Firehose delivery stream ."""
if not events : logger . info ( "No events provided: nothing delivered to Firehose" ) return records = [ ] for event in events : if not isinstance ( event , str ) : # csv events already have a newline event = json . dumps ( event ) + "\n" records . append ( { "Data" : event } ) firehose = boto3 ...
def peer_status ( ) : '''Return peer status information The return value is a dictionary with peer UUIDs as keys and dicts of peer information as values . Hostnames are listed in one list . GlusterFS separates one of the hostnames but the only reason for this seems to be which hostname happens to be used fi...
root = _gluster_xml ( 'peer status' ) if not _gluster_ok ( root ) : return None result = { } for peer in _iter ( root , 'peer' ) : uuid = peer . find ( 'uuid' ) . text result [ uuid ] = { 'hostnames' : [ ] } for item in peer : if item . tag == 'hostname' : result [ uuid ] [ 'hostname...
def exit ( self ) -> None : """Raise SystemExit with correct status code and output logs ."""
total = sum ( len ( logs ) for logs in self . logs . values ( ) ) if self . json : self . logs [ 'total' ] = total print ( json . dumps ( self . logs , indent = self . indent ) ) else : for name , log in self . logs . items ( ) : if not log or self . parser [ name ] . as_bool ( "quiet" ) : ...
def do_rmdep ( self , args ) : """Removes dependent variables currently set for plotting / tabulating etc ."""
for arg in args . split ( ) : if arg in self . curargs [ "dependents" ] : self . curargs [ "dependents" ] . remove ( arg ) if arg in self . curargs [ "plottypes" ] : del self . curargs [ "plottypes" ] [ arg ] if arg in self . curargs [ "twinplots" ] : del self . curargs [ "twinplots"...
def from_credentials_db ( client_secrets , storage , api_version = "v3" , readonly = False , http_client = None , ga_hook = None ) : """Create a client for a web or installed application . Create a client with a credentials stored in stagecraft db . Args : client _ secrets : dict , client secrets ( downloadab...
credentials = storage . get ( ) return Client ( _build ( credentials , api_version , http_client ) , ga_hook )
def send_notice ( self , room_id , text_content , timestamp = None ) : """Perform PUT / rooms / $ room _ id / send / m . room . message with m . notice msgtype Args : room _ id ( str ) : The room ID to send the event in . text _ content ( str ) : The m . notice body to send . timestamp ( int ) : Set origin ...
body = { "msgtype" : "m.notice" , "body" : text_content } return self . send_message_event ( room_id , "m.room.message" , body , timestamp = timestamp )
def read ( self , size = None ) : """Read a length of bytes . Return empty on EOF . If ' size ' is omitted , return whole file ."""
if size is not None : return self . __sf . read ( size ) block_size = self . __class__ . __block_size b = bytearray ( ) received_bytes = 0 while 1 : partial = self . __sf . read ( block_size ) # self . _ _ log . debug ( " Reading ( % d ) bytes . ( % d ) bytes returned . " % # ( block _ size , len ( part...
def process_file ( filename ) : """Read a file from disk and parse it into a structured dict ."""
try : with codecs . open ( filename , encoding = 'utf-8' , mode = 'r' ) as f : file_contents = f . read ( ) except IOError : log . info ( 'Unable to read file: %s' , filename ) return None data = json . loads ( file_contents ) title = '' body_content = '' if 'current_page_name' in data : path = ...
def register ( self , * model_list , ** options ) : """Registers the given model ( s ) with the given databrowse site . The model ( s ) should be Model classes , not instances . If a databrowse class isn ' t given , it will use DefaultModelDatabrowse ( the default databrowse options ) . If a model is alread...
databrowse_class = options . pop ( 'databrowse_class' , DefaultModelDatabrowse ) for model in model_list : if model in self . registry : raise AlreadyRegistered ( 'The model %s is already registered' % model . __name__ ) self . registry [ model ] = databrowse_class
def get ( self , fallback = not_set ) : """Returns config value . See Also : : meth : ` . set ` and : attr : ` . value `"""
envvar_value = self . _get_envvar_value ( ) if envvar_value is not not_set : return envvar_value if self . has_value : if self . _value is not not_set : return self . _value else : return copy . deepcopy ( self . default ) elif fallback is not not_set : return fallback elif self . requir...
def convert_dict_to_compatible_tensor ( values , targets ) : """Converts dict ` values ` in tensors that are compatible with ` targets ` . Args : values : A dict to objects to convert with same keys as ` targets ` . targets : A dict returned by ` parse _ tensor _ info _ map ` . Returns : A map with the sa...
result = { } for key , value in sorted ( values . items ( ) ) : result [ key ] = _convert_to_compatible_tensor ( value , targets [ key ] , error_prefix = "Can't convert %r" % key ) return result
def logout ( self ) : """logout func ( quit browser )"""
try : self . browser . quit ( ) except Exception : raise exceptions . BrowserException ( self . brow_name , "not started" ) return False self . vbro . stop ( ) logger . info ( "logged out" ) return True
def absent ( name , auth = None , ** kwargs ) : '''Ensure a security group does not exist name Name of the security group'''
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** kwargs ) __salt__ [ 'neutronng.setup_clouds' ] ( auth ) kwargs [ 'project_id' ] = __salt__ [ 'keystoneng.project_get' ] ( name = kwargs [ 'project_name' ] ) secgroup = __salt__ [ 'neutronng.secur...
def list_functions ( * args , ** kwargs ) : # pylint : disable = unused - argument '''List the functions for all modules . Optionally , specify a module or modules from which to list . CLI Example : . . code - block : : bash salt ' * ' sys . list _ functions salt ' * ' sys . list _ functions sys salt ' ...
# # # NOTE : * * kwargs is used here to prevent a traceback when garbage # # # arguments are tacked on to the end . if not args : # We ' re being asked for all functions return sorted ( __salt__ ) names = set ( ) for module in args : if '*' in module or '.' in module : for func in fnmatch . filter ( __s...
def readTFAM ( fileName ) : """Reads the TFAM file . : param fileName : the name of the ` ` tfam ` ` file . : type fileName : str : returns : a representation the ` ` tfam ` ` file ( : py : class : ` numpy . array ` ) ."""
# Saving the TFAM file tfam = None with open ( fileName , 'r' ) as inputFile : tfam = [ tuple ( i . rstrip ( "\r\n" ) . split ( "\t" ) ) for i in inputFile . readlines ( ) ] tfam = np . array ( tfam ) return tfam
def output_story_prefixes ( self ) : """Writes the set of prefixes to a file this is useful for pretty printing in results . latex _ output ."""
if not self . test_story : raise NotImplementedError ( "I want to write the prefixes to a file" "called <test_story>_prefixes.txt, but there's no test_story." ) fn = os . path . join ( TGT_DIR , "%s_prefixes.txt" % self . test_story ) with open ( fn , "w" ) as f : for utter_id in self . test_prefixes : ...
def as_dictionary ( self ) : """Return the service agreement template as a dictionary . : return : dict"""
template = { 'contractName' : self . contract_name , 'events' : [ e . as_dictionary ( ) for e in self . agreement_events ] , 'fulfillmentOrder' : self . fulfillment_order , 'conditionDependency' : self . condition_dependency , 'conditions' : [ cond . as_dictionary ( ) for cond in self . conditions ] } return { # ' type...
def _processImpurityMatrix ( self ) : """Process the impurity matrix so that it can be used to correct observed reporter intensities ."""
processedMatrix = _normalizeImpurityMatrix ( self . impurityMatrix ) processedMatrix = _padImpurityMatrix ( processedMatrix , self . matrixPreChannels , self . matrixPostChannels ) processedMatrix = _transposeMatrix ( processedMatrix ) return processedMatrix
def check_ellipsis ( text ) : """Use an ellipsis instead of three dots ."""
err = "typography.symbols.ellipsis" msg = u"'...' is an approximation, use the ellipsis symbol '…'." regex = "\.\.\." return existence_check ( text , [ regex ] , err , msg , max_errors = 3 , require_padding = False , offset = 0 )
def get_chat_server ( self , channel ) : """Get an appropriate chat server for the given channel Usually the server is irc . twitch . tv . But because of the delicate twitch chat , they use a lot of servers . Big events are on special event servers . This method tries to find a good one . : param channel : ...
r = self . oldapi_request ( 'GET' , 'channels/%s/chat_properties' % channel . name ) json = r . json ( ) servers = json [ 'chat_servers' ] try : r = self . get ( TWITCH_STATUSURL ) except requests . HTTPError : log . debug ( 'Error getting chat server status. Using random one.' ) address = servers [ 0 ] els...
def layerFromSource ( source ) : '''Returns the layer from the current project with the passed source Raises WrongLayerSourceException if no layer with that source is found'''
layers = _layerreg . mapLayers ( ) . values ( ) for layer in layers : if layer . source ( ) == source : return layer raise WrongLayerSourceException ( )
def update_one ( self , id_ , data , using_name = True ) : """Update one record . Any fields you don ' t specify will remain unchanged . Ref : http : / / helpdesk . knackhq . com / support / solutions / articles / 5000446111 - api - reference - root - access # update : param id _ : record id _ : param data : ...
data = self . convert_values ( data ) if using_name : data = self . convert_keys ( data ) url = "https://api.knackhq.com/v1/objects/%s/records/%s" % ( self . key , id_ ) res = self . put ( url , data ) return res
def get_dict_diff_str ( d1 , d2 , title ) : """Returns same as ` get _ dict _ diff ` , but as a readable string ."""
added , removed , changed = get_dict_diff ( d1 , d2 ) lines = [ title ] if added : lines . append ( "Added attributes: %s" % [ '.' . join ( x ) for x in added ] ) if removed : lines . append ( "Removed attributes: %s" % [ '.' . join ( x ) for x in removed ] ) if changed : lines . append ( "Changed attribute...
def form_node_label_prediction_matrix ( y_pred , y_test ) : """Given the discriminator distances , this function forms the node - label prediction matrix . It is assumed that the number of true labels is known . Inputs : - y _ pred : A NumPy array that contains the distance from the discriminator for each label...
number_of_test_nodes = y_pred . shape [ 0 ] # We calculate the number of true labels for each node . true_number_of_labels = np . squeeze ( y_test . sum ( axis = 1 ) ) # We sort the prediction array for each node . index = np . argsort ( y_pred , axis = 1 ) row = np . empty ( y_test . getnnz ( ) , dtype = np . int64 ) ...
def _clean_java_out ( version_str ) : """Remove extra environmental information reported in java when querying for versions . Java will report information like _ JAVA _ OPTIONS environmental variables in the output ."""
out = [ ] for line in version_str . decode ( ) . split ( "\n" ) : if line . startswith ( "Picked up" ) : pass if line . find ( "setlocale" ) > 0 : pass else : out . append ( line ) return "\n" . join ( out )
def forward_list ( self ) : '''adb forward - - list'''
version = self . version ( ) if int ( version [ 1 ] ) <= 1 and int ( version [ 2 ] ) <= 0 and int ( version [ 3 ] ) < 31 : raise EnvironmentError ( "Low adb version." ) lines = self . raw_cmd ( "forward" , "--list" ) . communicate ( ) [ 0 ] . decode ( "utf-8" ) . strip ( ) . splitlines ( ) return [ line . strip ( )...
def parse_source_file ( filename ) : """Parse source file into AST node Parameters filename : str File path Returns node : AST node content : utf - 8 encoded string"""
# can ' t use codecs . open ( filename , ' r ' , ' utf - 8 ' ) here b / c ast doesn ' t # work with unicode strings in Python2.7 " SyntaxError : encoding # declaration in Unicode string " In python 2.7 the string can ' t be # encoded and have information about its encoding . That is particularly # problematic since sou...
def to_edgelist ( self ) : """Export the current transforms as a list of edge tuples , with each tuple having the format : ( node _ a , node _ b , { metadata } ) Returns edgelist : ( n , ) list of tuples"""
# save cleaned edges export = [ ] # loop through ( node , node , edge attributes ) for edge in nx . to_edgelist ( self . transforms ) : a , b , c = edge # geometry is a node property but save it to the # edge so we don ' t need two dictionaries if 'geometry' in self . transforms . node [ b ] : c...