signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def randint ( self , a : int , b : int , n : Optional [ int ] = None ) -> Union [ List [ int ] , int ] : """Generate n numbers as a list or a single one if no n is given . n is used to minimize the number of requests made and return type changes to be compatible with : py : mod : ` random ` ' s interface"""
max_n = self . config . MAX_NUMBER_OF_INTEGERS return self . _generate_randoms ( self . _request_randints , max_n = max_n , a = a , b = b , n = n )
def ensemble_mean_std_max_min ( ens ) : """Calculate ensemble statistics between a results from an ensemble of climate simulations Returns a dataset containing ensemble mean , standard - deviation , minimum and maximum for input climate simulations . Parameters ens : Ensemble dataset ( see xclim . utils . c...
dsOut = ens . drop ( ens . data_vars ) for v in ens . data_vars : dsOut [ v + '_mean' ] = ens [ v ] . mean ( dim = 'realization' ) dsOut [ v + '_stdev' ] = ens [ v ] . std ( dim = 'realization' ) dsOut [ v + '_max' ] = ens [ v ] . max ( dim = 'realization' ) dsOut [ v + '_min' ] = ens [ v ] . min ( dim ...
def from_first_relation ( cls , vertex0 , vertex1 ) : """Intialize a fresh match based on the first relation"""
result = cls ( [ ( vertex0 , vertex1 ) ] ) result . previous_ends1 = set ( [ vertex1 ] ) return result
def get_best_fit_rot_mat ( from_coord , to_coord ) : """Compute best - fit rotation matrix . The best - fit rotation matrix rotates from _ coord such that the RMSD between the 2 sets of coordinates are minimized after the rotation . Parameters from _ coord , to _ coord : np . array Nx3 coordinate arrays ,...
superimpose_inst . set ( to_coord . astype ( 'float64' ) , from_coord . astype ( 'float64' ) ) superimpose_inst . run ( ) return superimpose_inst . get_rotran ( ) [ 0 ] . T
def _entry_offset ( self , index , entries , description ) : '''Gets the offset of the first entry that matches the description . @ index - Index into the entries list to begin searching . @ entries - Dictionary of result entries . @ description - Case insensitive description . Returns the offset , if a mat...
description = description . lower ( ) for ( offset , infos ) in entries [ index : ] : for info in infos : if info [ 'description' ] . lower ( ) . startswith ( description ) : return offset return - 1
def _large_mrca ( self , ts ) : """Find the MRCA using a temporary table ."""
cursor = self . db . cursor ( ) cursor . execute ( """ DROP TABLE IF EXISTS _mrca_temp """ ) cursor . execute ( """ CREATE TEMPORARY TABLE _mrca_temp( child TEXT PRIMARY KEY REFERENCES taxa (tax_id) NOT NULL ) """ ) cursor . executemany ( """ ...
def get_min_instability ( self , min_voltage = None , max_voltage = None ) : """The minimum instability along a path for a specific voltage range . Args : min _ voltage : The minimum allowable voltage . max _ voltage : The maximum allowable voltage . Returns : Minimum decomposition energy of all compounds...
data = [ ] for pair in self . _select_in_voltage_range ( min_voltage , max_voltage ) : if pair . decomp_e_charge is not None : data . append ( pair . decomp_e_charge ) if pair . decomp_e_discharge is not None : data . append ( pair . decomp_e_discharge ) return min ( data ) if len ( data ) > 0 e...
def restore ( self , repository , snapshot , body = None , params = None ) : """Restore a snapshot . ` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / modules - snapshots . html > ` _ : arg repository : A repository name : arg snapshot : A snapshot name : arg body : Deta...
for param in ( repository , snapshot ) : if param in SKIP_IN_PATH : raise ValueError ( "Empty value passed for a required argument." ) return self . transport . perform_request ( 'POST' , _make_path ( '_snapshot' , repository , snapshot , '_restore' ) , params = params , body = body )
def remove_vowels_from_string ( input_string : str ) -> str : """This function removes all vowels from a given string and returns the string without vowels . Examples : > > > remove _ vowels _ from _ string ( " " ) > > > remove _ vowels _ from _ string ( " abcdef \n ghijklm " ) ' bcdf \n ghjklm ' > > > re...
vowels = 'aeiouAEIOU' return '' . join ( [ char for char in input_string if char not in vowels ] )
def com_google_fonts_check_xavgcharwidth ( ttFont ) : """Check if OS / 2 xAvgCharWidth is correct ."""
current_value = ttFont [ 'OS/2' ] . xAvgCharWidth ACCEPTABLE_ERROR = 10 # Width deviation tolerance in font units # Since version 3 , the average is computed using _ all _ glyphs in a font . if ttFont [ 'OS/2' ] . version >= 3 : calculation_rule = "the average of the widths of all glyphs in the font" if not ttF...
def format_options ( options ) : '''Helper function for formatting the content of the options line'''
# split on one of the following tokens : ' - ' or ' [ [ ' or ' ] ] ' lines = [ '' ] for token in re . split ( r'( -|\[\[|\]\])' , options ) : if token in [ '[[' , ']]' ] : lines . append ( token ) lines . append ( '' ) elif token == ' -' : lines . append ( token ) else : line...
def starting_offset ( source_code , offset ) : """Return the offset in which the completion should be inserted Usually code assist proposals should be inserted like : : completion = proposal . name result = ( source _ code [ : starting _ offset ] + completion + source _ code [ offset : ] ) Where starting ...
word_finder = worder . Worder ( source_code , True ) expression , starting , starting_offset = word_finder . get_splitted_primary_before ( offset ) return starting_offset
def check_cluster ( cluster_config , data_path , java_home , check_replicas , batch_size , minutes , start_time , end_time , ) : """Check the integrity of the Kafka log files in a cluster . start _ time and end _ time should be in the format specified by TIME _ FORMAT _ REGEX . : param data _ path : the path ...
brokers = get_broker_list ( cluster_config ) broker_files = find_files ( data_path , brokers , minutes , start_time , end_time ) if not check_replicas : # remove replicas broker_files = filter_leader_files ( cluster_config , broker_files ) processes = [ ] print ( "Starting {n} parallel processes" . format ( n = len...
def _local_call ( self , call_conf ) : '''Execute local call'''
try : ret = self . _get_caller ( call_conf ) . call ( ) except SystemExit : ret = 'Data is not available at this moment' self . out . error ( ret ) except Exception as ex : ret = 'Unhandled exception occurred: {}' . format ( ex ) log . debug ( ex , exc_info = True ) self . out . error ( ret ) re...
def adapter_remove_nio_binding ( self , adapter_number , port_number ) : """Removes an adapter NIO binding . : param adapter _ number : adapter number : param port _ number : port number : returns : NIO instance"""
try : adapter = self . _adapters [ adapter_number ] except IndexError : raise IOUError ( 'Adapter {adapter_number} does not exist on IOU "{name}"' . format ( name = self . _name , adapter_number = adapter_number ) ) if not adapter . port_exists ( port_number ) : raise IOUError ( "Port {port_number} does not...
def execute_once ( self , swap = None , spell_changes = None , spell_destructions = None , random_fill = False ) : """Execute the board only one time . Do not execute chain reactions . Arguments : swap - pair of adjacent positions spell _ changes - sequence of ( position , tile ) changes spell _ destruction...
bcopy = self . copy ( ) # work with a copy , not self total_destroyed_tile_groups = list ( ) # swap if any bcopy . _swap ( swap ) # spell changes if any bcopy . _change ( spell_changes ) # spell destructions and record if any # first convert simple positions to groups spell_destructions = spell_destructions or tuple ( ...
def tparse ( instring , lenout = _default_len_out ) : """Parse a time string and return seconds past the J2000 epoch on a formal calendar . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / tparse _ c . html : param instring : Input time string , UTC . : type instring : str :...
errmsg = stypes . stringToCharP ( lenout ) lenout = ctypes . c_int ( lenout ) instring = stypes . stringToCharP ( instring ) sp2000 = ctypes . c_double ( ) libspice . tparse_c ( instring , lenout , ctypes . byref ( sp2000 ) , errmsg ) return sp2000 . value , stypes . toPythonString ( errmsg )
def output ( self , value ) : """Sets the client ' s output ( on , off , int ) Sets the general purpose output on some display modules to this value . Use on to set all outputs to high state , and off to set all to low state . The meaning of the integer value depends on your specific device , usually it is ...
response = self . request ( ( "output %s" % ( value ) ) . encode ( ) ) if "success" in response : return None else : return response
def responsive_sleep ( self , seconds , wait_reason = '' ) : """Sleep for the specified number of seconds , logging every ' wait _ log _ interval ' seconds with progress info ."""
for x in xrange ( int ( seconds ) ) : if ( self . config . wait_log_interval and not x % self . config . wait_log_interval ) : self . config . logger . debug ( '%s: %dsec of %dsec' % ( wait_reason , x , seconds ) ) self . quit_check ( ) time . sleep ( 1.0 )
def add_msg ( self , pkt ) : """Add a TLS message ( e . g . TLSClientHello or TLSApplicationData ) inside the latest record to be sent through the socket . We believe a good automaton should not use the first test ."""
if not self . buffer_out : self . add_record ( ) r = self . buffer_out [ - 1 ] if isinstance ( r , TLS13 ) : self . buffer_out [ - 1 ] . inner . msg . append ( pkt ) else : self . buffer_out [ - 1 ] . msg . append ( pkt )
def get_weights_fn ( modality_type , value = None ) : """Gets default weights function ; if none available , return value ."""
if modality_type in ( ModalityType . CTC_SYMBOL , ModalityType . IDENTITY_SYMBOL , ModalityType . MULTI_LABEL , ModalityType . SYMBOL , ModalityType . SYMBOL_ONE_HOT ) : return common_layers . weights_nonzero elif modality_type in ModalityType . get_choices ( ) : return common_layers . weights_all return value
def from_bytes ( self , raw ) : '''Return an Ethernet object reconstructed from raw bytes , or an Exception if we can ' t resurrect the packet .'''
if len ( raw ) < TCP . _MINLEN : raise NotEnoughDataError ( "Not enough bytes ({}) to reconstruct an TCP object" . format ( len ( raw ) ) ) fields = struct . unpack ( TCP . _PACKFMT , raw [ : TCP . _MINLEN ] ) self . _src = fields [ 0 ] self . _dst = fields [ 1 ] self . _seq = fields [ 2 ] self . _ack = fields [ 3 ...
def _set_reserved_vlan ( self , v , load = False ) : """Setter method for reserved _ vlan , mapped from YANG variable / reserved _ vlan ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ reserved _ vlan is considered as a private method . Backends looking t...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = reserved_vlan . reserved_vlan , is_container = 'container' , presence = False , yang_name = "reserved-vlan" , rest_name = "reserved-vlan" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods ,...
def insert_one ( self , data , using_name = True ) : """Insert one record . Ref : http : / / helpdesk . knackhq . com / support / solutions / articles / 5000446111 - api - reference - root - access # create For more information of the raw structure of all data type , read this : http : / / helpdesk . knackhq ...
data = self . convert_values ( data ) if using_name : data = self . convert_keys ( data ) res = self . post ( self . post_url , data ) return res
def serve ( self , host = '127.0.0.1' , port = 8888 , limit = 100 , ** kwargs ) : """Start a local proxy server . The server distributes incoming requests to a pool of found proxies . When the server receives an incoming request , it chooses the optimal proxy ( based on the percentage of errors and average re...
if limit <= 0 : raise ValueError ( 'In serve mode value of the limit cannot be less than or ' 'equal to zero. Otherwise, a parsing of providers will be ' 'endless' ) self . _server = Server ( host = host , port = port , proxies = self . _proxies , timeout = self . _timeout , max_tries = kwargs . pop ( 'max_tries' ,...
def process_args ( self , args ) : """Process the args we have . ' args ' is always a ShutItInit object ."""
shutit_global . shutit_global_object . yield_to_draw ( ) assert isinstance ( args , ShutItInit ) , shutit_util . print_debug ( ) if args . action == 'version' : shutit_global . shutit_global_object . shutit_print ( 'ShutIt version: ' + shutit . shutit_version ) shutit_global . shutit_global_object . handle_exit...
def readSources ( self ) : """Read the source elements . < source filename = " LightCondensed . ufo " location = " location - token - aaa " name = " master - token - aaa1 " > < info mute = " 1 " copy = " 1 " / > < kerning mute = " 1 " / > < glyph mute = " 1 " name = " thirdGlyph " / > < / source >"""
for sourceCount , sourceElement in enumerate ( self . root . findall ( ".sources/source" ) ) : # shall we just read the UFO here ? filename = sourceElement . attrib . get ( 'filename' ) # filename is a path relaive to the documentpath . resolve first . sourcePath = os . path . abspath ( os . path . join ( o...
def sapm_celltemp ( poa_global , wind_speed , temp_air , model = 'open_rack_cell_glassback' ) : '''Estimate cell and module temperatures per the Sandia PV Array Performance Model ( SAPM , SAND2004-3535 ) , from the incident irradiance , wind speed , ambient temperature , and SAPM module parameters . Paramet...
temp_models = TEMP_MODEL_PARAMS [ 'sapm' ] if isinstance ( model , str ) : model = temp_models [ model . lower ( ) ] elif isinstance ( model , ( dict , pd . Series ) ) : model = [ model [ 'a' ] , model [ 'b' ] , model [ 'deltaT' ] ] a = model [ 0 ] b = model [ 1 ] deltaT = model [ 2 ] E0 = 1000. # Reference irr...
def _init_project_service ( self , version ) : """Method to initialize the Project Service from the config data Args : version ( string ) : Version of Boss API to use . Returns : None Raises : ( KeyError ) : if given invalid version ."""
project_cfg = self . _load_config_section ( CONFIG_PROJECT_SECTION ) self . _token_project = project_cfg [ CONFIG_TOKEN ] proto = project_cfg [ CONFIG_PROTOCOL ] host = project_cfg [ CONFIG_HOST ] self . _project = ProjectService ( host , version ) self . _project . base_protocol = proto self . _project . set_auth ( se...
def exec_cmd ( rtsp , cmd ) : '''根据命令执行操作'''
global CUR_RANGE , CUR_SCALE if cmd in ( 'exit' , 'teardown' ) : rtsp . do_teardown ( ) elif cmd == 'pause' : CUR_SCALE = 1 ; CUR_RANGE = 'npt=now-' rtsp . do_pause ( ) elif cmd == 'help' : PRINT ( play_ctrl_help ( ) ) elif cmd == 'forward' : if CUR_SCALE < 0 : CUR_SCALE = 1 CUR_SCAL...
def _upsert ( context , params , data ) : """Insert or update data and add / update appropriate timestamps"""
table = params . get ( "table" ) table = datastore . get_table ( table , primary_id = False ) unique_keys = ensure_list ( params . get ( "unique" ) ) data [ "__last_seen" ] = datetime . datetime . utcnow ( ) if len ( unique_keys ) : updated = table . update ( data , unique_keys , return_count = True ) if update...
def _call ( self , x ) : """Apply the functional to the given point ."""
# Since the proximal projects onto our feasible set we can simply # check if it changes anything proj = self . proximal ( 1 ) ( x ) return np . inf if x . dist ( proj ) > 0 else 0
def count ( self , with_limit_and_skip = False ) : """Get the size of the results set for this query . Returns the number of documents in the results set for this query . Does not take : meth : ` limit ` and : meth : ` skip ` into account by default - set ` with _ limit _ and _ skip ` to ` ` True ` ` if that ...
validate_boolean ( "with_limit_and_skip" , with_limit_and_skip ) cmd = SON ( [ ( "count" , self . __collection . name ) , ( "query" , self . __spec ) ] ) if self . __max_time_ms is not None : cmd [ "maxTimeMS" ] = self . __max_time_ms if self . __comment : cmd [ "$comment" ] = self . __comment if self . __hint ...
def validate ( self , val ) : """Validates that the val matches the expected fields for this struct . val must be a dict , and must contain only fields represented by this struct and its ancestors . Returns two element tuple : ( bool , string ) - ` bool ` - True if valid , False if not - ` string ` - Desc...
if type ( val ) is not dict : return False , "%s is not a dict" % ( str ( val ) ) for k , v in val . items ( ) : field = self . field ( k ) if field : ok , msg = self . contract . validate ( field , field . is_array , v ) if not ok : return False , "field '%s': %s" % ( field . na...
def _generate_compose_file ( self , command , additional_volumes = None , additional_env_vars = None ) : """Writes a config file describing a training / hosting environment . This method generates a docker compose configuration file , it has an entry for each container that will be created ( based on self . hos...
boto_session = self . sagemaker_session . boto_session additional_volumes = additional_volumes or [ ] additional_env_vars = additional_env_vars or { } environment = [ ] optml_dirs = set ( ) aws_creds = _aws_credentials ( boto_session ) if aws_creds is not None : environment . extend ( aws_creds ) additional_env_var...
def __quarters ( self , from_date = None ) : """Get a set of quarters with available items from a given index date . : param from _ date : : return : list of ` pandas . Period ` corresponding to quarters"""
s = Search ( using = self . _es_conn , index = self . _es_index ) if from_date : # Work around to solve conversion problem of ' _ _ ' to ' . ' in field name q = Q ( 'range' ) q . __setattr__ ( self . _sort_on_field , { 'gte' : from_date } ) s = s . filter ( q ) # from : to parameters ( = > from : 0 , size :...
def competition_urls ( self ) : """Returns ' kaggle : / / ' urls ."""
return [ KaggleFile ( self . _competition_name , fname ) . to_url ( ) for fname in self . competition_files # pylint : disable = not - an - iterable ]
def save_as_pil ( self , fname , pixel_array = None ) : """This method saves the image from a numpy array using Pillow ( PIL fork ) : param fname : Location and name of the image file to be saved . : param pixel _ array : Numpy pixel array , i . e . ` ` numpy ( ) ` ` return value This method will return Tru...
if pixel_array is None : pixel_array = self . numpy from PIL import Image as pillow pil_image = pillow . fromarray ( pixel_array . astype ( 'uint8' ) ) pil_image . save ( fname ) return True
def screenshot_raw ( self , includes = 'subtitles' ) : """Mapped mpv screenshot _ raw command , see man mpv ( 1 ) . Returns a pillow Image object ."""
from PIL import Image res = self . node_command ( 'screenshot-raw' , includes ) if res [ 'format' ] != 'bgr0' : raise ValueError ( 'Screenshot in unknown format "{}". Currently, only bgr0 is supported.' . format ( res [ 'format' ] ) ) img = Image . frombytes ( 'RGBA' , ( res [ 'w' ] , res [ 'h' ] ) , res [ 'data' ]...
def invert_pixel_mask ( mask ) : '''Invert pixel mask ( 0 - > 1 , 1 ( and greater ) - > 0 ) . Parameters mask : array - like Mask . Returns inverted _ mask : array - like Inverted Mask .'''
inverted_mask = np . ones ( shape = ( 80 , 336 ) , dtype = np . dtype ( '>u1' ) ) inverted_mask [ mask >= 1 ] = 0 return inverted_mask
def com_google_fonts_check_fvar_name_entries ( ttFont ) : """All name entries referenced by fvar instances exist on the name table ?"""
failed = False for instance in ttFont [ "fvar" ] . instances : entries = [ entry for entry in ttFont [ "name" ] . names if entry . nameID == instance . subfamilyNameID ] if len ( entries ) == 0 : failed = True yield FAIL , ( f"Named instance with coordinates {instance.coordinates}" f" lacks an e...
def _openbsd_remotes_on ( port , which_end ) : '''OpenBSD specific helper function . Returns set of ipv4 host addresses of remote established connections on local or remote tcp port . Parses output of shell ' netstat ' to get connections $ netstat - nf inet Active Internet connections Proto Recv - Q Sen...
remotes = set ( ) try : data = subprocess . check_output ( [ 'netstat' , '-nf' , 'inet' ] ) # pylint : disable = minimum - python - version except subprocess . CalledProcessError : log . error ( 'Failed netstat' ) raise lines = data . split ( '\n' ) for line in lines : if 'ESTABLISHED' not in line :...
def write_top_half ( f , row_metadata_df , col_metadata_df , metadata_null , filler_null ) : """Write the top half of the gct file : top - left filler values , row metadata headers , and top - right column metadata . Args : f ( file handle ) : handle for output file row _ metadata _ df ( pandas df ) col _...
# Initialize the top half of the gct including the third line size_of_top_half_df = ( 1 + col_metadata_df . shape [ 1 ] , 1 + row_metadata_df . shape [ 1 ] + col_metadata_df . shape [ 0 ] ) top_half_df = pd . DataFrame ( np . full ( size_of_top_half_df , filler_null , dtype = object ) ) # Assemble the third line of the...
def terminate ( self ) : """Terminate all processes"""
for w in self . q . values ( ) : try : w . terminate ( ) except : pass self . q = { }
def setposition ( self , moves = [ ] ) : """Move list is a list of moves ( i . e . [ ' e2e4 ' , ' e7e5 ' , . . . ] ) each entry as a string . Moves must be in full algebraic notation ."""
self . put ( 'position startpos moves %s' % Engine . _movelisttostr ( moves ) ) self . isready ( )
def _run_scalpel_paired ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) : """Detect indels with Scalpel . This is used for paired tumor / normal samples ."""
config = items [ 0 ] [ "config" ] if out_file is None : out_file = "%s-paired-variants.vcf.gz" % os . path . splitext ( align_bams [ 0 ] ) [ 0 ] if not utils . file_exists ( out_file ) : with file_transaction ( config , out_file ) as tx_out_file : paired = get_paired_bams ( align_bams , items ) ...
def get_library_version ( module_name ) : """Get version number from ` ` module _ name ` ` ' s ` ` _ _ version _ _ ` ` attribute . . . versionadded : : 1.2.0 : param module _ name : The module name , e . g . ` ` luma . oled ` ` . : type module _ name : str : rtype : str"""
try : module = importlib . import_module ( 'luma.' + module_name ) if hasattr ( module , '__version__' ) : return module . __version__ else : return None except ImportError : return None
def disvg ( paths = None , colors = None , filename = os_path . join ( getcwd ( ) , 'disvg_output.svg' ) , stroke_widths = None , nodes = None , node_colors = None , node_radii = None , openinbrowser = True , timestamp = False , margin_size = 0.1 , mindim = 600 , dimensions = None , viewbox = None , text = None , text_...
_default_relative_node_radius = 5e-3 _default_relative_stroke_width = 1e-3 _default_path_color = '#000000' # black _default_node_color = '#ff0000' # red _default_font_size = 12 # append directory to filename ( if not included ) if os_path . dirname ( filename ) == '' : filename = os_path . join ( getcwd ( ) , filen...
def add_page ( self , pattern , classname ) : """Add a new page to the web application . Only available after that the Plugin Manager is loaded"""
if not self . _loaded : raise PluginManagerNotLoadedException ( ) self . _app . add_mapping ( pattern , classname )
def get_all_group_policies ( self , group_name , marker = None , max_items = None ) : """List the names of the policies associated with the specified group . : type group _ name : string : param group _ name : The name of the group the policy is associated with . : type marker : string : param marker : Use ...
params = { 'GroupName' : group_name } if marker : params [ 'Marker' ] = marker if max_items : params [ 'MaxItems' ] = max_items return self . get_response ( 'ListGroupPolicies' , params , list_marker = 'PolicyNames' )
def esi_client_factory ( token = None , datasource = None , spec_file = None , version = None , ** kwargs ) : """Generates an ESI client . : param token : : class : ` esi . Token ` used to access authenticated endpoints . : param datasource : Name of the ESI datasource to access . : param spec _ file : Absolu...
client = requests_client . RequestsClient ( ) if token or datasource : client . authenticator = TokenAuthenticator ( token = token , datasource = datasource ) api_version = version or app_settings . ESI_API_VERSION if spec_file : return read_spec ( spec_file , http_client = client ) else : spec = build_spec...
def upload_file ( self , url , file , callback = None , extra_headers = { } ) : """Uploads a file to W & B with failure resumption Args : url ( str ) : The url to download file ( str ) : The path to the file you want to upload callback ( : obj : ` func ` , optional ) : A callback which is passed the number ...
extra_headers = extra_headers . copy ( ) response = None if os . stat ( file . name ) . st_size == 0 : raise CommError ( "%s is an empty file" % file . name ) try : progress = Progress ( file , callback = callback ) response = requests . put ( url , data = progress , headers = extra_headers ) response ....
def _namify_arguments ( mapping ) : """Ensure that a mapping of names to parameters has the parameters set to the correct name ."""
result = [ ] for name , parameter in mapping . iteritems ( ) : parameter . name = name result . append ( parameter ) return result
def _create_controls ( self , can_kill ) : """Creates the button controls , and links them to event handlers"""
DEBUG_MSG ( "_create_controls()" , 1 , self ) # Need the following line as Windows toolbars default to 15x16 self . SetToolBitmapSize ( wx . Size ( 16 , 16 ) ) self . AddSimpleTool ( _NTB_X_PAN_LEFT , _load_bitmap ( 'stock_left.xpm' ) , 'Left' , 'Scroll left' ) self . AddSimpleTool ( _NTB_X_PAN_RIGHT , _load_bitmap ( '...
def show_busy ( self ) : """Hide the question group box and enable the busy cursor ."""
self . progress_bar . show ( ) self . question_group . setEnabled ( False ) self . question_group . setVisible ( False ) enable_busy_cursor ( ) self . repaint ( ) qApp . processEvents ( ) self . busy = True
def get_template_names ( self ) : """Return the page ' s specified template name , or a fallback if one hasn ' t been chosen ."""
posted_name = self . request . POST . get ( 'template_name' ) if posted_name : return [ posted_name , ] else : return super ( PagePreviewView , self ) . get_template_names ( )
def _long_to_bytes ( n , length , byteorder ) : """Convert a long to a bytestring For use in python version prior to 3.2 Source : http : / / bugs . python . org / issue16580 # msg177208"""
if byteorder == 'little' : indexes = range ( length ) else : indexes = reversed ( range ( length ) ) return bytearray ( ( n >> i * 8 ) & 0xff for i in indexes )
def post ( self , resource , data = None , json = None ) : """Sends a POST request Returns : RTMResponse"""
return self . do ( resource , 'POST' , data = data , json = json )
def get_dict ( cls ) : """Return dictionary with conspect / subconspect info ."""
mdt = cls . get ( ) if not mdt : return { } return conspectus . subs_by_mdt . get ( mdt , { } )
def router_fabric_virtual_gateway_address_family_ipv6_gateway_mac_address ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) router = ET . SubElement ( config , "router" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) fabric_virtual_gateway = ET . SubElement ( router , "fabric-virtual-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-anycast-gateway" ) address_family = ET . SubElement ( fabric_virtual_...
def partition_range ( stop , annotations = None ) : """Partition the range from 0 to ` stop ` based on annotations . > > > partition _ range ( 50 , annotations = [ [ ( 0 , 21 ) , ( 30 , 35 ) ] , . . . [ ( 15 , 32 ) , ( 40 , 46 ) ] ] ) [ ( 0 , 15 , { 0 } ) , (15 , 21 , { 0 , 1 } ) , (21 , 30 , { 1 } ) , ...
annotations = annotations or [ ] partitioning = [ ] part_start , part_levels = 0 , None # We loop over the range , only touching positions where levels potentially # change . for p in sorted ( set ( itertools . chain ( [ 0 , stop ] , * itertools . chain ( * annotations ) ) ) ) : if p == stop : partitioning ...
def insert ( self , collection , doc , callback = None ) : """Insert an item into a collection Arguments : collection - the collection to be modified doc - The document to insert . May not yet have an _ id attribute , in which case Meteor will generate one for you . Keyword Arguments : callback - Option...
self . call ( "/" + collection + "/insert" , [ doc ] , callback = callback )
def wait_for_ilo_after_reset ( ilo_object ) : """Continuously polls for iLO to come up after reset ."""
is_ilo_up_after_reset = lambda : ilo_object . get_product_name ( ) is not None is_ilo_up_after_reset . __name__ = 'is_ilo_up_after_reset' wait_for_operation_to_complete ( is_ilo_up_after_reset , failover_exc = exception . IloConnectionError , failover_msg = 'iLO is not up after reset.' )
def setOrga ( request , hproPk = None ) : """Change the current orga"""
if settings . PIAPI_STANDALONE : request . session [ 'plugit-standalone-organame' ] = request . GET . get ( 'name' ) request . session [ 'plugit-standalone-orgapk' ] = request . GET . get ( 'pk' ) else : ( _ , _ , hproject ) = getPlugItObject ( hproPk ) from organizations . models import Organization ...
def _resolve_dotted_name ( dotted_name ) : """Returns objects from strings Deals e . g . with ' torch . nn . Softmax ( dim = - 1 ) ' . Modified from palladium : https : / / github . com / ottogroup / palladium / blob / 8a066a9a7690557d9b1b6ed54b7d1a1502ba59e3 / palladium / util . py with added support for i...
if not isinstance ( dotted_name , str ) : return dotted_name if '.' not in dotted_name : return dotted_name args = None params = None match = P_PARAMS . match ( dotted_name ) if match : dotted_name = match . group ( 'name' ) params = match . group ( 'params' ) module , name = dotted_name . rsplit ( '.' ...
def mean ( data ) : """Return the sample arithmetic mean of data . If ` ` data ` ` is empty , StatisticsError will be raised ."""
if iter ( data ) is data : data = list ( data ) n = len ( data ) if n < 1 : raise StatisticsError ( 'mean requires at least one data point' ) return sum ( data ) / n
def vxvyvz_to_vrpmllpmbb ( vx , vy , vz , l , b , d , XYZ = False , degree = False ) : """NAME : vxvyvz _ to _ vrpmllpmbb PURPOSE : Transform velocities in the rectangular Galactic coordinate frame to the spherical Galactic coordinate frame ( can take vector inputs ) INPUT : vx - velocity towards the Gala...
# Whether to use degrees and scalar input is handled by decorators if XYZ : # undo the incorrect conversion that the decorator did if degree : l *= 180. / nu . pi b *= 180. / nu . pi lbd = XYZ_to_lbd ( l , b , d , degree = False ) l = lbd [ : , 0 ] b = lbd [ : , 1 ] d = lbd [ : , 2 ]...
def get_objectives ( self ) : """Gets all ` ` Objectives ` ` . In plenary mode , the returned list contains all known objectives or an error results . Otherwise , the returned list may contain only those objectives that are accessible through this session . return : ( osid . learning . ObjectiveList ) - an ...
# Implemented from template for # osid . resource . ResourceLookupSession . get _ resources # NOTE : This implementation currently ignores plenary view collection = JSONClientValidated ( 'learning' , collection = 'Objective' , runtime = self . _runtime ) result = collection . find ( self . _view_filter ( ) ) . sort ( '...
def run_notebook ( notebook_path ) : """Execute a notebook via nbconvert and collect output . : returns ( parsed nb object , execution errors )"""
dirname , __ = os . path . split ( notebook_path ) os . chdir ( dirname ) with tempfile . NamedTemporaryFile ( suffix = ".ipynb" ) as fout : args = [ "jupyter-nbconvert" , "--to" , "notebook" , "--execute" , "--allow-errors" , "--ExecutePreprocessor.timeout=300" , "--output" , fout . name , notebook_path ] try ...
def __read_graph ( self , network_filename ) : """Read . ncol network file : param network _ filename : complete path for the . ncol file : return : an undirected network"""
self . g = nx . read_edgelist ( network_filename , nodetype = int )
def update_dataset ( dataset_id , name , data_type , val , unit_id , metadata = { } , flush = True , ** kwargs ) : """Update an existing dataset"""
if dataset_id is None : raise HydraError ( "Dataset must have an ID to be updated." ) user_id = kwargs . get ( 'user_id' ) dataset = db . DBSession . query ( Dataset ) . filter ( Dataset . id == dataset_id ) . one ( ) # This dataset been seen before , so it may be attached # to other scenarios , which may be locked...
def get_value ( self , node ) : """Convert value from an AST node ."""
if not isinstance ( node , ast . Dict ) : raise TypeError ( "must be a dictionary" ) evaluator = SafeEvaluator ( ) try : value = evaluator . run ( node ) except Exception as ex : # TODO : Handle errors . raise ex try : # Ensure value is a serializable dictionary . value = json . loads ( json . dumps ( v...
def sweNextTransit ( obj , jd , lat , lon , flag ) : """Returns the julian date of the next transit of an object . The flag should be ' RISE ' or ' SET ' ."""
sweObj = SWE_OBJECTS [ obj ] flag = swisseph . CALC_RISE if flag == 'RISE' else swisseph . CALC_SET trans = swisseph . rise_trans ( jd , sweObj , lon , lat , 0 , 0 , 0 , flag ) return trans [ 1 ] [ 0 ]
def convert_image_to_rgb_mode ( image , fill_color = ( 255 , 255 , 255 ) ) : """Convert the specified image instance to RGB mode . @ param image : a Python Library Image ( PIL ) instance to convert its pixel format to RGB , discarding the alpha channel . @ param fill _ color : color to be used to fill transpa...
if image . mode not in ( 'RGBA' , 'LA' ) : return image # In most cases simply discarding the alpha channel will give # undesirable result , because transparent pixels also have some # unpredictable colors . It is much better to fill transparent pixels # with a specified color . background_image = Image . new ( ima...
def post_unpack_merkleblock ( d , f ) : """A post - processing " post _ unpack " to merkleblock messages . It validates the merkle proofs ( throwing an exception if there ' s an error ) , and returns the list of transaction hashes in " tx _ hashes " . The transactions are supposed to be sent immediately after...
level_widths = [ ] count = d [ "total_transactions" ] while count > 1 : level_widths . append ( count ) count += 1 count //= 2 level_widths . append ( 1 ) level_widths . reverse ( ) tx_acc = [ ] flags = d [ "flags" ] hashes = list ( reversed ( d [ "hashes" ] ) ) left_hash , flag_index = _recurse ( level_wid...
def local_service ( self , name_or_id ) : """Get the locally synced information for a service . This method is safe to call outside of the background event loop without any race condition . Internally it uses a thread - safe mutex to protect the local copies of supervisor data and ensure that it cannot chan...
if not self . _loop . inside_loop ( ) : self . _state_lock . acquire ( ) try : if isinstance ( name_or_id , int ) : if name_or_id not in self . _name_map : raise ArgumentError ( "Unknown ID used to look up service" , id = name_or_id ) name = self . _name_map [ name_or_id ] else :...
def select_army ( self , shift ) : """Select the entire army ."""
action = sc_pb . Action ( ) action . action_ui . select_army . selection_add = shift return action
def __get_resource_entry_data ( self , bundleId , languageId , resourceKey , fallback = False ) : """` ` GET / { serviceInstanceId } / v2 / bundles / { bundleId } / { languageId } / { resourceKey } ` ` Gets the resource entry information ."""
url = self . __get_base_bundle_url ( ) + '/' + bundleId + '/' + languageId + '/' + resourceKey params = { 'fallback' : 'true' } if fallback else None response = self . __perform_rest_call ( requestURL = url , params = params ) if not response : return None resourceEntryData = response . get ( self . __RESPONSE_RESO...
def _get_logger ( self ) : """Get the appropriate logger Prevents uninitialized servers in write - only mode from failing ."""
if self . logger : return self . logger elif self . server : return self . server . logger else : return default_logger
def verify ( full , dataset_uri ) : """Verify the integrity of a dataset ."""
dataset = dtoolcore . DataSet . from_uri ( dataset_uri ) all_okay = True generated_manifest = dataset . generate_manifest ( ) generated_identifiers = set ( generated_manifest [ "items" ] . keys ( ) ) manifest_identifiers = set ( dataset . identifiers ) for i in generated_identifiers . difference ( manifest_identifiers ...
def dot_eth_label ( name ) : """Convert from a name , like ' ethfinex . eth ' , to a label , like ' ethfinex ' If name is already a label , this should be a noop , except for converting to a string and validating the name syntax ."""
label = name_to_label ( name , registrar = 'eth' ) if len ( label ) < MIN_ETH_LABEL_LENGTH : raise InvalidLabel ( 'name %r is too short' % label ) else : return label
def p_recipe ( self , t ) : """recipe : RECIPE _ LINE | RECIPE _ LINE recipe"""
if len ( t ) == 3 : t [ 0 ] = t [ 1 ] + t [ 2 ] else : t [ 0 ] = t [ 1 ]
def add_edge ( self , u , v , ** attr ) : """Add an edge from u to v and update edge attributes"""
if u not in self . vertices : self . vertices [ u ] = [ ] self . pred [ u ] = [ ] self . succ [ u ] = [ ] if v not in self . vertices : self . vertices [ v ] = [ ] self . pred [ v ] = [ ] self . succ [ v ] = [ ] vertex = ( u , v ) self . edges [ vertex ] = { } self . edges [ vertex ] . update ( ...
def buy_item ( self , item_name , abbr ) : url = 'https://www.duolingo.com/2017-06-30/users/{}/purchase-store-item' url = url . format ( self . user_data . id ) data = { 'name' : item_name , 'learningLanguage' : abbr } request = self . _make_req ( url , data ) """status code ' 200 ' indicates that t...
if request . status_code == 400 and request . json ( ) [ 'error' ] == 'ALREADY_HAVE_STORE_ITEM' : raise AlreadyHaveStoreItemException ( 'Already equipped with ' + item_name + '.' ) if not request . ok : # any other error : raise Exception ( 'Not possible to buy item.' )
def _get_mps_od_net ( input_image_shape , batch_size , output_size , anchors , config , weights = { } ) : """Initializes an MpsGraphAPI for object detection ."""
network = _MpsGraphAPI ( network_id = _MpsGraphNetworkType . kODGraphNet ) c_in , h_in , w_in = input_image_shape c_out = output_size h_out = h_in // 32 w_out = w_in // 32 c_view = c_in h_view = h_in w_view = w_in network . init ( batch_size , c_in , h_in , w_in , c_out , h_out , w_out , weights = weights , config = co...
def get_summary ( url , spk = True ) : '''simple function to retrieve the header of a BSP file and return SPK object'''
# connect to file at URL bspurl = urllib2 . urlopen ( url ) # retrieve the " tip " of a file at URL bsptip = bspurl . read ( 10 ** 5 ) # first 100kB # save data in fake file object ( in - memory ) bspstr = StringIO ( bsptip ) # load into DAF object daf = DAF ( bspstr ) # return either SPK or DAF object if spk : # make ...
def direct_normal_radiation ( self , value = 9999.0 ) : """Corresponds to IDD Field ` direct _ normal _ radiation ` Args : value ( float ) : value for IDD Field ` direct _ normal _ radiation ` Unit : Wh / m2 value > = 0.0 Missing value : 9999.0 if ` value ` is None it will not be checked against the s...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `direct_normal_radiation`' . format ( value ) ) if value < 0.0 : raise ValueError ( 'value need to be greater or equal 0.0 ' 'for field `direct_...
def copy ( self ) : """Returns a copy of Markov Chain Model . Return Type : MarkovChain : Copy of MarkovChain . Examples : > > > from pgmpy . models import MarkovChain > > > from pgmpy . factors . discrete import State > > > model = MarkovChain ( ) > > > model . add _ variables _ from ( [ ' intel ' , ...
markovchain_copy = MarkovChain ( variables = list ( self . cardinalities . keys ( ) ) , card = list ( self . cardinalities . values ( ) ) , start_state = self . state ) if self . transition_models : markovchain_copy . transition_models = self . transition_models . copy ( ) return markovchain_copy
def kde ( self , term , bandwidth = 2000 , samples = 1000 , kernel = 'gaussian' ) : """Estimate the kernel density of the instances of term in the text . Args : term ( str ) : A stemmed term . bandwidth ( int ) : The kernel bandwidth . samples ( int ) : The number of evenly - spaced sample points . kernel...
# Get the offsets of the term instances . terms = np . array ( self . terms [ term ] ) [ : , np . newaxis ] # Fit the density estimator on the terms . kde = KernelDensity ( kernel = kernel , bandwidth = bandwidth ) . fit ( terms ) # Score an evely - spaced array of samples . x_axis = np . linspace ( 0 , len ( self . to...
def check_collision_state ( cls , collision_state , history_id_key , history_id , block_id , checked_ops , affected_opcodes ) : """Given a history ID , see if it already exists at the given block ID ( i . e . it ' s not expired ) , using the given collision state . Return True if so ; False if not . If ther...
# seen before in this block ? if collision_state . has_key ( block_id ) : if collision_state [ block_id ] . has_key ( history_id_key ) : if history_id in collision_state [ block_id ] [ history_id_key ] : rc = True else : collision_state [ block_id ] [ history_id_key ] . appen...
def unit_id ( self , unit_id = None ) : """Get or set unit ID field : param unit _ id : unit ID ( 0 to 255 ) or None for get value : type unit _ id : int or None : returns : unit ID or None if set fail : rtype : int or None"""
if unit_id is None : return self . __unit_id if 0 <= int ( unit_id ) < 256 : self . __unit_id = int ( unit_id ) return self . __unit_id else : return None
def copy ( self ) : """Create a flat copy of the dict ."""
missing = object ( ) result = object . __new__ ( self . __class__ ) for name in self . __slots__ : val = getattr ( self , name , missing ) if val is not missing : setattr ( result , name , val ) return result
def read_xml ( self , file_configuration ) : """parses C + + code , defined on the file _ configurations and returns GCCXML generated file content"""
xml_file_path = None delete_xml_file = True fc = file_configuration reader = source_reader . source_reader_t ( self . __config , None , self . __decl_factory ) try : if fc . content_type == fc . CONTENT_TYPE . STANDARD_SOURCE_FILE : self . logger . info ( 'Parsing source file "%s" ... ' , fc . data ) ...
def get_consul_configuration_from_environment ( ) -> ConsulConfiguration : """Gets configuration on how to connect to Consul from the environment . : return : the configuration derived from the environment : raises KeyError : if a required environment variable has not been set"""
address = os . environ [ CONSUL_ADDRESS_ENVIRONMENT_VARIABLE ] if "://" in address : raise EnvironmentError ( f"Invalid host: {address}. Do not specify scheme in host - set that in " f"{CONSUL_SCHEME_ENVIRONMENT_VARIABLE}" ) host_port_split = address . split ( ":" ) host = host_port_split [ 0 ] if len ( host_port_s...
def cookie_parts ( name , kaka ) : """Give me the parts of the cookie payload : param name : A name of a cookie object : param kaka : The cookie : return : A list of parts or None if there is no cookie object with the given name"""
cookie_obj = SimpleCookie ( as_unicode ( kaka ) ) morsel = cookie_obj . get ( name ) if morsel : return morsel . value . split ( "|" ) else : return None
def build_owner ( args ) : """Factory for creating owners , based on - - sort option ."""
if args . sort_by == 'cover' : return CoverageOwners ( args . root , args . verbose ) if os . path . isdir ( args . root ) : pass else : # File args . root , args . filter = os . path . split ( args . root ) if args . sort_by == 'date' : return DateOwners ( args . root , args . filter , args . details ,...
def find_gui_and_backend ( ) : """Return the gui and mpl backend ."""
matplotlib = sys . modules [ 'matplotlib' ] # WARNING : this assumes matplotlib 1.1 or newer ! ! backend = matplotlib . rcParams [ 'backend' ] # In this case , we need to find what the appropriate gui selection call # should be for IPython , so we can activate inputhook accordingly gui = backend2gui . get ( backend , N...
def right ( self , num = None ) : """WITH SLICES BEING FLAT , WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [ - num : ]"""
if num == None : return FlatList ( [ _get_list ( self ) [ - 1 ] ] ) if num <= 0 : return Null return FlatList ( _get_list ( self ) [ - num : ] )
def add_masquerade ( zone = None , permanent = True ) : '''Enable masquerade on a zone . If zone is omitted , default zone will be used . . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt ' * ' firewalld . add _ masquerade To enable masquerade on a specific zone . . code - blo...
if zone : cmd = '--zone={0} --add-masquerade' . format ( zone ) else : cmd = '--add-masquerade' if permanent : cmd += ' --permanent' return __firewall_cmd ( cmd )
def connect_input ( self , name , wire ) : """Connect the specified input to a wire ."""
self . _inputs [ name ] = wire wire . sinks . append ( self )