signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def stddev_samples ( data , xcol , ycollist , delta = 1.0 ) : """Create a sample list that contains the mean and standard deviation of the original list . Each element in the returned list contains following values : [ MEAN , STDDEV , MEAN - STDDEV * delta , MEAN + STDDEV * delta ] . > > > chart _ data . stddev _...
out = [ ] numcol = len ( ycollist ) try : for elem in data : total = 0 for col in ycollist : total += elem [ col ] mean = float ( total ) / numcol variance = 0 for col in ycollist : variance += ( mean - elem [ col ] ) ** 2 stddev = math . sqrt ...
def readGraph ( edgeList , nodeList = None , directed = False , idKey = 'ID' , eSource = 'From' , eDest = 'To' ) : """Reads the files given by _ edgeList _ and _ nodeList _ and creates a networkx graph for the files . This is designed only for the files produced by metaknowledge and is meant to be the reverse of ...
progArgs = ( 0 , "Starting to reading graphs" ) if metaknowledge . VERBOSE_MODE : progKwargs = { 'dummy' : False } else : progKwargs = { 'dummy' : True } with _ProgressBar ( * progArgs , ** progKwargs ) as PBar : if directed : grph = nx . DiGraph ( ) else : grph = nx . Graph ( ) if n...
def send_message ( self , options ) : """Sends a message to the wandb process changing the policy of saved files . This is primarily used internally by wandb . save"""
if not options . get ( "save_policy" ) : raise ValueError ( "Only configuring save_policy is supported" ) if self . socket : self . socket . send ( options ) elif self . _jupyter_agent : self . _jupyter_agent . start ( ) self . _jupyter_agent . rm . update_user_file_policy ( options [ "save_policy" ] ) ...
def deserialize_long ( attr ) : """Deserialize string into long ( Py2 ) or int ( Py3 ) . : param str attr : response string to be deserialized . : rtype : long or int : raises : ValueError if string format invalid ."""
if isinstance ( attr , ET . Element ) : attr = attr . text return _long_type ( attr )
def set_language ( self , language , dialect = None ) : """Set the language used for TTS . en : English es : Spanish | [ lan : latino or ca : castilian ]"""
self . currentAction = 'setting language' l = 0 if language == 'en' : l = 0 elif language == 'es' : l = 1 if dialect == 'ca' : l = 2 self . queue . put ( 'l%s' % ( l ) )
def select_data ( self , iteration_indices ) : """keep only data of ` iteration _ indices `"""
dat = self iteridx = iteration_indices dat . f = dat . f [ np . where ( [ x in iteridx for x in dat . f [ : , 0 ] ] ) [ 0 ] , : ] dat . D = dat . D [ np . where ( [ x in iteridx for x in dat . D [ : , 0 ] ] ) [ 0 ] , : ] try : iteridx = list ( iteridx ) iteridx . append ( iteridx [ - 1 ] ) # last entry is a...
def create_datacenter ( kwargs = None , call = None ) : '''Create a new data center in this VMware environment CLI Example : . . code - block : : bash salt - cloud - f create _ datacenter my - vmware - config name = " MyNewDatacenter "'''
if call != 'function' : raise SaltCloudSystemExit ( 'The create_datacenter function must be called with ' '-f or --function.' ) datacenter_name = kwargs . get ( 'name' ) if kwargs and 'name' in kwargs else None if not datacenter_name : raise SaltCloudSystemExit ( 'You must specify name of the new datacenter to ...
def asDictionary ( self ) : """returns the object as a python dictionary"""
template = { "x" : self . _x , "y" : self . _y , "spatialReference" : self . spatialReference } if not self . _z is None : template [ 'z' ] = self . _z if not self . _m is None : template [ 'z' ] = self . _m return template
def get_snapshots ( self ) : """Returns a list of all completed snapshots for this volume ID ."""
ec2 = self . get_ec2_connection ( ) rs = ec2 . get_all_snapshots ( ) all_vols = [ self . volume_id ] + self . past_volume_ids snaps = [ ] for snapshot in rs : if snapshot . volume_id in all_vols : if snapshot . progress == '100%' : snapshot . date = boto . utils . parse_ts ( snapshot . start_tim...
def get_res ( ds , t_srs = None , square = False ) : """Get GDAL Dataset raster resolution"""
gt = ds . GetGeoTransform ( ) ds_srs = get_ds_srs ( ds ) # This is Xres , Yres res = [ gt [ 1 ] , np . abs ( gt [ 5 ] ) ] if square : res = [ np . mean ( res ) , np . mean ( res ) ] if t_srs is not None and not ds_srs . IsSame ( t_srs ) : if True : # This diagonal approach is similar to the approach in gdaltran...
def publish_proto_in_ipfs ( ipfs_client , protodir ) : """make tar from protodir / * proto , and publish this tar in ipfs return base58 encoded ipfs hash"""
if ( not os . path . isdir ( protodir ) ) : raise Exception ( "Directory %s doesn't exists" % protodir ) files = glob . glob ( os . path . join ( protodir , "*.proto" ) ) if ( len ( files ) == 0 ) : raise Exception ( "Cannot find any %s files" % ( os . path . join ( protodir , "*.proto" ) ) ) # We are sorting f...
def update_image ( self , image_id , user_name , desc = None ) : """Create or update an Image in Image Registry ."""
desc = desc if desc else '' data = { "username" : user_name , "description" : desc } return self . _post ( '/images/%s' % image_id , data )
def _get_color_values ( adata , value_to_plot , groups = None , palette = None , use_raw = False , gene_symbols = None , layer = None ) : """Returns the value or color associated to each data point . For categorical data , the return value is list of colors taken from the category palette or from the given ` pa...
# when plotting , the color of the dots is determined for each plot # the data is either categorical or continuous and the data could be in # ' obs ' or in ' var ' categorical = False if value_to_plot is None : color_vector = 'lightgray' # check if value to plot is in obs elif value_to_plot in adata . obs . columns...
def get_more ( collection_name , num_to_return , cursor_id ) : """Get a * * getMore * * message ."""
data = __ZERO data += bson . _make_c_string ( collection_name ) data += struct . pack ( "<i" , num_to_return ) data += struct . pack ( "<q" , cursor_id ) return __pack_message ( 2005 , data )
def spherical ( coordinates ) : """No error is propagated"""
c = coordinates r = N . linalg . norm ( c , axis = 0 ) theta = N . arccos ( c [ 2 ] / r ) phi = N . arctan2 ( c [ 1 ] , c [ 0 ] ) return N . column_stack ( ( r , theta , phi ) )
def target_query ( plugin , port , location ) : """prepared ReQL for target"""
return ( ( r . row [ PLUGIN_NAME_KEY ] == plugin ) & ( r . row [ PORT_FIELD ] == port ) & ( r . row [ LOCATION_FIELD ] == location ) )
def notify ( title , message , jid , password , recipient , hostname = None , port = 5222 , path_to_certs = None , mtype = None , retcode = None ) : """Optional parameters * ` ` hostname ` ` ( if not from jid ) * ` ` port ` ` * ` ` path _ to _ certs ` ` * ` ` mtype ` ` ( ' chat ' required for Google Hangout...
xmpp_bot = NtfySendMsgBot ( jid , password , recipient , title , message , mtype ) # NOTE : Below plugins weren ' t needed for Google Hangouts # but may be useful ( from original sleekxmpp example ) # xmpp _ bot . register _ plugin ( ' xep _ 0030 ' ) # Service Discovery # xmpp _ bot . register _ plugin ( ' xep _ 0199 '...
def lstat ( self , path ) : """Retrieve information about a file on the remote system , without following symbolic links ( shortcuts ) . This otherwise behaves exactly the same as L { stat } . @ param path : the filename to stat @ type path : str @ return : an object containing attributes about the given ...
path = self . _adjust_cwd ( path ) self . _log ( DEBUG , 'lstat(%r)' % path ) t , msg = self . _request ( CMD_LSTAT , path ) if t != CMD_ATTRS : raise SFTPError ( 'Expected attributes' ) return SFTPAttributes . _from_msg ( msg )
def show_vcs_output_nodes_disconnected_from_cluster ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_vcs = ET . Element ( "show_vcs" ) config = show_vcs output = ET . SubElement ( show_vcs , "output" ) nodes_disconnected_from_cluster = ET . SubElement ( output , "nodes-disconnected-from-cluster" ) nodes_disconnected_from_cluster . text = kwargs . pop ( 'nodes_disconnected_from_c...
def cast ( func , value ) : """Cast the specified value to the specified type ( returned by func ) . Currently this only support int , float , bool . Should be extended if needed . Parameters : func ( func ) : Calback function to used cast to type ( int , bool , float ) . value ( any ) : value to be cast an...
if value is not None : if func == bool : return bool ( int ( value ) ) elif func in ( int , float ) : try : return func ( value ) except ValueError : return float ( 'nan' ) return func ( value ) return value
def certify_enum_value ( value , kind = None , required = True ) : """Certifier for enum values . : param value : The value to be certified . : param kind : The enum type that value should be an instance of . : param bool required : Whether the value can be ` None ` . Defaults to True . : raises Certi...
if certify_required ( value = value , required = required , ) : return try : kind ( value ) except : # noqa raise CertifierValueError ( message = "value {value!r} is not a valid member of {enum!r}" . format ( value = value , enum = kind . __name__ ) , value = value , required = required , )
def value ( self ) : """gets the value as a dictionary"""
return { "type" : self . _type , "name" : self . _name , "range" : [ self . _rangeMin , self . _rangeMax ] }
def request_help ( self , req , msg ) : """Return help on the available requests . Return a description of the available requests using a sequence of # help informs . Parameters request : str , optional The name of the request to return help for ( the default is to return help for all requests ) . Inf...
if not msg . arguments : for name , method in sorted ( self . _request_handlers . items ( ) ) : doc = method . __doc__ req . inform ( name , doc ) num_methods = len ( self . _request_handlers ) return req . make_reply ( "ok" , str ( num_methods ) ) else : name = msg . arguments [ 0 ] ...
def latsph ( radius , lon , lat ) : """Convert from latitudinal coordinates to spherical coordinates . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / latsph _ c . html : param radius : Distance of a point from the origin . : param lon : Angle of the point from the XZ plane in ...
radius = ctypes . c_double ( radius ) lon = ctypes . c_double ( lon ) lat = ctypes . c_double ( lat ) rho = ctypes . c_double ( ) colat = ctypes . c_double ( ) lons = ctypes . c_double ( ) libspice . latsph_c ( radius , lon , lat , ctypes . byref ( rho ) , ctypes . byref ( colat ) , ctypes . byref ( lons ) ) return rho...
def write ( self , outfname = None ) : """Write or overwrite a ` Survey ` to the specified . DAT file"""
outfname = outfname or self . filename with codecs . open ( outfname , 'wb' , 'windows-1252' ) as outf : for survey in self . surveys : outf . write ( '\r\n' . join ( survey . _serialize ( ) ) ) outf . write ( '\r\n' + '\f' + '\r\n' ) # ASCII " form feed " ^ L outf . write ( '\x1A' )
def get_default_storage_policy_of_datastore ( profile_manager , datastore ) : '''Returns the default storage policy reference assigned to a datastore . profile _ manager Reference to the profile manager . datastore Reference to the datastore .'''
# Retrieve all datastores visible hub = pbm . placement . PlacementHub ( hubId = datastore . _moId , hubType = 'Datastore' ) log . trace ( 'placement_hub = %s' , hub ) try : policy_id = profile_manager . QueryDefaultRequirementProfile ( hub ) except vim . fault . NoPermission as exc : log . exception ( exc ) ...
def get_bgcolor ( self , index ) : """Background color depending on value ."""
column = index . column ( ) if not self . bgcolor_enabled : return value = self . get_value ( index . row ( ) , column ) if self . max_min_col [ column ] is None or isna ( value ) : color = QColor ( BACKGROUND_NONNUMBER_COLOR ) if is_text_string ( value ) : color . setAlphaF ( BACKGROUND_STRING_ALPH...
def update_hash_from_str ( hsh , str_input ) : """Convert a str to object supporting buffer API and update a hash with it ."""
byte_input = str ( str_input ) . encode ( "UTF-8" ) hsh . update ( byte_input )
def do_cli ( function_name , stack_name , filter_pattern , tailing , start_time , end_time ) : """Implementation of the ` ` cli ` ` method"""
LOG . debug ( "'logs' command is called" ) with LogsCommandContext ( function_name , stack_name = stack_name , filter_pattern = filter_pattern , start_time = start_time , end_time = end_time , # output _ file is not yet supported by CLI output_file = None ) as context : if tailing : events_iterable = contex...
def extract ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : """Exports the table to GCS ; blocks until complete . Args : destination : the destination URI ( s ) . Can be a single URI or a list . format : the format to use for the exported data ; one of '...
job = self . extract_async ( destination , format = format , csv_delimiter = csv_delimiter , csv_header = csv_header , compress = compress ) if job is not None : job . wait ( ) return job
def assistant_fallback_actions ( self ) : """Access the assistant _ fallback _ actions : returns : twilio . rest . preview . understand . assistant . assistant _ fallback _ actions . AssistantFallbackActionsList : rtype : twilio . rest . preview . understand . assistant . assistant _ fallback _ actions . Assist...
if self . _assistant_fallback_actions is None : self . _assistant_fallback_actions = AssistantFallbackActionsList ( self . _version , assistant_sid = self . _solution [ 'sid' ] , ) return self . _assistant_fallback_actions
def _controller_buffer ( self , port ) : """Find the pointer to a controller and setup a NumPy buffer . Args : port : the port of the controller to setup Returns : a NumPy buffer with the controller ' s binary data"""
# get the address of the controller address = _LIB . Controller ( self . _env , port ) # create a memory buffer using the ctypes pointer for this vector buffer_ = ctypes . cast ( address , ctypes . POINTER ( CONTROLLER_VECTOR ) ) . contents # create a NumPy buffer from the binary data and return it return np . frombuff...
def main ( ) : """Do the default action of ` twitter ` command ."""
from twitter . cmdline import Action , OPTIONS twitter = Twitter . from_oauth_file ( ) Action ( ) ( twitter , OPTIONS )
def _weighting ( weights , exponent ) : """Return a weighting whose type is inferred from the arguments ."""
if np . isscalar ( weights ) : weighting = NumpyTensorSpaceConstWeighting ( weights , exponent ) elif weights is None : weighting = NumpyTensorSpaceConstWeighting ( 1.0 , exponent ) else : # last possibility : make an array arr = np . asarray ( weights ) weighting = NumpyTensorSpaceArrayWeighting ( arr ...
def parse_command ( bot : NoneBot , cmd_string : str ) -> Tuple [ Optional [ Command ] , Optional [ str ] ] : """Parse a command string ( typically from a message ) . : param bot : NoneBot instance : param cmd _ string : command string : return : ( Command object , current arg string )"""
logger . debug ( f'Parsing command: {cmd_string}' ) matched_start = None for start in bot . config . COMMAND_START : # loop through COMMAND _ START to find the longest matched start curr_matched_start = None if isinstance ( start , type ( re . compile ( '' ) ) ) : m = start . search ( cmd_string ) ...
def perform_step ( file_contents , step ) : """Performs a step of the transformation . : param text file _ contents : Contends of the cheetah template : param function step : Function taking xmldoc and returning new contents : returns : new contents of the file ."""
assert type ( file_contents ) is not bytes xmldoc = parse ( file_contents ) return step ( xmldoc )
def correct_bitstring_probs ( p , assignment_probabilities ) : """Given a 2d array of corrupted bitstring probabilities ( outer axis iterates over shots , inner axis over bits ) and a list of assignment probability matrices ( one for each bit in the readout ) compute the corrected probabilities . : param np ....
return _apply_local_transforms ( p , ( np . linalg . inv ( ap ) for ap in assignment_probabilities ) )
def find_peaks ( array , baseline = 0.1 , return_subarrays = False ) : """This will try to identify the indices of the peaks in array , returning a list of indices in ascending order . Runs along the data set until it jumps above baseline . Then it considers all the subsequent data above the baseline as part of...
peaks = [ ] if return_subarrays : subarray_values = [ ] subarray_indices = [ ] # loop over the data n = 0 while n < len ( array ) : # see if we ' re above baseline , then start the " we ' re in a peak " loop if array [ n ] > baseline : # start keeping track of the subarray here if return_subarrays :...
def _reduce_helper ( input_shape , output_shape , input_tensor_layout , reduction_fn_string = "SUM" ) : """Returns slicewise function and reduced mesh dimensions . Args : input _ shape : a Shape output _ shape : a Shape input _ tensor _ layout : a TensorLayout reduction _ fn _ string : " SUM " or " MAX " ...
reduce_dims_indices = [ i for i , d in enumerate ( input_shape . dims ) if d not in output_shape . dims ] reduced_input_shape = Shape ( [ d for d in input_shape . dims if d in output_shape . dims ] ) perm = [ reduced_input_shape . dims . index ( d ) for d in output_shape . dims ] def reduce_slice_fn ( xslice ) : re...
def last_updated ( self , subpath = None ) : """Returns the time of the last modification of the Readme or specified subpath , or None if the file does not exist . The return value is a number giving the number of seconds since the epoch ( see the time module ) . Raises werkzeug . exceptions . NotFound if t...
try : return os . path . getmtime ( self . readme_for ( subpath ) ) except ReadmeNotFoundError : return None # OSError for Python 3 base class , EnvironmentError for Python 2 except ( OSError , EnvironmentError ) as ex : if ex . errno == errno . ENOENT : return None raise
def get_network_project ( network_id , ** kwargs ) : """get the project that a network is in"""
net_proj = db . DBSession . query ( Project ) . join ( Network , and_ ( Project . id == Network . id , Network . id == network_id ) ) . first ( ) if net_proj is None : raise HydraError ( "Network %s not found" % network_id ) return net_proj
def add ( self , * matches , ** kw ) : # kw = default = None , boolean = False '''Add an argument ; this is optional , and mostly useful for setting up aliases or setting boolean = True Apparently ` def add ( self , * matches , default = None , boolean = False ) : ` is invalid syntax in Python . Not only is this ...
# python syntax hack default = kw . get ( 'default' , None ) boolean = kw . get ( 'boolean' , False ) del kw # do not use kw after this line ! It ' s a hack ; it should never have been there in the first place . positional = None names = [ ] for match in matches : if match . startswith ( '--' ) : names . ap...
def MD_ConfigsPermutate ( df_md ) : """Given a MD DataFrame , return a Nx4 array which permutes the current injection dipoles ."""
g_current_injections = df_md . groupby ( [ 'a' , 'b' ] ) ab = np . array ( list ( g_current_injections . groups . keys ( ) ) ) config_mgr = ConfigManager ( nr_of_electrodes = ab . max ( ) ) config_mgr . gen_configs_permutate ( ab , silent = True ) return config_mgr . configs
def custom_environment ( self , ** kwargs ) : """A context manager around the above ` ` update _ environment ` ` method to restore the environment back to its previous state after operation . ` ` Examples ` ` : : with self . custom _ environment ( GIT _ SSH = ' / bin / ssh _ wrapper ' ) : repo . remotes . o...
old_env = self . update_environment ( ** kwargs ) try : yield finally : self . update_environment ( ** old_env )
def get_cal_data ( data_df , cal_dict , param ) : '''Get data along specified axis during calibration intervals Args data _ df : pandas . DataFrame Pandas dataframe with lleo data cal _ dict : dict Calibration dictionary Returns lower : pandas dataframe slice of lleo datafram containing points at - ...
param = param . lower ( ) . replace ( ' ' , '_' ) . replace ( '-' , '_' ) idx_lower_start = cal_dict [ 'parameters' ] [ param ] [ 'lower' ] [ 'start' ] idx_lower_end = cal_dict [ 'parameters' ] [ param ] [ 'lower' ] [ 'end' ] idx_upper_start = cal_dict [ 'parameters' ] [ param ] [ 'upper' ] [ 'start' ] idx_upper_end = ...
def _get_dotgraphs ( self , hdrgo , usrgos , pltargs , go2parentids ) : """Get a GO DAG in a dot - language string for a single Group of user GOs ."""
gosubdagplotnts = self . _get_gosubdagplotnts ( hdrgo , usrgos , pltargs , go2parentids ) # Create DAG graphs as dot language strings . Loop through GoSubDagPlotNt list dotstrs = [ obj . get_dotstr ( ) for obj in gosubdagplotnts ] return dotstrs
def create_iam_role ( self , account ) : """Create a new IAM role . Returns the ARN of the newly created role Args : account ( : obj : ` Account ` ) : Account where to create the IAM role Returns : ` str `"""
try : iam = self . session . client ( 'iam' ) trust = get_template ( 'vpc_flow_logs_iam_role_trust.json' ) . render ( ) policy = get_template ( 'vpc_flow_logs_role_policy.json' ) . render ( ) newrole = iam . create_role ( Path = '/' , RoleName = self . role_name , AssumeRolePolicyDocument = trust ) [ 'R...
def hourly ( place ) : """return data as list of dicts with all data filled in ."""
# time in utc ? lat , lon = place url = "https://api.forecast.io/forecast/%s/%s,%s?solar" % ( APIKEY , lat , lon ) w_data = json . loads ( urllib2 . urlopen ( url ) . read ( ) ) hourly_data = w_data [ 'hourly' ] [ 'data' ] mangled = [ ] for i in hourly_data : mangled . append ( mangle ( i ) ) return mangled
def load_handgeometry ( ) : """Hand Geometry Dataset . The data of this dataset is a 3d numpy array vector with shape ( 224 , 224 , 3) containing 112 224x224 RGB photos of hands , and the target is a 1d numpy float array containing the width of the wrist in centimeters ."""
dataset_path = _load ( 'handgeometry' ) df = _load_csv ( dataset_path , 'data' ) X = _load_images ( os . path . join ( dataset_path , 'images' ) , df . image ) y = df . target . values return Dataset ( load_handgeometry . __doc__ , X , y , r2_score )
def delay ( self , identifier : typing . Any , until : typing . Union [ int , float ] = - 1 , ) -> bool : """Delay a deferred function until the given time . Args : identifier ( typing . Any ) : The identifier returned from a call to defer or defer _ for . until ( typing . Union [ int , float ] ) : A numeri...
raise NotImplementedError ( )
def slice_along_axis ( dataset , n = 5 , axis = 'x' , tolerance = None , generate_triangles = False , contour = False ) : """Create many slices of the input dataset along a specified axis . Parameters n : int The number of slices to create axis : str or int The axis to generate the slices along . Perpendi...
axes = { 'x' : 0 , 'y' : 1 , 'z' : 2 } output = vtki . MultiBlock ( ) if isinstance ( axis , int ) : ax = axis axis = list ( axes . keys ( ) ) [ list ( axes . values ( ) ) . index ( ax ) ] elif isinstance ( axis , str ) : try : ax = axes [ axis ] except KeyError : raise RuntimeError ( 'A...
def full_name ( self ) : """The full name of this route ' s view function , including the module path and controller name , if any ."""
if not self . view_func : return None prefix = self . view_func . __module__ if self . _controller_cls : prefix = f'{prefix}.{self._controller_cls.__name__}' return f'{prefix}.{self.method_name}'
def _convert_port_bindings ( self , value ) : """" PortBindings " : { "6379 / tcp " : [ " HostIp " : " " , " HostPort " : " 6379" """
converted = { } if not value : return converted if isinstance ( value , list ) : value = self . _convert_port_bindings_from_list ( value ) if isinstance ( value , dict ) : for port_protocol , host_bindings in six . iteritems ( value ) : if '/' in port_protocol : port , protocol = port_pr...
def _cnf_formula ( lexer , varname , nvars , nclauses ) : """Return a DIMACS CNF formula ."""
clauses = _clauses ( lexer , varname , nvars ) if len ( clauses ) < nclauses : fstr = "formula has fewer than {} clauses" raise Error ( fstr . format ( nclauses ) ) if len ( clauses ) > nclauses : fstr = "formula has more than {} clauses" raise Error ( fstr . format ( nclauses ) ) return ( 'and' , ) + c...
def _check_list_minions ( self , expr , greedy , ignore_missing = False ) : # pylint : disable = unused - argument '''Return the minions found by looking via a list'''
if isinstance ( expr , six . string_types ) : expr = [ m for m in expr . split ( ',' ) if m ] minions = self . _pki_minions ( ) return { 'minions' : [ x for x in expr if x in minions ] , 'missing' : [ ] if ignore_missing else [ x for x in expr if x not in minions ] }
def _add_kickoff_task ( cls , base_path , mapreduce_spec , eta , countdown , queue_name ) : """Enqueues a new kickoff task ."""
params = { "mapreduce_id" : mapreduce_spec . mapreduce_id } # Task is not named so that it can be added within a transaction . kickoff_task = taskqueue . Task ( url = base_path + "/kickoffjob_callback/" + mapreduce_spec . mapreduce_id , headers = util . _get_task_headers ( mapreduce_spec . mapreduce_id ) , params = par...
def ListFileEntries ( self , base_path_specs , output_writer ) : """Lists file entries in the base path specification . Args : base _ path _ specs ( list [ dfvfs . PathSpec ] ) : source path specification . output _ writer ( StdoutWriter ) : output writer ."""
for base_path_spec in base_path_specs : file_system = resolver . Resolver . OpenFileSystem ( base_path_spec ) file_entry = resolver . Resolver . OpenFileEntry ( base_path_spec ) if file_entry is None : logging . warning ( 'Unable to open base path specification:\n{0:s}' . format ( base_path_spec . c...
def CheckForNonStandardConstructs ( filename , clean_lines , linenum , nesting_state , error ) : r"""Logs an error if we see certain non - ANSI constructs ignored by gcc - 2. Complain about several constructs which gcc - 2 accepts , but which are not standard C + + . Warning about these in lint is one way to ea...
# Remove comments from the line , but leave in strings for now . line = clean_lines . lines [ linenum ] if Search ( r'printf\s*\(.*".*%[-+ ]?\d*q' , line ) : error ( filename , linenum , 'runtime/printf_format' , 3 , '%q in format strings is deprecated. Use %ll instead.' ) if Search ( r'printf\s*\(.*".*%\d+\$' , l...
def _get_hosted_zone_limit ( self , limit_type , hosted_zone_id ) : """Return a hosted zone limit [ recordsets | vpc _ associations ] : rtype : dict"""
result = self . conn . get_hosted_zone_limit ( Type = limit_type , HostedZoneId = hosted_zone_id ) return result
def _add_to_batch ( self , partition_key , row_key , request ) : '''Validates batch - specific rules . : param str partition _ key : PartitionKey of the entity . : param str row _ key : RowKey of the entity . : param request : the request to insert , update or delete entity'''
# All same partition keys if self . _partition_key : if self . _partition_key != partition_key : raise AzureBatchValidationError ( _ERROR_INCORRECT_PARTITION_KEY_IN_BATCH ) else : self . _partition_key = partition_key # All different row keys if row_key in self . _row_keys : raise AzureBatchValidati...
def trigger_hook ( self , __name , * args , ** kwargs ) : '''Trigger a hook and return a list of results .'''
return [ hook ( * args , ** kwargs ) for hook in self . _hooks [ __name ] [ : ] ]
def most_even ( number , group ) : """Divide a number into a list of numbers as even as possible ."""
count , rest = divmod ( number , group ) counts = zip_longest ( [ count ] * group , [ 1 ] * rest , fillvalue = 0 ) chunks = [ sum ( one ) for one in counts ] logging . debug ( 'chunks: %s' , chunks ) return chunks
def process_exception ( self , request , exception ) : """Add user details ."""
if request . user and hasattr ( request . user , 'email' ) : request . META [ 'USER' ] = request . user . email
def extract_date ( value ) : """Convert timestamp to datetime and set everything to zero except a date"""
dtime = value . to_datetime ( ) dtime = ( dtime - timedelta ( hours = dtime . hour ) - timedelta ( minutes = dtime . minute ) - timedelta ( seconds = dtime . second ) - timedelta ( microseconds = dtime . microsecond ) ) return dtime
def set_device_scale ( self , x_scale , y_scale ) : """Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface . One common use for this is to render to very high resolution display devices at a scale factor , so that code that assumes 1 pixel will be a certai...
cairo . cairo_surface_set_device_scale ( self . _pointer , x_scale , y_scale ) self . _check_status ( )
def run_plasmid_extractor ( self ) : """Create and run the plasmid extractor system call"""
logging . info ( 'Extracting plasmids' ) # Define the system call extract_command = 'PlasmidExtractor.py -i {inf} -o {outf} -p {plasdb} -d {db} -t {cpus} -nc' . format ( inf = self . path , outf = self . plasmid_output , plasdb = os . path . join ( self . plasmid_db , 'plasmid_db.fasta' ) , db = self . plasmid_db , cpu...
def project_activity ( index , start , end ) : """Compute the metrics for the project activity section of the enriched github pull requests index . Returns a dictionary containing a " metric " key . This key contains the metrics for this section . : param index : index object : param start : start date to...
results = { "metrics" : [ SubmittedPRs ( index , start , end ) , ClosedPRs ( index , start , end ) ] } return results
def _get_device_template ( disk , disk_info , template = None ) : '''Returns the template format to create a disk in open nebula . . versionadded : : 2018.3.0'''
def _require_disk_opts ( * args ) : for arg in args : if arg not in disk_info : raise SaltCloudSystemExit ( 'The disk {0} requires a {1}\ argument' . format ( disk , arg ) ) _require_disk_opts ( 'disk_type' , 'size' ) size = disk_info [ 'size' ] disk_type = disk_info [ 'disk_...
def filter_record ( self , record ) : """Filter a single record"""
quality_scores = record . letter_annotations [ 'phred_quality' ] # Simple case - window covers whole sequence if len ( record ) <= self . window_size : mean_score = mean ( quality_scores ) if mean_score >= self . min_mean_score : return record else : raise FailedFilter ( mean_score ) # Find ...
def clear_unattached_processes ( self ) : """Removes Process objects from the snapshot referring to processes not being debugged ."""
for pid in self . get_process_ids ( ) : aProcess = self . get_process ( pid ) if not aProcess . is_being_debugged ( ) : self . _del_process ( aProcess )
def get_files_from_textfile ( textfile_handler ) : """Yield the file names and widths by parsing a text file handler ."""
for line in textfile_handler : line = line . rstrip ( ) try : ( image_name , width ) = line . rsplit ( ',' , 1 ) width = int ( width ) except ValueError : image_name = line width = None yield ( image_name , width )
def get_lines ( self , force = False ) : """Return a list of lists or strings , representing the code body . Each list is a block , each string is a statement . force ( True or False ) : if an attribute object cannot be included , it is usually skipped to be processed later . With ' force ' set , there will...
code_lines = [ ] # Don ' t return anything if this is an instance that should be skipped if self . skip ( ) : return [ ] # Initialise our new object # e . g . model _ name _ 35 = Model ( ) code_lines += self . instantiate ( ) # Add each field # e . g . model _ name _ 35 . field _ one = 1034.91 # model _ name _ 35 ....
def manage_pump ( self , operation ) : """Updates control module knowledge of pump requests . If any sensor module requests water , the pump will turn on ."""
if operation == "on" : self . controls [ "pump" ] = "on" elif operation == "off" : self . controls [ "pump" ] = "off" return True
def add_layer3_vlan_cluster_interface ( self , interface_id , vlan_id , nodes = None , cluster_virtual = None , network_value = None , macaddress = None , cvi_mode = 'packetdispatch' , zone_ref = None , comment = None , ** kw ) : """Add IP addresses to VLANs on a firewall cluster . The minimum params required are...
interfaces = { 'nodes' : nodes if nodes else [ ] , 'cluster_virtual' : cluster_virtual , 'network_value' : network_value } interfaces . update ( ** kw ) _interface = { 'interface_id' : interface_id , 'interfaces' : [ interfaces ] , 'macaddress' : macaddress , 'cvi_mode' : cvi_mode if macaddress else 'none' , 'zone_ref'...
def infer_shape ( self , node , input_shapes ) : """Return a list of output shapes based on ` ` input _ shapes ` ` . This method is optional . It allows to compute the shape of the output without having to evaluate . Parameters node : ` theano . gof . graph . Apply ` The node of this Op in the computation...
if isinstance ( self . operator , Functional ) : return [ ( ) ] else : # Need to convert to native to avoid error in Theano from # future . int return [ tuple ( native ( si ) for si in self . operator . range . shape ) ]
def user_to_uid ( user ) : '''Convert user name to a uid Args : user ( str ) : The user to lookup Returns : str : The user id of the user CLI Example : . . code - block : : bash salt ' * ' file . user _ to _ uid myusername'''
if user is None : user = salt . utils . user . get_user ( ) return salt . utils . win_dacl . get_sid_string ( user )
def get_title ( mode = 'title' ) : '''Return the terminal / console title . Arguments : str : mode , one of ( ' title ' , ' icon ' ) or int ( 20-21 ) : see links below . - ` Control sequences < http : / / invisible - island . net / xterm / ctlseqs / ctlseqs . html # h2 - Operating - System - Commands > ` ...
title = None if is_a_tty ( ) and not env . SSH_CLIENT : if os_name == 'nt' : from . windows import get_title return get_title ( ) elif sys . platform == 'darwin' : if env . TERM_PROGRAM and env . TERM_PROGRAM == 'iTerm.app' : pass else : return elif os...
def zscan_iter ( self , name , match = None , count = None , score_cast_func = float ) : """Make an iterator using the ZSCAN command so that the client doesn ' t need to remember the cursor position . ` ` match ` ` allows for filtering the keys by pattern ` ` count ` ` allows for hint the minimum number of re...
if self . _pipe is not None : raise InvalidOperation ( 'cannot pipeline scan operations' ) cursor = '0' while cursor != 0 : cursor , data = self . zscan ( name , cursor = cursor , match = match , count = count , score_cast_func = score_cast_func ) for item in data : yield item
def _active_keys_by_month ( ignore_internal_keys , monthly_minimum , cached = True ) : """Returns a dict of ( year , month ) - > active _ keys . The dict will contain a key for each month observed in the data ."""
cache_key = '_active_keys_by_month({0!r},{1!r})[{date!s}]' . format ( ignore_internal_keys , monthly_minimum , date = datetime . date . today ( ) ) if cached == True : result = cache . get ( cache_key ) if result is not None : return result keys_issued_period = _keys_issued_date_range ( ) # We first do ...
def get_selected_profiles ( self , registered_org = None , registered_name = None , registered_version = None ) : """Return the ` CIM _ RegisteredProfile ` instances representing a filtered subset of the management profiles advertised by the WBEM server , that can be filtered by registered organization , regist...
org_vm = ValueMapping . for_property ( self , self . interop_ns , 'CIM_RegisteredProfile' , 'RegisteredOrganization' ) org_lower = registered_org . lower ( ) if registered_org is not None else None name_lower = registered_name . lower ( ) if registered_name is not None else None version_lower = registered_version . low...
def encode_request ( name , entries ) : """Encode request into client _ message"""
client_message = ClientMessage ( payload_size = calculate_size ( name , entries ) ) client_message . set_message_type ( REQUEST_TYPE ) client_message . set_retryable ( RETRYABLE ) client_message . append_str ( name ) client_message . append_int ( len ( entries ) ) for entries_item in six . iteritems ( entries ) : c...
def rankingEval ( self ) : '''Sorting the pop . base on the fitnessEval result'''
fitnessAll = numpy . zeros ( self . length ) fitnessNorm = numpy . zeros ( self . length ) for i in range ( self . length ) : self . Ind [ i ] . fitnessEval ( ) fitnessAll [ i ] = self . Ind [ i ] . fitness maxFitness = fitnessAll . max ( ) for i in range ( self . length ) : fitnessNorm [ i ] = ( maxFitness...
def _typedef ( obj , derive = False , infer = False ) : '''Create a new typedef for an object .'''
t = type ( obj ) v = _Typedef ( base = _basicsize ( t , obj = obj ) , kind = _kind_dynamic , type = t ) # # _ printf ( ' new % r % r / % r % s ' , t , _ basicsize ( t ) , _ itemsize ( t ) , _ repr ( dir ( obj ) ) ) if ismodule ( obj ) : # handle module like dict v . dup ( item = _dict_typedef . item + _sizeof_CPyMo...
def _case_insensitive_rpartition ( input_string : str , separator : str ) -> typing . Tuple [ str , str , str ] : """Same as str . rpartition ( ) , except that the partitioning is done case insensitive ."""
lowered_input_string = input_string . lower ( ) lowered_separator = separator . lower ( ) try : split_index = lowered_input_string . rindex ( lowered_separator ) except ValueError : # Did not find the separator in the input _ string . # Follow https : / / docs . python . org / 3 / library / stdtypes . html # text -...
def is_resource_protected ( self , request , ** kwargs ) : """Determines if a resource should be protected . Returns true if and only if the resource ' s access _ state matches an entry in the return value of get _ protected _ states ( ) ."""
access_state = self . _get_resource_access_state ( request ) protected_states = self . get_protected_states ( ) return access_state in protected_states
def add_size_info ( self ) : """Get size of file content and modification time from filename path ."""
if self . is_directory ( ) : # Directory size always differs from the customer index . html # that is generated . So return without calculating any size . return filename = self . get_os_filename ( ) self . size = fileutil . get_size ( filename ) self . modified = datetime . utcfromtimestamp ( fileutil . get_mtime ...
def series ( * coros_or_futures , timeout = None , loop = None , return_exceptions = False ) : """Run the given coroutine functions in series , each one running once the previous execution has completed . If any coroutines raises an exception , no more coroutines are executed . Otherwise , the coroutines retu...
return ( yield from gather ( * coros_or_futures , loop = loop , limit = 1 , timeout = timeout , return_exceptions = return_exceptions ) )
async def fini ( self ) : '''Shut down the object and notify any onfini ( ) coroutines . Returns : Remaining ref count'''
assert self . anitted , f'{self.__class__.__name__} initialized improperly. Must use Base.anit class method.' if self . isfini : return if __debug__ : import synapse . lib . threads as s_threads # avoid import cycle assert s_threads . iden ( ) == self . tid self . _syn_refs -= 1 if self . _syn_refs > 0...
def login ( self , password = '' , captcha = '' , email_code = '' , twofactor_code = '' , language = 'english' ) : """Attempts web login and returns on a session with cookies set : param password : password , if it wasn ' t provided on instance init : type password : : class : ` str ` : param captcha : text r...
if self . logged_on : return self . session if password : self . password = password else : if self . password : password = self . password else : raise LoginIncorrect ( "password is not specified" ) if not captcha and self . captcha_code : captcha = self . captcha_code self . _load_...
def directive ( self , name , default = None ) : """Returns the loaded directive with the specified name , or default if passed name is not present"""
return getattr ( self , '_directives' , { } ) . get ( name , hug . defaults . directives . get ( name , default ) )
def attention_lm_ae_extended ( ) : """Experiment with the exp _ factor params ."""
hparams = attention_lm_moe_base_long_seq ( ) hparams . attention_layers = "eeee" hparams . attention_local = True # hparams . factored _ logits = 1 # Necessary when the number of expert grow bigger hparams . attention_moe_k = 2 hparams . attention_exp_factor = 4 # hparams . attention _ exp _ inputdim = 128 hparams . la...
def out_of_china ( lng , lat ) : """判断是否在国内 , 不在国内不做偏移 : param lng : : param lat : : return :"""
if lng < 72.004 or lng > 137.8347 : return True if lat < 0.8293 or lat > 55.8271 : return True return False
def grid_reload_from_ids ( oargrid_jobids ) : """Reload all running or pending jobs of Grid ' 5000 from their ids Args : oargrid _ jobids ( list ) : list of ` ` ( site , oar _ jobid ) ` ` identifying the jobs on each site Returns : The list of python - grid5000 jobs retrieved"""
gk = get_api_client ( ) jobs = [ ] for site , job_id in oargrid_jobids : jobs . append ( gk . sites [ site ] . jobs [ job_id ] ) return jobs
def add_attribute_model ( self , name , # type : str attr , # type : AttributeModel writeable_func = None , # type : Optional [ Callable ] ) : # type : ( . . . ) - > AttributeModel """Register a pre - existing AttributeModel to be added to the Block"""
return self . _field_registry . add_attribute_model ( name , attr , writeable_func , self . _part )
def run ( self , series , exponent = None ) : ''': type series : List : type exponent : int : rtype : float'''
try : return self . calculateHurst ( series , exponent ) except Exception as e : print ( " Error: %s" % e )
def to_native ( self , value , context = None ) : """Schematics deserializer override We return a us . states . State object so the abbreviation or long name can be trivially accessed . Additionally , some geo type ops are available . TIP : The us . states library expects unicode so we must ensure value i...
if isinstance ( value , us . states . State ) : return value try : state = us . states . lookup ( unicode ( value ) ) if not state : raise TypeError return state except TypeError : raise ConversionError ( self . messages [ 'convert' ] )
def inspect ( orm_class , attribute_name ) : """: param attribute _ name : name of the mapped attribute to inspect . : returns : list of 2 - tuples containing information about the inspected attribute ( first element : mapped entity attribute kind ; second attribute : mapped entity attribute )"""
key = ( orm_class , attribute_name ) elems = OrmAttributeInspector . __cache . get ( key ) if elems is None : elems = OrmAttributeInspector . __inspect ( key ) OrmAttributeInspector . __cache [ key ] = elems return elems
def Convert ( self , metadata , value , token = None ) : """Converts a single ArtifactFilesDownloaderResult ."""
for r in self . BatchConvert ( [ ( metadata , value ) ] , token = token ) : yield r
def fetch ( self ) : """Fetch a AuthorizedConnectAppInstance : returns : Fetched AuthorizedConnectAppInstance : rtype : twilio . rest . api . v2010 . account . authorized _ connect _ app . AuthorizedConnectAppInstance"""
params = values . of ( { } ) payload = self . _version . fetch ( 'GET' , self . _uri , params = params , ) return AuthorizedConnectAppInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , connect_app_sid = self . _solution [ 'connect_app_sid' ] , )
def _credssp_processor ( self , context ) : """Implements a state machine : return :"""
http_response = ( yield ) credssp_context = self . _get_credssp_header ( http_response ) if credssp_context is None : raise Exception ( 'The remote host did not respond with a \'www-authenticate\' header containing ' '\'CredSSP\' as an available authentication mechanism' ) # 1 . First , secure the channel with a TL...