idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
19,100 | def export_flow_process_data ( params , process ) : output_flow = eTree . SubElement ( process , consts . Consts . sequence_flow ) output_flow . set ( consts . Consts . id , params [ consts . Consts . id ] ) output_flow . set ( consts . Consts . name , params [ consts . Consts . name ] ) output_flow . set ( consts . Consts . source_ref , params [ consts . Consts . source_ref ] ) output_flow . set ( consts . Consts . target_ref , params [ consts . Consts . target_ref ] ) if consts . Consts . condition_expression in params : condition_expression_params = params [ consts . Consts . condition_expression ] condition_expression = eTree . SubElement ( output_flow , consts . Consts . condition_expression ) condition_expression . set ( consts . Consts . id , condition_expression_params [ consts . Consts . id ] ) condition_expression . set ( consts . Consts . id , condition_expression_params [ consts . Consts . id ] ) condition_expression . text = condition_expression_params [ consts . Consts . condition_expression ] output_flow . set ( consts . Consts . name , condition_expression_params [ consts . Consts . condition_expression ] ) | Creates a new SequenceFlow XML element for given edge parameters and adds it to process element . | 310 | 19 |
19,101 | def export_flow_di_data ( params , plane ) : output_flow = eTree . SubElement ( plane , BpmnDiagramGraphExport . bpmndi_namespace + consts . Consts . bpmn_edge ) output_flow . set ( consts . Consts . id , params [ consts . Consts . id ] + "_gui" ) output_flow . set ( consts . Consts . bpmn_element , params [ consts . Consts . id ] ) waypoints = params [ consts . Consts . waypoints ] for waypoint in waypoints : waypoint_element = eTree . SubElement ( output_flow , "omgdi:waypoint" ) waypoint_element . set ( consts . Consts . x , waypoint [ 0 ] ) waypoint_element . set ( consts . Consts . y , waypoint [ 1 ] ) | Creates a new BPMNEdge XML element for given edge parameters and adds it to plane element . | 199 | 21 |
19,102 | def indent ( elem , level = 0 ) : i = "\n" + level * " " j = "\n" + ( level - 1 ) * " " if len ( elem ) : if not elem . text or not elem . text . strip ( ) : elem . text = i + " " if not elem . tail or not elem . tail . strip ( ) : elem . tail = i for subelem in elem : BpmnDiagramGraphExport . indent ( subelem , level + 1 ) if not elem . tail or not elem . tail . strip ( ) : elem . tail = j else : if level and ( not elem . tail or not elem . tail . strip ( ) ) : elem . tail = j return elem | Helper function adds indentation to XML output . | 172 | 9 |
19,103 | def split_join_classification ( element , classification_labels , nodes_classification ) : classification_join = "Join" classification_split = "Split" if len ( element [ 1 ] [ consts . Consts . incoming_flow ] ) >= 2 : classification_labels . append ( classification_join ) if len ( element [ 1 ] [ consts . Consts . outgoing_flow ] ) >= 2 : classification_labels . append ( classification_split ) nodes_classification [ element [ 0 ] ] = classification_labels | Add the Split Join classification if the element qualifies for . | 116 | 11 |
19,104 | def get_all_gateways ( bpmn_graph ) : gateways = filter ( lambda node : node [ 1 ] [ 'type' ] in GATEWAY_TYPES , bpmn_graph . get_nodes ( ) ) return gateways | Returns a list with all gateways in diagram | 57 | 9 |
19,105 | def all_control_flow_elements_count ( bpmn_graph ) : gateway_counts = get_gateway_counts ( bpmn_graph ) events_counts = get_events_counts ( bpmn_graph ) control_flow_elements_counts = gateway_counts . copy ( ) control_flow_elements_counts . update ( events_counts ) return sum ( [ count for name , count in control_flow_elements_counts . items ( ) ] ) | Returns the total count of all control flow elements in the BPMNDiagramGraph instance . | 116 | 19 |
19,106 | def export_process_to_csv ( bpmn_diagram , directory , filename ) : nodes = copy . deepcopy ( bpmn_diagram . get_nodes ( ) ) start_nodes = [ ] export_elements = [ ] for node in nodes : incoming_list = node [ 1 ] . get ( consts . Consts . incoming_flow ) if len ( incoming_list ) == 0 : start_nodes . append ( node ) if len ( start_nodes ) != 1 : raise bpmn_exception . BpmnPythonError ( "Exporting to CSV format accepts only one start event" ) nodes_classification = utils . BpmnImportUtils . generate_nodes_clasification ( bpmn_diagram ) start_node = start_nodes . pop ( ) BpmnDiagramGraphCsvExport . export_node ( bpmn_diagram , export_elements , start_node , nodes_classification ) try : os . makedirs ( directory ) except OSError as exception : if exception . errno != errno . EEXIST : raise file_object = open ( directory + filename , "w" ) file_object . write ( "Order,Activity,Condition,Who,Subprocess,Terminated\n" ) BpmnDiagramGraphCsvExport . write_export_node_to_file ( file_object , export_elements ) file_object . close ( ) | Root method of CSV export functionality . | 323 | 7 |
19,107 | def export_node ( bpmn_graph , export_elements , node , nodes_classification , order = 0 , prefix = "" , condition = "" , who = "" , add_join = False ) : node_type = node [ 1 ] [ consts . Consts . type ] if node_type == consts . Consts . start_event : return BpmnDiagramGraphCsvExport . export_start_event ( bpmn_graph , export_elements , node , nodes_classification , order = order , prefix = prefix , condition = condition , who = who ) elif node_type == consts . Consts . end_event : return BpmnDiagramGraphCsvExport . export_end_event ( export_elements , node , order = order , prefix = prefix , condition = condition , who = who ) else : return BpmnDiagramGraphCsvExport . export_element ( bpmn_graph , export_elements , node , nodes_classification , order = order , prefix = prefix , condition = condition , who = who , add_join = add_join ) | General method for node exporting | 244 | 5 |
19,108 | def export_start_event ( bpmn_graph , export_elements , node , nodes_classification , order = 0 , prefix = "" , condition = "" , who = "" ) : # Assuming that there is only one event definition event_definitions = node [ 1 ] . get ( consts . Consts . event_definitions ) if event_definitions is not None and len ( event_definitions ) > 0 : event_definition = node [ 1 ] [ consts . Consts . event_definitions ] [ 0 ] else : event_definition = None if event_definition is None : activity = node [ 1 ] [ consts . Consts . node_name ] elif event_definition [ consts . Consts . definition_type ] == "messageEventDefinition" : activity = "message " + node [ 1 ] [ consts . Consts . node_name ] elif event_definition [ consts . Consts . definition_type ] == "timerEventDefinition" : activity = "timer " + node [ 1 ] [ consts . Consts . node_name ] else : activity = node [ 1 ] [ consts . Consts . node_name ] export_elements . append ( { "Order" : prefix + str ( order ) , "Activity" : activity , "Condition" : condition , "Who" : who , "Subprocess" : "" , "Terminated" : "" } ) outgoing_flow_id = node [ 1 ] [ consts . Consts . outgoing_flow ] [ 0 ] outgoing_flow = bpmn_graph . get_flow_by_id ( outgoing_flow_id ) outgoing_node = bpmn_graph . get_node_by_id ( outgoing_flow [ 2 ] [ consts . Consts . target_ref ] ) return BpmnDiagramGraphCsvExport . export_node ( bpmn_graph , export_elements , outgoing_node , nodes_classification , order + 1 , prefix , who ) | Start event export | 433 | 3 |
19,109 | def export_end_event ( export_elements , node , order = 0 , prefix = "" , condition = "" , who = "" ) : # Assuming that there is only one event definition event_definitions = node [ 1 ] . get ( consts . Consts . event_definitions ) if event_definitions is not None and len ( event_definitions ) > 0 : event_definition = node [ 1 ] [ consts . Consts . event_definitions ] [ 0 ] else : event_definition = None if event_definition is None : activity = node [ 1 ] [ consts . Consts . node_name ] elif event_definition [ consts . Consts . definition_type ] == "messageEventDefinition" : activity = "message " + node [ 1 ] [ consts . Consts . node_name ] else : activity = node [ 1 ] [ consts . Consts . node_name ] export_elements . append ( { "Order" : prefix + str ( order ) , "Activity" : activity , "Condition" : condition , "Who" : who , "Subprocess" : "" , "Terminated" : "yes" } ) # No outgoing elements for EndEvent return None | End event export | 262 | 3 |
19,110 | def write_export_node_to_file ( file_object , export_elements ) : for export_element in export_elements : # Order,Activity,Condition,Who,Subprocess,Terminated file_object . write ( export_element [ "Order" ] + "," + export_element [ "Activity" ] + "," + export_element [ "Condition" ] + "," + export_element [ "Who" ] + "," + export_element [ "Subprocess" ] + "," + export_element [ "Terminated" ] + "\n" ) | Exporting process to CSV file | 126 | 6 |
19,111 | def bpmn_diagram_to_png ( bpmn_diagram , file_name ) : g = bpmn_diagram . diagram_graph graph = pydotplus . Dot ( ) for node in g . nodes ( data = True ) : if node [ 1 ] . get ( consts . Consts . type ) == consts . Consts . task : n = pydotplus . Node ( name = node [ 0 ] , shape = "box" , style = "rounded" , label = node [ 1 ] . get ( consts . Consts . node_name ) ) elif node [ 1 ] . get ( consts . Consts . type ) == consts . Consts . exclusive_gateway : n = pydotplus . Node ( name = node [ 0 ] , shape = "diamond" , label = node [ 1 ] . get ( consts . Consts . node_name ) ) else : n = pydotplus . Node ( name = node [ 0 ] , label = node [ 1 ] . get ( consts . Consts . node_name ) ) graph . add_node ( n ) for edge in g . edges ( data = True ) : e = pydotplus . Edge ( src = edge [ 0 ] , dst = edge [ 1 ] , label = edge [ 2 ] . get ( consts . Consts . name ) ) graph . add_edge ( e ) graph . write ( file_name + ".png" , format = 'png' ) | Create a png picture for given diagram | 328 | 8 |
19,112 | def get_node_by_id ( self , node_id ) : tmp_nodes = self . diagram_graph . nodes ( data = True ) for node in tmp_nodes : if node [ 0 ] == node_id : return node | Gets a node with requested ID . Returns a tuple where first value is node ID second - a dictionary of all node attributes . | 53 | 26 |
19,113 | def get_nodes_id_list_by_type ( self , node_type ) : tmp_nodes = self . diagram_graph . nodes ( data = True ) id_list = [ ] for node in tmp_nodes : if node [ 1 ] [ consts . Consts . type ] == node_type : id_list . append ( node [ 0 ] ) return id_list | Get a list of node s id by requested type . Returns a list of ids | 86 | 17 |
19,114 | def add_process_to_diagram ( self , process_name = "" , process_is_closed = False , process_is_executable = False , process_type = "None" ) : plane_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) process_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) self . process_elements [ process_id ] = { consts . Consts . name : process_name , consts . Consts . is_closed : "true" if process_is_closed else "false" , consts . Consts . is_executable : "true" if process_is_executable else "false" , consts . Consts . process_type : process_type } self . plane_attributes [ consts . Consts . id ] = plane_id self . plane_attributes [ consts . Consts . bpmn_element ] = process_id return process_id | Adds a new process to diagram and corresponding participant process diagram and plane | 231 | 13 |
19,115 | def add_flow_node_to_diagram ( self , process_id , node_type , name , node_id = None ) : if node_id is None : node_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) self . diagram_graph . add_node ( node_id ) self . diagram_graph . node [ node_id ] [ consts . Consts . id ] = node_id self . diagram_graph . node [ node_id ] [ consts . Consts . type ] = node_type self . diagram_graph . node [ node_id ] [ consts . Consts . node_name ] = name self . diagram_graph . node [ node_id ] [ consts . Consts . incoming_flow ] = [ ] self . diagram_graph . node [ node_id ] [ consts . Consts . outgoing_flow ] = [ ] self . diagram_graph . node [ node_id ] [ consts . Consts . process ] = process_id # Adding some dummy constant values self . diagram_graph . node [ node_id ] [ consts . Consts . width ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . height ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . x ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . y ] = "100" return node_id , self . diagram_graph . node [ node_id ] | Helper function that adds a new Flow Node to diagram . It is used to add a new node of specified type . Adds a basic information inherited from Flow Node type . | 353 | 33 |
19,116 | def add_start_event_to_diagram ( self , process_id , start_event_name = "" , start_event_definition = None , parallel_multiple = False , is_interrupting = True , node_id = None ) : start_event_id , start_event = self . add_flow_node_to_diagram ( process_id , consts . Consts . start_event , start_event_name , node_id ) self . diagram_graph . node [ start_event_id ] [ consts . Consts . parallel_multiple ] = "true" if parallel_multiple else "false" self . diagram_graph . node [ start_event_id ] [ consts . Consts . is_interrupting ] = "true" if is_interrupting else "false" start_event_definitions = { "message" : "messageEventDefinition" , "timer" : "timerEventDefinition" , "conditional" : "conditionalEventDefinition" , "signal" : "signalEventDefinition" , "escalation" : "escalationEventDefinition" } event_def_list = [ ] if start_event_definition == "message" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "message" , start_event_definitions ) ) elif start_event_definition == "timer" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "timer" , start_event_definitions ) ) elif start_event_definition == "conditional" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "conditional" , start_event_definitions ) ) elif start_event_definition == "signal" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "signal" , start_event_definitions ) ) elif start_event_definition == "escalation" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "escalation" , start_event_definitions ) ) self . diagram_graph . node [ start_event_id ] [ consts . Consts . event_definitions ] = event_def_list return start_event_id , start_event | Adds a StartEvent element to BPMN diagram . | 534 | 11 |
19,117 | def add_inclusive_gateway_to_diagram ( self , process_id , gateway_name = "" , gateway_direction = "Unspecified" , default = None , node_id = None ) : inclusive_gateway_id , inclusive_gateway = self . add_gateway_to_diagram ( process_id , consts . Consts . inclusive_gateway , gateway_name = gateway_name , gateway_direction = gateway_direction , node_id = node_id ) self . diagram_graph . node [ inclusive_gateway_id ] [ consts . Consts . default ] = default return inclusive_gateway_id , inclusive_gateway | Adds an inclusiveGateway element to BPMN diagram . | 147 | 12 |
19,118 | def add_parallel_gateway_to_diagram ( self , process_id , gateway_name = "" , gateway_direction = "Unspecified" , node_id = None ) : parallel_gateway_id , parallel_gateway = self . add_gateway_to_diagram ( process_id , consts . Consts . parallel_gateway , gateway_name = gateway_name , gateway_direction = gateway_direction , node_id = node_id ) return parallel_gateway_id , parallel_gateway | Adds an parallelGateway element to BPMN diagram . | 117 | 12 |
19,119 | def get_nodes_positions ( self ) : nodes = self . get_nodes ( ) output = { } for node in nodes : output [ node [ 0 ] ] = ( float ( node [ 1 ] [ consts . Consts . x ] ) , float ( node [ 1 ] [ consts . Consts . y ] ) ) return output | Getter method for nodes positions . | 76 | 7 |
19,120 | def create_tree ( path , depth = DEPTH ) : os . mkdir ( path ) for i in range ( NUM_FILES ) : filename = os . path . join ( path , 'file{0:03}.txt' . format ( i ) ) with open ( filename , 'wb' ) as f : f . write ( b'foo' ) if depth <= 1 : return for i in range ( NUM_DIRS ) : dirname = os . path . join ( path , 'dir{0:03}' . format ( i ) ) create_tree ( dirname , depth - 1 ) | Create a directory tree at path with given depth and NUM_DIRS and NUM_FILES at each level . | 131 | 23 |
19,121 | def get_tree_size ( path ) : size = 0 try : for entry in scandir . scandir ( path ) : if entry . is_symlink ( ) : pass elif entry . is_dir ( ) : size += get_tree_size ( os . path . join ( path , entry . name ) ) else : size += entry . stat ( ) . st_size except OSError : pass return size | Return total size of all files in directory tree at path . | 94 | 12 |
19,122 | def unfold ( tensor , mode ) : return np . moveaxis ( tensor , mode , 0 ) . reshape ( ( tensor . shape [ mode ] , - 1 ) ) | Returns the mode - mode unfolding of tensor . | 39 | 10 |
19,123 | def khatri_rao ( matrices ) : n_columns = matrices [ 0 ] . shape [ 1 ] n_factors = len ( matrices ) start = ord ( 'a' ) common_dim = 'z' target = '' . join ( chr ( start + i ) for i in range ( n_factors ) ) source = ',' . join ( i + common_dim for i in target ) operation = source + '->' + target + common_dim return np . einsum ( operation , * matrices ) . reshape ( ( - 1 , n_columns ) ) | Khatri - Rao product of a list of matrices . | 133 | 13 |
19,124 | def soft_cluster_factor ( factor ) : # copy factor of interest f = np . copy ( factor ) # cluster based on score of maximum absolute value cluster_ids = np . argmax ( np . abs ( f ) , axis = 1 ) scores = f [ range ( f . shape [ 0 ] ) , cluster_ids ] # resort within each cluster perm = [ ] for cluster in np . unique ( cluster_ids ) : idx = np . where ( cluster_ids == cluster ) [ 0 ] perm += list ( idx [ np . argsort ( scores [ idx ] ) ] [ : : - 1 ] ) return cluster_ids , perm | Returns soft - clustering of data based on CP decomposition results . | 140 | 14 |
19,125 | def hclust_linearize ( U ) : from scipy . cluster import hierarchy Z = hierarchy . ward ( U ) return hierarchy . leaves_list ( hierarchy . optimal_leaf_ordering ( Z , U ) ) | Sorts the rows of a matrix by hierarchical clustering . | 47 | 12 |
19,126 | def reverse_segment ( path , n1 , n2 ) : q = path . copy ( ) if n2 > n1 : q [ n1 : ( n2 + 1 ) ] = path [ n1 : ( n2 + 1 ) ] [ : : - 1 ] return q else : seg = np . hstack ( ( path [ n1 : ] , path [ : ( n2 + 1 ) ] ) ) [ : : - 1 ] brk = len ( q ) - n1 q [ n1 : ] = seg [ : brk ] q [ : ( n2 + 1 ) ] = seg [ brk : ] return q | Reverse the nodes between n1 and n2 . | 142 | 12 |
19,127 | def full ( self ) : # Compute tensor unfolding along first mode unf = sci . dot ( self . factors [ 0 ] , khatri_rao ( self . factors [ 1 : ] ) . T ) # Inverse unfolding along first mode return sci . reshape ( unf , self . shape ) | Converts KTensor to a dense ndarray . | 65 | 11 |
19,128 | def rebalance ( self ) : # Compute norms along columns for each factor matrix norms = [ sci . linalg . norm ( f , axis = 0 ) for f in self . factors ] # Multiply norms across all modes lam = sci . multiply . reduce ( norms ) ** ( 1 / self . ndim ) # Update factors self . factors = [ f * ( lam / fn ) for f , fn in zip ( self . factors , norms ) ] return self | Rescales factors across modes so that all norms match . | 100 | 12 |
19,129 | def permute ( self , idx ) : # Check that input is a true permutation if set ( idx ) != set ( range ( self . rank ) ) : raise ValueError ( 'Invalid permutation specified.' ) # Update factors self . factors = [ f [ : , idx ] for f in self . factors ] return self . factors | Permutes the columns of the factor matrices inplace | 73 | 12 |
19,130 | def kruskal_align ( U , V , permute_U = False , permute_V = False ) : # Compute similarity matrices. unrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in U . factors ] vnrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in V . factors ] sim_matrices = [ np . dot ( u . T , v ) for u , v in zip ( unrm , vnrm ) ] cost = 1 - np . mean ( np . abs ( sim_matrices ) , axis = 0 ) # Solve matching problem via Hungarian algorithm. indices = Munkres ( ) . compute ( cost . copy ( ) ) prmU , prmV = zip ( * indices ) # Compute mean factor similarity given the optimal matching. similarity = np . mean ( 1 - cost [ prmU , prmV ] ) # If U and V are of different ranks, identify unmatched factors. unmatched_U = list ( set ( range ( U . rank ) ) - set ( prmU ) ) unmatched_V = list ( set ( range ( V . rank ) ) - set ( prmV ) ) # If permuting both U and V, order factors from most to least similar. if permute_U and permute_V : idx = np . argsort ( cost [ prmU , prmV ] ) # If permute_U is False, then order the factors such that the ordering # for U is unchanged. elif permute_V : idx = np . argsort ( prmU ) # If permute_V is False, then order the factors such that the ordering # for V is unchanged. elif permute_U : idx = np . argsort ( prmV ) # If permute_U and permute_V are both False, then we are done and can # simply return the similarity. else : return similarity # Re-order the factor permutations. prmU = [ prmU [ i ] for i in idx ] prmV = [ prmV [ i ] for i in idx ] # Permute the factors. if permute_U : U . permute ( prmU ) if permute_V : V . permute ( prmV ) # Flip the signs of factors. flips = np . sign ( [ F [ prmU , prmV ] for F in sim_matrices ] ) flips [ 0 ] *= np . prod ( flips , axis = 0 ) # always flip an even number of factors if permute_U : for i , f in enumerate ( flips ) : U . factors [ i ] *= f elif permute_V : for i , f in enumerate ( flips ) : V . factors [ i ] *= f # Return the similarity score return similarity | Aligns two KTensors and returns a similarity score . | 629 | 13 |
19,131 | def plot_objective ( ensemble , partition = 'train' , ax = None , jitter = 0.1 , scatter_kw = dict ( ) , line_kw = dict ( ) ) : if ax is None : ax = plt . gca ( ) if partition == 'train' : pass elif partition == 'test' : raise NotImplementedError ( 'Cross-validation is on the TODO list.' ) else : raise ValueError ( "partition must be 'train' or 'test'." ) # compile statistics for plotting x , obj , min_obj = [ ] , [ ] , [ ] for rank in sorted ( ensemble . results ) : # reconstruction errors for rank-r models o = ensemble . objectives ( rank ) obj . extend ( o ) x . extend ( np . full ( len ( o ) , rank ) ) min_obj . append ( min ( o ) ) # add horizontal jitter ux = np . unique ( x ) x = np . array ( x ) + ( np . random . rand ( len ( x ) ) - 0.5 ) * jitter # make plot ax . scatter ( x , obj , * * scatter_kw ) ax . plot ( ux , min_obj , * * line_kw ) ax . set_xlabel ( 'model rank' ) ax . set_ylabel ( 'objective' ) return ax | Plots objective function as a function of model rank . | 294 | 11 |
19,132 | def plot_similarity ( ensemble , ax = None , jitter = 0.1 , scatter_kw = dict ( ) , line_kw = dict ( ) ) : if ax is None : ax = plt . gca ( ) # compile statistics for plotting x , sim , mean_sim = [ ] , [ ] , [ ] for rank in sorted ( ensemble . results ) : # reconstruction errors for rank-r models s = ensemble . similarities ( rank ) [ 1 : ] sim . extend ( s ) x . extend ( np . full ( len ( s ) , rank ) ) mean_sim . append ( np . mean ( s ) ) # add horizontal jitter ux = np . unique ( x ) x = np . array ( x ) + ( np . random . rand ( len ( x ) ) - 0.5 ) * jitter # make plot ax . scatter ( x , sim , * * scatter_kw ) ax . plot ( ux , mean_sim , * * line_kw ) ax . set_xlabel ( 'model rank' ) ax . set_ylabel ( 'model similarity' ) ax . set_ylim ( [ 0 , 1.1 ] ) return ax | Plots similarity across optimization runs as a function of model rank . | 254 | 13 |
19,133 | def _broadcast_arg ( U , arg , argtype , name ) : # if input is not iterable, broadcast it all dimensions of the tensor if arg is None or isinstance ( arg , argtype ) : return [ arg for _ in range ( U . ndim ) ] # check if iterable input is valid elif np . iterable ( arg ) : if len ( arg ) != U . ndim : raise ValueError ( 'Parameter {} was specified as a sequence of ' 'incorrect length. The length must match the ' 'number of tensor dimensions ' '(U.ndim={})' . format ( name , U . ndim ) ) elif not all ( [ isinstance ( a , argtype ) for a in arg ] ) : raise TypeError ( 'Parameter {} specified as a sequence of ' 'incorrect type. ' 'Expected {}.' . format ( name , argtype ) ) else : return arg # input is not iterable and is not the corrent type. else : raise TypeError ( 'Parameter {} specified as a {}.' ' Expected {}.' . format ( name , type ( arg ) , argtype ) ) | Broadcasts plotting option arg to all factors . | 246 | 9 |
19,134 | def _check_cpd_inputs ( X , rank ) : if X . ndim < 3 : raise ValueError ( "Array with X.ndim > 2 expected." ) if rank <= 0 or not isinstance ( rank , int ) : raise ValueError ( "Rank is invalid." ) | Checks that inputs to optimization function are appropriate . | 63 | 10 |
19,135 | def _check_random_state ( random_state ) : if random_state is None or isinstance ( random_state , int ) : return sci . random . RandomState ( random_state ) elif isinstance ( random_state , sci . random . RandomState ) : return random_state else : raise TypeError ( 'Seed should be None, int or np.random.RandomState' ) | Checks and processes user input for seeding random numbers . | 86 | 12 |
19,136 | def randn_ktensor ( shape , rank , norm = None , random_state = None ) : # Check input. rns = _check_random_state ( random_state ) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor ( [ rns . standard_normal ( ( i , rank ) ) for i in shape ] ) return _rescale_tensor ( factors , norm ) | Generates a random N - way tensor with rank R where the entries are drawn from the standard normal distribution . | 96 | 23 |
19,137 | def fit ( self , X , ranks , replicates = 1 , verbose = True ) : # Make ranks iterable if necessary. if not isinstance ( ranks , collections . Iterable ) : ranks = ( ranks , ) # Iterate over model ranks, optimize multiple replicates at each rank. for r in ranks : # Initialize storage if r not in self . results : self . results [ r ] = [ ] # Display fitting progress. if verbose : itr = trange ( replicates , desc = 'Fitting rank-{} models' . format ( r ) , leave = False ) else : itr = range ( replicates ) # Fit replicates. for i in itr : model_fit = self . _fit_method ( X , r , * * self . _fit_options ) self . results [ r ] . append ( model_fit ) # Print summary of results. if verbose : min_obj = min ( [ res . obj for res in self . results [ r ] ] ) max_obj = max ( [ res . obj for res in self . results [ r ] ] ) elapsed = sum ( [ res . total_time for res in self . results [ r ] ] ) print ( 'Rank-{} models: min obj, {:.2f}; ' 'max obj, {:.2f}; time to fit, ' '{:.1f}s' . format ( r , min_obj , max_obj , elapsed ) ) # Sort results from lowest to largest loss. for r in ranks : idx = np . argsort ( [ result . obj for result in self . results [ r ] ] ) self . results [ r ] = [ self . results [ r ] [ i ] for i in idx ] # Align best model within each rank to best model of next larger rank. # Here r0 is the rank of the lower-dimensional model and r1 is the rank # of the high-dimensional model. for i in reversed ( range ( 1 , len ( ranks ) ) ) : r0 , r1 = ranks [ i - 1 ] , ranks [ i ] U = self . results [ r0 ] [ 0 ] . factors V = self . results [ r1 ] [ 0 ] . factors kruskal_align ( U , V , permute_U = True ) # For each rank, align everything to the best model for r in ranks : # store best factors U = self . results [ r ] [ 0 ] . factors # best model factors self . results [ r ] [ 0 ] . similarity = 1.0 # similarity to itself # align lesser fit models to best models for res in self . results [ r ] [ 1 : ] : res . similarity = kruskal_align ( U , res . factors , permute_V = True ) | Fits CP tensor decompositions for different choices of rank . | 599 | 14 |
19,138 | def objectives ( self , rank ) : self . _check_rank ( rank ) return [ result . obj for result in self . results [ rank ] ] | Returns objective values of models with specified rank . | 32 | 9 |
19,139 | def similarities ( self , rank ) : self . _check_rank ( rank ) return [ result . similarity for result in self . results [ rank ] ] | Returns similarity scores for models with specified rank . | 32 | 9 |
19,140 | def factors ( self , rank ) : self . _check_rank ( rank ) return [ result . factors for result in self . results [ rank ] ] | Returns KTensor factors for models with specified rank . | 32 | 10 |
19,141 | def _create_model_class ( self , model ) : cls_name = model . replace ( '.' , '_' ) # Hack for Python 2 (no need to do this for Python 3) if sys . version_info [ 0 ] < 3 : if isinstance ( cls_name , unicode ) : cls_name = cls_name . encode ( 'utf-8' ) # Retrieve server fields info and generate corresponding local fields attrs = { '_env' : self , '_odoo' : self . _odoo , '_name' : model , '_columns' : { } , } fields_get = self . _odoo . execute ( model , 'fields_get' ) for field_name , field_data in fields_get . items ( ) : if field_name not in FIELDS_RESERVED : Field = fields . generate_field ( field_name , field_data ) attrs [ '_columns' ] [ field_name ] = Field attrs [ field_name ] = Field # Case where no field 'name' exists, we generate one (which will be # in readonly mode) in purpose to be filled with the 'name_get' method if 'name' not in attrs [ '_columns' ] : field_data = { 'type' : 'text' , 'string' : 'Name' , 'readonly' : True } Field = fields . generate_field ( 'name' , field_data ) attrs [ '_columns' ] [ 'name' ] = Field attrs [ 'name' ] = Field return type ( cls_name , ( Model , ) , attrs ) | Generate the model proxy class . | 368 | 7 |
19,142 | def get_all ( rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) sessions = { } for name in conf . sections ( ) : sessions [ name ] = { 'type' : conf . get ( name , 'type' ) , 'host' : conf . get ( name , 'host' ) , 'protocol' : conf . get ( name , 'protocol' ) , 'port' : conf . getint ( name , 'port' ) , 'timeout' : conf . getfloat ( name , 'timeout' ) , 'user' : conf . get ( name , 'user' ) , 'passwd' : conf . get ( name , 'passwd' ) , 'database' : conf . get ( name , 'database' ) , } return sessions | Return all session configurations from the rc_file file . | 191 | 11 |
19,143 | def get ( name , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : raise ValueError ( "'%s' session does not exist in %s" % ( name , rc_file ) ) return { 'type' : conf . get ( name , 'type' ) , 'host' : conf . get ( name , 'host' ) , 'protocol' : conf . get ( name , 'protocol' ) , 'port' : conf . getint ( name , 'port' ) , 'timeout' : conf . getfloat ( name , 'timeout' ) , 'user' : conf . get ( name , 'user' ) , 'passwd' : conf . get ( name , 'passwd' ) , 'database' : conf . get ( name , 'database' ) , } | Return the session configuration identified by name from the rc_file file . | 208 | 14 |
19,144 | def save ( name , data , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : conf . add_section ( name ) for key in data : value = data [ key ] conf . set ( name , key , str ( value ) ) with open ( os . path . expanduser ( rc_file ) , 'w' ) as file_ : os . chmod ( os . path . expanduser ( rc_file ) , stat . S_IREAD | stat . S_IWRITE ) conf . write ( file_ ) | Save the data session configuration under the name name in the rc_file file . | 150 | 16 |
19,145 | def remove ( name , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : raise ValueError ( "'%s' session does not exist in %s" % ( name , rc_file ) ) conf . remove_section ( name ) with open ( os . path . expanduser ( rc_file ) , 'wb' ) as file_ : conf . write ( file_ ) | Remove the session configuration identified by name from the rc_file file . | 117 | 14 |
19,146 | def get_json_log_data ( data ) : log_data = data for param in LOG_HIDDEN_JSON_PARAMS : if param in data [ 'params' ] : if log_data is data : log_data = copy . deepcopy ( data ) log_data [ 'params' ] [ param ] = "**********" return log_data | Returns a new data dictionary with hidden params for log purpose . | 79 | 12 |
19,147 | def http ( self , url , data = None , headers = None ) : return self . _connector . proxy_http ( url , data , headers ) | Low level method to execute raw HTTP queries . | 33 | 9 |
19,148 | def _check_logged_user ( self ) : if not self . _env or not self . _password or not self . _login : raise error . InternalError ( "Login required" ) | Check if a user is logged . Otherwise an error is raised . | 42 | 13 |
19,149 | def login ( self , db , login = 'admin' , password = 'admin' ) : # Get the user's ID and generate the corresponding user record data = self . json ( '/web/session/authenticate' , { 'db' : db , 'login' : login , 'password' : password } ) uid = data [ 'result' ] [ 'uid' ] if uid : context = data [ 'result' ] [ 'user_context' ] self . _env = Environment ( self , db , uid , context = context ) self . _login = login self . _password = password else : raise error . RPCError ( "Wrong login ID or password" ) | Log in as the given user with the password passwd on the database db . | 149 | 16 |
19,150 | def exec_workflow ( self , model , record_id , signal ) : if tools . v ( self . version ) [ 0 ] >= 11 : raise DeprecationWarning ( u"Workflows have been removed in Odoo >= 11.0" ) self . _check_logged_user ( ) # Execute the workflow query args_to_send = [ self . env . db , self . env . uid , self . _password , model , signal , record_id ] data = self . json ( '/jsonrpc' , { 'service' : 'object' , 'method' : 'exec_workflow' , 'args' : args_to_send } ) return data . get ( 'result' ) | Execute the workflow signal on the instance having the ID record_id of model . | 156 | 17 |
19,151 | def create ( self , password , db , demo = False , lang = 'en_US' , admin_password = 'admin' ) : self . _odoo . json ( '/jsonrpc' , { 'service' : 'db' , 'method' : 'create_database' , 'args' : [ password , db , demo , lang , admin_password ] } ) | Request the server to create a new database named db which will have admin_password as administrator password and localized with the lang parameter . You have to set the flag demo to True in order to insert demonstration data . | 82 | 42 |
19,152 | def duplicate ( self , password , db , new_db ) : self . _odoo . json ( '/jsonrpc' , { 'service' : 'db' , 'method' : 'duplicate_database' , 'args' : [ password , db , new_db ] } ) | Duplicate db as new_db . | 64 | 9 |
19,153 | def timeout ( self , timeout ) : self . _proxy_json . _timeout = timeout self . _proxy_http . _timeout = timeout | Set the timeout . | 30 | 4 |
19,154 | def is_int ( value ) : if isinstance ( value , bool ) : return False try : int ( value ) return True except ( ValueError , TypeError ) : return False | Return True if value is an integer . | 38 | 8 |
19,155 | def check_value ( self , value ) : #if self.readonly: # raise error.Error( # "'{field_name}' field is readonly".format( # field_name=self.name)) if value and self . size : if not is_string ( value ) : raise ValueError ( "Value supplied has to be a string" ) if len ( value ) > self . size : raise ValueError ( "Lenght of the '{0}' is limited to {1}" . format ( self . name , self . size ) ) if not value and self . required : raise ValueError ( "'{0}' field is required" . format ( self . name ) ) return value | Check the validity of a value for the field . | 151 | 10 |
19,156 | def _check_relation ( self , relation ) : selection = [ val [ 0 ] for val in self . selection ] if relation not in selection : raise ValueError ( ( "The value '{value}' supplied doesn't match with the possible" " values '{selection}' for the '{field_name}' field" ) . format ( value = relation , selection = selection , field_name = self . name , ) ) return relation | Raise a ValueError if relation is not allowed among the possible values . | 94 | 15 |
19,157 | def _with_context ( self , * args , * * kwargs ) : context = dict ( args [ 0 ] if args else self . env . context , * * kwargs ) return self . with_env ( self . env ( context = context ) ) | As the with_context class method but for recordset . | 57 | 12 |
19,158 | def _with_env ( self , env ) : res = self . _browse ( env , self . _ids ) return res | As the with_env class method but for recordset . | 28 | 12 |
19,159 | def _init_values ( self , context = None ) : if context is None : context = self . env . context # Get basic fields (no relational ones) basic_fields = [ ] for field_name in self . _columns : field = self . _columns [ field_name ] if not getattr ( field , 'relation' , False ) : basic_fields . append ( field_name ) # Fetch values from the server if self . ids : rows = self . __class__ . read ( self . ids , basic_fields , context = context , load = '_classic_write' ) ids_fetched = set ( ) for row in rows : ids_fetched . add ( row [ 'id' ] ) for field_name in row : if field_name == 'id' : continue self . _values [ field_name ] [ row [ 'id' ] ] = row [ field_name ] ids_in_error = set ( self . ids ) - ids_fetched if ids_in_error : raise ValueError ( "There is no '{model}' record with IDs {ids}." . format ( model = self . _name , ids = list ( ids_in_error ) ) ) # No ID: fields filled with default values else : default_get = self . __class__ . default_get ( list ( self . _columns ) , context = context ) for field_name in self . _columns : self . _values [ field_name ] [ None ] = default_get . get ( field_name , False ) | Retrieve field values from the server . May be used to restore the original values in the purpose to cancel all changes made . | 345 | 25 |
19,160 | def from_wei ( number : int , unit : str ) -> Union [ int , decimal . Decimal ] : if unit . lower ( ) not in units : raise ValueError ( "Unknown unit. Must be one of {0}" . format ( "/" . join ( units . keys ( ) ) ) ) if number == 0 : return 0 if number < MIN_WEI or number > MAX_WEI : raise ValueError ( "value must be between 1 and 2**256 - 1" ) unit_value = units [ unit . lower ( ) ] with localcontext ( ) as ctx : ctx . prec = 999 d_number = decimal . Decimal ( value = number , context = ctx ) result_value = d_number / unit_value return result_value | Takes a number of wei and converts it to any other ether unit . | 165 | 16 |
19,161 | def to_wei ( number : int , unit : str ) -> int : if unit . lower ( ) not in units : raise ValueError ( "Unknown unit. Must be one of {0}" . format ( "/" . join ( units . keys ( ) ) ) ) if is_integer ( number ) or is_string ( number ) : d_number = decimal . Decimal ( value = number ) elif isinstance ( number , float ) : d_number = decimal . Decimal ( value = str ( number ) ) elif isinstance ( number , decimal . Decimal ) : d_number = number else : raise TypeError ( "Unsupported type. Must be one of integer, float, or string" ) s_number = str ( number ) unit_value = units [ unit . lower ( ) ] if d_number == 0 : return 0 if d_number < 1 and "." in s_number : with localcontext ( ) as ctx : multiplier = len ( s_number ) - s_number . index ( "." ) - 1 ctx . prec = multiplier d_number = decimal . Decimal ( value = number , context = ctx ) * 10 ** multiplier unit_value /= 10 ** multiplier with localcontext ( ) as ctx : ctx . prec = 999 result_value = decimal . Decimal ( value = d_number , context = ctx ) * unit_value if result_value < MIN_WEI or result_value > MAX_WEI : raise ValueError ( "Resulting wei value must be between 1 and 2**256 - 1" ) return int ( result_value ) | Takes a number of a unit and converts it to wei . | 347 | 14 |
19,162 | def validate_conversion_arguments ( to_wrap ) : @ functools . wraps ( to_wrap ) def wrapper ( * args , * * kwargs ) : _assert_one_val ( * args , * * kwargs ) if kwargs : _validate_supported_kwarg ( kwargs ) if len ( args ) == 0 and "primitive" not in kwargs : _assert_hexstr_or_text_kwarg_is_text_type ( * * kwargs ) return to_wrap ( * args , * * kwargs ) return wrapper | Validates arguments for conversion functions . - Only a single argument is present - Kwarg must be primitive hexstr or text - If it is hexstr or text that it is a text type | 131 | 38 |
19,163 | def replace_exceptions ( old_to_new_exceptions : Dict [ Type [ BaseException ] , Type [ BaseException ] ] ) -> Callable [ ... , Any ] : old_exceptions = tuple ( old_to_new_exceptions . keys ( ) ) def decorator ( to_wrap : Callable [ ... , Any ] ) -> Callable [ ... , Any ] : @ functools . wraps ( to_wrap ) # String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn # Ignore so we don't have to import `Iterable` def wrapper ( * args : Iterable [ Any ] , * * kwargs : Dict [ str , Any ] ) -> Callable [ ... , Any ] : try : return to_wrap ( * args , * * kwargs ) except old_exceptions as err : try : raise old_to_new_exceptions [ type ( err ) ] from err except KeyError : raise TypeError ( "could not look up new exception to use for %r" % err ) from err return wrapper return decorator | Replaces old exceptions with new exceptions to be raised in their place . | 242 | 14 |
19,164 | def collapse_if_tuple ( abi ) : typ = abi [ "type" ] if not typ . startswith ( "tuple" ) : return typ delimited = "," . join ( collapse_if_tuple ( c ) for c in abi [ "components" ] ) # Whatever comes after "tuple" is the array dims. The ABI spec states that # this will have the form "", "[]", or "[k]". array_dim = typ [ 5 : ] collapsed = "({}){}" . format ( delimited , array_dim ) return collapsed | Converts a tuple from a dict to a parenthesized list of its types . | 130 | 17 |
19,165 | def is_hex_address ( value : Any ) -> bool : if not is_text ( value ) : return False elif not is_hex ( value ) : return False else : unprefixed = remove_0x_prefix ( value ) return len ( unprefixed ) == 40 | Checks if the given string of text type is an address in hexadecimal encoded form . | 59 | 20 |
19,166 | def is_binary_address ( value : Any ) -> bool : if not is_bytes ( value ) : return False elif len ( value ) != 20 : return False else : return True | Checks if the given string is an address in raw bytes form . | 40 | 14 |
19,167 | def is_address ( value : Any ) -> bool : if is_checksum_formatted_address ( value ) : return is_checksum_address ( value ) elif is_hex_address ( value ) : return True elif is_binary_address ( value ) : return True else : return False | Checks if the given string in a supported value is an address in any of the known formats . | 66 | 20 |
19,168 | def to_normalized_address ( value : AnyStr ) -> HexAddress : try : hex_address = hexstr_if_str ( to_hex , value ) . lower ( ) except AttributeError : raise TypeError ( "Value must be any string, instead got type {}" . format ( type ( value ) ) ) if is_address ( hex_address ) : return HexAddress ( hex_address ) else : raise ValueError ( "Unknown format {}, attempted to normalize to {}" . format ( value , hex_address ) ) | Converts an address to its normalized hexadecimal representation . | 116 | 13 |
19,169 | def is_normalized_address ( value : Any ) -> bool : if not is_address ( value ) : return False else : return value == to_normalized_address ( value ) | Returns whether the provided value is an address in its normalized form . | 40 | 13 |
19,170 | def is_canonical_address ( address : Any ) -> bool : if not is_bytes ( address ) or len ( address ) != 20 : return False return address == to_canonical_address ( address ) | Returns True if the value is an address in its canonical form . | 45 | 13 |
19,171 | def is_same_address ( left : AnyAddress , right : AnyAddress ) -> bool : if not is_address ( left ) or not is_address ( right ) : raise ValueError ( "Both values must be valid addresses" ) else : return to_normalized_address ( left ) == to_normalized_address ( right ) | Checks if both addresses are same or not . | 72 | 10 |
19,172 | def to_checksum_address ( value : AnyStr ) -> ChecksumAddress : norm_address = to_normalized_address ( value ) address_hash = encode_hex ( keccak ( text = remove_0x_prefix ( norm_address ) ) ) checksum_address = add_0x_prefix ( "" . join ( ( norm_address [ i ] . upper ( ) if int ( address_hash [ i ] , 16 ) > 7 else norm_address [ i ] ) for i in range ( 2 , 42 ) ) ) return ChecksumAddress ( HexAddress ( checksum_address ) ) | Makes a checksum address given a supported format . | 132 | 11 |
19,173 | def get_msi_token ( resource , port = 50342 , msi_conf = None ) : request_uri = os . environ . get ( "MSI_ENDPOINT" , 'http://localhost:{}/oauth2/token' . format ( port ) ) payload = { 'resource' : resource } if msi_conf : if len ( msi_conf ) > 1 : raise ValueError ( "{} are mutually exclusive" . format ( list ( msi_conf . keys ( ) ) ) ) payload . update ( msi_conf ) try : result = requests . post ( request_uri , data = payload , headers = { 'Metadata' : 'true' } ) _LOGGER . debug ( "MSI: Retrieving a token from %s, with payload %s" , request_uri , payload ) result . raise_for_status ( ) except Exception as ex : # pylint: disable=broad-except _LOGGER . warning ( "MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused " "by the MSI extension not yet fully provisioned." , request_uri , ex ) raise token_entry = result . json ( ) return token_entry [ 'token_type' ] , token_entry [ 'access_token' ] , token_entry | Get MSI token if MSI_ENDPOINT is set . | 294 | 13 |
19,174 | def get_msi_token_webapp ( resource ) : try : msi_endpoint = os . environ [ 'MSI_ENDPOINT' ] msi_secret = os . environ [ 'MSI_SECRET' ] except KeyError as err : err_msg = "{} required env variable was not found. You might need to restart your app/function." . format ( err ) _LOGGER . critical ( err_msg ) raise RuntimeError ( err_msg ) request_uri = '{}/?resource={}&api-version=2017-09-01' . format ( msi_endpoint , resource ) headers = { 'secret' : msi_secret } err = None try : result = requests . get ( request_uri , headers = headers ) _LOGGER . debug ( "MSI: Retrieving a token from %s" , request_uri ) if result . status_code != 200 : err = result . text # Workaround since not all failures are != 200 if 'ExceptionMessage' in result . text : err = result . text except Exception as ex : # pylint: disable=broad-except err = str ( ex ) if err : err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'." . format ( request_uri , err ) _LOGGER . critical ( err_msg ) raise RuntimeError ( err_msg ) _LOGGER . debug ( 'MSI: token retrieved' ) token_entry = result . json ( ) return token_entry [ 'token_type' ] , token_entry [ 'access_token' ] , token_entry | Get a MSI token from inside a webapp or functions . | 359 | 12 |
19,175 | def _configure ( self , * * kwargs ) : if kwargs . get ( 'china' ) : err_msg = ( "china parameter is deprecated, " "please use " "cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD" ) warnings . warn ( err_msg , DeprecationWarning ) self . _cloud_environment = AZURE_CHINA_CLOUD else : self . _cloud_environment = AZURE_PUBLIC_CLOUD self . _cloud_environment = kwargs . get ( 'cloud_environment' , self . _cloud_environment ) auth_endpoint = self . _cloud_environment . endpoints . active_directory resource = self . _cloud_environment . endpoints . active_directory_resource_id self . _tenant = kwargs . get ( 'tenant' , "common" ) self . _verify = kwargs . get ( 'verify' ) # 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY self . resource = kwargs . get ( 'resource' , resource ) self . _proxies = kwargs . get ( 'proxies' ) self . _timeout = kwargs . get ( 'timeout' ) self . _cache = kwargs . get ( 'cache' ) self . store_key = "{}_{}" . format ( auth_endpoint . strip ( '/' ) , self . store_key ) self . secret = None self . _context = None | Configure authentication endpoint . | 345 | 5 |
19,176 | def _convert_token ( self , token ) : # Beware that ADAL returns a pointer to its own dict, do # NOT change it in place token = token . copy ( ) # If it's from ADAL, expiresOn will be in ISO form. # Bring it back to float, using expiresIn if "expiresOn" in token and "expiresIn" in token : token [ "expiresOn" ] = token [ 'expiresIn' ] + time . time ( ) return { self . _case . sub ( r'\1_\2' , k ) . lower ( ) : v for k , v in token . items ( ) } | Convert token fields from camel case . | 142 | 8 |
19,177 | def signed_session ( self , session = None ) : self . set_token ( ) # Adal does the caching. self . _parse_token ( ) return super ( AADMixin , self ) . signed_session ( session ) | Create token - friendly Requests session using auto - refresh . Used internally when a request is made . | 51 | 20 |
19,178 | def refresh_session ( self , session = None ) : if 'refresh_token' in self . token : try : token = self . _context . acquire_token_with_refresh_token ( self . token [ 'refresh_token' ] , self . id , self . resource , self . secret # This is needed when using Confidential Client ) self . token = self . _convert_token ( token ) except adal . AdalError as err : raise_with_traceback ( AuthenticationError , "" , err ) return self . signed_session ( session ) | Return updated session if token has expired attempts to refresh using newly acquired token . | 124 | 15 |
19,179 | def _validate ( url ) : if url is None : return parsed = urlparse ( url ) if not parsed . scheme or not parsed . netloc : raise ValueError ( "Invalid URL header" ) | Validate a url . | 43 | 5 |
19,180 | def _raise_if_bad_http_status_and_method ( self , response ) : code = response . status_code if code in { 200 , 202 } or ( code == 201 and self . method in { 'PUT' , 'PATCH' } ) or ( code == 204 and self . method in { 'DELETE' , 'POST' } ) : return raise BadStatus ( "Invalid return status for {!r} operation" . format ( self . method ) ) | Check response status code is valid for a Put or Patch request . Must be 200 201 202 or 204 . | 104 | 21 |
19,181 | def _deserialize ( self , response ) : # Hacking response with initial status_code previous_status = response . status_code response . status_code = self . initial_status_code resource = self . get_outputs ( response ) response . status_code = previous_status # Hack for Storage or SQL, to workaround the bug in the Python generator if resource is None : previous_status = response . status_code for status_code_to_test in [ 200 , 201 ] : try : response . status_code = status_code_to_test resource = self . get_outputs ( response ) except ClientException : pass else : return resource finally : response . status_code = previous_status return resource | Attempt to deserialize resource from response . | 154 | 9 |
19,182 | def get_status_from_location ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) code = response . status_code if code == 202 : self . status = "InProgress" else : self . status = 'Succeeded' if self . _is_empty ( response ) : self . resource = None else : self . resource = self . _deserialize ( response ) | Process the latest status update retrieved from a location header . | 96 | 11 |
19,183 | def _polling_cookie ( self ) : parsed_url = urlparse ( self . _response . request . url ) host = parsed_url . hostname . strip ( '.' ) if host == 'localhost' : return { 'cookie' : self . _response . headers . get ( 'set-cookie' , '' ) } return { } | Collect retry cookie - we only want to do this for the test server at this point unless we implement a proper cookie policy . | 74 | 26 |
19,184 | def remove_done_callback ( self , func ) : if self . _done is None or self . _done . is_set ( ) : raise ValueError ( "Process is complete." ) self . _callbacks = [ c for c in self . _callbacks if c != func ] | Remove a callback from the long running operation . | 62 | 9 |
19,185 | def register_rp_hook ( r , * args , * * kwargs ) : if r . status_code == 409 and 'msrest' in kwargs : rp_name = _check_rp_not_registered_err ( r ) if rp_name : session = kwargs [ 'msrest' ] [ 'session' ] url_prefix = _extract_subscription_url ( r . request . url ) if not _register_rp ( session , url_prefix , rp_name ) : return req = r . request # Change the 'x-ms-client-request-id' otherwise the Azure endpoint # just returns the same 409 payload without looking at the actual query if 'x-ms-client-request-id' in req . headers : req . headers [ 'x-ms-client-request-id' ] = str ( uuid . uuid1 ( ) ) return session . send ( req ) | This is a requests hook to register RP automatically . | 207 | 10 |
19,186 | def _register_rp ( session , url_prefix , rp_name ) : post_url = "{}providers/{}/register?api-version=2016-02-01" . format ( url_prefix , rp_name ) get_url = "{}providers/{}?api-version=2016-02-01" . format ( url_prefix , rp_name ) _LOGGER . warning ( "Resource provider '%s' used by this operation is not " "registered. We are registering for you." , rp_name ) post_response = session . post ( post_url ) if post_response . status_code != 200 : _LOGGER . warning ( "Registration failed. Please register manually." ) return False while True : time . sleep ( 10 ) rp_info = session . get ( get_url ) . json ( ) if rp_info [ 'registrationState' ] == 'Registered' : _LOGGER . warning ( "Registration succeeded." ) return True | Synchronously register the RP is paremeter . Return False if we have a reason to believe this didn t work | 220 | 24 |
19,187 | def parse_resource_id ( rid ) : if not rid : return { } match = _ARMID_RE . match ( rid ) if match : result = match . groupdict ( ) children = _CHILDREN_RE . finditer ( result [ 'children' ] or '' ) count = None for count , child in enumerate ( children ) : result . update ( { key + '_%d' % ( count + 1 ) : group for key , group in child . groupdict ( ) . items ( ) } ) result [ 'last_child_num' ] = count + 1 if isinstance ( count , int ) else None result = _populate_alternate_kwargs ( result ) else : result = dict ( name = rid ) return { key : value for key , value in result . items ( ) if value is not None } | Parses a resource_id into its various parts . | 182 | 12 |
19,188 | def _populate_alternate_kwargs ( kwargs ) : resource_namespace = kwargs [ 'namespace' ] resource_type = kwargs . get ( 'child_type_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'type' ] resource_name = kwargs . get ( 'child_name_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'name' ] _get_parents_from_parts ( kwargs ) kwargs [ 'resource_namespace' ] = resource_namespace kwargs [ 'resource_type' ] = resource_type kwargs [ 'resource_name' ] = resource_name return kwargs | Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands . | 177 | 22 |
19,189 | def _get_parents_from_parts ( kwargs ) : parent_builder = [ ] if kwargs [ 'last_child_num' ] is not None : parent_builder . append ( '{type}/{name}/' . format ( * * kwargs ) ) for index in range ( 1 , kwargs [ 'last_child_num' ] ) : child_namespace = kwargs . get ( 'child_namespace_{}' . format ( index ) ) if child_namespace is not None : parent_builder . append ( 'providers/{}/' . format ( child_namespace ) ) kwargs [ 'child_parent_{}' . format ( index ) ] = '' . join ( parent_builder ) parent_builder . append ( '{{child_type_{0}}}/{{child_name_{0}}}/' . format ( index ) . format ( * * kwargs ) ) child_namespace = kwargs . get ( 'child_namespace_{}' . format ( kwargs [ 'last_child_num' ] ) ) if child_namespace is not None : parent_builder . append ( 'providers/{}/' . format ( child_namespace ) ) kwargs [ 'child_parent_{}' . format ( kwargs [ 'last_child_num' ] ) ] = '' . join ( parent_builder ) kwargs [ 'resource_parent' ] = '' . join ( parent_builder ) if kwargs [ 'name' ] else None return kwargs | Get the parents given all the children parameters . | 346 | 9 |
19,190 | def resource_id ( * * kwargs ) : kwargs = { k : v for k , v in kwargs . items ( ) if v is not None } rid_builder = [ '/subscriptions/{subscription}' . format ( * * kwargs ) ] try : try : rid_builder . append ( 'resourceGroups/{resource_group}' . format ( * * kwargs ) ) except KeyError : pass rid_builder . append ( 'providers/{namespace}' . format ( * * kwargs ) ) rid_builder . append ( '{type}/{name}' . format ( * * kwargs ) ) count = 1 while True : try : rid_builder . append ( 'providers/{{child_namespace_{}}}' . format ( count ) . format ( * * kwargs ) ) except KeyError : pass rid_builder . append ( '{{child_type_{0}}}/{{child_name_{0}}}' . format ( count ) . format ( * * kwargs ) ) count += 1 except KeyError : pass return '/' . join ( rid_builder ) | Create a valid resource id string from the given parts . | 251 | 11 |
19,191 | def is_valid_resource_id ( rid , exception_type = None ) : is_valid = False try : is_valid = rid and resource_id ( * * parse_resource_id ( rid ) ) . lower ( ) == rid . lower ( ) except KeyError : pass if not is_valid and exception_type : raise exception_type ( ) return is_valid | Validates the given resource id . | 81 | 7 |
19,192 | def is_valid_resource_name ( rname , exception_type = None ) : match = _ARMNAME_RE . match ( rname ) if match : return True if exception_type : raise exception_type ( ) return False | Validates the given resource name to ARM guidelines individual services may be more restrictive . | 50 | 16 |
19,193 | async def _delay ( self ) : if self . _response is None : await asyncio . sleep ( 0 ) if self . _response . headers . get ( 'retry-after' ) : await asyncio . sleep ( int ( self . _response . headers [ 'retry-after' ] ) ) else : await asyncio . sleep ( self . _timeout ) | Check for a retry - after header to set timeout otherwise use configured timeout . | 80 | 16 |
19,194 | async def update_status ( self ) : if self . _operation . async_url : self . _response = await self . request_status ( self . _operation . async_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_async ( self . _response ) elif self . _operation . location_url : self . _response = await self . request_status ( self . _operation . location_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_location ( self . _response ) elif self . _operation . method == "PUT" : initial_url = self . _operation . initial_response . request . url self . _response = await self . request_status ( initial_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_resource ( self . _response ) else : raise BadResponse ( "Unable to find status link for polling." ) | Update the current status of the LRO . | 253 | 9 |
19,195 | async def request_status ( self , status_link ) : # ARM requires to re-inject 'x-ms-client-request-id' while polling header_parameters = { 'x-ms-client-request-id' : self . _operation . initial_response . request . headers [ 'x-ms-client-request-id' ] } request = self . _client . get ( status_link , headers = header_parameters ) return await self . _client . async_send ( request , stream = False , * * self . _operation_config ) | Do a simple GET to this status link . | 125 | 9 |
19,196 | def message ( self , value ) : try : import ast value = ast . literal_eval ( value ) except ( SyntaxError , TypeError , ValueError ) : pass try : value = value . get ( 'value' , value ) msg_data = value . split ( '\n' ) self . _message = msg_data [ 0 ] except AttributeError : self . _message = value return try : self . request_id = msg_data [ 1 ] . partition ( ':' ) [ 2 ] time_str = msg_data [ 2 ] . partition ( ':' ) self . error_time = Deserializer . deserialize_iso ( "" . join ( time_str [ 2 : ] ) ) except ( IndexError , DeserializationError ) : pass | Attempt to deconstruct error message to retrieve further error data . | 166 | 12 |
19,197 | def get_cloud_from_metadata_endpoint ( arm_endpoint , name = None , session = None ) : cloud = Cloud ( name or arm_endpoint ) cloud . endpoints . management = arm_endpoint cloud . endpoints . resource_manager = arm_endpoint _populate_from_metadata_endpoint ( cloud , arm_endpoint , session ) return cloud | Get a Cloud object from an ARM endpoint . | 83 | 9 |
19,198 | def _as_json ( self , response ) : # Assume ClientResponse has "body", and otherwise it's a requests.Response content = response . text ( ) if hasattr ( response , "body" ) else response . text try : return json . loads ( content ) except ValueError : raise DeserializationError ( "Error occurred in deserializing the response body." ) | Assuming this is not empty return the content as JSON . | 80 | 11 |
19,199 | def should_do_final_get ( self ) : return ( ( self . async_url or not self . resource ) and self . method in { 'PUT' , 'PATCH' } ) or ( self . lro_options [ 'final-state-via' ] == _LOCATION_FINAL_STATE and self . location_url and self . async_url and self . method == 'POST' ) | Check whether the polling should end doing a final GET . | 89 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.