idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
236,900 | def _fit_stacking_model ( self , X , y , cost_mat , max_iter = 100 ) : self . f_staking = CostSensitiveLogisticRegression ( verbose = self . verbose , max_iter = max_iter ) X_stacking = _create_stacking_set ( self . estimators_ , self . estimators_features_ , self . estimators_weight_ , X , self . combination ) self . ... | Private function used to fit the stacking model . |
236,901 | def _evaluate_oob_savings ( self , X , y , cost_mat ) : estimators_weight = [ ] for estimator , samples , features in zip ( self . estimators_ , self . estimators_samples_ , self . estimators_features_ ) : if not np . any ( ~ samples ) : oob_pred = estimator . predict ( X [ : , features ] ) oob_savings = max ( 0 , savi... | Private function used to calculate the OOB Savings of each estimator . |
236,902 | def predict ( self , X , cost_mat = None ) : if self . n_features_ != X . shape [ 1 ] : raise ValueError ( "Number of features of the model must " "match the input. Model n_features is {0} and " "input n_features is {1}." "" . format ( self . n_features_ , X . shape [ 1 ] ) ) if self . combination in [ 'stacking' , 'st... | Predict class for X . |
236,903 | def predict_proba ( self , X ) : if self . n_features_ != X . shape [ 1 ] : raise ValueError ( "Number of features of the model must " "match the input. Model n_features is {0} and " "input n_features is {1}." "" . format ( self . n_features_ , X . shape [ 1 ] ) ) n_jobs , n_estimators , starts = _partition_estimators ... | Predict class probabilities for X . |
236,904 | def cost_sampling ( X , y , cost_mat , method = 'RejectionSampling' , oversampling_norm = 0.1 , max_wc = 97.5 ) : cost_mis = cost_mat [ : , 0 ] cost_mis [ y == 1 ] = cost_mat [ y == 1 , 1 ] wc = np . minimum ( cost_mis / np . percentile ( cost_mis , max_wc ) , 1 ) n_samples = X . shape [ 0 ] filter_ = list ( range ( n_... | Cost - proportionate sampling . |
236,905 | def _creditscoring_costmat ( income , debt , pi_1 , cost_mat_parameters ) : def calculate_a ( cl_i , int_ , n_term ) : return cl_i * ( ( int_ * ( 1 + int_ ) ** n_term ) / ( ( 1 + int_ ) ** n_term - 1 ) ) def calculate_pv ( a , int_ , n_term ) : return a / int_ * ( 1 - 1 / ( 1 + int_ ) ** n_term ) def calculate_cl ( k ,... | Private function to calculate the cost matrix of credit scoring models . |
236,906 | def predict_proba ( self , p ) : if p . size != p . shape [ 0 ] : p = p [ : , 1 ] calibrated_proba = np . zeros ( p . shape [ 0 ] ) for i in range ( self . calibration_map . shape [ 0 ] ) : calibrated_proba [ np . logical_and ( self . calibration_map [ i , 1 ] <= p , self . calibration_map [ i , 0 ] > p ) ] = self . ca... | Calculate the calibrated probabilities |
236,907 | def cross_val_score ( estimator , X , y = None , scoring = None , cv = None , n_jobs = 1 , verbose = 0 , fit_params = None , pre_dispatch = '2*n_jobs' ) : X , y = indexable ( X , y ) cv = _check_cv ( cv , X , y , classifier = is_classifier ( estimator ) ) scorer = check_scoring ( estimator , scoring = scoring ) paralle... | Evaluate a score by cross - validation |
236,908 | def _safe_split ( estimator , X , y , indices , train_indices = None ) : if hasattr ( estimator , 'kernel' ) and isinstance ( estimator . kernel , collections . Callable ) : raise ValueError ( "Cannot use a custom kernel function. " "Precompute the kernel matrix instead." ) if not hasattr ( X , "shape" ) : if getattr (... | Create subset of dataset and properly handle kernels . |
236,909 | def _score ( estimator , X_test , y_test , scorer ) : if y_test is None : score = scorer ( estimator , X_test ) else : score = scorer ( estimator , X_test , y_test ) if not isinstance ( score , numbers . Number ) : raise ValueError ( "scoring must return a number, got %s (%s) instead." % ( str ( score ) , type ( score ... | Compute the score of an estimator on a given test set . |
236,910 | def _shuffle ( y , labels , random_state ) : if labels is None : ind = random_state . permutation ( len ( y ) ) else : ind = np . arange ( len ( labels ) ) for label in np . unique ( labels ) : this_mask = ( labels == label ) ind [ this_mask ] = random_state . permutation ( ind [ this_mask ] ) return y [ ind ] | Return a shuffled copy of y eventually shuffle among same labels . |
236,911 | def check_cv ( cv , X = None , y = None , classifier = False ) : return _check_cv ( cv , X = X , y = y , classifier = classifier , warn_mask = True ) | Input checker utility for building a CV in a user friendly way . |
236,912 | def _borderlineSMOTE ( X , y , minority_target , N , k ) : n_samples , _ = X . shape neigh = NearestNeighbors ( n_neighbors = k ) neigh . fit ( X ) safe_minority_indices = list ( ) danger_minority_indices = list ( ) for i in range ( n_samples ) : if y [ i ] != minority_target : continue nn = neigh . kneighbors ( X [ i ... | Returns synthetic minority samples . |
236,913 | def fit ( self , y_true_cal = None , y_prob_cal = None ) : if self . calibration : self . cal = ROCConvexHull ( ) self . cal . fit ( y_true_cal , y_prob_cal [ : , 1 ] ) | If calibration then train the calibration of probabilities |
236,914 | def fit ( self , y_prob , cost_mat , y_true ) : if self . calibration : cal = ROCConvexHull ( ) cal . fit ( y_true , y_prob [ : , 1 ] ) y_prob [ : , 1 ] = cal . predict_proba ( y_prob [ : , 1 ] ) y_prob [ : , 0 ] = 1 - y_prob [ : , 1 ] thresholds = np . unique ( y_prob ) cost = np . zeros ( thresholds . shape ) for i i... | Calculate the optimal threshold using the ThresholdingOptimization . |
236,915 | def predict ( self , y_prob ) : y_pred = np . floor ( y_prob [ : , 1 ] + ( 1 - self . threshold_ ) ) return y_pred | Calculate the prediction using the ThresholdingOptimization . |
236,916 | def undersampling ( X , y , cost_mat = None , per = 0.5 ) : n_samples = X . shape [ 0 ] num_y1 = y . sum ( ) num_y0 = n_samples - num_y1 filter_rand = np . random . rand ( int ( num_y1 + num_y0 ) ) if num_y1 < num_y0 : num_y0_new = num_y1 * 1.0 / per - num_y1 num_y0_new_per = num_y0_new * 1.0 / num_y0 filter_0 = np . l... | Under - sampling . |
236,917 | def _node_cost ( self , y_true , cost_mat ) : n_samples = len ( y_true ) costs = np . zeros ( 2 ) costs [ 0 ] = cost_loss ( y_true , np . zeros ( y_true . shape ) , cost_mat ) costs [ 1 ] = cost_loss ( y_true , np . ones ( y_true . shape ) , cost_mat ) pi = np . array ( [ 1 - y_true . mean ( ) , y_true . mean ( ) ] ) i... | Private function to calculate the cost of a node . |
236,918 | def _calculate_gain ( self , cost_base , y_true , X , cost_mat , split ) : if cost_base == 0.0 : return 0.0 , int ( np . sign ( y_true . mean ( ) - 0.5 ) == 1 ) j , l = split filter_Xl = ( X [ : , j ] <= l ) filter_Xr = ~ filter_Xl n_samples , n_features = X . shape if np . nonzero ( filter_Xl ) [ 0 ] . shape [ 0 ] in ... | Private function to calculate the gain in cost of using split in the current node . |
236,919 | def _best_split ( self , y_true , X , cost_mat ) : n_samples , n_features = X . shape num_pct = self . num_pct cost_base , y_pred , y_prob = self . _node_cost ( y_true , cost_mat ) gains = np . zeros ( ( n_features , num_pct ) ) pred = np . zeros ( ( n_features , num_pct ) ) splits = np . zeros ( ( n_features , num_pct... | Private function to calculate the split that gives the best gain . |
236,920 | def _tree_grow ( self , y_true , X , cost_mat , level = 0 ) : if len ( X . shape ) == 1 : tree = dict ( y_pred = y_true , y_prob = 0.5 , level = level , split = - 1 , n_samples = 1 , gain = 0 ) return tree split , gain , Xl_pred , y_pred , y_prob = self . _best_split ( y_true , X , cost_mat ) n_samples , n_features = X... | Private recursive function to grow the decision tree . |
236,921 | def _nodes ( self , tree ) : def recourse ( temp_tree_ , nodes ) : if isinstance ( temp_tree_ , dict ) : if temp_tree_ [ 'split' ] != - 1 : nodes . append ( temp_tree_ [ 'node' ] ) if temp_tree_ [ 'split' ] != - 1 : for k in [ 'sl' , 'sr' ] : recourse ( temp_tree_ [ k ] , nodes ) return None nodes_ = [ ] recourse ( tre... | Private function that find the number of nodes in a tree . |
236,922 | def _classify ( self , X , tree , proba = False ) : n_samples , n_features = X . shape predicted = np . ones ( n_samples ) if tree [ 'split' ] == - 1 : if not proba : predicted = predicted * tree [ 'y_pred' ] else : predicted = predicted * tree [ 'y_prob' ] else : j , l = tree [ 'split' ] filter_Xl = ( X [ : , j ] <= l... | Private function that classify a dataset using tree . |
236,923 | def predict ( self , X ) : if self . pruned : tree_ = self . tree_ . tree_pruned else : tree_ = self . tree_ . tree return self . _classify ( X , tree_ , proba = False ) | Predict class of X . |
236,924 | def predict_proba ( self , X ) : n_samples , n_features = X . shape prob = np . zeros ( ( n_samples , 2 ) ) if self . pruned : tree_ = self . tree_ . tree_pruned else : tree_ = self . tree_ . tree prob [ : , 1 ] = self . _classify ( X , tree_ , proba = True ) prob [ : , 0 ] = 1 - prob [ : , 1 ] return prob | Predict class probabilities of the input samples X . |
236,925 | def _delete_node ( self , tree , node ) : temp_tree = copy . deepcopy ( tree ) def recourse ( temp_tree_ , del_node ) : if isinstance ( temp_tree_ , dict ) : if temp_tree_ [ 'split' ] != - 1 : if temp_tree_ [ 'node' ] == del_node : del temp_tree_ [ 'sr' ] del temp_tree_ [ 'sl' ] del temp_tree_ [ 'node' ] temp_tree_ [ '... | Private function that eliminate node from tree . |
236,926 | def _pruning ( self , X , y_true , cost_mat ) : nodes = self . _nodes ( self . tree_ . tree_pruned ) n_nodes = len ( nodes ) gains = np . zeros ( n_nodes ) y_pred = self . _classify ( X , self . tree_ . tree_pruned ) cost_base = cost_loss ( y_true , y_pred , cost_mat ) for m , node in enumerate ( nodes ) : temp_tree = ... | Private function that prune the decision tree . |
236,927 | def pruning ( self , X , y , cost_mat ) : self . tree_ . tree_pruned = copy . deepcopy ( self . tree_ . tree ) if self . tree_ . n_nodes > 0 : self . _pruning ( X , y , cost_mat ) nodes_pruned = self . _nodes ( self . tree_ . tree_pruned ) self . tree_ . n_nodes_pruned = len ( nodes_pruned ) | Function that prune the decision tree . |
236,928 | def cost_loss ( y_true , y_pred , cost_mat ) : y_true = column_or_1d ( y_true ) y_true = ( y_true == 1 ) . astype ( np . float ) y_pred = column_or_1d ( y_pred ) y_pred = ( y_pred == 1 ) . astype ( np . float ) cost = y_true * ( ( 1 - y_pred ) * cost_mat [ : , 1 ] + y_pred * cost_mat [ : , 2 ] ) cost += ( 1 - y_true ) ... | Cost classification loss . |
236,929 | def savings_score ( y_true , y_pred , cost_mat ) : y_true = column_or_1d ( y_true ) y_pred = column_or_1d ( y_pred ) n_samples = len ( y_true ) cost_base = min ( cost_loss ( y_true , np . zeros ( n_samples ) , cost_mat ) , cost_loss ( y_true , np . ones ( n_samples ) , cost_mat ) ) cost = cost_loss ( y_true , y_pred , ... | Savings score . |
236,930 | def brier_score_loss ( y_true , y_prob ) : y_true = column_or_1d ( y_true ) y_prob = column_or_1d ( y_prob ) return np . mean ( ( y_true - y_prob ) ** 2 ) | Compute the Brier score |
236,931 | def _logistic_cost_loss ( w , X , y , cost_mat , alpha ) : if w . shape [ 0 ] == w . size : return _logistic_cost_loss_i ( w , X , y , cost_mat , alpha ) else : n_w = w . shape [ 0 ] out = np . zeros ( n_w ) for i in range ( n_w ) : out [ i ] = _logistic_cost_loss_i ( w [ i ] , X , y , cost_mat , alpha ) return out | Computes the logistic loss . |
236,932 | def predict ( self , X , cut_point = 0.5 ) : return np . floor ( self . predict_proba ( X ) [ : , 1 ] + ( 1 - cut_point ) ) | Predicted class . |
236,933 | def list_tags ( userdata ) : macros = re . findall ( '@(.*?)@' , userdata ) logging . info ( 'List of available macros:' ) for macro in macros : logging . info ( '\t%r' , macro ) | List all used macros within a UserData script . |
236,934 | def handle_tags ( userdata , macros ) : macro_vars = re . findall ( '@(.*?)@' , userdata ) for macro_var in macro_vars : if macro_var == '!all_macros_export' : macro_var_export_list = [ ] for defined_macro in macros : macro_var_export_list . append ( 'export %s="%s"' % ( defined_macro , macros [ defined_macro ] ) ) mac... | Insert macro values or auto export variables in UserData scripts . |
236,935 | def retry_on_ec2_error ( self , func , * args , ** kwargs ) : exception_retry_count = 6 while True : try : return func ( * args , ** kwargs ) except ( boto . exception . EC2ResponseError , ssl . SSLError ) as msg : exception_retry_count -= 1 if exception_retry_count <= 0 : raise msg time . sleep ( 5 ) | Call the given method with the given arguments retrying if the call failed due to an EC2ResponseError . This method will wait at most 30 seconds and perform up to 6 retries . If the method still fails it will propagate the error . |
236,936 | def connect ( self , region , ** kw_params ) : self . ec2 = boto . ec2 . connect_to_region ( region , ** kw_params ) if not self . ec2 : raise EC2ManagerException ( 'Unable to connect to region "%s"' % region ) self . remote_images . clear ( ) if self . images and any ( ( 'image_name' in img and 'image_id' not in img )... | Connect to a EC2 . |
236,937 | def resolve_image_name ( self , image_name ) : scopes = [ 'self' , 'amazon' , 'aws-marketplace' ] if image_name in self . remote_images : return self . remote_images [ image_name ] for scope in scopes : logger . info ( 'Retrieving available AMIs owned by %s...' , scope ) remote_images = self . ec2 . get_all_images ( ow... | Look up an AMI for the connected region based on an image name . |
236,938 | def create_on_demand ( self , instance_type = 'default' , tags = None , root_device_type = 'ebs' , size = 'default' , vol_type = 'gp2' , delete_on_termination = False ) : name , size = self . _get_default_name_size ( instance_type , size ) if root_device_type == 'ebs' : self . images [ instance_type ] [ 'block_device_m... | Create one or more EC2 on - demand instances . |
236,939 | def create_spot_requests ( self , price , instance_type = 'default' , root_device_type = 'ebs' , size = 'default' , vol_type = 'gp2' , delete_on_termination = False , timeout = None ) : name , size = self . _get_default_name_size ( instance_type , size ) if root_device_type == 'ebs' : self . images [ instance_type ] [ ... | Request creation of one or more EC2 spot instances . |
236,940 | def check_spot_requests ( self , requests , tags = None ) : instances = [ None ] * len ( requests ) ec2_requests = self . retry_on_ec2_error ( self . ec2 . get_all_spot_instance_requests , request_ids = requests ) for req in ec2_requests : if req . instance_id : instance = self . retry_on_ec2_error ( self . ec2 . get_o... | Check status of one or more EC2 spot instance requests . |
236,941 | def cancel_spot_requests ( self , requests ) : ec2_requests = self . retry_on_ec2_error ( self . ec2 . get_all_spot_instance_requests , request_ids = requests ) for req in ec2_requests : req . cancel ( ) | Cancel one or more EC2 spot instance requests . |
236,942 | def create_spot ( self , price , instance_type = 'default' , tags = None , root_device_type = 'ebs' , size = 'default' , vol_type = 'gp2' , delete_on_termination = False , timeout = None ) : request_ids = self . create_spot_requests ( price , instance_type = instance_type , root_device_type = root_device_type , size = ... | Create one or more EC2 spot instances . |
236,943 | def _scale_down ( self , instances , count ) : i = sorted ( instances , key = lambda i : i . launch_time , reverse = True ) if not i : return [ ] running = len ( i ) logger . info ( '%d instance/s are running.' , running ) logger . info ( 'Scaling down %d instances of those.' , count ) if count > running : logger . inf... | Return a list of |count| last created instances by launch time . |
236,944 | def _configure_ebs_volume ( self , vol_type , name , size , delete_on_termination ) : root_dev = boto . ec2 . blockdevicemapping . BlockDeviceType ( ) root_dev . delete_on_termination = delete_on_termination root_dev . volume_type = vol_type if size != 'default' : root_dev . size = size bdm = boto . ec2 . blockdevicema... | Sets the desired root EBS size otherwise the default EC2 value is used . |
236,945 | def stop ( self , instances , count = 0 ) : if not instances : return if count > 0 : instances = self . _scale_down ( instances , count ) self . ec2 . stop_instances ( [ i . id for i in instances ] ) | Stop each provided running instance . |
236,946 | def terminate ( self , instances , count = 0 ) : if not instances : return if count > 0 : instances = self . _scale_down ( instances , count ) self . ec2 . terminate_instances ( [ i . id for i in instances ] ) | Terminate each provided running or stopped instance . |
236,947 | def find ( self , instance_ids = None , filters = None ) : instances = [ ] reservations = self . retry_on_ec2_error ( self . ec2 . get_all_instances , instance_ids = instance_ids , filters = filters ) for reservation in reservations : instances . extend ( reservation . instances ) return instances | Flatten list of reservations to a list of instances . |
236,948 | def load ( self , root , module_path , pkg_name ) : root = os . path . join ( root , module_path ) import_name = os . path . join ( pkg_name , module_path ) . replace ( os . sep , '.' ) for ( _ , name , _ ) in pkgutil . iter_modules ( [ root ] ) : self . modules [ name ] = import_module ( '.' + name , package = import_... | Load modules dynamically . |
236,949 | def command_line_interfaces ( self ) : interfaces = [ ] for _ , module in self . modules . items ( ) : for entry in dir ( module ) : if entry . endswith ( 'CommandLine' ) : interfaces . append ( ( module , entry ) ) return interfaces | Return the CommandLine classes from each provider . |
236,950 | def pluralize ( item ) : assert isinstance ( item , ( int , list ) ) if isinstance ( item , int ) : return 's' if item > 1 else '' if isinstance ( item , list ) : return 's' if len ( item ) > 1 else '' return '' | Nothing to see here . |
236,951 | def validate ( self ) : if not self . conf . get ( 'auth_token' ) : raise PacketManagerException ( 'The auth token for Packet is not defined but required.' ) if not self . conf . get ( 'projects' ) : raise PacketManagerException ( 'Required "projects" section is missing.' ) projects = self . conf . get ( 'projects' ) i... | Perform some basic configuration validation . |
236,952 | def print_projects ( self , projects ) : for project in projects : print ( '{}: {}' . format ( project . name , project . id ) ) | Print method for projects . |
236,953 | def print_operating_systems ( self , operating_systems ) : for _os in operating_systems : print ( '{}: {}' . format ( _os . name , _os . slug ) ) | Print method for operating systems . |
236,954 | def print_plans ( self , plans ) : for plan in plans : print ( 'Name: {} "{}" Price: {} USD' . format ( plan . name , plan . slug , plan . pricing [ 'hour' ] ) ) self . pprint ( plan . specs ) print ( '\n' ) | Print method for plans . |
236,955 | def print_facilities ( self , facilities ) : for facility in facilities : print ( '{} - ({}): {}' . format ( facility . code , facility . name , "," . join ( facility . features ) ) ) | Print method for facilities . |
236,956 | def list_devices ( self , project_id , conditions = None , params = None ) : default_params = { 'per_page' : 1000 } if params : default_params . update ( params ) data = self . api ( 'projects/%s/devices' % project_id , params = default_params ) devices = [ ] for device in self . filter ( conditions , data [ 'devices' ... | Retrieve list of devices in a project by one of more conditions . |
236,957 | def print_devices ( self , devices ) : for device in devices : print ( 'ID: {} OS: {} IP: {} State: {} ({}) Tags: {}' . format ( device . id , device . operating_system . slug , self . get_public_ip ( device . ip_addresses ) , device . state , 'spot' if device . spot_instance else 'on-demand' , device . tags ) ) | Print method for devices . |
236,958 | def filter ( criterias , devices ) : if not criterias : return devices result = [ ] for device in devices : for criteria_name , criteria_values in criterias . items ( ) : if criteria_name in device . keys ( ) : if isinstance ( device [ criteria_name ] , list ) : for criteria_value in criteria_values : if criteria_value... | Filter a device by criterias on the root level of the dictionary . |
236,959 | def get_public_ip ( addresses , version = 4 ) : for addr in addresses : if addr [ 'public' ] and addr [ 'address_family' ] == version : return addr . get ( 'address' ) return None | Return either the devices public IPv4 or IPv6 address . |
236,960 | def validate_capacity ( self , servers ) : try : return self . manager . validate_capacity ( servers ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) | Validates if a deploy can be fulfilled . |
236,961 | def create_volume ( self , project_id , plan , size , facility , label = "" ) : try : return self . manager . create_volume ( project_id , label , plan , size , facility ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) | Creates a new volume . |
236,962 | def attach_volume_to_device ( self , volume_id , device_id ) : try : volume = self . manager . get_volume ( volume_id ) volume . attach ( device_id ) except packet . baseapi . Error as msg : raise PacketManagerException ( msg ) return volume | Attaches the created Volume to a Device . |
236,963 | def create_demand ( self , project_id , facility , plan , operating_system , tags = None , userdata = '' , hostname = None , count = 1 ) : tags = { } if tags is None else tags hostname = self . get_random_hostname ( ) if hostname is None else hostname devices = [ ] for i in range ( 1 , count + 1 ) : new_hostname = host... | Create a new on demand device under the given project . |
236,964 | def stop ( self , devices ) : for device in devices : self . logger . info ( 'Stopping: %s' , device . id ) try : device . power_off ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to stop instance "{}"' . format ( device . id ) ) | Power - Off one or more running devices . |
236,965 | def reboot ( self , devices ) : for device in devices : self . logger . info ( 'Rebooting: %s' , device . id ) try : device . reboot ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to reboot instance "{}"' . format ( device . id ) ) | Reboot one or more devices . |
236,966 | def terminate ( self , devices ) : for device in devices : self . logger . info ( 'Terminating: %s' , device . id ) try : device . delete ( ) except packet . baseapi . Error : raise PacketManagerException ( 'Unable to terminate instance "{}"' . format ( device . id ) ) | Terminate one or more running or stopped instances . |
236,967 | def parse_args ( cls ) : dirs = appdirs . AppDirs ( __title__ , 'Mozilla Security' ) if not os . path . isdir ( dirs . user_config_dir ) : shutil . copytree ( os . path . join ( cls . HOME , 'examples' ) , dirs . user_config_dir ) shutil . copytree ( os . path . join ( cls . HOME , 'userdata' ) , os . path . join ( dir... | Main argument parser of Laniakea . |
236,968 | def main ( cls ) : args = cls . parse_args ( ) if args . focus : Focus . init ( ) else : Focus . disable ( ) logging . basicConfig ( format = '[Laniakea] %(asctime)s %(levelname)s: %(message)s' , level = args . verbosity * 10 , datefmt = '%Y-%m-%d %H:%M:%S' ) logger . info ( 'Loading Laniakea configuration from %s' , F... | Main entry point of Laniakea . |
236,969 | def tags ( self , tags = None ) : if tags is None or not tags : return self nodes = [ ] for node in self . nodes : if any ( tag in node . extra [ 'tags' ] for tag in tags ) : nodes . append ( node ) self . nodes = nodes return self | Filter by tags . |
236,970 | def state ( self , states = None ) : if states is None or not states : return self nodes = [ ] for node in self . nodes : if any ( state . lower ( ) == node . state . lower ( ) for state in states ) : nodes . append ( node ) self . nodes = nodes return self | Filter by state . |
236,971 | def name ( self , names = None ) : if names is None or not names : return self nodes = [ ] for node in self . nodes : if any ( name == node . name for name in names ) : nodes . append ( node ) self . nodes = nodes return self | Filter by node name . |
236,972 | def is_preemptible ( self ) : nodes = [ ] for node in self . nodes : if Kurz . is_preemtible ( node ) : nodes . append ( node ) return self | Filter by preemptible scheduling . |
236,973 | def expr ( self , callback ) : nodes = [ ] for node in self . nodes : if callback ( node ) : nodes . append ( node ) self . nodes = nodes return self | Filter by custom expression . |
236,974 | def connect ( self , ** kwargs ) : try : self . gce = get_driver ( Provider . GCE ) ( self . user_id , self . key , project = self . project , ** kwargs ) except : raise ComputeEngineManagerException ( "Unable to connect to Google Compute Engine." ) | Connect to Google Compute Engine . |
236,975 | def is_connected ( self , attempts = 3 ) : if self . gce is None : while attempts > 0 : self . logger . info ( "Attempting to connect ..." ) try : self . connect ( ) except ComputeEngineManagerException : attempts -= 1 continue self . logger . info ( "Connection established." ) return True self . logger . error ( "Unab... | Try to reconnect if neccessary . |
236,976 | def create ( self , size , number , meta , name = None , image = None , attempts = 3 ) : if name is None : name = Common . get_random_hostname ( ) if image is None and number == 1 : raise ComputeEngineManagerException ( "Base image not provided." ) successful = 0 nodes = [ ] while number - successful > 0 and attempts >... | Create container VM nodes . Uses a container declaration which is undocumented . |
236,977 | def stop ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'stopped' : logging . warning ( 'Node %s is already "stopped".' , node . name ) continue try : status = self . gce . ex_stop_node ( node ) if status : result ... | Stop one or many nodes . |
236,978 | def start ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'running' : logging . warning ( 'Node %s is already "running".' , node . name ) continue try : status = self . gce . ex_start_node ( node ) if status : resul... | Start one or many nodes . |
236,979 | def reboot ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes result = [ ] for node in nodes : if node . state == 'stopped' : logging . warning ( 'Node %s is "stopped" and can not be rebooted.' , node . name ) continue try : status = self . gce . reboot_node ( node ) if... | Reboot one or many nodes . |
236,980 | def terminate ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes failed_kill = [ ] result = self . gce . ex_destroy_multiple_nodes ( nodes , poll_interval = 1 , ignore_errors = False ) for i , success in enumerate ( result ) : if success : logging . info ( 'Successfully... | Destroy one or many nodes . |
236,981 | def terminate_with_threads ( self , nodes = None ) : if not self . is_connected ( ) : return None nodes = nodes or self . nodes failed_kill = [ ] def worker ( gce , node ) : self . logger . info ( "Terminating node: %s" , node . name ) terminated = gce . destroy_node ( node ) if not terminated : failed_kill . append ( ... | Destroy one or many nodes threaded . |
236,982 | def terminate_ex ( self , nodes , threads = False , attempts = 3 ) : while nodes and attempts > 0 : if threads : nodes = self . terminate_with_threads ( nodes ) else : nodes = self . terminate ( nodes ) if nodes : logger . info ( "Attempt to terminate the remaining instances once more." ) attempts -= 1 return nodes | Wrapper method for terminate . |
236,983 | def build_bootdisk ( self , image , size = 10 , auto_delete = True ) : if image is None : raise ComputeEngineManagerException ( "Image must not be None." ) return { 'boot' : True , 'autoDelete' : auto_delete , 'initializeParams' : { 'sourceImage' : "projects/cos-cloud/global/images/{}" . format ( image ) , 'diskSizeGb'... | Buid a disk struct . |
236,984 | def build_container_vm ( self , container , disk , zone = "us-east1-b" , tags = None , preemptible = True ) : if tags is None : tags = [ ] if container is None : raise ComputeEngineManagerException ( "Container declaration must not be None." ) if disk is None : raise ComputeEngineManagerException ( "Disk structure must... | Build kwargs for a container VM . |
236,985 | def filter ( self , zone = 'all' ) : if not self . is_connected ( ) : return None nodes = self . gce . list_nodes ( zone ) return Filter ( nodes ) | Filter nodes by their attributes . |
236,986 | def enu2aer ( e : np . ndarray , n : np . ndarray , u : np . ndarray , deg : bool = True ) -> Tuple [ float , float , float ] : e = np . asarray ( e ) n = np . asarray ( n ) u = np . asarray ( u ) with np . errstate ( invalid = 'ignore' ) : e [ abs ( e ) < 1e-3 ] = 0. n [ abs ( n ) < 1e-3 ] = 0. u [ abs ( u ) < 1e-3 ] ... | ENU to Azimuth Elevation Range |
236,987 | def aer2enu ( az : float , el : float , srange : float , deg : bool = True ) -> Tuple [ float , float , float ] : if deg : el = radians ( el ) az = radians ( az ) with np . errstate ( invalid = 'ignore' ) : if ( np . asarray ( srange ) < 0 ) . any ( ) : raise ValueError ( 'Slant range [0, Infinity)' ) r = srange * cos... | Azimuth Elevation Slant range to target to East north Up |
236,988 | def enu2geodetic ( e : float , n : float , u : float , lat0 : float , lon0 : float , h0 : float , ell = None , deg : bool = True ) -> Tuple [ float , float , float ] : x , y , z = enu2ecef ( e , n , u , lat0 , lon0 , h0 , ell , deg = deg ) return ecef2geodetic ( x , y , z , ell , deg = deg ) | East North Up to target to geodetic coordinates |
236,989 | def track2 ( lat1 : float , lon1 : float , lat2 : float , lon2 : float , ell : Ellipsoid = None , npts : int = 100 , deg : bool = True ) : if ell is None : ell = Ellipsoid ( ) if npts <= 1 : raise ValueError ( 'npts must be greater than 1' ) if npts == 2 : return [ lat1 , lat2 ] , [ lon1 , lon2 ] if deg is True : rlat1... | computes great circle tracks starting at the point lat1 lon1 and ending at lat2 lon2 |
236,990 | def datetime2sidereal ( time : datetime , lon_radians : float , usevallado : bool = True ) -> float : usevallado = usevallado or Time is None if usevallado : jd = juliandate ( str2dt ( time ) ) gst = julian2sidereal ( jd ) tsr = gst + lon_radians else : tsr = Time ( time ) . sidereal_time ( kind = 'apparent' , longitud... | Convert datetime to sidereal time |
236,991 | def juliandate ( time : datetime ) -> float : times = np . atleast_1d ( time ) assert times . ndim == 1 jd = np . empty ( times . size ) for i , t in enumerate ( times ) : if t . month < 3 : year = t . year - 1 month = t . month + 12 else : year = t . year month = t . month A = int ( year / 100.0 ) B = 2 - A + int ( A ... | Python datetime to Julian time |
236,992 | def julian2sidereal ( Jdate : float ) -> float : jdate = np . atleast_1d ( Jdate ) assert jdate . ndim == 1 tsr = np . empty ( jdate . size ) for i , jd in enumerate ( jdate ) : tUT1 = ( jd - 2451545.0 ) / 36525. gmst_sec = ( 67310.54841 + ( 876600 * 3600 + 8640184.812866 ) * tUT1 + 0.093104 * tUT1 ** 2 - 6.2e-6 * tUT1... | Convert Julian time to sidereal time |
236,993 | def get_radius_normal ( lat_radians : float , ell : Ellipsoid = None ) -> float : if ell is None : ell = Ellipsoid ( ) a = ell . a b = ell . b return a ** 2 / sqrt ( a ** 2 * cos ( lat_radians ) ** 2 + b ** 2 * sin ( lat_radians ) ** 2 ) | Compute normal radius of planetary body |
236,994 | def ecef2enuv ( u : float , v : float , w : float , lat0 : float , lon0 : float , deg : bool = True ) -> Tuple [ float , float , float ] : if deg : lat0 = radians ( lat0 ) lon0 = radians ( lon0 ) t = cos ( lon0 ) * u + sin ( lon0 ) * v uEast = - sin ( lon0 ) * u + cos ( lon0 ) * v wUp = cos ( lat0 ) * t + sin ( lat0 ) ... | VECTOR from observer to target ECEF = > ENU |
236,995 | def ecef2enu ( x : float , y : float , z : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , h0 , ell , deg = deg ) return uvw2enu ( x - x0 , y - y0 , z - z0 , lat0 , lon0 , deg = deg ) | from observer to target ECEF = > ENU |
236,996 | def eci2geodetic ( eci : np . ndarray , t : datetime , useastropy : bool = True ) -> Tuple [ float , float , float ] : ecef = np . atleast_2d ( eci2ecef ( eci , t , useastropy = useastropy ) ) return np . asarray ( ecef2geodetic ( ecef [ : , 0 ] , ecef [ : , 1 ] , ecef [ : , 2 ] ) ) . squeeze ( ) | convert ECI to geodetic coordinates |
236,997 | def enu2ecef ( e1 : float , n1 : float , u1 : float , lat0 : float , lon0 : float , h0 : float , ell : Ellipsoid = None , deg : bool = True ) -> Tuple [ float , float , float ] : x0 , y0 , z0 = geodetic2ecef ( lat0 , lon0 , h0 , ell , deg = deg ) dx , dy , dz = enu2uvw ( e1 , n1 , u1 , lat0 , lon0 , deg = deg ) return ... | ENU to ECEF |
236,998 | def aer2ned ( az : float , elev : float , slantRange : float , deg : bool = True ) -> Tuple [ float , float , float ] : e , n , u = aer2enu ( az , elev , slantRange , deg = deg ) return n , e , - u | converts azimuth elevation range to target from observer to North East Down |
236,999 | def ned2aer ( n : float , e : float , d : float , deg : bool = True ) -> Tuple [ float , float , float ] : return enu2aer ( e , n , - d , deg = deg ) | converts North East Down to azimuth elevation range |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.