idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
57,900
def by_current_session ( cls ) : session = Session . current_session ( ) if session is None : return None return cls . where_id ( session . user_id )
Returns current user session
57,901
def AdvancedJsonify ( data , status_code ) : response = jsonify ( data ) response . status_code = status_code return response
Advanced Jsonify Response Maker
57,902
def response ( self , callback = None ) : if not callback : callback = type ( self ) . AdvancedJsonify resp = { "status" : "error" , "message" : self . message } if self . step : resp [ "step" ] = self . step self . LOGGER . error ( self . message , extra = { "step" : self . step , "context" : self . context } ) return callback ( resp , status_code = self . code )
View representation of the object
57,903
def __json ( self ) : if self . exclude_list is None : self . exclude_list = [ ] fields = { } for key , item in vars ( self ) . items ( ) : if hasattr ( self , '_sa_instance_state' ) : if len ( orm . attributes . instance_state ( self ) . unloaded ) > 0 : mapper = inspect ( self ) for column in mapper . attrs : column . key column . value if str ( key ) . startswith ( '_' ) or key in self . exclude_list : continue fields [ key ] = item obj = Json . safe_object ( fields ) return str ( obj )
Using the exclude lists convert fields to a string .
57,904
def manage ( cls , entity , unit_of_work ) : if hasattr ( entity , '__everest__' ) : if not unit_of_work is entity . __everest__ . unit_of_work : raise ValueError ( 'Trying to register an entity that has been ' 'registered with another session!' ) else : entity . __everest__ = cls ( entity , unit_of_work )
Manages the given entity under the given Unit Of Work .
57,905
def release ( cls , entity , unit_of_work ) : if not hasattr ( entity , '__everest__' ) : raise ValueError ( 'Trying to unregister an entity that has not ' 'been registered yet!' ) elif not unit_of_work is entity . __everest__ . unit_of_work : raise ValueError ( 'Trying to unregister an entity that has been ' 'registered with another session!' ) delattr ( entity , '__everest__' )
Releases the given entity from management under the given Unit Of Work .
57,906
def get_state_data ( cls , entity ) : 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 ] )
Returns the state data for the given entity .
57,907
def set_state_data ( cls , entity , data ) : attr_names = get_domain_class_attribute_names ( type ( entity ) ) nested_items = [ ] for attr , new_attr_value in iteritems_ ( data ) : if not attr . entity_attr in attr_names : raise ValueError ( 'Can not set attribute "%s" for entity ' '"%s".' % ( attr . entity_attr , entity ) ) if '.' in attr . entity_attr : nested_items . append ( ( attr , new_attr_value ) ) continue else : setattr ( entity , attr . entity_attr , new_attr_value ) for attr , new_attr_value in nested_items : try : set_nested_attribute ( entity , attr . entity_attr , new_attr_value ) except AttributeError as exc : if not new_attr_value is None : raise exc
Sets the state data for the given entity to the given data .
57,908
def transfer_state_data ( cls , source_entity , target_entity ) : state_data = cls . get_state_data ( source_entity ) cls . set_state_data ( target_entity , state_data )
Transfers instance state data from the given source entity to the given target entity .
57,909
def __set_data ( self , data ) : ent = self . __entity_ref ( ) self . set_state_data ( ent , data )
Sets the given state data on the given entity of the given class .
57,910
def pretty_print ( self , carrot = True ) : output = [ '\n' ] output . extend ( [ line . pretty_print ( ) for line in self . partpyobj . get_surrounding_lines ( 1 , 0 ) ] ) if carrot : output . append ( '\n' + ( ' ' * ( self . partpyobj . col + 5 ) ) + '^' + '\n' ) if self . partpymsg : output . append ( self . partpymsg ) return '' . join ( output )
Print the previous and current line with line numbers and a carret under the current character position .
57,911
def get_event ( self , num ) : if num < 0 or num >= self . params [ "events_num" ] : raise IndexError ( "Index out of range [0:%s]" % ( self . params [ "events_num" ] ) ) ch_num = self . params [ 'channel_number' ] ev_size = self . params [ 'b_size' ] event = { } self . file . seek ( 7168 + num * ( 96 + 2 * ch_num * ev_size ) ) event [ "text_hdr" ] = self . file . read ( 64 ) event [ "ev_num" ] = struct . unpack ( 'I' , self . file . read ( 4 ) ) [ 0 ] self . file . read ( 4 ) start_time = struct . unpack ( 'Q' , self . file . read ( 8 ) ) [ 0 ] event [ "start_time" ] = datetime . fromtimestamp ( start_time ) ns_since_epoch = struct . unpack ( 'Q' , self . file . read ( 8 ) ) [ 0 ] if ns_since_epoch : event [ 'ns_since_epoch' ] = ns_since_epoch self . file . read ( 8 ) event_data = self . file . read ( 2 * ev_size * ch_num ) event [ "data" ] = np . fromstring ( event_data , np . short ) return event
Extract event from dataset .
57,912
def update_event_data ( self , num , data ) : if num < 0 or num >= self . params [ "events_num" ] : raise IndexError ( "Index out of range [0:%s]" % ( self . params [ "events_num" ] ) ) if isinstance ( data , np . ndarray ) : raise TypeError ( "data should be np.ndarray" ) if data . dtype != np . short : raise TypeError ( "data array dtype should be dtype('int16')" ) ch_num = self . params [ 'channel_number' ] ev_size = self . params [ 'b_size' ] if data . shape != ( ch_num * ev_size , ) : raise Exception ( "data should contain same number of elements " "(%s)" % ( ch_num * ev_size ) ) self . file . seek ( 7168 + num * ( 96 + 2 * ch_num * ev_size ) + 96 ) self . file . write ( data . tostring ( ) ) self . file . flush ( )
Update event data in dataset .
57,913
def str_to_pool ( upstream ) : name = re . search ( 'upstream +(.*?) +{' , upstream ) . group ( 1 ) nodes = re . findall ( 'server +(.*?);' , upstream ) return name , nodes
Given a string containing an nginx upstream section return the pool name and list of nodes .
57,914
def calculate_vss ( self , method = None ) : if self . variance == float ( 0 ) : return self . vss else : if method == "gaussian" or method is None : return gauss ( self . vss , self . variance ) elif method == "random" : return uniform ( self . vss - self . variance , self . vss + self . variance ) else : raise ValueError ( "Method of vss calculation not recognized, please use 'gaussian' or 'random'" )
Calculate the vertical swimming speed of this behavior . Takes into account the vertical swimming speed and the variance .
57,915
def _check_experiment ( self , name ) : with h5py . File ( name = self . path , mode = "r" ) as h5 : sigpath = "/Experiments/{}/metadata/Signal" . format ( name ) signal_type = h5 [ sigpath ] . attrs [ "signal_type" ] if signal_type != "hologram" : msg = "Signal type '{}' not supported: {}[{}]" . format ( signal_type , self . path , name ) warnings . warn ( msg , WrongSignalTypeWarnging ) return signal_type == "hologram"
Check the signal type of the experiment
57,916
def _get_experiments ( self ) : explist = [ ] with h5py . File ( name = self . path , mode = "r" ) as h5 : if "Experiments" not in h5 : msg = "Group 'Experiments' not found in {}." . format ( self . path ) raise HyperSpyNoDataFoundError ( msg ) for name in h5 [ "Experiments" ] : if self . _check_experiment ( name ) : explist . append ( name ) explist . sort ( ) if not explist : msg = "No supported data found: {}" . format ( self . path ) raise HyperSpyNoDataFoundError ( msg ) return explist
Get all experiments from the hdf5 file
57,917
def verify ( path ) : valid = False try : h5 = h5py . File ( path , mode = "r" ) except ( OSError , IsADirectoryError ) : pass else : if ( "file_format" in h5 . attrs and h5 . attrs [ "file_format" ] . lower ( ) == "hyperspy" and "Experiments" in h5 ) : valid = True return valid
Verify that path has the HyperSpy file format
57,918
def transform ( self , df ) : for name , function in self . outputs : df [ name ] = function ( df )
Transforms a DataFrame in place . Computes all outputs of the DataFrame .
57,919
def pop ( self ) : node = self . nodes . pop ( ) self . __keys . remove ( node . key )
Removes the last traversal path node from this traversal path .
57,920
def parent ( self ) : if len ( self . nodes ) > 0 : parent = self . nodes [ - 1 ] . proxy else : parent = None return parent
Returns the proxy from the last node visited on the path or None if no node has been visited yet .
57,921
def relation_operation ( self ) : if len ( self . nodes ) > 0 : rel_op = self . nodes [ - 1 ] . relation_operation else : rel_op = None return rel_op
Returns the relation operation from the last node visited on the path or None if no node has been visited yet .
57,922
def ensure_unicode ( text ) : u if isinstance ( text , str ) : try : return text . decode ( pyreadline_codepage , u"replace" ) except ( LookupError , TypeError ) : return text . decode ( u"ascii" , u"replace" ) return text
u helper to ensure that text passed to WriteConsoleW is unicode
57,923
def ensure_str ( text ) : u if isinstance ( text , unicode ) : try : return text . encode ( pyreadline_codepage , u"replace" ) except ( LookupError , TypeError ) : return text . encode ( u"ascii" , u"replace" ) return text
u Convert unicode to str using pyreadline_codepage
57,924
def unwrap_raw ( content ) : starting_symbol = get_start_symbol ( content ) ending_symbol = ']' if starting_symbol == '[' else '}' start = content . find ( starting_symbol , 0 ) end = content . rfind ( ending_symbol ) return content [ start : end + 1 ]
unwraps the callback and returns the raw content
57,925
def combine_word_list ( word_list ) : bag_of_words = collections . defaultdict ( int ) for word in word_list : bag_of_words [ word ] += 1 return bag_of_words
Combine word list into a bag - of - words .
57,926
def reduce_list_of_bags_of_words ( list_of_keyword_sets ) : bag_of_words = dict ( ) get_bag_of_words_keys = bag_of_words . keys for keyword_set in list_of_keyword_sets : for keyword in keyword_set : if keyword in get_bag_of_words_keys ( ) : bag_of_words [ keyword ] += 1 else : bag_of_words [ keyword ] = 1 return bag_of_words
Reduces a number of keyword sets to a bag - of - words .
57,927
def query_list_of_words ( target_word , list_of_words , edit_distance = 1 ) : new_list_of_words = list ( ) found_list_of_words = list ( ) append_left_keyword = new_list_of_words . append append_found_keyword = found_list_of_words . append for word in list_of_words : if len ( word ) > 6 : effective_edit_distance = edit_distance else : effective_edit_distance = 0 if abs ( len ( word ) - len ( target_word ) ) <= effective_edit_distance : if nltk . edit_distance ( word , target_word ) <= effective_edit_distance : append_found_keyword ( word ) else : append_left_keyword ( word ) else : append_left_keyword ( word ) return new_list_of_words , found_list_of_words
Checks whether a target word is within editing distance of any one in a set of keywords .
57,928
def fixup_instance ( sender , ** kwargs ) : instance = kwargs [ 'instance' ] for model_field in instance . _meta . fields : if not isinstance ( model_field , JSONAttributeField ) : continue if hasattr ( instance , '_attr_field' ) : raise FieldError ( 'multiple JSONAttributeField fields: ' 'only one is allowed per model!' ) field_name = model_field . name attrs = getattr ( instance , field_name ) if not isinstance ( attrs , JSONAttributes ) : setattr ( instance , field_name , JSONAttributes ( attrs ) ) attrs = getattr ( instance , field_name ) attrs . _instance = instance attrs . _get_from_instance = functools . partial ( getattr , instance , field_name ) instance . _attr_field = attrs if not hasattr ( instance , '_attr_field' ) : raise FieldError ( 'missing JSONAttributeField field in ' 'fixup_instance decorator' )
Cache JSONAttributes data on instance and vice versa for convenience .
57,929
def size ( self ) : if self is NULL : return 0 return 1 + self . left . size ( ) + self . right . size ( )
Recursively find size of a tree . Slow .
57,930
def find_prekeyed ( self , value , key ) : while self is not NULL : direction = cmp ( value , key ( self . value ) ) if direction < 0 : self = self . left elif direction > 0 : self = self . right elif direction == 0 : return self . value
Find a value in a node using a key function . The value is already a key .
57,931
def rotate_left ( self ) : right = self . right new = self . _replace ( right = self . right . left , red = True ) top = right . _replace ( left = new , red = self . red ) return top
Rotate the node to the left .
57,932
def flip ( self ) : left = self . left . _replace ( red = not self . left . red ) right = self . right . _replace ( red = not self . right . red ) top = self . _replace ( left = left , right = right , red = not self . red ) return top
Flip colors of a node and its children .
57,933
def balance ( self ) : if self . right . red : self = self . rotate_left ( ) if self . left . red and self . left . left . red : self = self . rotate_right ( ) if self . left . red and self . right . red : self = self . flip ( ) return self
Balance a node .
57,934
def insert ( self , value , key ) : if self is NULL : return Node ( value , NULL , NULL , True ) , True direction = cmp ( key ( value ) , key ( self . value ) ) if direction < 0 : left , insertion = self . left . insert ( value , key ) self = self . _replace ( left = left ) elif direction > 0 : right , insertion = self . right . insert ( value , key ) self = self . _replace ( right = right ) elif direction == 0 : self = self . _replace ( value = value ) insertion = False return self . balance ( ) , insertion
Insert a value into a tree rooted at the given node and return whether this was an insertion or update .
57,935
def move_red_left ( self ) : self = self . flip ( ) if self . right is not NULL and self . right . left . red : self = self . _replace ( right = self . right . rotate_right ( ) ) self = self . rotate_left ( ) . flip ( ) return self
Shuffle red to the left of a tree .
57,936
def move_red_right ( self ) : self = self . flip ( ) if self . left is not NULL and self . left . left . red : self = self . rotate_right ( ) . flip ( ) return self
Shuffle red to the right of a tree .
57,937
def delete_min ( self ) : if self . left is NULL : return NULL , self . value if not self . left . red and not self . left . left . red : self = self . move_red_left ( ) left , value = self . left . delete_min ( ) self = self . _replace ( left = left ) return self . balance ( ) , value
Delete the left - most value from a tree .
57,938
def delete_max ( self ) : if self . left . red : self = self . rotate_right ( ) if self . right is NULL : return NULL , self . value if not self . right . red and not self . right . left . red : self = self . move_red_right ( ) right , value = self . right . delete_max ( ) self = self . _replace ( right = right ) return self . balance ( ) , value
Delete the right - most value from a tree .
57,939
def delete ( self , value , key ) : if self is NULL : raise KeyError ( value ) direction = cmp ( key ( value ) , key ( self . value ) ) if direction < 0 : if ( not self . left . red and self . left is not NULL and not self . left . left . red ) : self = self . move_red_left ( ) left = self . left . delete ( value , key ) self = self . _replace ( left = left ) else : if self . left . red : self = self . rotate_right ( ) if direction == 0 and self . right is NULL : return NULL if ( not self . right . red and self . right is not NULL and not self . right . left . red ) : self = self . move_red_right ( ) if direction > 0 : right = self . right . delete ( value , key ) self = self . _replace ( right = right ) else : rnode = self . right while rnode is not NULL : rnode = rnode . left right , replacement = self . right . delete_min ( ) self = self . _replace ( value = replacement , right = right ) return self . balance ( )
Delete a value from a tree .
57,940
def pop_max ( self ) : if self . root is NULL : raise KeyError ( "pop from an empty blackjack" ) self . root , value = self . root . delete_max ( ) self . _len -= 1 return value
Remove the maximum value and return it .
57,941
def pop_min ( self ) : if self . root is NULL : raise KeyError ( "pop from an empty blackjack" ) self . root , value = self . root . delete_min ( ) self . _len -= 1 return value
Remove the minimum value and return it .
57,942
def install_readline ( hook ) : global readline_hook , readline_ref readline_hook = hook PyOS_RFP = c_void_p . from_address ( Console . GetProcAddress ( sys . dllhandle , "PyOS_ReadlineFunctionPointer" ) ) if sys . version < '2.3' : readline_ref = HOOKFUNC22 ( hook_wrapper ) else : readline_ref = HOOKFUNC23 ( hook_wrapper_23 ) func_start = c_void_p . from_address ( addressof ( readline_ref ) ) . value PyOS_RFP . value = func_start
Set up things for the interpreter to call our function like GNU readline .
57,943
def fixcoord ( self , x , y ) : u if x < 0 or y < 0 : info = CONSOLE_SCREEN_BUFFER_INFO ( ) self . GetConsoleScreenBufferInfo ( self . hout , byref ( info ) ) if x < 0 : x = info . srWindow . Right - x y = info . srWindow . Bottom + y return c_int ( y << 16 | x )
u Return a long with x and y packed inside also handle negative x and y .
57,944
def write_scrolling ( self , text , attr = None ) : u x , y = self . pos ( ) w , h = self . size ( ) scroll = 0 chunks = self . motion_char_re . split ( text ) for chunk in chunks : n = self . write_color ( chunk , attr ) if len ( chunk ) == 1 : if chunk [ 0 ] == u'\n' : x = 0 y += 1 elif chunk [ 0 ] == u'\r' : x = 0 elif chunk [ 0 ] == u'\t' : x = 8 * ( int ( x / 8 ) + 1 ) if x > w : x -= w y += 1 elif chunk [ 0 ] == u'\007' : pass elif chunk [ 0 ] == u'\010' : x -= 1 if x < 0 : y -= 1 else : x += 1 if x == w : x = 0 y += 1 if y == h : scroll += 1 y = h - 1 else : x += n l = int ( x / w ) x = x % w y += l if y >= h : scroll += y - h + 1 y = h - 1 return scroll
u write text at current cursor position while watching for scrolling . If the window scrolls because you are at the bottom of the screen buffer all positions that you are storing will be shifted by the scroll amount . For example I remember the cursor position of the prompt so that I can redraw the line but if the window scrolls the remembered position is off . This variant of write tries to keep track of the cursor position so that it will know when the screen buffer is scrolled . It returns the number of lines that the buffer scrolled .
57,945
def page ( self , attr = None , fill = u' ' ) : u if attr is None : attr = self . attr if len ( fill ) != 1 : raise ValueError info = CONSOLE_SCREEN_BUFFER_INFO ( ) self . GetConsoleScreenBufferInfo ( self . hout , byref ( info ) ) if info . dwCursorPosition . X != 0 or info . dwCursorPosition . Y != 0 : self . SetConsoleCursorPosition ( self . hout , self . fixcoord ( 0 , 0 ) ) w = info . dwSize . X n = DWORD ( 0 ) for y in range ( info . dwSize . Y ) : self . FillConsoleOutputAttribute ( self . hout , attr , w , self . fixcoord ( 0 , y ) , byref ( n ) ) self . FillConsoleOutputCharacterW ( self . hout , ord ( fill [ 0 ] ) , w , self . fixcoord ( 0 , y ) , byref ( n ) ) self . attr = attr
u Fill the entire screen .
57,946
def scroll ( self , rect , dx , dy , attr = None , fill = ' ' ) : u if attr is None : attr = self . attr x0 , y0 , x1 , y1 = rect source = SMALL_RECT ( x0 , y0 , x1 - 1 , y1 - 1 ) dest = self . fixcoord ( x0 + dx , y0 + dy ) style = CHAR_INFO ( ) style . Char . AsciiChar = ensure_str ( fill [ 0 ] ) style . Attributes = attr return self . ScrollConsoleScreenBufferW ( self . hout , byref ( source ) , byref ( source ) , dest , byref ( style ) )
u Scroll a rectangle .
57,947
def get ( self ) : u inputHookFunc = c_void_p . from_address ( self . inputHookPtr ) . value Cevent = INPUT_RECORD ( ) count = DWORD ( 0 ) while 1 : if inputHookFunc : call_function ( inputHookFunc , ( ) ) status = self . ReadConsoleInputW ( self . hin , byref ( Cevent ) , 1 , byref ( count ) ) if status and count . value == 1 : e = event ( self , Cevent ) return e
u Get next event from queue .
57,948
def getchar ( self ) : u Cevent = INPUT_RECORD ( ) count = DWORD ( 0 ) while 1 : status = self . ReadConsoleInputW ( self . hin , byref ( Cevent ) , 1 , byref ( count ) ) if ( status and ( count . value == 1 ) and ( Cevent . EventType == 1 ) and Cevent . Event . KeyEvent . bKeyDown ) : sym = keysym ( Cevent . Event . KeyEvent . wVirtualKeyCode ) if len ( sym ) == 0 : sym = Cevent . Event . KeyEvent . uChar . AsciiChar return sym
u Get next character from queue .
57,949
def peek ( self ) : u Cevent = INPUT_RECORD ( ) count = DWORD ( 0 ) status = self . PeekConsoleInputW ( self . hin , byref ( Cevent ) , 1 , byref ( count ) ) if status and count == 1 : return event ( self , Cevent )
u Check event queue .
57,950
def cursor ( self , visible = None , size = None ) : u info = CONSOLE_CURSOR_INFO ( ) if self . GetConsoleCursorInfo ( self . hout , byref ( info ) ) : if visible is not None : info . bVisible = visible if size is not None : info . dwSize = size self . SetConsoleCursorInfo ( self . hout , byref ( info ) )
u Set cursor on or off .
57,951
def inherit_docstrings ( cls ) : @ functools . wraps ( cls ) def _inherit_docstrings ( cls ) : if not isinstance ( cls , ( type , colorise . compat . ClassType ) ) : raise RuntimeError ( "Type is not a class" ) for name , value in colorise . compat . iteritems ( vars ( cls ) ) : if isinstance ( getattr ( cls , name ) , types . MethodType ) : if not getattr ( value , '__doc__' , None ) : for base in cls . __bases__ : basemethod = getattr ( base , name , None ) if basemethod and getattr ( base , '__doc__' , None ) : value . __doc__ = basemethod . __doc__ return cls return _inherit_docstrings ( cls )
Class decorator for inheriting docstrings .
57,952
def upload ( config ) : token = get_keeper_token ( config [ 'keeper_url' ] , config [ 'keeper_user' ] , config [ 'keeper_password' ] ) build_resource = register_build ( config , token ) ltdconveyor . upload_dir ( build_resource [ 'bucket_name' ] , build_resource [ 'bucket_root_dir' ] , config [ 'build_dir' ] , aws_access_key_id = config [ 'aws_id' ] , aws_secret_access_key = config [ 'aws_secret' ] , surrogate_key = build_resource [ 'surrogate_key' ] , cache_control = 'max-age=31536000' , surrogate_control = None , upload_dir_redirect_objects = True ) confirm_build ( config , token , build_resource )
Upload the build documentation site to LSST the Docs .
57,953
def get_keeper_token ( base_url , username , password ) : token_endpoint = base_url + '/token' r = requests . get ( token_endpoint , auth = ( username , password ) ) if r . status_code != 200 : raise RuntimeError ( 'Could not authenticate to {0}: error {1:d}\n{2}' . format ( base_url , r . status_code , r . json ( ) ) ) return r . json ( ) [ 'token' ]
Get a temporary auth token from LTD Keeper .
57,954
def install ( board_id = 'atmega88' , mcu = 'atmega88' , f_cpu = 20000000 , upload = 'usbasp' , core = 'arduino' , replace_existing = True , ) : board = AutoBunch ( ) board . name = TEMPL . format ( mcu = mcu , f_cpu = f_cpu , upload = upload ) board . upload . using = upload board . upload . maximum_size = 8 * 1024 board . build . mcu = mcu board . build . f_cpu = str ( f_cpu ) + 'L' board . build . core = core board . build . variant = 'standard' install_board ( board_id , board , replace_existing = replace_existing )
install atmega88 board .
57,955
def _compute_bgid ( self , bg = None ) : if bg is None : bg = self . _bgdata if isinstance ( bg , qpimage . QPImage ) : if "identifier" in bg : return bg [ "identifier" ] else : data = [ bg . amp , bg . pha ] for key in sorted ( list ( bg . meta . keys ( ) ) ) : val = bg . meta [ key ] data . append ( "{}={}" . format ( key , val ) ) return hash_obj ( data ) elif ( isinstance ( bg , list ) and isinstance ( bg [ 0 ] , qpimage . QPImage ) ) : data = [ ] for bgii in bg : data . append ( self . _compute_bgid ( bgii ) ) return hash_obj ( data ) elif ( isinstance ( bg , SeriesData ) and ( len ( bg ) == 1 or len ( bg ) == len ( self ) ) ) : return bg . identifier else : raise ValueError ( "Unknown background data type: {}" . format ( bg ) )
Return a unique identifier for the background data
57,956
def identifier ( self ) : if self . background_identifier is None : idsum = self . _identifier_data ( ) else : idsum = hash_obj ( [ self . _identifier_data ( ) , self . background_identifier ] ) return idsum
Return a unique identifier for the given data set
57,957
def get_time ( self , idx ) : qpi = self . get_qpimage_raw ( idx ) if "time" in qpi . meta : thetime = qpi . meta [ "time" ] else : thetime = np . nan return thetime
Return time of data at index idx
57,958
def set_bg ( self , dataset ) : if isinstance ( dataset , qpimage . QPImage ) : self . _bgdata = [ dataset ] elif ( isinstance ( dataset , list ) and len ( dataset ) == len ( self ) and isinstance ( dataset [ 0 ] , qpimage . QPImage ) ) : self . _bgdata = dataset elif ( isinstance ( dataset , SeriesData ) and ( len ( dataset ) == 1 or len ( dataset ) == len ( self ) ) ) : self . _bgdata = dataset else : raise ValueError ( "Bad length or type for bg: {}" . format ( dataset ) ) self . background_identifier = self . _compute_bgid ( )
Set background data
57,959
def get_time ( self , idx = 0 ) : thetime = super ( SingleData , self ) . get_time ( idx = 0 ) return thetime
Time of the data
57,960
def do ( self , fn , message = None , * args , ** kwargs ) : self . items . put ( ChainItem ( fn , self . do , message , * args , ** kwargs ) ) return self
Add a do action to the steps . This is a function to execute
57,961
def expect ( self , value , message = 'Failed: "{actual} {operator} {expected}" after step "{step}"' , operator = '==' ) : if operator not in self . valid_operators : raise ValueError ( 'Illegal operator specified for ' ) self . items . put ( ChainItem ( value , self . expect , message , operator = operator ) ) return self
Add an assertion action to the steps . This will evaluate the return value of the last do step and compare it to the value passed here using the specified operator .
57,962
def perform ( self ) : last_value = None last_step = None while self . items . qsize ( ) : item = self . items . get ( ) if item . flag == self . do : last_value = item . item ( * item . args , ** item . kwargs ) last_step = item . message elif item . flag == self . expect : message = item . message local = { 'value' : last_value , 'expectation' : item . item } expression = 'value {operator} expectation' . format ( operator = item . operator ) result = eval ( expression , local ) format_vars = { 'actual' : last_value , 'expected' : item . item , 'step' : last_step , 'operator' : item . operator } for var , val in format_vars . iteritems ( ) : message = message . replace ( '{' + str ( var ) + '}' , str ( val ) ) assert result , message return last_value
Runs through all of the steps in the chain and runs each of them in sequence .
57,963
def get_volumes ( self ) : vols = [ self . find_volume ( name ) for name in self . virsp . listVolumes ( ) ] return vols
Return a list of all Volumes in this Storage Pool
57,964
def install ( replace_existing = False ) : bunch = AutoBunch ( ) bunch . name = 'DAPA' bunch . protocol = 'dapa' bunch . force = 'true' install_programmer ( 'dapa' , bunch , replace_existing = replace_existing )
install dapa programmer .
57,965
def get_terminal_converted ( self , attr ) : value = self . data . get ( attr . repr_name ) return self . converter_registry . convert_to_representation ( value , attr . value_type )
Returns the value of the specified attribute converted to a representation value .
57,966
def set_terminal_converted ( self , attr , repr_value ) : value = self . converter_registry . convert_from_representation ( repr_value , attr . value_type ) self . data [ attr . repr_name ] = value
Converts the given representation value and sets the specified attribute value to the converted value .
57,967
def load ( self , filename , offset ) : try : self . offset = offset except IOError : self . logger . error ( 'Unable to load EfiSystem volume' )
Will eventually load information for Apple_Boot volume . \ Not yet implemented
57,968
def send ( self , filenames = None ) : try : with self . ssh_client . connect ( ) as ssh_conn : with self . sftp_client . connect ( ssh_conn ) as sftp_conn : for filename in filenames : sftp_conn . copy ( filename = filename ) self . archive ( filename = filename ) if self . update_history_model : self . update_history ( filename = filename ) except SSHClientError as e : raise TransactionFileSenderError ( e ) from e except SFTPClientError as e : raise TransactionFileSenderError ( e ) from e return filenames
Sends the file to the remote host and archives the sent file locally .
57,969
def compile ( self , name , folder = None , data = None ) : template_name = name . replace ( os . sep , "" ) if folder is None : folder = "" full_name = os . path . join ( folder . strip ( os . sep ) , template_name ) if data is None : data = { } try : self . templates [ template_name ] = self . jinja . get_template ( full_name ) . render ( data ) except TemplateNotFound as template_error : if current_app . config [ 'DEBUG' ] : raise template_error
renders template_name + self . extension file with data using jinja
57,970
def create_token ( self , data , token_valid_for = 180 ) -> str : jwt_token = jwt . encode ( { 'data' : data , 'exp' : datetime . utcnow ( ) + timedelta ( seconds = token_valid_for ) } , self . app_secret ) return Security . encrypt ( jwt_token )
Create encrypted JWT
57,971
def verify_token ( self , token ) -> bool : try : self . data = jwt . decode ( Security . decrypt ( token ) , self . app_secret ) return True except ( Exception , BaseException ) as error : self . errors . append ( error ) return False return False
Verify encrypted JWT
57,972
def verify_http_auth_token ( self ) -> bool : authorization_token = self . get_http_token ( ) if authorization_token is not None : if self . verify_token ( authorization_token ) : if self . data is not None : self . data = self . data [ 'data' ] return True return False else : return False return False
Use request information to validate JWT
57,973
def create_token_with_refresh_token ( self , data , token_valid_for = 180 , refresh_token_valid_for = 86400 ) : refresh_token = None refresh_token = jwt . encode ( { 'exp' : datetime . utcnow ( ) + timedelta ( seconds = refresh_token_valid_for ) } , self . app_secret ) . decode ( "utf-8" ) jwt_token = jwt . encode ( { 'data' : data , 'refresh_token' : refresh_token , 'exp' : datetime . utcnow ( ) + timedelta ( seconds = token_valid_for ) } , self . app_secret ) return Security . encrypt ( jwt_token )
Create an encrypted JWT with a refresh_token
57,974
def verify_refresh_token ( self , expired_token ) -> bool : try : decoded_token = jwt . decode ( Security . decrypt ( expired_token ) , self . app_secret , options = { 'verify_exp' : False } ) if 'refresh_token' in decoded_token and decoded_token [ 'refresh_token' ] is not None : try : jwt . decode ( decoded_token [ 'refresh_token' ] , self . app_secret ) self . data = decoded_token return True except ( Exception , BaseException ) as error : self . errors . append ( error ) return False except ( Exception , BaseException ) as error : self . errors . append ( error ) return False return False
Use request information to validate refresh JWT
57,975
def verify_http_auth_refresh_token ( self ) -> bool : authorization_token = self . get_http_token ( ) if authorization_token is not None : if self . verify_refresh_token ( authorization_token ) : if self . data is not None : self . data = self . data [ 'data' ] return True return False else : return False return False
Use expired token to check refresh token information
57,976
def status ( self , status_code = None ) : if status_code is not None : self . response_model . status = status_code return str ( self . response_model . status )
Set status or Get Status
57,977
def message ( self , message = None ) : if message is not None : self . response_model . message = message return self . response_model . message
Set response message
57,978
def data ( self , data = None ) : if data is not None : self . response_model . data = data return self . response_model . data
Set response data
57,979
def quick_response ( self , status_code ) : translator = Translator ( environ = self . environ ) if status_code == 404 : self . status ( 404 ) self . message ( translator . trans ( 'http_messages.404' ) ) elif status_code == 401 : self . status ( 401 ) self . message ( translator . trans ( 'http_messages.401' ) ) elif status_code == 400 : self . status ( 400 ) self . message ( translator . trans ( 'http_messages.400' ) ) elif status_code == 200 : self . status ( 200 ) self . message ( translator . trans ( 'http_messages.200' ) )
Quickly construct response using a status code
57,980
def memoize ( func ) : cache = { } def memoizer ( ) : if 0 not in cache : cache [ 0 ] = func ( ) return cache [ 0 ] return functools . wraps ( func ) ( memoizer )
Cache forever .
57,981
def getinputencoding ( stream = None ) : if stream is None : stream = sys . stdin encoding = stream . encoding if not encoding : encoding = getpreferredencoding ( ) return encoding
Return preferred encoding for reading from stream .
57,982
def getoutputencoding ( stream = None ) : if stream is None : stream = sys . stdout encoding = stream . encoding if not encoding : encoding = getpreferredencoding ( ) return encoding
Return preferred encoding for writing to stream .
57,983
def decode ( string , encoding = None , errors = None ) : if encoding is None : encoding = getpreferredencoding ( ) if errors is None : errors = getpreferrederrors ( ) return string . decode ( encoding , errors )
Decode from specified encoding .
57,984
def encode ( string , encoding = None , errors = None ) : if encoding is None : encoding = getpreferredencoding ( ) if errors is None : errors = getpreferrederrors ( ) return string . encode ( encoding , errors )
Encode to specified encoding .
57,985
def _get_response_mime_type ( self ) : view_name = self . request . view_name if view_name != '' : mime_type = get_registered_mime_type_for_name ( view_name ) else : mime_type = None acc = None for acc in self . request . accept : if acc == '*/*' : mime_type = self . __get_default_response_mime_type ( ) break try : mime_type = get_registered_mime_type_for_string ( acc . lower ( ) ) except KeyError : pass else : break if mime_type is None : if not acc is None : headers = [ ( 'Location' , self . request . path_url ) , ( 'Content-Type' , TextPlainMime . mime_type_string ) , ] mime_strings = get_registered_mime_strings ( ) exc = HTTPNotAcceptable ( 'Requested MIME content type(s) ' 'not acceptable.' , body = ',' . join ( mime_strings ) , headers = headers ) raise exc mime_type = self . __get_default_response_mime_type ( ) return mime_type
Returns the reponse MIME type for this view .
57,986
def _get_result ( self , resource ) : if self . _convert_response : self . _update_response_body ( resource ) result = self . request . response else : result = dict ( context = resource ) return result
Converts the given resource to a result to be returned from the view . Unless a custom renderer is employed this will involve creating a representer and using it to convert the resource to a string .
57,987
def _update_response_body ( self , resource ) : rpr = self . _get_response_representer ( resource ) self . request . response . content_type = rpr . content_type . mime_type_string rpr_body = rpr . to_bytes ( resource ) self . request . response . body = rpr_body
Creates a representer and updates the response body with the byte representation created for the given resource .
57,988
def _update_response_location_header ( self , resource ) : location = resource_to_url ( resource , request = self . request ) loc_hdr = ( 'Location' , location ) hdr_names = [ hdr [ 0 ] . upper ( ) for hdr in self . request . response . headerlist ] try : idx = hdr_names . index ( 'LOCATION' ) except ValueError : self . request . response . headerlist . append ( loc_hdr ) else : self . request . response . headerlist [ idx ] = loc_hdr
Adds a new or replaces an existing Location header to the response headers pointing to the URL of the given resource .
57,989
def _get_request_representer ( self ) : try : mime_type = get_registered_mime_type_for_string ( self . request . content_type ) except KeyError : raise HTTPUnsupportedMediaType ( ) return as_representer ( self . context , mime_type )
Returns a representer for the content type specified in the request .
57,990
def _extract_request_data ( self ) : rpr = self . _get_request_representer ( ) return rpr . data_from_bytes ( self . request . body )
Extracts the data from the representation submitted in the request body and returns it .
57,991
def _handle_conflict ( self , name ) : err = HTTPConflict ( 'Member "%s" already exists!' % name ) . exception return self . request . get_response ( err )
Handles requests that triggered a conflict .
57,992
def check ( self ) : request = get_current_request ( ) ignore_guid = request . params . get ( 'ignore-message' ) coll = request . root [ '_messages' ] vote = False if ignore_guid : ignore_mb = coll . get ( ignore_guid ) if not ignore_mb is None and ignore_mb . text == self . message . text : vote = True return vote
Implements user message checking for views .
57,993
def create_307_response ( self ) : request = get_current_request ( ) msg_mb = UserMessageMember ( self . message ) coll = request . root [ '_messages' ] coll . add ( msg_mb ) qs = self . __get_new_query_string ( request . query_string , self . message . slug ) resubmit_url = "%s?%s" % ( request . path_url , qs ) headers = [ ( 'Warning' , '299 %s' % self . message . text ) , ] http_exc = HttpWarningResubmit ( location = resubmit_url , detail = self . message . text , headers = headers ) return request . get_response ( http_exc )
Creates a 307 Temporary Redirect response including a HTTP Warning header with code 299 that contains the user message received during processing the request .
57,994
def mkdir ( * args ) : path = '' for chunk in args : path = os . path . join ( path , chunk ) if not os . path . isdir ( path ) : os . mkdir ( path ) return path
Create a directory specified by a sequence of subdirectories
57,995
def shell ( cmd , * args , ** kwargs ) : if kwargs . get ( 'rel_path' ) and not cmd . startswith ( "/" ) : cmd = os . path . join ( kwargs [ 'rel_path' ] , cmd ) status = 0 try : output = subprocess . check_output ( ( cmd , ) + args , stderr = kwargs . get ( 'stderr' ) ) except subprocess . CalledProcessError as e : if kwargs . get ( 'raise_on_status' , True ) : raise e output = e . output status = e . returncode except OSError as e : if kwargs . get ( 'raise_on_status' , True ) : raise e if 'stderr' in kwargs : kwargs [ 'stderr' ] . write ( e . message ) return - 1 , "" if six . PY3 : output = output . decode ( 'utf8' ) return status , output
Execute shell command and return output
57,996
def listen_for_events ( ) : import_event_modules ( ) conn = redis_connection . get_connection ( ) pubsub = conn . pubsub ( ) pubsub . subscribe ( "eventlib" ) for message in pubsub . listen ( ) : if message [ 'type' ] != 'message' : continue data = loads ( message [ "data" ] ) if 'name' in data : event_name = data . pop ( 'name' ) process_external ( event_name , data )
Pubsub event listener
57,997
def sendrequest ( self , request ) : url = urlparse . urlparse ( self . connection . healthserviceurl ) conn = None if url . scheme == 'https' : conn = httplib . HTTPSConnection ( url . netloc ) else : conn = httplib . HTTPConnection ( url . netloc ) conn . putrequest ( 'POST' , url . path ) conn . putheader ( 'Content-Type' , 'text/xml' ) conn . putheader ( 'Content-Length' , '%d' % len ( request ) ) conn . endheaders ( ) try : conn . send ( request ) except socket . error , v : if v [ 0 ] == 32 : conn . close ( ) raise response = conn . getresponse ( ) . read ( ) return etree . fromstring ( response )
Recieves a request xml as a string and posts it to the health service url specified in the settings . py
57,998
def commit ( self , unit_of_work ) : MemoryRepository . commit ( self , unit_of_work ) if self . is_initialized : entity_classes_to_dump = set ( ) for state in unit_of_work . iterator ( ) : entity_classes_to_dump . add ( type ( state . entity ) ) for entity_cls in entity_classes_to_dump : self . __dump_entities ( entity_cls )
Dump all resources that were modified by the given session back into the repository .
57,999
def _validate_pdf_file ( self ) : if self [ 'pdf_path' ] is None : self . _logger . error ( '--pdf argument must be set' ) sys . exit ( 1 ) if not os . path . exists ( self [ 'pdf_path' ] ) : self . _logger . error ( 'Cannot find PDF ' + self [ 'pdf_path' ] ) sys . exit ( 1 )
Validate that the pdf_path configuration is set and the referenced file exists .