idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
19,200 | def visualize_diagram ( bpmn_diagram ) : g = bpmn_diagram . diagram_graph pos = bpmn_diagram . get_nodes_positions ( ) nx . draw_networkx_nodes ( g , pos , node_shape = 's' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . task ) ) nx . draw_networkx_nodes ( g , pos , node... | Shows a simple visualization of diagram |
19,201 | 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 = no... | Create a png picture for given diagram |
19,202 | 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 . |
19,203 | 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 |
19,204 | 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 ] = {... | Adds a new process to diagram and corresponding participant process diagram and plane |
19,205 | 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 . no... | 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 . |
19,206 | 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 ) ... | Adds a StartEvent element to BPMN diagram . |
19,207 | 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_direc... | Adds an inclusiveGateway element to BPMN diagram . |
19,208 | 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_direct... | Adds an parallelGateway element to BPMN diagram . |
19,209 | 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 . |
19,210 | 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:0... | Create a directory tree at path with given depth and NUM_DIRS and NUM_FILES at each level . |
19,211 | 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 . |
19,212 | def unfold ( tensor , mode ) : return np . moveaxis ( tensor , mode , 0 ) . reshape ( ( tensor . shape [ mode ] , - 1 ) ) | Returns the mode - mode unfolding of tensor . |
19,213 | 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 ... | Khatri - Rao product of a list of matrices . |
19,214 | def soft_cluster_factor ( factor ) : f = np . copy ( factor ) cluster_ids = np . argmax ( np . abs ( f ) , axis = 1 ) scores = f [ range ( f . shape [ 0 ] ) , cluster_ids ] perm = [ ] for cluster in np . unique ( cluster_ids ) : idx = np . where ( cluster_ids == cluster ) [ 0 ] perm += list ( idx [ np . argsort ( score... | Returns soft - clustering of data based on CP decomposition results . |
19,215 | 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 . |
19,216 | 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 . |
19,217 | def full ( self ) : unf = sci . dot ( self . factors [ 0 ] , khatri_rao ( self . factors [ 1 : ] ) . T ) return sci . reshape ( unf , self . shape ) | Converts KTensor to a dense ndarray . |
19,218 | def rebalance ( self ) : norms = [ sci . linalg . norm ( f , axis = 0 ) for f in self . factors ] lam = sci . multiply . reduce ( norms ) ** ( 1 / self . ndim ) self . factors = [ f * ( lam / fn ) for f , fn in zip ( self . factors , norms ) ] return self | Rescales factors across modes so that all norms match . |
19,219 | def permute ( self , idx ) : if set ( idx ) != set ( range ( self . rank ) ) : raise ValueError ( 'Invalid permutation specified.' ) self . factors = [ f [ : , idx ] for f in self . factors ] return self . factors | Permutes the columns of the factor matrices inplace |
19,220 | def kruskal_align ( U , V , permute_U = False , permute_V = False ) : 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... | Aligns two KTensors and returns a similarity score . |
19,221 | 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 ( "pa... | Plots objective function as a function of model rank . |
19,222 | def plot_similarity ( ensemble , ax = None , jitter = 0.1 , scatter_kw = dict ( ) , line_kw = dict ( ) ) : if ax is None : ax = plt . gca ( ) x , sim , mean_sim = [ ] , [ ] , [ ] for rank in sorted ( ensemble . results ) : s = ensemble . similarities ( rank ) [ 1 : ] sim . extend ( s ) x . extend ( np . full ( len ( s ... | Plots similarity across optimization runs as a function of model rank . |
19,223 | def _broadcast_arg ( U , arg , argtype , name ) : if arg is None or isinstance ( arg , argtype ) : return [ arg for _ in range ( U . ndim ) ] 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... | Broadcasts plotting option arg to all factors . |
19,224 | 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 . |
19,225 | 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 . |
19,226 | def randn_ktensor ( shape , rank , norm = None , random_state = None ) : rns = _check_random_state ( random_state ) 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 . |
19,227 | def fit ( self , X , ranks , replicates = 1 , verbose = True ) : if not isinstance ( ranks , collections . Iterable ) : ranks = ( ranks , ) for r in ranks : if r not in self . results : self . results [ r ] = [ ] if verbose : itr = trange ( replicates , desc = 'Fitting rank-{} models' . format ( r ) , leave = False ) e... | Fits CP tensor decompositions for different choices of rank . |
19,228 | 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 . |
19,229 | 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 . |
19,230 | 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 . |
19,231 | def _create_model_class ( self , model ) : cls_name = model . replace ( '.' , '_' ) if sys . version_info [ 0 ] < 3 : if isinstance ( cls_name , unicode ) : cls_name = cls_name . encode ( 'utf-8' ) attrs = { '_env' : self , '_odoo' : self . _odoo , '_name' : model , '_columns' : { } , } fields_get = self . _odoo . exec... | Generate the model proxy class . |
19,232 | 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' ) ,... | Return all session configurations from the rc_file file . |
19,233 | 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 , 'h... | Return the session configuration identified by name from the rc_file file . |
19,234 | 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_f... | Save the data session configuration under the name name in the rc_file file . |
19,235 | 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 )... | Remove the session configuration identified by name from the rc_file file . |
19,236 | 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 . |
19,237 | def http ( self , url , data = None , headers = None ) : return self . _connector . proxy_http ( url , data , headers ) | Low level method to execute raw HTTP queries . |
19,238 | 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 . |
19,239 | def login ( self , db , login = 'admin' , password = 'admin' ) : 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 = ... | Log in as the given user with the password passwd on the database db . |
19,240 | 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 ( ) args_to_send = [ self . env . db , self . env . uid , self . _password , model , signal , record_id ] data = s... | Execute the workflow signal on the instance having the ID record_id of model . |
19,241 | 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 . |
19,242 | 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 . |
19,243 | def timeout ( self , timeout ) : self . _proxy_json . _timeout = timeout self . _proxy_http . _timeout = timeout | Set the timeout . |
19,244 | 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 . |
19,245 | def check_value ( self , value ) : 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 : rais... | Check the validity of a value for the field . |
19,246 | 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 , ... | Raise a ValueError if relation is not allowed among the possible values . |
19,247 | 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 . |
19,248 | def _with_env ( self , env ) : res = self . _browse ( env , self . _ids ) return res | As the with_env class method but for recordset . |
19,249 | def _init_values ( self , context = None ) : if context is None : context = self . env . context basic_fields = [ ] for field_name in self . _columns : field = self . _columns [ field_name ] if not getattr ( field , 'relation' , False ) : basic_fields . append ( field_name ) if self . ids : rows = self . __class__ . re... | Retrieve field values from the server . May be used to restore the original values in the purpose to cancel all changes made . |
19,250 | 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... | Takes a number of wei and converts it to any other ether unit . |
19,251 | 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 )... | Takes a number of a unit and converts it to wei . |
19,252 | 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... | 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 |
19,253 | 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 ) def wrapper (... | Replaces old exceptions with new exceptions to be raised in their place . |
19,254 | 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" ] ) array_dim = typ [ 5 : ] collapsed = "({}){}" . format ( delimited , array_dim ) return collapsed | Converts a tuple from a dict to a parenthesized list of its types . |
19,255 | 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 . |
19,256 | 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 . |
19,257 | 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 . |
19,258 | 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 : r... | Converts an address to its normalized hexadecimal representation . |
19,259 | 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 . |
19,260 | 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 . |
19,261 | 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 . |
19,262 | 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 nor... | Makes a checksum address given a supported format . |
19,263 | 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_co... | Get MSI token if MSI_ENDPOINT is set . |
19,264 | 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 RuntimeE... | Get a MSI token from inside a webapp or functions . |
19,265 | 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 ... | Configure authentication endpoint . |
19,266 | def _convert_token ( self , token ) : token = token . copy ( ) 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 . |
19,267 | def signed_session ( self , session = None ) : self . set_token ( ) 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 . |
19,268 | 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 ) self . token = self . _convert_token ( token ) except adal . AdalError as err : raise_w... | Return updated session if token has expired attempts to refresh using newly acquired token . |
19,269 | 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 . |
19,270 | 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 (... | Check response status code is valid for a Put or Patch request . Must be 200 201 202 or 204 . |
19,271 | def _deserialize ( self , response ) : previous_status = response . status_code response . status_code = self . initial_status_code resource = self . get_outputs ( response ) response . status_code = previous_status if resource is None : previous_status = response . status_code for status_code_to_test in [ 200 , 201 ] ... | Attempt to deserialize resource from response . |
19,272 | 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 . _deserializ... | Process the latest status update retrieved from a location header . |
19,273 | 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 . |
19,274 | 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 . |
19,275 | 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 ) :... | This is a requests hook to register RP automatically . |
19,276 | 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.... | Synchronously register the RP is paremeter . Return False if we have a reason to believe this didn t work |
19,277 | 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 ke... | Parses a resource_id into its various parts . |
19,278 | 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_paren... | Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands . |
19,279 | 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_name... | Get the parents given all the children parameters . |
19,280 | 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 ( 'provid... | Create a valid resource id string from the given parts . |
19,281 | 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 . |
19,282 | 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 . |
19,283 | 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 . |
19,284 | 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 : ... | Update the current status of the LRO . |
19,285 | async def request_status ( self , status_link ) : 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 , str... | Do a simple GET to this status link . |
19,286 | 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 .... | Attempt to deconstruct error message to retrieve further error data . |
19,287 | 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 . |
19,288 | def _as_json ( self , 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 . |
19,289 | 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 . |
19,290 | def set_initial_status ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : self . resource = None else : try : self . resource = self . _deserialize ( response ) except DeserializationError : self . resource = None self . set_async_url_if_present ( response ... | Process first response after initiating long running operation and set self . status attribute . |
19,291 | def parse_resource ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if not self . _is_empty ( response ) : self . resource = self . _deserialize ( response ) else : self . resource = None | Assuming this response is a resource use the deserialization callback to parse it . If body is empty assuming no resource to return . |
19,292 | def get_status_from_async ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : raise BadResponse ( 'The response from long running operation ' 'does not contain a body.' ) self . status = self . _get_async_status ( response ) if not self . status : raise BadR... | Process the latest status update retrieved from a azure - asyncoperation header . |
19,293 | def initialize ( self , client , initial_response , deserialization_callback ) : self . _client = client self . _response = initial_response self . _operation = LongRunningOperation ( initial_response , deserialization_callback , self . _lro_options ) try : self . _operation . set_initial_status ( initial_response ) ex... | Set the initial status of this LRO . |
19,294 | def worker ( ) : import torch import torch . distributed as dist from torch . multiprocessing import Process import numpy as np print ( "Initializing distributed pytorch" ) os . environ [ 'MASTER_ADDR' ] = str ( args . master_addr ) os . environ [ 'MASTER_PORT' ] = str ( args . master_port ) dist . init_process_group (... | Initialize the distributed environment . |
19,295 | def make_job ( name : str = '' , run_name : str = '' , num_tasks : int = 0 , install_script : str = '' , ** kwargs ) -> backend . Job : return _backend . make_job ( name = name , run_name = run_name , num_tasks = num_tasks , install_script = install_script , ** kwargs ) | Create a job using current backend . Blocks until all tasks are up and initialized . |
19,296 | def make_task ( name = '' , run_name = '' , ** kwargs ) -> Task : ncluster_globals . task_launched = True name = ncluster_globals . auto_assign_task_name_if_needed ( name ) tmux_session = name . replace ( '.' , '=' ) tmux_window_id = 0 util . log ( f'killing session {tmux_session}' ) if not util . is_set ( "NCLUSTER_NO... | Create task also create dummy run if not specified . |
19,297 | def _run_raw ( self , cmd , ignore_errors = False ) : result = os . system ( cmd ) if result != 0 : if ignore_errors : self . log ( f"command ({cmd}) failed." ) assert False , "_run_raw failed" | Runs command directly skipping tmux interface |
19,298 | def upload ( self , local_fn , remote_fn = None , dont_overwrite = False ) : if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if remote_fn is None : remote_fn = os . path . basename ( local_fn ) if dont_overwrite and self . exists ( remote_fn ) : self . log ( "Remo... | Uploads file to remote instance . If location not specified dumps it into default directory . Creates missing directories in path name . |
19,299 | def logdir ( self ) : run_name = ncluster_globals . get_run_for_task ( self ) logdir = ncluster_globals . get_logdir ( run_name ) if logdir : return logdir if ncluster_globals . is_chief ( self , run_name ) : chief = self else : chief = ncluster_globals . get_chief ( run_name ) chief . setup_logdir ( ) return ncluster_... | Returns logging directory creating one if necessary . See Logdir section of design doc on naming convention . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.