idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,800
def client_port ( self ) : address = self . _client . getpeername ( ) if isinstance ( address , tuple ) : return address [ 1 ] return 0
Client connection s TCP port .
61,801
def command_err ( self , code = 1 , errmsg = 'MockupDB command failure' , * args , ** kwargs ) : kwargs . setdefault ( 'ok' , 0 ) kwargs [ 'code' ] = code kwargs [ 'errmsg' ] = errmsg self . replies ( * args , ** kwargs ) return True
Error reply to a command .
61,802
def unpack ( cls , msg , client , server , request_id ) : payload_document = OrderedDict ( ) flags , = _UNPACK_UINT ( msg [ : 4 ] ) pos = 4 if flags != 0 and flags != 2 : raise ValueError ( 'OP_MSG flag must be 0 or 2 not %r' % ( flags , ) ) while pos < len ( msg ) : payload_type , = _UNPACK_BYTE ( msg [ pos : pos + 1 ...
Parse message and return an OpMsg .
61,803
def unpack ( cls , msg , client , server , request_id ) : flags , = _UNPACK_INT ( msg [ : 4 ] ) namespace , pos = _get_c_string ( msg , 4 ) is_command = namespace . endswith ( '.$cmd' ) num_to_skip , = _UNPACK_INT ( msg [ pos : pos + 4 ] ) pos += 4 num_to_return , = _UNPACK_INT ( msg [ pos : pos + 4 ] ) pos += 4 docs =...
Parse message and return an OpQuery or Command .
61,804
def unpack ( cls , msg , client , server , request_id ) : flags , = _UNPACK_INT ( msg [ : 4 ] ) namespace , pos = _get_c_string ( msg , 4 ) num_to_return , = _UNPACK_INT ( msg [ pos : pos + 4 ] ) pos += 4 cursor_id , = _UNPACK_LONG ( msg [ pos : pos + 8 ] ) return OpGetMore ( namespace = namespace , flags = flags , _cl...
Parse message and return an OpGetMore .
61,805
def unpack ( cls , msg , client , server , _ ) : num_of_cursor_ids , = _UNPACK_INT ( msg [ 4 : 8 ] ) cursor_ids = [ ] pos = 8 for _ in range ( num_of_cursor_ids ) : cursor_ids . append ( _UNPACK_INT ( msg [ pos : pos + 4 ] ) [ 0 ] ) pos += 4 return OpKillCursors ( _client = client , cursor_ids = cursor_ids , _server = ...
Parse message and return an OpKillCursors .
61,806
def unpack ( cls , msg , client , server , request_id ) : flags , = _UNPACK_INT ( msg [ : 4 ] ) namespace , pos = _get_c_string ( msg , 4 ) docs = bson . decode_all ( msg [ pos : ] , CODEC_OPTIONS ) return cls ( * docs , namespace = namespace , flags = flags , _client = client , request_id = request_id , _server = serv...
Parse message and return an OpInsert .
61,807
def reply_bytes ( self , request ) : flags = struct . pack ( "<i" , self . _flags ) cursor_id = struct . pack ( "<q" , self . _cursor_id ) starting_from = struct . pack ( "<i" , self . _starting_from ) number_returned = struct . pack ( "<i" , len ( self . _docs ) ) reply_id = random . randint ( 0 , 1000000 ) response_t...
Take a Request and return an OP_REPLY message as bytes .
61,808
def reply_bytes ( self , request ) : flags = struct . pack ( "<I" , self . _flags ) payload_type = struct . pack ( "<b" , 0 ) payload_data = bson . BSON . encode ( self . doc ) data = b'' . join ( [ flags , payload_type , payload_data ] ) reply_id = random . randint ( 0 , 1000000 ) response_to = request . request_id he...
Take a Request and return an OP_MSG message as bytes .
61,809
def run ( self ) : self . _listening_sock , self . _address = ( bind_domain_socket ( self . _address ) if self . _uds_path else bind_tcp_socket ( self . _address ) ) if self . _ssl : certfile = os . path . join ( os . path . dirname ( __file__ ) , 'server.pem' ) self . _listening_sock = _ssl . wrap_socket ( self . _lis...
Begin serving . Returns the bound port or 0 for domain socket .
61,810
def stop ( self ) : self . _stopped = True threads = [ self . _accept_thread ] threads . extend ( self . _server_threads ) self . _listening_sock . close ( ) for sock in list ( self . _server_socks ) : try : sock . shutdown ( socket . SHUT_RDWR ) except socket . error : pass try : sock . close ( ) except socket . error...
Stop serving . Always call this to clean up after yourself .
61,811
def receives ( self , * args , ** kwargs ) : timeout = kwargs . pop ( 'timeout' , self . _request_timeout ) end = time . time ( ) + timeout matcher = Matcher ( * args , ** kwargs ) while not self . _stopped : try : request = self . _request_q . get ( timeout = 0.05 ) except Empty : if time . time ( ) > end : raise Asse...
Pop the next Request and assert it matches .
61,812
def autoresponds ( self , matcher , * args , ** kwargs ) : return self . _insert_responder ( "top" , matcher , * args , ** kwargs )
Send a canned reply to all matching client requests . matcher is a Matcher or a command name or an instance of OpInsert OpQuery etc .
61,813
def append_responder ( self , matcher , * args , ** kwargs ) : return self . _insert_responder ( "bottom" , matcher , * args , ** kwargs )
Add a responder of last resort .
61,814
def uri ( self ) : if self . _uds_path : uri = 'mongodb://%s' % ( quote_plus ( self . _uds_path ) , ) else : uri = 'mongodb://%s' % ( format_addr ( self . _address ) , ) return uri + '/?ssl=true' if self . _ssl else uri
Connection string to pass to ~pymongo . mongo_client . MongoClient .
61,815
def _accept_loop ( self ) : self . _listening_sock . setblocking ( 0 ) while not self . _stopped and not _shutting_down : try : if select . select ( [ self . _listening_sock . fileno ( ) ] , [ ] , [ ] , 1 ) : client , client_addr = self . _listening_sock . accept ( ) client . setblocking ( True ) self . _log ( 'connect...
Accept client connections and spawn a thread for each .
61,816
def _server_loop ( self , client , client_addr ) : while not self . _stopped and not _shutting_down : try : with self . _unlock ( ) : request = mock_server_receive_request ( client , self ) self . _requests_count += 1 self . _log ( '%d\t%r' % ( request . client_port , request ) ) for responder in reversed ( self . _aut...
Read requests from one client socket client .
61,817
def check_password ( self , username , password ) : try : if SUPPORTS_VERIFY : kerberos . checkPassword ( username . lower ( ) , password , getattr ( settings , "KRB5_SERVICE" , "" ) , getattr ( settings , "KRB5_REALM" , "" ) , getattr ( settings , "KRB5_VERIFY_KDC" , True ) ) else : kerberos . checkPassword ( username...
The actual password checking logic . Separated from the authenticate code from Django for easier updating
61,818
def main ( ) : from optparse import OptionParser parser = OptionParser ( 'Start mock MongoDB server' ) parser . add_option ( '-p' , '--port' , dest = 'port' , default = 27017 , help = 'port on which mock mongod listens' ) parser . add_option ( '-q' , '--quiet' , action = 'store_false' , dest = 'verbose' , default = Tru...
Start an interactive MockupDB .
61,819
def _initialize_distance_grid ( self ) : p = [ self . _grid_distance ( i ) for i in range ( self . num_neurons ) ] return np . array ( p )
Initialize the distance grid by calls to _grid_dist .
61,820
def _grid_distance ( self , index ) : dimensions = np . cumprod ( self . map_dimensions [ 1 : : ] [ : : - 1 ] ) [ : : - 1 ] coord = [ ] for idx , dim in enumerate ( dimensions ) : if idx != 0 : value = ( index % dimensions [ idx - 1 ] ) // dim else : value = index // dim coord . append ( value ) coord . append ( index ...
Calculate the distance grid for a single index position .
61,821
def topographic_error ( self , X , batch_size = 1 ) : dist = self . transform ( X , batch_size ) res = dist . argsort ( 1 ) [ : , : 2 ] dgrid = self . distance_grid . reshape ( self . num_neurons , self . num_neurons ) res = np . asarray ( [ dgrid [ x , y ] for x , y in res ] ) return np . sum ( res > 1.0 ) / len ( res...
Calculate the topographic error .
61,822
def neighbors ( self , distance = 2.0 ) : dgrid = self . distance_grid . reshape ( self . num_neurons , self . num_neurons ) for x , y in zip ( * np . nonzero ( dgrid <= distance ) ) : if x != y : yield x , y
Get all neighbors for all neurons .
61,823
def neighbor_difference ( self ) : differences = np . zeros ( self . num_neurons ) num_neighbors = np . zeros ( self . num_neurons ) distance , _ = self . distance_function ( self . weights , self . weights ) for x , y in self . neighbors ( ) : differences [ x ] += distance [ x , y ] num_neighbors [ x ] += 1 return dif...
Get the euclidean distance between a node and its neighbors .
61,824
def spread ( self , X ) : distance , _ = self . distance_function ( X , self . weights ) dists_per_neuron = defaultdict ( list ) for x , y in zip ( np . argmin ( distance , 1 ) , distance ) : dists_per_neuron [ x ] . append ( y [ x ] ) out = np . zeros ( self . num_neurons ) average_spread = { k : np . mean ( v ) for k...
Calculate the average spread for each node .
61,825
def receptive_field ( self , X , identities , max_len = 10 , threshold = 0.9 , batch_size = 1 ) : receptive_fields = defaultdict ( list ) predictions = self . predict ( X , batch_size ) if len ( predictions ) != len ( identities ) : raise ValueError ( "X and identities are not the same length: " "{0} and {1}" . format ...
Calculate the receptive field of the SOM on some data .
61,826
def invert_projection ( self , X , identities ) : distances = self . transform ( X ) if len ( distances ) != len ( identities ) : raise ValueError ( "X and identities are not the same length: " "{0} and {1}" . format ( len ( X ) , len ( identities ) ) ) node_match = [ ] for d in distances . __getattribute__ ( self . ar...
Calculate the inverted projection .
61,827
def map_weights ( self ) : first_dim = self . map_dimensions [ 0 ] if len ( self . map_dimensions ) != 1 : second_dim = np . prod ( self . map_dimensions [ 1 : ] ) else : second_dim = 1 return self . weights . reshape ( ( first_dim , second_dim , self . data_dimensionality ) )
Reshaped weights for visualization .
61,828
def load ( cls , path ) : data = json . load ( open ( path ) ) weights = data [ 'weights' ] weights = np . asarray ( weights , dtype = np . float64 ) s = cls ( data [ 'map_dimensions' ] , data [ 'params' ] [ 'lr' ] [ 'orig' ] , data [ 'data_dimensionality' ] , influence = data [ 'params' ] [ 'infl' ] [ 'orig' ] , lr_la...
Load a SOM from a JSON file saved with this package ..
61,829
def remove_dirs ( self , directory ) : LOG . info ( 'Removing directory [ %s ]' , directory ) local_files = self . _drectory_local_files ( directory = directory ) for file_name in local_files : try : os . remove ( file_name [ 'local_object' ] ) except OSError as exp : LOG . error ( str ( exp ) ) directories = sorted ( ...
Delete a directory recursively .
61,830
def _return_container_objects ( self ) : container_objects = self . job_args . get ( 'object' ) if container_objects : return True , [ { 'container_object' : i } for i in container_objects ] container_objects = self . job_args . get ( 'objects_file' ) if container_objects : container_objects = os . path . expanduser ( ...
Return a list of objects to delete .
61,831
def _index_fs ( self ) : indexed_objects = self . _return_deque ( ) directory = self . job_args . get ( 'directory' ) if directory : indexed_objects = self . _return_deque ( deque = indexed_objects , item = self . _drectory_local_files ( directory = directory ) ) object_names = self . job_args . get ( 'object' ) if obj...
Returns a deque object full of local file system items .
61,832
def match_filter ( self , idx_list , pattern , dict_type = False , dict_key = 'name' ) : if dict_type is False : return self . _return_deque ( [ obj for obj in idx_list if re . search ( pattern , obj ) ] ) elif dict_type is True : return self . _return_deque ( [ obj for obj in idx_list if re . search ( pattern , obj . ...
Return Matched items in indexed files .
61,833
def print_horiz_table ( self , data ) : return_objects = list ( ) fields = self . job_args . get ( 'fields' ) if not fields : fields = set ( ) for item_dict in data : for field_item in item_dict . keys ( ) : fields . add ( field_item ) fields = sorted ( fields ) for obj in data : item_struct = dict ( ) for item in fiel...
Print a horizontal pretty table from data .
61,834
def print_virt_table ( self , data ) : table = prettytable . PrettyTable ( ) keys = sorted ( data . keys ( ) ) table . add_column ( 'Keys' , keys ) table . add_column ( 'Values' , [ data . get ( i ) for i in keys ] ) for tbl in table . align . keys ( ) : table . align [ tbl ] = 'l' self . printer ( table )
Print a vertical pretty table from data .
61,835
def printer ( self , message , color_level = 'info' ) : if self . job_args . get ( 'colorized' ) : print ( cloud_utils . return_colorized ( msg = message , color = color_level ) ) else : print ( message )
Print Messages and Log it .
61,836
def _get_method ( method ) : module = method . split ( ':' ) _module_import = module [ 0 ] class_name = module [ - 1 ] module_import = __import__ ( _module_import , fromlist = [ class_name ] ) return getattr ( module_import , class_name )
Return an imported object .
61,837
def run_manager ( self , job_override = None ) : for arg_name , arg_value in self . job_args . items ( ) : if arg_name . endswith ( '_headers' ) : if isinstance ( arg_value , list ) : self . job_args [ arg_name ] = self . _list_headers ( headers = arg_value ) elif not arg_name : self . job_args [ arg_name ] = self . _s...
The run manager .
61,838
def range_initialization ( X , num_weights ) : X_ = X . reshape ( - 1 , X . shape [ - 1 ] ) min_val , max_val = X_ . min ( 0 ) , X_ . max ( 0 ) data_range = max_val - min_val return data_range * np . random . rand ( num_weights , X . shape [ - 1 ] ) + min_val
Initialize the weights by calculating the range of the data .
61,839
def fit ( self , X , num_epochs = 10 , updates_epoch = None , stop_param_updates = dict ( ) , batch_size = 1 , show_progressbar = False , show_epoch = False , refit = True ) : if self . data_dimensionality is None : self . data_dimensionality = X . shape [ - 1 ] self . weights = np . zeros ( ( self . num_neurons , self...
Fit the learner to some data .
61,840
def _init_weights ( self , X ) : X = np . asarray ( X , dtype = np . float64 ) if self . scaler is not None : X = self . scaler . fit_transform ( X ) if self . initializer is not None : self . weights = self . initializer ( X , self . num_neurons ) for v in self . params . values ( ) : v [ 'value' ] = v [ 'orig' ] retu...
Set the weights and normalize data before starting training .
61,841
def _pre_train ( self , stop_param_updates , num_epochs , updates_epoch ) : updates = { k : stop_param_updates . get ( k , num_epochs ) * updates_epoch for k , v in self . params . items ( ) } single_steps = { k : np . exp ( - ( ( 1.0 - ( 1.0 / v ) ) ) * self . params [ k ] [ 'factor' ] ) for k , v in updates . items (...
Set parameters and constants before training .
61,842
def fit_predict ( self , X , num_epochs = 10 , updates_epoch = 10 , stop_param_updates = dict ( ) , batch_size = 1 , show_progressbar = False ) : self . fit ( X , num_epochs , updates_epoch , stop_param_updates , batch_size , show_progressbar ) return self . predict ( X , batch_size = batch_size )
First fit then predict .
61,843
def fit_transform ( self , X , num_epochs = 10 , updates_epoch = 10 , stop_param_updates = dict ( ) , batch_size = 1 , show_progressbar = False , show_epoch = False ) : self . fit ( X , num_epochs , updates_epoch , stop_param_updates , batch_size , show_progressbar , show_epoch ) return self . transform ( X , batch_siz...
First fit then transform .
61,844
def _update_params ( self , constants ) : for k , v in constants . items ( ) : self . params [ k ] [ 'value' ] *= v influence = self . _calculate_influence ( self . params [ 'infl' ] [ 'value' ] ) return influence * self . params [ 'lr' ] [ 'value' ]
Update params and return new influence .
61,845
def _create_batches ( self , X , batch_size , shuffle_data = True ) : if shuffle_data : X = shuffle ( X ) if batch_size > X . shape [ 0 ] : batch_size = X . shape [ 0 ] max_x = int ( np . ceil ( X . shape [ 0 ] / batch_size ) ) X = np . resize ( X , ( max_x , batch_size , X . shape [ - 1 ] ) ) return X
Create batches out of a sequence of data .
61,846
def _propagate ( self , x , influences , ** kwargs ) : activation , difference_x = self . forward ( x ) update = self . backward ( difference_x , influences , activation ) if update . shape [ 0 ] == 1 : self . weights += update [ 0 ] else : self . weights += update . mean ( 0 ) return activation
Propagate a single batch of examples through the network .
61,847
def _check_input ( self , X ) : if np . ndim ( X ) == 1 : X = np . reshape ( X , ( 1 , - 1 ) ) if X . ndim != 2 : raise ValueError ( "Your data is not a 2D matrix. " "Actual size: {0}" . format ( X . shape ) ) if X . shape [ 1 ] != self . data_dimensionality : raise ValueError ( "Your data size != weight dim: {0}, " "e...
Check the input for validity .
61,848
def transform ( self , X , batch_size = 100 , show_progressbar = False ) : X = self . _check_input ( X ) batched = self . _create_batches ( X , batch_size , shuffle_data = False ) activations = [ ] prev = self . _init_prev ( batched ) for x in tqdm ( batched , disable = not show_progressbar ) : prev = self . forward ( ...
Transform input to a distance matrix by measuring the L2 distance .
61,849
def predict ( self , X , batch_size = 1 , show_progressbar = False ) : dist = self . transform ( X , batch_size , show_progressbar ) res = dist . __getattribute__ ( self . argfunc ) ( 1 ) return res
Predict the BMU for each input data .
61,850
def quantization_error ( self , X , batch_size = 1 ) : dist = self . transform ( X , batch_size ) res = dist . __getattribute__ ( self . valfunc ) ( 1 ) return res
Calculate the quantization error .
61,851
def load ( cls , path ) : data = json . load ( open ( path ) ) weights = data [ 'weights' ] weights = np . asarray ( weights , dtype = np . float64 ) s = cls ( data [ 'num_neurons' ] , data [ 'data_dimensionality' ] , data [ 'params' ] [ 'lr' ] [ 'orig' ] , neighborhood = data [ 'params' ] [ 'infl' ] [ 'orig' ] , valfu...
Load a SOM from a JSON file saved with this package .
61,852
def save ( self , path ) : to_save = { } for x in self . param_names : attr = self . __getattribute__ ( x ) if type ( attr ) == np . ndarray : attr = [ [ float ( x ) for x in row ] for row in attr ] elif isinstance ( attr , types . FunctionType ) : attr = attr . __name__ to_save [ x ] = attr json . dump ( to_save , ope...
Save a SOM to a JSON file .
61,853
def get_authversion ( job_args ) : _version = job_args . get ( 'os_auth_version' ) for version , variants in AUTH_VERSION_MAP . items ( ) : if _version in variants : authversion = job_args [ 'os_auth_version' ] = version return authversion else : raise exceptions . AuthenticationProblem ( "Auth Version must be one of %...
Get or infer the auth version .
61,854
def get_headers ( self ) : try : return { 'X-Auth-User' : self . job_args [ 'os_user' ] , 'X-Auth-Key' : self . job_args [ 'os_apikey' ] } except KeyError as exp : raise exceptions . AuthenticationProblem ( 'Missing Credentials. Error: %s' , exp )
Setup headers for authentication request .
61,855
def auth_request ( self , url , headers , body ) : return self . req . post ( url , headers , body = body )
Perform auth request for token .
61,856
def parse_reqtype ( self ) : if self . job_args [ 'os_auth_version' ] == 'v1.0' : return dict ( ) else : setup = { 'username' : self . job_args . get ( 'os_user' ) } prefixes = self . job_args . get ( 'os_prefix' ) if self . job_args . get ( 'os_token' ) is not None : auth_body = { 'auth' : { 'token' : { 'id' : self . ...
Return the authentication body .
61,857
def execute ( ) : if len ( sys . argv ) <= 1 : raise SystemExit ( 'No Arguments provided. use [--help] for more information.' ) _args = arguments . ArgumentParserator ( arguments_dict = turbolift . ARGUMENTS , env_name = 'TURBO' , epilog = turbolift . VINFO , title = 'Turbolift' , detail = 'Multiprocessing Swift CLI to...
This is the run section of the application Turbolift .
61,858
def write ( self , log_file , msg ) : try : with open ( log_file , 'a' ) as LogFile : LogFile . write ( msg + os . linesep ) except : raise Exception ( 'Error Configuring PyLogger.TextStorage Class.' ) return os . path . isfile ( log_file )
Append message to . log file
61,859
def read ( self , log_file ) : if os . path . isdir ( os . path . dirname ( log_file ) ) and os . path . isfile ( log_file ) : with open ( log_file , 'r' ) as LogFile : data = LogFile . readlines ( ) data = "" . join ( line for line in data ) else : data = '' return data
Read messages from . log file
61,860
def fit ( self , X ) : if X . ndim > 2 : X = X . reshape ( ( np . prod ( X . shape [ : - 1 ] ) , X . shape [ - 1 ] ) ) self . mean = X . mean ( 0 ) self . std = X . std ( 0 ) self . is_fit = True return self
Fit the scaler based on some data .
61,861
def transform ( self , X ) : if not self . is_fit : raise ValueError ( "The scaler has not been fit yet." ) return ( X - self . mean ) / ( self . std + 10e-7 )
Transform your data to zero mean unit variance .
61,862
def stupid_hack ( most = 10 , wait = None ) : if wait is not None : time . sleep ( wait ) else : time . sleep ( random . randrange ( 1 , most ) )
Return a random time between 1 - 10 Seconds .
61,863
def time_stamp ( ) : fmt = '%Y-%m-%dT%H:%M:%S.%f' date = datetime . datetime date_delta = datetime . timedelta now = datetime . datetime . utcnow ( ) return fmt , date , date_delta , now
Setup time functions
61,864
def unique_list_dicts ( dlist , key ) : return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) )
Return a list of dictionaries which are sorted for only unique entries .
61,865
def quoter ( obj ) : try : try : return urllib . quote ( obj ) except AttributeError : return urllib . parse . quote ( obj ) except KeyError : return obj
Return a Quoted URL .
61,866
def start ( self ) : LOG . info ( 'Clone warm up...' ) self . _target_auth ( ) last_list_obj = None while True : self . indicator_options [ 'msg' ] = 'Gathering object list' with indicator . Spinner ( ** self . indicator_options ) : objects_list = self . _list_contents ( single_page_return = True , last_obj = last_list...
Clone objects from one container to another .
61,867
def authenticate ( job_args ) : job_args = utils . check_auth_plugin ( job_args ) auth_version = utils . get_authversion ( job_args = job_args ) auth_headers = { 'Content-Type' : 'application/json' , 'Accept' : 'application/json' } auth_headers . update ( job_args [ 'base_headers' ] ) if auth_version == 'v1.0' : auth =...
Authentication For Openstack API .
61,868
def getConfig ( self , key ) : if hasattr ( self , key ) : return getattr ( self , key ) else : return False
Get a Config Value
61,869
def addFilter ( self , filter ) : self . FILTERS . append ( filter ) return "FILTER#{}" . format ( len ( self . FILTERS ) - 1 )
Register Custom Filter
61,870
def addAction ( self , action ) : self . ACTIONS . append ( action ) return "ACTION#{}" . format ( len ( self . ACTIONS ) - 1 )
Register Custom Action
61,871
def removeFilter ( self , filter ) : filter = filter . split ( '#' ) del self . FILTERS [ int ( filter [ 1 ] ) ] return True
Remove Registered Filter
61,872
def removeAction ( self , action ) : action = action . split ( '#' ) del self . ACTIONS [ int ( action [ 1 ] ) ] return True
Remove Registered Action
61,873
def info ( self , msg ) : self . _execActions ( 'info' , msg ) msg = self . _execFilters ( 'info' , msg ) self . _processMsg ( 'info' , msg ) self . _sendMsg ( 'info' , msg )
Log Info Messages
61,874
def warning ( self , msg ) : self . _execActions ( 'warning' , msg ) msg = self . _execFilters ( 'warning' , msg ) self . _processMsg ( 'warning' , msg ) self . _sendMsg ( 'warning' , msg )
Log Warning Messages
61,875
def error ( self , msg ) : self . _execActions ( 'error' , msg ) msg = self . _execFilters ( 'error' , msg ) self . _processMsg ( 'error' , msg ) self . _sendMsg ( 'error' , msg )
Log Error Messages
61,876
def critical ( self , msg ) : self . _execActions ( 'critical' , msg ) msg = self . _execFilters ( 'critical' , msg ) self . _processMsg ( 'critical' , msg ) self . _sendMsg ( 'critical' , msg )
Log Critical Messages
61,877
def log ( self , msg ) : self . _execActions ( 'log' , msg ) msg = self . _execFilters ( 'log' , msg ) self . _processMsg ( 'log' , msg ) self . _sendMsg ( 'log' , msg )
Log Normal Messages
61,878
def _processMsg ( self , type , msg ) : now = datetime . datetime . now ( ) if self . LOG_FILE_PATH == '' : self . LOG_FILE_PATH = os . path . dirname ( os . path . abspath ( __file__ ) ) + '/' log_file = self . LOG_FILE_PATH + now . strftime ( self . LOG_FILE_FORMAT ) + '.log' msg = self . LOG_MESSAGE_FORMAT . format ...
Process Debug Messages
61,879
def _configMailer ( self ) : self . _MAILER = Mailer ( self . MAILER_HOST , self . MAILER_PORT ) self . _MAILER . login ( self . MAILER_USER , self . MAILER_PWD )
Config Mailer Class
61,880
def _sendMsg ( self , type , msg ) : if self . ALERT_STATUS and type in self . ALERT_TYPES : self . _configMailer ( ) self . _MAILER . send ( self . MAILER_FROM , self . ALERT_EMAIL , self . ALERT_SUBJECT , msg )
Send Alert Message To Emails
61,881
def _execFilters ( self , type , msg ) : for filter in self . FILTERS : msg = filter ( type , msg ) return msg
Execute Registered Filters
61,882
def _execActions ( self , type , msg ) : for action in self . ACTIONS : action ( type , msg )
Execute Registered Actions
61,883
def auth_plugins ( auth_plugins = None ) : __auth_plugins__ = { 'os_rax_auth' : { 'os_auth_url' : 'https://identity.api.rackspacecloud.com/v2.0/' 'tokens' , 'os_prefix' : { 'os_apikey' : 'RAX-KSKEY:apiKeyCredentials' , 'os_password' : 'passwordCredentials' } , 'args' : { 'commands' : [ '--os-rax-auth' ] , 'choices' : [...
Authentication plugins .
61,884
def check_basestring ( item ) : try : return isinstance ( item , ( basestring , unicode ) ) except NameError : return isinstance ( item , str )
Return bol on string check item .
61,885
def predict_distance ( self , X , batch_size = 1 , show_progressbar = False ) : X = self . _check_input ( X ) X_shape = reduce ( np . multiply , X . shape [ : - 1 ] , 1 ) batched = self . _create_batches ( X , batch_size , shuffle_data = False ) activations = [ ] activation = self . _init_prev ( batched ) for x in tqdm...
Predict distances to some input data .
61,886
def generate ( self , num_to_generate , starting_place ) : res = [ ] activ = starting_place [ None , : ] index = activ . __getattribute__ ( self . argfunc ) ( 1 ) item = self . weights [ index ] for x in range ( num_to_generate ) : activ = self . forward ( item , prev_activation = activ ) [ 0 ] index = activ . __getatt...
Generate data based on some initial position .
61,887
def forward ( self , x , ** kwargs ) : prev = kwargs [ 'prev_activation' ] distance_x , diff_x = self . distance_function ( x , self . weights ) distance_y , diff_y = self . distance_function ( prev , self . context_weights ) x_ = distance_x * self . alpha y_ = distance_y * self . beta activation = np . exp ( - ( x_ + ...
Perform a forward pass through the network .
61,888
def load ( cls , path ) : data = json . load ( open ( path ) ) weights = data [ 'weights' ] weights = np . asarray ( weights , dtype = np . float64 ) try : context_weights = data [ 'context_weights' ] context_weights = np . asarray ( context_weights , dtype = np . float64 ) except KeyError : context_weights = np . zero...
Load a recursive SOM from a JSON file .
61,889
def _return_base_data ( self , url , container , container_object = None , container_headers = None , object_headers = None ) : headers = self . job_args [ 'base_headers' ] headers . update ( { 'X-Auth-Token' : self . job_args [ 'os_token' ] } ) _container_uri = url . geturl ( ) . rstrip ( '/' ) if container : _contain...
Return headers and a parsed url .
61,890
def _chunk_putter ( self , uri , open_file , headers = None ) : count = 0 dynamic_hash = hashlib . sha256 ( self . job_args . get ( 'container' ) ) dynamic_hash = dynamic_hash . hexdigest ( ) while True : file_object = open_file . read ( self . job_args . get ( 'chunk_size' ) ) if not file_object : break with io . Byte...
Make many PUT request for a single chunked object .
61,891
def _putter ( self , uri , headers , local_object = None ) : if not local_object : return self . http . put ( url = uri , headers = headers ) with open ( local_object , 'rb' ) as f_open : large_object_size = self . job_args . get ( 'large_object_size' ) if not large_object_size : large_object_size = 5153960756 if os . ...
Place object into the container .
61,892
def _header_poster ( self , uri , headers ) : resp = self . http . post ( url = uri , body = None , headers = headers ) self . _resp_exception ( resp = resp ) return resp
POST Headers on a specified object in the container .
61,893
def _obj_index ( self , uri , base_path , marked_path , headers , spr = False ) : object_list = list ( ) l_obj = None container_uri = uri . geturl ( ) while True : marked_uri = urlparse . urljoin ( container_uri , marked_path ) resp = self . http . get ( url = marked_uri , headers = headers ) self . _resp_exception ( r...
Return an index of objects from within the container .
61,894
def _list_getter ( self , uri , headers , last_obj = None , spr = False ) : base_path = marked_path = ( '%s?limit=10000&format=json' % uri . path ) if last_obj : marked_path = self . _last_marker ( base_path = base_path , last_object = cloud_utils . quoter ( last_obj ) ) file_list = self . _obj_index ( uri = uri , base...
Get a list of all objects in a container .
61,895
def _resp_exception ( self , resp ) : message = [ 'Url: [ %s ] Reason: [ %s ] Request: [ %s ] Status Code: [ %s ]. ' , resp . url , resp . reason , resp . request , resp . status_code ] if not hasattr ( resp , 'status_code' ) : message [ 0 ] += 'No Status to check. Turbolift will retry...' raise exceptions . SystemProb...
If we encounter an exception in our upload .
61,896
def list_items ( self , url , container = None , last_obj = None , spr = False ) : headers , container_uri = self . _return_base_data ( url = url , container = container ) if container : resp = self . _header_getter ( uri = container_uri , headers = headers ) if resp . status_code == 404 : LOG . info ( 'Container [ %s ...
Builds a long list of objects found in a container .
61,897
def update_object ( self , url , container , container_object , object_headers , container_headers ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object , container_headers = container_headers , object_headers = object_headers , ) return self . ...
Update an existing object in a swift container .
61,898
def container_cdn_command ( self , url , container , container_object , cdn_headers ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_object = container_object , object_headers = cdn_headers ) if self . job_args . get ( 'purge' ) : return self . _deleter ( uri = cont...
Command your CDN enabled Container .
61,899
def put_container ( self , url , container , container_headers = None ) : headers , container_uri = self . _return_base_data ( url = url , container = container , container_headers = container_headers ) resp = self . _header_getter ( uri = container_uri , headers = headers ) if resp . status_code == 404 : return self ....
Create a container if it is not Found .