signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def is_successful ( self , retry = False ) : """If the instance runs successfully . : return : True if successful else False : rtype : bool"""
if not self . is_terminated ( retry = retry ) : return False retry_num = options . retry_times while retry_num > 0 : try : statuses = self . get_task_statuses ( ) return all ( task . status == Instance . Task . TaskStatus . SUCCESS for task in statuses . values ( ) ) except ( errors . Intern...
def managed ( name , value = None , host = DEFAULT_HOST , port = DEFAULT_PORT , time = DEFAULT_TIME , min_compress_len = DEFAULT_MIN_COMPRESS_LEN ) : '''Manage a memcached key . name The key to manage value The value to set for that key host The memcached server IP address port The memcached server ...
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } try : cur = __salt__ [ 'memcached.get' ] ( name , host , port ) except CommandExecutionError as exc : ret [ 'comment' ] = six . text_type ( exc ) return ret if cur == value : ret [ 'result' ] = True ret [ 'comment' ] = 'Ke...
def _timestamps_eq ( a , b ) : """Compares two timestamp operands for equivalence under the Ion data model ."""
assert isinstance ( a , datetime ) if not isinstance ( b , datetime ) : return False # Local offsets must be equivalent . if ( a . tzinfo is None ) ^ ( b . tzinfo is None ) : return False if a . utcoffset ( ) != b . utcoffset ( ) : return False for a , b in ( ( a , b ) , ( b , a ) ) : if isinstance ( a ...
def options ( self ) : """Train tickets query options ."""
arg = self . get ( 0 ) if arg . startswith ( '-' ) and not self . is_asking_for_help : return arg [ 1 : ] return '' . join ( x for x in arg if x in 'dgktz' )
def can_claim_fifty_moves ( self ) -> bool : """Draw by the fifty - move rule can be claimed once the clock of halfmoves since the last capture or pawn move becomes equal or greater to 100 and the side to move still has a legal move they can make ."""
# Fifty - move rule . if self . halfmove_clock >= 100 : if any ( self . generate_legal_moves ( ) ) : return True return False
def get_shell_folder ( name ) : """Get Windows Shell Folder locations from the registry ."""
try : import _winreg as winreg except ImportError : import winreg lm = winreg . ConnectRegistry ( None , winreg . HKEY_CURRENT_USER ) try : key = winreg . OpenKey ( lm , r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try : return winreg . QueryValueEx ( key , name ) [ 0 ] ...
def calc_info ( db , calc_id ) : """: param db : a : class : ` openquake . server . dbapi . Db ` instance : param calc _ id : calculation ID : returns : dictionary of info about the given calculation"""
job = db ( 'SELECT * FROM job WHERE id=?x' , calc_id , one = True ) response_data = { } response_data [ 'user_name' ] = job . user_name response_data [ 'status' ] = job . status response_data [ 'start_time' ] = str ( job . start_time ) response_data [ 'stop_time' ] = str ( job . stop_time ) response_data [ 'is_running'...
def delete_review_request ( self , reviewers = github . GithubObject . NotSet , team_reviewers = github . GithubObject . NotSet ) : """: calls : ` DELETE / repos / : owner / : repo / pulls / : number / requested _ reviewers < https : / / developer . github . com / v3 / pulls / review _ requests / > ` _ : param re...
post_parameters = dict ( ) if reviewers is not github . GithubObject . NotSet : assert all ( isinstance ( element , ( str , unicode ) ) for element in reviewers ) , reviewers post_parameters [ "reviewers" ] = reviewers if team_reviewers is not github . GithubObject . NotSet : assert all ( isinstance ( eleme...
def get_best_single_experiments ( nets , expvars ) : '''returns the experiments as a ` ` TermSet ` ` object [ instance ] .'''
netsf = nets . to_file ( ) expvarsf = expvars . to_file ( ) i = 1 # single experiment num_exp = String2TermSet ( 'pexperiment(' + str ( i ) + ')' ) num_expf = num_exp . to_file ( ) prg = [ netsf , expvarsf , num_expf , find_best_exp_sets_prg , elem_path_prg ] coptions = '--project --opt-mode=optN --opt-strategy=0 --opt...
def _convert_public_key ( ecdsa_curve_name , result ) : """Convert Ledger reply into PublicKey object ."""
if ecdsa_curve_name == 'nist256p1' : if ( result [ 64 ] & 1 ) != 0 : result = bytearray ( [ 0x03 ] ) + result [ 1 : 33 ] else : result = bytearray ( [ 0x02 ] ) + result [ 1 : 33 ] else : result = result [ 1 : ] keyX = bytearray ( result [ 0 : 32 ] ) keyY = bytearray ( result [ 32 : ]...
def _find_scalar_parameter ( expr ) : """Find all : class : ` ~ ibis . expr . types . ScalarParameter ` instances . Parameters expr : ibis . expr . types . Expr Returns Tuple [ bool , object ] The operation and the parent expresssion ' s resolved name ."""
op = expr . op ( ) if isinstance ( op , ops . ScalarParameter ) : result = op , expr . get_name ( ) else : result = None return lin . proceed , result
def process ( self , metric ) : """Send a metric to Riemann ."""
event = self . _metric_to_riemann_event ( metric ) try : self . client . send_event ( event ) except Exception as e : self . log . error ( "RiemannHandler: Error sending event to Riemann: %s" , e )
def utc2local ( date ) : """DokuWiki returns date with a + 0000 timezone . This function convert * date * to the local time ."""
date_offset = ( datetime . now ( ) - datetime . utcnow ( ) ) # Python < 2.7 don ' t have the ' total _ seconds ' method so calculate it by hand ! date_offset = ( date_offset . microseconds + ( date_offset . seconds + date_offset . days * 24 * 3600 ) * 1e6 ) / 1e6 date_offset = int ( round ( date_offset / 60 / 60 ) ) re...
def offset ( self , date , n_days ) : '''Return the date n _ days after ( or before if n _ days < 0 ) < date > note : not calender days , but self days !'''
# CONSIDER : raise an exception if a date is not in self index = self . index ( date ) + n_days if index < 0 : index = 0 if index > len ( self ) - 1 : index = len ( self ) - 1 return self [ index ]
def _validate_password ( self , password ) : """Validate GNTP Message against stored password"""
self . password = password if password is None : raise errors . AuthError ( 'Missing password' ) keyHash = self . info . get ( 'keyHash' , None ) if keyHash is None and self . password is None : return True if keyHash is None : raise errors . AuthError ( 'Invalid keyHash' ) if self . password is None : ...
def randomString ( size : int = 20 ) -> str : """Generate a random string in hex of the specified size DO NOT use python provided random class its a Pseudo Random Number Generator and not secure enough for our needs : param size : size of the random string to generate : return : the hexadecimal random strin...
def randomStr ( size ) : if not isinstance ( size , int ) : raise PlenumTypeError ( 'size' , size , int ) if not size > 0 : raise PlenumValueError ( 'size' , size , '> 0' ) # Approach 1 rv = randombytes ( size // 2 ) . hex ( ) return rv if size % 2 == 0 else rv + hex ( randombytes_un...
def images_path ( self ) : """Get the image storage directory"""
server_config = Config . instance ( ) . get_section_config ( "Server" ) images_path = os . path . expanduser ( server_config . get ( "images_path" , "~/GNS3/projects" ) ) os . makedirs ( images_path , exist_ok = True ) return images_path
def write_line ( self , line , count = 1 ) : """writes the line and count newlines after the line"""
self . write ( line ) self . write_newlines ( count )
def get_all ( self , sort_order = None , sort_target = 'key' ) : """Get all keys currently stored in etcd . : returns : sequence of ( value , metadata ) tuples"""
return self . get ( key = _encode ( b'\0' ) , metadata = True , sort_order = sort_order , sort_target = sort_target , range_end = _encode ( b'\0' ) , )
def _read_repos ( conf_file , repos , filename , regex ) : '''Read repos from configuration file'''
for line in conf_file : line = salt . utils . stringutils . to_unicode ( line ) if not regex . search ( line ) : continue repo = _create_repo ( line , filename ) # do not store duplicated uri ' s if repo [ 'uri' ] not in repos : repos [ repo [ 'uri' ] ] = [ repo ]
def objective ( layers , loss_function , target , aggregate = aggregate , deterministic = False , l1 = 0 , l2 = 0 , get_output_kw = None ) : """Default implementation of the NeuralNet objective . : param layers : The underlying layers of the NeuralNetwork : param loss _ function : The callable loss function to ...
if get_output_kw is None : get_output_kw = { } output_layer = layers [ - 1 ] network_output = get_output ( output_layer , deterministic = deterministic , ** get_output_kw ) loss = aggregate ( loss_function ( network_output , target ) ) if l1 : loss += regularization . regularize_layer_params ( layers . values (...
def host_members ( self ) : '''Return the members of the host committee .'''
host = self . host ( ) if host is None : return for member , full_member in host . members_objects : yield full_member
def __set_mutation_type ( self , hgvs_string ) : """Interpret the mutation type ( missense , etc . ) and set appropriate flags . Args : hgvs _ string ( str ) : hgvs syntax with " p . " removed"""
self . __set_lost_stop_status ( hgvs_string ) self . __set_lost_start_status ( hgvs_string ) self . __set_missense_status ( hgvs_string ) # missense mutations self . __set_indel_status ( ) # indel mutations self . __set_frame_shift_status ( ) # check for fs self . __set_premature_stop_codon_status ( hgvs_string )
def ensure_context_attribute_exists ( context , name , default_value = None ) : """Ensure a behave resource exists as attribute in the behave context . If this is not the case , the attribute is created by using the default _ value ."""
if not hasattr ( context , name ) : setattr ( context , name , default_value )
def remove_user_from_groups ( self , user_id , body , ** kwargs ) : # noqa : E501 """Remove user from groups . # noqa : E501 An endpoint for removing user from groups . * * Example usage : * * ` curl - X DELETE https : / / api . us - east - 1 . mbedcloud . com / v3 / users / { user - id } / groups - d ' [ 0162056...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . remove_user_from_groups_with_http_info ( user_id , body , ** kwargs ) # noqa : E501 else : ( data ) = self . remove_user_from_groups_with_http_info ( user_id , body , ** kwargs ) # noqa : E501 return data
def run ( self , h , recalculate = False ) : """Run the aggregating algorithm Parameters h : int How many steps to run the aggregating algorithm on recalculate : boolean Whether to recalculate the predictions or not Returns - np . ndarray of normalized weights , np . ndarray of losses for each model""...
data = self . data [ - h : ] predictions = self . _model_predict_is ( h , recalculate = recalculate ) . values weights = np . zeros ( ( h , len ( self . model_list ) ) ) normalized_weights = np . zeros ( ( h , len ( self . model_list ) ) ) ensemble_prediction = np . zeros ( h ) for t in range ( h ) : if t == 0 : ...
def get_state_data ( cls , entity ) : """Returns the state data for the given entity . This also works for unmanaged entities ."""
attrs = get_domain_class_attribute_iterator ( type ( entity ) ) return dict ( [ ( attr , get_nested_attribute ( entity , attr . entity_attr ) ) for attr in attrs if not attr . entity_attr is None ] )
def _compute_H ( self , t , index , t2 , index2 , update_derivatives = False , stationary = False ) : """Helper function for computing part of the ode1 covariance function . : param t : first time input . : type t : array : param index : Indices of first output . : type index : array of int : param t2 : s...
if stationary : raise NotImplementedError , "Error, stationary version of this covariance not yet implemented." # Vector of decays and delays associated with each output . Decay = self . decay [ index ] Decay2 = self . decay [ index2 ] t_mat = t [ : , None ] t2_mat = t2 [ None , : ] if self . delay is not None : ...
def _apply_identical_sequences_prefilter ( self , seq_path ) : """Input : seq _ path , a filepath to input FASTA reads Method : prepares and writes de - replicated reads to a temporary FASTA file , calls parent method to do the actual de - replication Return : exact _ match _ id _ map , a dictionary stori...
# creating mapping for de - replicated reads seqs_to_cluster , exact_match_id_map = self . _prefilter_exact_matches ( parse_fasta ( seq_path ) ) # create temporary file for storing the de - replicated reads fd , unique_seqs_fp = mkstemp ( prefix = 'SwarmExactMatchFilter' , suffix = '.fasta' ) close ( fd ) self . files_...
def progressbar ( length , label ) : """Creates a progressbar Parameters length int Length of the ProgressBar label str Label to give to the progressbar Returns click . progressbar Progressbar"""
return click . progressbar ( length = length , label = label , show_pos = True )
def showMethodToolTip ( self ) : """Pops up a tooltip message with the help for the object under the \ cursor . : return < bool > success"""
self . cancelCompletion ( ) obj , _ = self . objectAtCursor ( ) if not obj : return False docs = inspect . getdoc ( obj ) if not docs : return False # determine the cursor position rect = self . cursorRect ( ) cursor = self . textCursor ( ) point = QPoint ( rect . left ( ) , rect . top ( ) + 18 ) QToolTip . sho...
def send ( self , sender : PytgbotApiBot ) : """Send the message via pytgbot . : param sender : The bot instance to send with . : type sender : pytgbot . bot . Bot : rtype : PytgbotApiMessage"""
return sender . send_game ( # receiver , self . media , disable _ notification = self . disable _ notification , reply _ to _ message _ id = reply _ id game_short_name = self . game_short_name , chat_id = self . receiver , reply_to_message_id = self . reply_id , disable_notification = self . disable_notification , repl...
def strings ( filename , minimum = 4 ) : '''A strings generator , similar to the Unix strings utility . @ filename - The file to search for strings in . @ minimum - The minimum string length to search for . Yeilds printable ASCII strings from filename .'''
result = "" with BlockFile ( filename ) as f : while True : ( data , dlen ) = f . read_block ( ) if dlen < 1 : break for c in data : if c in string . printable : result += c continue elif len ( result ) >= minimum : ...
def send_reset_password_instructions ( self , user ) : """Sends the reset password instructions email for the specified user . Sends signal ` reset _ password _ instructions _ sent ` . : param user : The user to send the instructions to ."""
token = self . security_utils_service . generate_reset_password_token ( user ) reset_link = url_for ( 'security_controller.reset_password' , token = token , _external = True ) self . send_mail ( _ ( 'flask_unchained.bundles.security:email_subject.reset_password_instructions' ) , to = user . email , template = 'security...
def _validate_composite_distance ( distance ) : """Check that composite distance function is in valid form . Don ' t modify the composite distance in any way ."""
if not isinstance ( distance , list ) : raise TypeError ( "Input 'distance' must be a composite distance." ) if len ( distance ) < 1 : raise ValueError ( "Composite distances must have a least one distance " "component, consisting of a list of feature names, " "a distance function (string or function handle), "...
def __construct_data_item_reference ( self , hardware_source : HardwareSource . HardwareSource , data_channel : HardwareSource . DataChannel ) : """Construct a data item reference . Construct a data item reference and assign a data item to it . Update data item session id and session metadata . Also connect the...
session_id = self . session_id key = self . make_data_item_reference_key ( hardware_source . hardware_source_id , data_channel . channel_id ) data_item_reference = self . get_data_item_reference ( key ) with data_item_reference . mutex : data_item = data_item_reference . data_item # if we still don ' t have a d...
def encode_single ( self , typ : TypeStr , arg : Any ) -> bytes : """Encodes the python value ` ` arg ` ` as a binary value of the ABI type ` ` typ ` ` . : param typ : The string representation of the ABI type that will be used for encoding e . g . ` ` ' uint256 ' ` ` , ` ` ' bytes [ ] ' ` ` , ` ` ' ( int , i...
encoder = self . _registry . get_encoder ( typ ) return encoder ( arg )
def data_interp ( self , i , currenttime ) : """Method to streamline request for data from cache , Uses linear interpolation bewtween timesteps to get u , v , w , temp , salt"""
if self . active . value is True : while self . get_data . value is True : logger . debug ( "Waiting for DataController to release cache file so I can read from it..." ) timer . sleep ( 2 ) pass if self . need_data ( i + 1 ) : # Acquire lock for asking for data self . data_request_lock ....
def filter_messages ( relative_filepaths , root , messages ) : """This method post - processes all messages output by all tools , in order to filter out any based on the overall output . The main aim currently is to use information about messages suppressed by pylint due to inline comments , and use that to s...
paths_to_ignore , lines_to_ignore , messages_to_ignore = get_suppressions ( relative_filepaths , root , messages ) filtered = [ ] for message in messages : # first get rid of the pylint informational messages relative_message_path = os . path . relpath ( message . location . path ) if message . source == 'pylin...
def compileFST ( fst ) : u"""convert FST to byte array representing arcs"""
arcs = [ ] address = { } pos = 0 for ( num , s ) in enumerate ( fst . dictionary . values ( ) ) : for i , ( c , v ) in enumerate ( sorted ( s . trans_map . items ( ) , reverse = True ) ) : bary = bytearray ( ) flag = 0 output_size , output = 0 , bytes ( ) if i == 0 : flag...
def get_target_url ( endpoint_url , bucket_name = None , object_name = None , bucket_region = 'us-east-1' , query = None ) : """Construct final target url . : param endpoint _ url : Target endpoint url where request is served to . : param bucket _ name : Bucket component for the target url . : param object _ ...
# New url url = None # Parse url parsed_url = urlsplit ( endpoint_url ) # Get new host , scheme . scheme = parsed_url . scheme host = parsed_url . netloc # Strip 80/443 ports since curl & browsers do not # send them in Host header . if ( scheme == 'http' and parsed_url . port == 80 ) or ( scheme == 'https' and parsed_u...
def findall ( self , bs , start = None , end = None , count = None , bytealigned = None ) : """Find all occurrences of bs . Return generator of bit positions . bs - - The bitstring to find . start - - The bit position to start the search . Defaults to 0. end - - The bit position one past the last bit to searc...
if count is not None and count < 0 : raise ValueError ( "In findall, count must be >= 0." ) bs = Bits ( bs ) start , end = self . _validate_slice ( start , end ) if bytealigned is None : bytealigned = globals ( ) [ 'bytealigned' ] c = 0 if bytealigned and not bs . len % 8 and not self . _datastore . offset : # ...
def compute ( self , inputs , outputs ) : """Compute the location based on the ' displacement ' and ' anchorInput ' by first applying the movement , if ' displacement ' is present in the ' input ' array and then applying the sensation if ' anchorInput ' is present in the input array . The ' anchorGrowthCandid...
if inputs . get ( "resetIn" , False ) : self . reset ( ) if self . learningMode : # Initialize to random location after reset when learning self . activateRandomLocation ( ) # send empty output outputs [ "activeCells" ] [ : ] = 0 outputs [ "learnableCells" ] [ : ] = 0 outputs [ "sensoryA...
def init_log_config ( handler = None ) : """Set up the application logging ( not to be confused with check loggers ) ."""
for applog in lognames . values ( ) : # propagate except for root app logger ' linkcheck ' propagate = ( applog != LOG_ROOT ) configdict [ 'loggers' ] [ applog ] = dict ( level = 'INFO' , propagate = propagate ) logging . config . dictConfig ( configdict ) if handler is None : handler = ansicolor . ColoredS...
def _get_decision_trees_bulk ( self , payload , valid_indices , invalid_indices , invalid_dts ) : """Tool for the function get _ decision _ trees _ bulk . : param list payload : contains the informations necessary for getting the trees . Its form is the same than for the function . get _ decision _ trees _ bu...
valid_dts = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/decision_tree" . format ( self . _base_url ) , "POST" ) if invalid_indices == [ ] : return valid_dts # Put the valid and invalid decision trees in their original index return self . _recreate_list_with_indices ( vali...
def mapColorRampToValues ( cls , colorRamp , minValue , maxValue , alpha = 1.0 ) : """Creates color ramp based on min and max values of all the raster pixels from all rasters . If pixel value is one of the no data values it will be excluded in the color ramp interpolation . Returns colorRamp , slope , intercept ...
minRampIndex = 0 # Always zero maxRampIndex = float ( len ( colorRamp ) - 1 ) # Map color ramp indices to values using equation of a line # Resulting equation will be : # rampIndex = slope * value + intercept if minValue != maxValue : slope = ( maxRampIndex - minRampIndex ) / ( maxValue - minValue ) intercept =...
def select_action_key ( self , next_action_arr , next_q_arr ) : '''Select action by Q ( state , action ) . Args : next _ action _ arr : ` np . ndarray ` of actions . next _ q _ arr : ` np . ndarray ` of Q - Values . Retruns : ` np . ndarray ` of keys .'''
epsilon_greedy_flag = bool ( np . random . binomial ( n = 1 , p = self . epsilon_greedy_rate ) ) if epsilon_greedy_flag is False : key = np . random . randint ( low = 0 , high = next_action_arr . shape [ 0 ] ) else : key = next_q_arr . argmax ( ) return key
def memo_update ( self , tid , session , memo = None , flag = None , reset = None ) : '''taobao . trade . memo . update 修改一笔交易备注 需要商家或以上权限才可调用此接口 , 可重复调用本接口更新交易备注 , 本接口同时具有添加备注的功能'''
request = TOPRequest ( 'taobao.trade.memo.update' ) request [ 'tid' ] = tid if memo != None : request [ 'memo' ] = memo if flag != None : request [ 'flag' ] = flag if reset != None : request [ 'reset' ] = reset self . create ( self . execute ( request , session ) [ 'trade' ] ) return self
def list_bandwidth_limit_rules ( self , policy_id , retrieve_all = True , ** _params ) : """Fetches a list of all bandwidth limit rules for the given policy ."""
return self . list ( 'bandwidth_limit_rules' , self . qos_bandwidth_limit_rules_path % policy_id , retrieve_all , ** _params )
def shear ( cls , x_angle = 0 , y_angle = 0 ) : """Create a shear transform along one or both axes . : param x _ angle : Angle in degrees to shear along the x - axis . : type x _ angle : float : param y _ angle : Angle in degrees to shear along the y - axis . : type y _ angle : float : rtype : Affine"""
sx = math . tan ( math . radians ( x_angle ) ) sy = math . tan ( math . radians ( y_angle ) ) return tuple . __new__ ( cls , ( 1.0 , sy , 0.0 , sx , 1.0 , 0.0 , 0.0 , 0.0 , 1.0 ) )
def image1 ( d , u , v , w , dmind , dtind , beamnum , irange ) : """Parallelizable function for imaging a chunk of data for a single dm . Assumes data is dedispersed and resampled , so this just images each integration . Simple one - stage imaging that returns dict of params . returns dictionary with keys of...
i0 , i1 = irange data_resamp = numpyview ( data_resamp_mem , 'complex64' , datashape ( d ) ) # logger . info ( ' i0 { 0 } , i1 { 1 } , dm { 2 } , dt { 3 } , len { 4 } ' . format ( i0 , i1 , dmind , dtind , len ( data _ resamp ) ) ) ims , snr , candints = rtlib . imgallfullfilterxyflux ( n . outer ( u , d [ 'freq' ] / d...
def render_template ( env , filename , values = None ) : """Render a jinja template"""
if not values : values = { } tmpl = env . get_template ( filename ) return tmpl . render ( values )
def AddXrefFrom ( self , ref_kind , classobj , methodobj , offset ) : """Creates a crossreference from this class . XrefFrom means , that the current class is called by another class . : param REF _ TYPE ref _ kind : type of call : param classobj : : class : ` ClassAnalysis ` object to link : param methodob...
self . xreffrom [ classobj ] . add ( ( ref_kind , methodobj , offset ) )
def mean ( a , axis = None , mdtol = 1 ) : """Request the mean of an Array over any number of axes . . . note : : Currently limited to operating on a single axis . : param axis : Axis or axes along which the operation is performed . The default ( axis = None ) is to perform the operation over all the dimens...
axes = _normalise_axis ( axis , a ) if axes is None or len ( axes ) != 1 : msg = "This operation is currently limited to a single axis" raise AxisSupportError ( msg ) dtype = ( np . array ( [ 0 ] , dtype = a . dtype ) / 1. ) . dtype kwargs = dict ( mdtol = mdtol ) return _Aggregation ( a , axes [ 0 ] , _MeanStr...
def quote_string_if_needed ( arg : str ) -> str : """Quotes a string if it contains spaces and isn ' t already quoted"""
if is_quoted ( arg ) or ' ' not in arg : return arg if '"' in arg : quote = "'" else : quote = '"' return quote + arg + quote
def add_custom_metadata ( self , key , value , meta_type = None ) : """Add custom metadata to the Video . meta _ type is required for XML API ."""
self . metadata . append ( { 'key' : key , 'value' : value , 'type' : meta_type } )
def chi2comb_cdf ( q , chi2s , gcoef , lim = 1000 , atol = 1e-4 ) : r"""Function distribution of combination of chi - squared distributions . Parameters q : float Value point at which distribution function is to be evaluated . chi2s : ChiSquared Chi - squared distributions . gcoef : float Coefficient ...
int_type = "i" if array ( int_type , [ 0 ] ) . itemsize != ffi . sizeof ( "int" ) : int_type = "l" if array ( int_type , [ 0 ] ) . itemsize != ffi . sizeof ( "int" ) : raise RuntimeError ( "Could not infer a proper integer representation." ) if array ( "d" , [ 0.0 ] ) . itemsize != ffi . sizeof ( "doubl...
def top_n_from_distribution ( distrib , top_n = 10 , row_labels = None , col_labels = None , val_labels = None ) : """Get ` top _ n ` values from LDA model ' s distribution ` distrib ` as DataFrame . Can be used for topic - word distributions and document - topic distributions . Set ` row _ labels ` to a format s...
import pandas as pd if len ( distrib ) == 0 : raise ValueError ( '`distrib` must contain values' ) if top_n < 1 : raise ValueError ( '`top_n` must be at least 1' ) elif top_n > distrib . shape [ 1 ] : raise ValueError ( '`top_n` cannot be larger than num. of values in `distrib` rows' ) if row_labels is None...
def self ( self ) -> 'EFBChat' : """Set the chat as yourself . In this context , " yourself " means the user behind the master channel . Every channel should relate this to the corresponding target . Returns : EFBChat : This object ."""
self . chat_name = "You" self . chat_alias = None self . chat_uid = EFBChat . SELF_ID self . chat_type = ChatType . User return self
def get_node_size ( node ) : """Get size of memory on C { node } . @ param node : node idx @ type node : C { int } @ return : free memory / total memory @ rtype : C { tuple } ( C { int } , C { int } )"""
free = c_longlong ( ) if node < 0 or node > get_max_node ( ) : raise ValueError ( node ) size = libnuma . numa_node_size64 ( node , byref ( free ) ) return ( free . value , size )
def ReceiveMessagesRelationalFlows ( self , client_id , messages ) : """Receives and processes messages for flows stored in the relational db . Args : client _ id : The client which sent the messages . messages : A list of GrrMessage RDFValues ."""
now = time . time ( ) unprocessed_msgs = [ ] message_handler_requests = [ ] dropped_count = 0 for session_id , msgs in iteritems ( collection . Group ( messages , operator . attrgetter ( "session_id" ) ) ) : # Remove and handle messages to WellKnownFlows leftover_msgs = self . HandleWellKnownFlows ( msgs ) for ...
def atanh ( x ) : """atanh ( x ) Hyperbolic arc tan function ."""
_math = infer_math ( x ) if _math is math : return _math . atanh ( x ) else : return _math . arctanh ( x )
def slicer ( document , first_page = None , last_page = None , suffix = 'sliced' , tempdir = None ) : """Slice a PDF document to remove pages ."""
# Set output file name if tempdir : with NamedTemporaryFile ( suffix = '.pdf' , dir = tempdir , delete = False ) as temp : output = temp . name elif suffix : output = os . path . join ( os . path . dirname ( document ) , add_suffix ( document , suffix ) ) else : with NamedTemporaryFile ( suffix = '....
def init_printing ( * , reset = False , init_sympy = True , ** kwargs ) : """Initialize the printing system . This determines the behavior of the : func : ` ascii ` , : func : ` unicode ` , and : func : ` latex ` functions , as well as the ` ` _ _ str _ _ ` ` and ` ` _ _ repr _ _ ` ` of any : class : ` . Expr...
# return either None ( default ) or a dict of frozen attributes if # ` ` _ freeze = True ` ` is given as a keyword argument ( internal use in # ` configure _ printing ` only ) logger = logging . getLogger ( __name__ ) if reset : SympyPrinter . _global_settings = { } if init_sympy : if kwargs . get ( 'repr_forma...
def module2package ( mod , dist , pkg_map = None , py_vers = ( 'py' , ) ) : """Return a corresponding package name for a python module . mod : python module name dist : a linux distribution as returned by ` platform . linux _ distribution ( ) [ 0 ] ` pkg _ map : a custom package mapping . None means autodet...
if not pkg_map : pkg_map = get_pkg_map ( dist ) for rule in pkg_map : pkglist = rule ( mod , dist ) if pkglist : break else : tr_func = get_default_tr_func ( dist ) pkglist = tr_func ( mod ) output = [ ] for v in py_vers : if v == 'py' : output . append ( pkglist [ 0 ] ) elif...
def make_uninstall ( parser ) : """Remove Ceph packages from remote hosts ."""
parser . add_argument ( 'host' , metavar = 'HOST' , nargs = '+' , help = 'hosts to uninstall Ceph from' , ) parser . set_defaults ( func = uninstall , )
def set_victims_to ( self , victims_to ) : """Update victims _ to in Cache and backend ."""
assert victims_to is None or isinstance ( victims_to , Cache ) , "store_to needs to be None or a Cache object." assert victims_to is None or victims_to . cl_size == self . cl_size , "cl_size may only increase towards main memory." self . victims_to = victims_to self . backend . victims_to = victims_to . backend
def construct_prefix_tree ( targets : Union [ torch . Tensor , List [ List [ List [ int ] ] ] ] , target_mask : Optional [ torch . Tensor ] = None ) -> List [ Dict [ Tuple [ int , ... ] , Set [ int ] ] ] : """Takes a list of valid target action sequences and creates a mapping from all possible ( valid ) action pr...
batched_allowed_transitions : List [ Dict [ Tuple [ int , ... ] , Set [ int ] ] ] = [ ] if not isinstance ( targets , list ) : assert targets . dim ( ) == 3 , "targets tensor needs to be batched!" targets = targets . detach ( ) . cpu ( ) . numpy ( ) . tolist ( ) if target_mask is not None : target_mask = ta...
def QA_SU_save_future_min_all ( engine , client = DATABASE ) : """[ summary ] Arguments : engine { [ type ] } - - [ description ] Keyword Arguments : client { [ type ] } - - [ description ] ( default : { DATABASE } )"""
engine = select_save_engine ( engine ) engine . QA_SU_save_future_min_all ( client = client )
def join_ ( self , channel , key = None , process_only = False ) : """Joins a channel . Returns a tuple of information regarding the channel . Channel Information : * [ 0 ] - A tuple containing / NAMES . * [ 1 ] - Channel topic . * [ 2 ] - Tuple containing information regarding of whom set the topic . *...
with self . lock : topic = '' users = [ ] set_by = '' time_set = '' self . is_in_channel ( channel , False ) if not process_only : if key : self . send ( 'JOIN %s %s' % ( channel , key ) ) else : self . send ( 'JOIN %s' % channel ) while self . readabl...
def which ( name , flags = os . X_OK ) : """Search PATH for executable files with the given name . . . note : : This function was taken verbatim from the twisted framework , licence available here : http : / / twistedmatrix . com / trac / browser / tags / releases / twisted - 8.2.0 / LICENSE On newer versio...
result = [ ] # pylint : disable = W0141 extensions = [ _f for _f in os . environ . get ( 'PATHEXT' , '' ) . split ( os . pathsep ) if _f ] # pylint : enable = W0141 path = os . environ . get ( 'PATH' , None ) # In c6c9b26 we removed this hard coding for issue # 529 but I am # adding it back here in case the user ' s pa...
def _read_midi_length ( fileobj ) : """Returns the duration in seconds . Can raise all kind of errors . . ."""
TEMPO , MIDI = range ( 2 ) def read_chunk ( fileobj ) : info = fileobj . read ( 8 ) if len ( info ) != 8 : raise SMFError ( "truncated" ) chunklen = struct . unpack ( ">I" , info [ 4 : ] ) [ 0 ] data = fileobj . read ( chunklen ) if len ( data ) != chunklen : raise SMFError ( "trunca...
def aq_telemetry_f_encode ( self , Index , value1 , value2 , value3 , value4 , value5 , value6 , value7 , value8 , value9 , value10 , value11 , value12 , value13 , value14 , value15 , value16 , value17 , value18 , value19 , value20 ) : '''Sends up to 20 raw float values . Index : Index of message ( uint16 _ t ) ...
return MAVLink_aq_telemetry_f_message ( Index , value1 , value2 , value3 , value4 , value5 , value6 , value7 , value8 , value9 , value10 , value11 , value12 , value13 , value14 , value15 , value16 , value17 , value18 , value19 , value20 )
def get_all ( self , name , failobj = None ) : """Return a list of all the values for the named field . These will be sorted in the order they appeared in the original message , and may contain duplicates . Any fields deleted and re - inserted are always appended to the header list . If no such fields exist...
values = [ ] name = name . lower ( ) for k , v in self . _headers : if k . lower ( ) == name : values . append ( self . policy . header_fetch_parse ( k , v ) ) if not values : return failobj return values
def out_8 ( library , session , space , offset , data , extended = False ) : """Write in an 8 - bit value from the specified memory space and offset . Corresponds to viOut8 * functions of the VISA library . : param library : the visa library wrapped by ctypes . : param session : Unique logical identifier to a...
if extended : return library . viOut8Ex ( session , space , offset , data ) else : return library . viOut8 ( session , space , offset , data )
def hybrid_forward ( self , F , row , col , counts ) : """Compute embedding of words in batch . Parameters row : mxnet . nd . NDArray or mxnet . sym . Symbol Array of token indices for source words . Shape ( batch _ size , ) . row : mxnet . nd . NDArray or mxnet . sym . Symbol Array of token indices for c...
emb_in = self . source_embedding ( row ) emb_out = self . context_embedding ( col ) if self . _dropout : emb_in = F . Dropout ( emb_in , p = self . _dropout ) emb_out = F . Dropout ( emb_out , p = self . _dropout ) bias_in = self . source_bias ( row ) . squeeze ( ) bias_out = self . context_bias ( col ) . squee...
def default_security_rules_list ( security_group , resource_group , ** kwargs ) : '''. . versionadded : : 2019.2.0 List default security rules within a security group . : param security _ group : The network security group to query . : param resource _ group : The resource group name assigned to the network...
result = { } secgroup = network_security_group_get ( security_group = security_group , resource_group = resource_group , ** kwargs ) if 'error' in secgroup : return secgroup try : result = secgroup [ 'default_security_rules' ] except KeyError as exc : log . error ( 'No default security rules found for %s!' ...
def refresh ( name ) : '''Initiate a Traffic Server configuration file reread . Use this command to update the running configuration after any configuration file modification . The timestamp of the last reconfiguration event ( in seconds since epoch ) is published in the proxy . node . config . reconfigure _ ...
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' } if __opts__ [ 'test' ] : ret [ 'comment' ] = 'Refreshing local node configuration' return ret __salt__ [ 'trafficserver.refresh' ] ( ) ret [ 'result' ] = True ret [ 'comment' ] = 'Refreshed local node configuration' return ret
def trim_saddle_points ( peaks , dt , max_iters = 10 ) : r"""Removes peaks that were mistakenly identified because they lied on a saddle or ridge in the distance transform that was not actually a true local peak . Parameters peaks : ND - array A boolean image containing True values to mark peaks in the di...
peaks = sp . copy ( peaks ) if dt . ndim == 2 : from skimage . morphology import square as cube else : from skimage . morphology import cube labels , N = spim . label ( peaks ) slices = spim . find_objects ( labels ) for i in range ( N ) : s = extend_slice ( s = slices [ i ] , shape = peaks . shape , pad = ...
def _clear ( self , node , left , right ) : """propagates the lazy updates for this node to the subtrees . as a result the maxval , minval , sumval values for the node are up to date ."""
if self . lazyset [ node ] is not None : # first do the pending set val = self . lazyset [ node ] self . minval [ node ] = val self . maxval [ node ] = val self . sumval [ node ] = val * ( right - left ) self . lazyset [ node ] = None if left < right - 1 : # not a leaf self . lazyset [ 2...
def drawstarsfile ( self , filename , r = 10 , colour = None ) : """Same as drawstarlist but we read the stars from a file . Here we read a text file of hand picked stars . Same format as for cosmouline , that is : # comment starA 23.4 45.6 [ other stuff . . . ] Then we pass this to drawstarlist ,"""
if not os . path . isfile ( filename ) : print "File does not exist :" print filename print "Line format to write : name x y [other stuff ...]" raise RuntimeError , "Cannot read star catalog." catfile = open ( filename , "r" ) lines = catfile . readlines ( ) catfile . close dictlist = [ ] # We will appe...
def from_caller_file ( ) : '''return a ` Path ` from the path of caller file'''
import inspect curframe = inspect . currentframe ( ) calframe = inspect . getouterframes ( curframe , 2 ) filename = calframe [ 1 ] . filename if not os . path . isfile ( filename ) : raise RuntimeError ( 'caller is not a file' ) return Path ( filename )
def get_site_t2g_eg_resolved_dos ( self , site ) : """Get the t2g , eg projected DOS for a particular site . Args : site : Site in Structure associated with CompleteDos . Returns : A dict { " e _ g " : Dos , " t2g " : Dos } containing summed e _ g and t2g DOS for the site ."""
t2g_dos = [ ] eg_dos = [ ] for s , atom_dos in self . pdos . items ( ) : if s == site : for orb , pdos in atom_dos . items ( ) : if orb in ( Orbital . dxy , Orbital . dxz , Orbital . dyz ) : t2g_dos . append ( pdos ) elif orb in ( Orbital . dx2 , Orbital . dz2 ) : ...
def check_vprint ( s , vprinter ) : '''checked verbose printing'''
if vprinter is True : print ( s ) ; elif callable ( vprinter ) : vprinter ( s ) ;
def mousePressEvent ( self , event ) : """Override Qt method"""
if self . slider and event . button ( ) == Qt . LeftButton : vsb = self . editor . verticalScrollBar ( ) value = self . position_to_value ( event . pos ( ) . y ( ) ) vsb . setValue ( value - vsb . pageStep ( ) / 2 )
def _process_stages ( self , limit = None ) : """This table provides mappings between ZFIN stage IDs and ZFS terms , and includes the starting and ending hours for the developmental stage . Currently only processing the mapping from the ZFIN stage ID to the ZFS ID . : param limit : : return :"""
if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "Processing stages" ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'stage' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "iso-8859-1" ) as csvfile : filereader = csv ...
def wait_for ( func ) : """A decorator to invoke a function periodically until it returns a truthy value ."""
def wrapped ( * args , ** kwargs ) : timeout = kwargs . pop ( 'timeout' , 15 ) start = time ( ) result = None while time ( ) - start < timeout : result = func ( * args , ** kwargs ) if result : break sleep ( 0.2 ) return result return wrapped
def slugify ( string ) : """Return a slug for the unicode _ string . ( lowercase , only letters and numbers , hyphens replace spaces )"""
filtered_string = [ ] if isinstance ( string , str ) : string = unicode ( string , 'utf-8' ) for i in unicodedata . normalize ( 'NFKC' , string ) : cat = unicodedata . category ( i ) [ 0 ] # filter out all the non letter and non number characters from the # input ( L is letter and N is number ) if c...
def turbulent_Sandall ( Re , Pr , fd ) : r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [ 2 ] _ as in [ 1 ] _ . . . math : : Nu = \ frac { ( f / 8 ) RePr } { 12.48Pr ^ { 2/3 } - 7.853Pr ^ { 1/3 } + 3.613 \ ln Pr + 5.8 + C } \ \ C = 2.78 \ ln ( ( f / 8 ) ^ { 0.5 } ...
C = 2.78 * log ( ( fd / 8. ) ** 0.5 * Re / 45. ) return ( fd / 8. ) ** 0.5 * Re * Pr / ( 12.48 * Pr ** ( 2 / 3. ) - 7.853 * Pr ** ( 1 / 3. ) + 3.613 * log ( Pr ) + 5.8 + C )
def get_exchangeable_nodes ( self , n ) : """A C | Subtrees A , B , C and D are the exchangeable nodes \ / | around the edge headed by n - - > n | The NNI exchanges either A or B with either C or D / B D A C C A | Subtree A is exchanged \ / +NNI(A,C) \ / | with subtree C. - - > n = = = = = > - - > n /...
parent = n . parent_node a , b = random . sample ( n . child_nodes ( ) , 2 ) if parent . parent_node is None : if self . tree . rooted : c , d = random . sample ( n . sister_nodes ( ) [ 0 ] . child_nodes ( ) , 2 ) else : c , d = random . sample ( n . sister_nodes ( ) , 2 ) else : c = random ...
def publish ( self , channel : str , value : Any ) : """Sends a new value to the data bus : param channel : Defines the name of the value : param value : Defines the value itself"""
self . _r . publish ( channel , str ( value ) )
def macro_attachment_create ( self , macro_id , data , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / macros # create - macro - attachment"
api_path = "/api/v2/macros/{macro_id}/attachments.json" api_path = api_path . format ( macro_id = macro_id ) return self . call ( api_path , method = "POST" , data = data , ** kwargs )
def set_color_scheme ( self , foreground_color , background_color ) : """Set color scheme of the console ( foreground and background ) ."""
self . ansi_handler . set_color_scheme ( foreground_color , background_color ) background_color = QColor ( background_color ) foreground_color = QColor ( foreground_color ) self . set_palette ( background = background_color , foreground = foreground_color ) self . set_pythonshell_font ( )
def validated_element ( x , tags = None , attrs = None ) : """Checks if the root element of an XML document or Element meets the supplied criteria . * tags * if specified is either a single allowable tag name or sequence of allowable alternatives * attrs * if specified is a sequence of required attributes , eac...
ele = to_ele ( x ) if tags : if isinstance ( tags , ( str , bytes ) ) : tags = [ tags ] if ele . tag not in tags : raise XMLError ( "Element [%s] does not meet requirement" % ele . tag ) if attrs : for req in attrs : if isinstance ( req , ( str , bytes ) ) : req = [ req ]...
def update_prompt ( self ) : """Update the prompt"""
prefix = "" if self . _local_endpoint is not None : prefix += "(%s:%d) " % self . _local_endpoint prefix += self . engine . region if self . engine . partial : self . prompt = len ( prefix ) * " " + "> " else : self . prompt = prefix + "> "
def install ( pecls , defaults = False , force = False , preferred_state = 'stable' ) : '''. . versionadded : : 0.17.0 Installs one or several pecl extensions . pecls The pecl extensions to install . defaults Use default answers for extensions such as pecl _ http which ask questions before installation ...
if isinstance ( pecls , six . string_types ) : pecls = [ pecls ] preferred_state = '-d preferred_state={0}' . format ( _cmd_quote ( preferred_state ) ) if force : return _pecl ( '{0} install -f {1}' . format ( preferred_state , _cmd_quote ( ' ' . join ( pecls ) ) ) , defaults = defaults ) else : _pecl ( '{0...
def distance ( self , other ) : """Distance between the center of this region and another . Parameters other : one region , or array - like Either another region , or the center of another region ."""
from numpy . linalg import norm if isinstance ( other , one ) : other = other . center return norm ( self . center - asarray ( other ) , ord = 2 )
def base_url ( self ) : """Base URL for resolving resource URLs"""
if self . doc . package_url : return self . doc . package_url return self . doc . _ref
def distinct_sequence_check ( sequence ) : """Given a sequence , this function checks if it is cheerful or not . A sequence is defined as cheerful if its length is three or more and every consecutive three characters are unique . Example : distinct _ sequence _ check ( ' a ' ) - > False distinct _ sequence ...
if len ( sequence ) < 3 : return False for i in range ( len ( sequence ) - 2 ) : if sequence [ i ] == sequence [ i + 1 ] or sequence [ i + 1 ] == sequence [ i + 2 ] or sequence [ i ] == sequence [ i + 2 ] : return False return True
def reproject ( rasterobject , reference , outname , targetres = None , resampling = 'bilinear' , format = 'GTiff' ) : """reproject a raster file Parameters rasterobject : Raster or str the raster image to be reprojected reference : Raster , Vector , str , int or osr . SpatialReference either a projection...
if isinstance ( rasterobject , str ) : rasterobject = Raster ( rasterobject ) if not isinstance ( rasterobject , Raster ) : raise RuntimeError ( 'rasterobject must be of type Raster or str' ) if isinstance ( reference , ( Raster , Vector ) ) : projection = reference . projection if targetres is not None...