idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
19,800 | def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if attrs is None : attrs = self . read_json ( ) if ignore is None : ignore = set ( ) ignore . add ( 'password' ) return super ( Registry , self ) . read ( entity , attrs , ignore , params ) | Do not read the password argument . |
19,801 | def create_missing ( self ) : if getattr ( self , 'content_type' , '' ) == 'docker' : self . _fields [ 'docker_upstream_name' ] . required = True super ( Repository , self ) . create_missing ( ) | Conditionally mark docker_upstream_name as required . |
19,802 | def upload_content ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . post ( self . path ( 'upload_content' ) , ** kwargs ) json = _handle_response ( response , self . _server_config , synchronous ) if json [ 'stat... | Upload a file or files to the current repository . |
19,803 | def import_uploads ( self , uploads = None , upload_ids = None , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) if uploads : data = { 'uploads' : uploads } elif upload_ids : data = { 'upload_ids' : upload_ids } response = client . put ( se... | Import uploads into a repository |
19,804 | def available_repositories ( self , ** kwargs ) : if 'data' not in kwargs : kwargs [ 'data' ] = dict ( ) kwargs [ 'data' ] [ 'product_id' ] = self . product . id kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . path ( 'available_repositories' ... | Lists available repositories for the repository set |
19,805 | def enable ( self , synchronous = True , ** kwargs ) : if 'data' not in kwargs : kwargs [ 'data' ] = dict ( ) kwargs [ 'data' ] [ 'product_id' ] = self . product . id kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . put ( self . path ( 'enable' ) , ** kwar... | Enables the RedHat Repository |
19,806 | def import_puppetclasses ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) if 'environment' in kwargs : if isinstance ( kwargs [ 'environment' ] , Environment ) : environment_id = kwargs . pop ( 'environment' ) . id else : environmen... | Import puppet classes from puppet Capsule . |
19,807 | def _org_path ( self , which , payload ) : return Subscription ( self . _server_config , organization = payload [ 'organization_id' ] , ) . path ( which ) | A helper method for generating paths with organization IDs in them . |
19,808 | def manifest_history ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . _org_path ( 'manifest_history' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , s... | Obtain manifest history for subscriptions . |
19,809 | def read ( self , entity = None , attrs = None , ignore = None , params = None ) : if ignore is None : ignore = set ( ) ignore . add ( 'organization' ) return super ( Subscription , self ) . read ( entity , attrs , ignore , params ) | Ignore organization field as it s never returned by the server and is only added to entity to be able to use organization path dependent helpers . |
19,810 | def refresh_manifest ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . put ( self . _org_path ( 'refresh_manifest' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , s... | Refresh previously imported manifest for Red Hat provider . |
19,811 | def upload ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . post ( self . _org_path ( 'upload' , kwargs [ 'data' ] ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous , timeou... | Upload a subscription manifest . |
19,812 | def create_payload ( self ) : data = super ( SyncPlan , self ) . create_payload ( ) if isinstance ( data . get ( 'sync_date' ) , datetime ) : data [ 'sync_date' ] = data [ 'sync_date' ] . strftime ( '%Y-%m-%d %H:%M:%S' ) return data | Convert sync_date to a string . |
19,813 | def update_payload ( self , fields = None ) : data = super ( SyncPlan , self ) . update_payload ( fields ) if isinstance ( data . get ( 'sync_date' ) , datetime ) : data [ 'sync_date' ] = data [ 'sync_date' ] . strftime ( '%Y-%m-%d %H:%M:%S' ) return data | Convert sync_date to a string if datetime object provided . |
19,814 | def deploy_script ( self , synchronous = True , ** kwargs ) : kwargs = kwargs . copy ( ) kwargs . update ( self . _server_config . get_client_kwargs ( ) ) response = client . get ( self . path ( 'deploy_script' ) , ** kwargs ) return _handle_response ( response , self . _server_config , synchronous ) | Helper for Config s deploy_script method . |
19,815 | def ensure_local_net ( network_name : str = DOCKER_STARCRAFT_NETWORK , subnet_cidr : str = SUBNET_CIDR ) -> None : logger . info ( f"checking whether docker has network {network_name}" ) ipam_pool = docker . types . IPAMPool ( subnet = subnet_cidr ) ipam_config = docker . types . IPAMConfig ( pool_configs = [ ipam_pool... | Create docker local net if not found . |
19,816 | def ensure_local_image ( local_image : str , parent_image : str = SC_PARENT_IMAGE , java_image : str = SC_JAVA_IMAGE , starcraft_base_dir : str = SCBW_BASE_DIR , starcraft_binary_link : str = SC_BINARY_LINK , ) -> None : logger . info ( f"checking if there is local image {local_image}" ) docker_images = docker_client .... | Check if local_image is present locally . If it is not pull parent images and build . This includes pulling starcraft binary . |
19,817 | def check_dockermachine ( ) -> bool : logger . debug ( "checking docker-machine presence" ) try : out = subprocess . check_output ( [ "docker-machine" , "version" ] ) . decode ( "utf-8" ) . replace ( "docker-machine.exe" , "" ) . replace ( "docker-machine" , "" ) . strip ( ) logger . debug ( f"using docker machine vers... | Checks that docker - machine is available on the computer |
19,818 | def dockermachine_ip ( ) -> Optional [ str ] : if not check_dockermachine ( ) : return None try : out = subprocess . check_output ( [ 'docker-machine' , 'ip' ] ) return out . decode ( "utf-8" ) . strip ( ) except Exception : logger . debug ( f"docker machine not present" ) return None | Gets IP address of the default docker machine Returns None if no docker - machine executable in the PATH and if there no Docker machine with name default present |
19,819 | def xoscmounts ( host_mount ) : callback_lower_drive_letter = lambda pat : pat . group ( 1 ) . lower ( ) host_mount = re . sub ( r"^([a-zA-Z])\:" , callback_lower_drive_letter , host_mount ) host_mount = re . sub ( r"^([a-z])" , "//\\1" , host_mount ) host_mount = re . sub ( r"\\" , "/" , host_mount ) return host_mount | Cross OS compatible mount dirs |
19,820 | def chisquare ( n_ij , weighted ) : if weighted : m_ij = n_ij / n_ij nan_mask = np . isnan ( m_ij ) m_ij [ nan_mask ] = 0.000001 w_ij = m_ij n_ij_col_sum = n_ij . sum ( axis = 1 ) n_ij_row_sum = n_ij . sum ( axis = 0 ) alpha , beta , eps = ( 1 , 1 , 1 ) while eps > 10e-6 : alpha = alpha * np . vstack ( n_ij_col_sum / m... | Calculates the chisquare for a matrix of ind_v x dep_v for the unweighted and SPSS weighted case |
19,821 | def best_split ( self , ind , dep ) : if isinstance ( dep , ContinuousColumn ) : return self . best_con_split ( ind , dep ) else : return self . best_cat_heuristic_split ( ind , dep ) | determine which splitting function to apply |
19,822 | def from_numpy ( ndarr , arr , alpha_merge = 0.05 , max_depth = 2 , min_parent_node_size = 30 , min_child_node_size = 30 , split_titles = None , split_threshold = 0 , weights = None , variable_types = None , dep_variable_type = 'categorical' ) : vectorised_array = [ ] variable_types = variable_types or [ 'nominal' ] * ... | Create a CHAID object from numpy |
19,823 | def build_tree ( self ) : self . _tree_store = [ ] self . node ( np . arange ( 0 , self . data_size , dtype = np . int ) , self . vectorised_array , self . observed ) | Build chaid tree |
19,824 | def from_pandas_df ( df , i_variables , d_variable , alpha_merge = 0.05 , max_depth = 2 , min_parent_node_size = 30 , min_child_node_size = 30 , split_threshold = 0 , weight = None , dep_variable_type = 'categorical' ) : ind_df = df [ list ( i_variables . keys ( ) ) ] ind_values = ind_df . values dep_values = df [ d_va... | Helper method to pre - process a pandas data frame in order to run CHAID analysis |
19,825 | def node ( self , rows , ind , dep , depth = 0 , parent = None , parent_decisions = None ) : depth += 1 if self . max_depth < depth : terminal_node = Node ( choices = parent_decisions , node_id = self . node_count , parent = parent , indices = rows , dep_v = dep ) self . _tree_store . append ( terminal_node ) self . no... | internal method to create a node in the tree |
19,826 | def to_tree ( self ) : tree = TreeLibTree ( ) for node in self : tree . create_node ( node , node . node_id , parent = node . parent ) return tree | returns a TreeLib tree |
19,827 | def node_predictions ( self ) : pred = np . zeros ( self . data_size ) for node in self : if node . is_terminal : pred [ node . indices ] = node . node_id return pred | Determines which rows fall into which node |
19,828 | def model_predictions ( self ) : if isinstance ( self . observed , ContinuousColumn ) : return ValueError ( "Cannot make model predictions on a continuous scale" ) pred = np . zeros ( self . data_size ) . astype ( 'object' ) for node in self : if node . is_terminal : pred [ node . indices ] = max ( node . members , key... | Determines the highest frequency of categorical dependent variable in the terminal node where that row fell |
19,829 | def bell_set ( self , collection , ordinal = False ) : if len ( collection ) == 1 : yield [ collection ] return first = collection [ 0 ] for smaller in self . bell_set ( collection [ 1 : ] ) : for n , subset in enumerate ( smaller ) : if not ordinal or ( ordinal and is_sorted ( smaller [ : n ] + [ [ first ] + subset ] ... | Calculates the Bell set |
19,830 | def substitute_values ( self , vect ) : try : unique = np . unique ( vect ) except : unique = set ( vect ) unique = [ x for x in unique if not isinstance ( x , float ) or not isnan ( x ) ] arr = np . copy ( vect ) for new_id , value in enumerate ( unique ) : np . place ( arr , arr == value , new_id ) self . metadata [ ... | Internal method to substitute integers into the vector and construct metadata to convert back to the original vector . |
19,831 | def sub_split_values ( self , sub ) : for i , arr in enumerate ( self . splits ) : self . split_map [ i ] = [ sub . get ( x , x ) for x in arr ] for split in self . surrogates : split . sub_split_values ( sub ) | Substitutes the splits with other values into the split_map |
19,832 | def name_columns ( self , sub ) : if self . column_id is not None and len ( sub ) > self . column_id : self . split_name = sub [ self . column_id ] for split in self . surrogates : split . name_columns ( sub ) | Substitutes the split column index with a human readable string |
19,833 | def three_partition ( x ) : f = [ 0 ] * ( 1 << len ( x ) ) for i in range ( len ( x ) ) : for S in range ( 1 << i ) : f [ S | ( 1 << i ) ] = f [ S ] + x [ i ] for A in range ( 1 << len ( x ) ) : for B in range ( 1 << len ( x ) ) : if A & B == 0 and f [ A ] == f [ B ] and 3 * f [ A ] == f [ - 1 ] : return ( A , B , ( ( ... | partition a set of integers in 3 parts of same total value |
19,834 | def freivalds ( A , B , C ) : n = len ( A ) x = [ randint ( 0 , 1000000 ) for j in range ( n ) ] return mult ( A , mult ( B , x ) ) == mult ( C , x ) | Tests matrix product AB = C by Freivalds |
19,835 | def min_scalar_prod ( x , y ) : x = sorted ( x ) y = sorted ( y ) return sum ( x [ i ] * y [ - i - 1 ] for i in range ( len ( x ) ) ) | Permute vector to minimize scalar product |
19,836 | def laser_mirrors ( rows , cols , mir ) : n = len ( mir ) orien = [ None ] * ( n + 2 ) orien [ n ] = 0 orien [ n + 1 ] = 0 succ = [ [ None for direc in range ( 4 ) ] for i in range ( n + 2 ) ] L = [ ( mir [ i ] [ 0 ] , mir [ i ] [ 1 ] , i ) for i in range ( n ) ] L . append ( ( 0 , - 1 , n ) ) L . append ( ( 0 , cols ,... | Orienting mirrors to allow reachability by laser beam |
19,837 | def solve ( succ , orien , i , direc ) : assert orien [ i ] is not None j = succ [ i ] [ direc ] if j is None : return False if j == len ( orien ) - 1 : return True if orien [ j ] is None : for x in [ 0 , 1 ] : orien [ j ] = x if solve ( succ , orien , j , reflex [ direc ] [ x ] ) : return True orien [ j ] = None retur... | Can a laser leaving mirror i in direction direc reach exit ? |
19,838 | def dancing_links ( size_universe , sets ) : header = Cell ( None , None , 0 , None ) col = [ ] for j in range ( size_universe ) : col . append ( Cell ( header , None , 0 , None ) ) for i in range ( len ( sets ) ) : row = None for j in sets [ i ] : col [ j ] . S += 1 row = Cell ( row , col [ j ] , i , col [ j ] ) sol =... | Exact set cover by the dancing links algorithm |
19,839 | def two_sat ( formula ) : n = max ( abs ( clause [ p ] ) for p in ( 0 , 1 ) for clause in formula ) graph = [ [ ] for node in range ( 2 * n ) ] for x , y in formula : graph [ _vertex ( - x ) ] . append ( _vertex ( y ) ) graph [ _vertex ( - y ) ] . append ( _vertex ( x ) ) sccp = tarjan ( graph ) comp_id = [ None ] * ( ... | Solving a 2 - SAT boolean formula |
19,840 | def rectangles_from_grid ( P , black = 1 ) : rows = len ( P ) cols = len ( P [ 0 ] ) t = [ 0 ] * cols best = None for i in range ( rows ) : for j in range ( cols ) : if P [ i ] [ j ] == black : t [ j ] += 1 else : t [ j ] = 0 ( area , left , height , right ) = rectangles_from_histogram ( t ) alt = ( area , left , i , r... | Largest area rectangle in a binary matrix |
19,841 | def min_mean_cycle ( graph , weight , start = 0 ) : INF = float ( 'inf' ) n = len ( graph ) dist = [ [ INF ] * n ] prec = [ [ None ] * n ] dist [ 0 ] [ start ] = 0 for ell in range ( 1 , n + 1 ) : dist . append ( [ INF ] * n ) prec . append ( [ None ] * n ) for node in range ( n ) : for neighbor in graph [ node ] : alt... | Minimum mean cycle by Karp |
19,842 | def floyd_warshall ( weight ) : V = range ( len ( weight ) ) for k in V : for u in V : for v in V : weight [ u ] [ v ] = min ( weight [ u ] [ v ] , weight [ u ] [ k ] + weight [ k ] [ v ] ) for v in V : if weight [ v ] [ v ] < 0 : return True return False | All pairs shortest paths by Floyd - Warshall |
19,843 | def bellman_ford ( graph , weight , source = 0 ) : n = len ( graph ) dist = [ float ( 'inf' ) ] * n prec = [ None ] * n dist [ source ] = 0 for nb_iterations in range ( n ) : changed = False for node in range ( n ) : for neighbor in graph [ node ] : alt = dist [ node ] + weight [ node ] [ neighbor ] if alt < dist [ nei... | Single source shortest paths by Bellman - Ford |
19,844 | def roman2int ( s ) : val = 0 pos10 = 1000 beg = 0 for pos in range ( 3 , - 1 , - 1 ) : for digit in range ( 9 , - 1 , - 1 ) : r = roman [ pos ] [ digit ] if s . startswith ( r , beg ) : beg += len ( r ) val += digit * pos10 break pos10 //= 10 return val | Decode roman number |
19,845 | def int2roman ( val ) : s = '' pos10 = 1000 for pos in range ( 3 , - 1 , - 1 ) : digit = val // pos10 s += roman [ pos ] [ digit ] val %= pos10 pos10 //= 10 return s | Code roman number |
19,846 | def dijkstra ( graph , weight , source = 0 , target = None ) : n = len ( graph ) assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] ) prec = [ None ] * n black = [ False ] * n dist = [ float ( 'inf' ) ] * n dist [ source ] = 0 heap = [ ( 0 , source ) ] while heap : dist_node , node = heappop... | single source shortest paths by Dijkstra |
19,847 | def dijkstra_update_heap ( graph , weight , source = 0 , target = None ) : n = len ( graph ) assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] ) prec = [ None ] * n dist = [ float ( 'inf' ) ] * n dist [ source ] = 0 heap = OurHeap ( [ ( dist [ node ] , node ) for node in range ( n ) ] ) whi... | single source shortest paths by Dijkstra with a heap implementing item updates |
19,848 | def manacher ( s ) : assert set . isdisjoint ( { '$' , '^' , '#' } , s ) if s == "" : return ( 0 , 1 ) t = "^#" + "#" . join ( s ) + "#$" c = 1 d = 1 p = [ 0 ] * len ( t ) for i in range ( 2 , len ( t ) - 1 ) : mirror = 2 * c - i p [ i ] = max ( 0 , min ( d - i , p [ mirror ] ) ) while t [ i + 1 + p [ i ] ] == t [ i - ... | Longest palindrome in a string by Manacher |
19,849 | def bfs ( graph , start = 0 ) : to_visit = deque ( ) dist = [ float ( 'inf' ) ] * len ( graph ) prec = [ None ] * len ( graph ) dist [ start ] = 0 to_visit . appendleft ( start ) while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if dist [ neighbor ] == float ( 'inf' ) : dist [ neighbor ] = dis... | Shortest path in unweighted graph by BFS |
19,850 | def read_graph ( filename , directed = False , weighted = False , default_weight = None ) : with open ( filename , 'r' ) as f : while True : line = f . readline ( ) if line [ 0 ] != '#' : break nb_nodes , nb_edges = tuple ( map ( int , line . split ( ) ) ) graph = [ [ ] for u in range ( nb_nodes ) ] if weighted : weigh... | Read a graph from a text file |
19,851 | def write_graph ( dotfile , graph , directed = False , node_label = None , arc_label = None , comment = "" , node_mark = set ( ) , arc_mark = set ( ) ) : with open ( dotfile , 'w' ) as f : if directed : f . write ( "digraph G{\n" ) else : f . write ( "graph G{\n" ) if comment : f . write ( 'label="%s";\n' % comment ) V... | Writes a graph to a file in the DOT format |
19,852 | def tree_prec_to_adj ( prec , root = 0 ) : n = len ( prec ) graph = [ [ prec [ u ] ] for u in range ( n ) ] graph [ root ] = [ ] for u in range ( n ) : if u != root : graph [ prec [ u ] ] . append ( u ) return graph | Transforms a tree given as predecessor table into adjacency list form |
19,853 | def matrix_to_listlist ( weight ) : graph = [ [ ] for _ in range ( len ( weight ) ) ] for u in range ( len ( graph ) ) : for v in range ( len ( graph ) ) : if weight [ u ] [ v ] != None : graph [ u ] . append ( v ) return graph | transforms a squared weight matrix in a adjacency table of type listlist encoding the directed graph corresponding to the entries of the matrix different from None |
19,854 | def listlist_and_matrix_to_listdict ( graph , weight = None ) : if weight : return [ { v : weight [ u ] [ v ] for v in graph [ u ] } for u in range ( len ( graph ) ) ] else : return [ { v : None for v in graph [ u ] } for u in range ( len ( graph ) ) ] | Transforms the weighted adjacency list representation of a graph of type listlist + optional weight matrix into the listdict representation |
19,855 | def listdict_to_listlist_and_matrix ( sparse ) : V = range ( len ( sparse ) ) graph = [ [ ] for _ in V ] weight = [ [ None for v in V ] for u in V ] for u in V : for v in sparse [ u ] : graph [ u ] . append ( v ) weight [ u ] [ v ] = sparse [ u ] [ v ] return graph , weight | Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation |
19,856 | def extract_path ( prec , v ) : L = [ ] while v is not None : L . append ( v ) v = prec [ v ] assert v not in L return L [ : : - 1 ] | extracts a path in form of vertex list from source to vertex v given a precedence table prec leading to the source |
19,857 | def make_flow_labels ( graph , flow , capac ) : V = range ( len ( graph ) ) arc_label = [ { v : "" for v in graph [ u ] } for u in V ] for u in V : for v in graph [ u ] : if flow [ u ] [ v ] >= 0 : arc_label [ u ] [ v ] = "%s/%s" % ( flow [ u ] [ v ] , capac [ u ] [ v ] ) else : arc_label [ u ] [ v ] = None return arc_... | Generate arc labels for a flow in a graph with capacities . |
19,858 | def dilworth ( graph ) : n = len ( graph ) match = max_bipartite_matching ( graph ) part = [ None ] * n nb_chains = 0 for v in range ( n - 1 , - 1 , - 1 ) : if part [ v ] is None : u = v while u is not None : part [ u ] = nb_chains u = match [ u ] nb_chains += 1 return part | Decompose a DAG into a minimum number of chains by Dilworth |
19,859 | def extract ( code , tree , prefix = [ ] ) : if isinstance ( tree , list ) : l , r = tree prefix . append ( '0' ) extract ( code , l , prefix ) prefix . pop ( ) prefix . append ( '1' ) extract ( code , r , prefix ) prefix . pop ( ) else : code [ tree ] = '' . join ( prefix ) | Extract Huffman code from a Huffman tree |
19,860 | def next_permutation ( tab ) : n = len ( tab ) pivot = None for i in range ( n - 1 ) : if tab [ i ] < tab [ i + 1 ] : pivot = i if pivot is None : return False for i in range ( pivot + 1 , n ) : if tab [ i ] > tab [ pivot ] : swap = i tab [ swap ] , tab [ pivot ] = tab [ pivot ] , tab [ swap ] i = pivot + 1 j = n - 1 w... | find the next permutation of tab in the lexicographical order |
19,861 | def intervals_union ( S ) : E = [ ( low , - 1 ) for ( low , high ) in S ] E += [ ( high , + 1 ) for ( low , high ) in S ] nb_open = 0 last = None retval = [ ] for x , _dir in sorted ( E ) : if _dir == - 1 : if nb_open == 0 : last = x nb_open += 1 else : nb_open -= 1 if nb_open == 0 : retval . append ( ( last , x ) ) re... | Union of intervals |
19,862 | def _augment ( graph , capacity , flow , val , u , target , visit ) : visit [ u ] = True if u == target : return val for v in graph [ u ] : cuv = capacity [ u ] [ v ] if not visit [ v ] and cuv > flow [ u ] [ v ] : res = min ( val , cuv - flow [ u ] [ v ] ) delta = _augment ( graph , capacity , flow , res , v , target ... | Find an augmenting path from u to target with value at most val |
19,863 | def ford_fulkerson ( graph , capacity , s , t ) : add_reverse_arcs ( graph , capacity ) n = len ( graph ) flow = [ [ 0 ] * n for _ in range ( n ) ] INF = float ( 'inf' ) while _augment ( graph , capacity , flow , INF , s , t , [ False ] * n ) > 0 : pass return ( flow , sum ( flow [ s ] ) ) | Maximum flow by Ford - Fulkerson |
19,864 | def windows_k_distinct ( x , k ) : dist , i , j = 0 , 0 , 0 occ = { xi : 0 for xi in x } while j < len ( x ) : while dist == k : occ [ x [ i ] ] -= 1 if occ [ x [ i ] ] == 0 : dist -= 1 i += 1 while j < len ( x ) and ( dist < k or occ [ x [ j ] ] ) : if occ [ x [ j ] ] == 0 : dist += 1 occ [ x [ j ] ] += 1 j += 1 if di... | Find all largest windows containing exactly k distinct elements |
19,865 | def bezout ( a , b ) : if b == 0 : return ( 1 , 0 ) else : u , v = bezout ( b , a % b ) return ( v , u - ( a // b ) * v ) | Bezout coefficients for a and b |
19,866 | def predictive_text ( dic ) : freq = { } for word , weight in dic : prefix = "" for x in word : prefix += x if prefix in freq : freq [ prefix ] += weight else : freq [ prefix ] = weight prop = { } for prefix in freq : code = code_word ( prefix ) if code not in prop or freq [ prop [ code ] ] < freq [ prefix ] : prop [ c... | Predictive text for mobile phones |
19,867 | def rectangles_from_points ( S ) : answ = 0 pairs = { } for j in range ( len ( S ) ) : for i in range ( j ) : px , py = S [ i ] qx , qy = S [ j ] center = ( px + qx , py + qy ) dist = ( px - qx ) ** 2 + ( py - qy ) ** 2 sign = ( center , dist ) if sign in pairs : answ += len ( pairs [ sign ] ) pairs [ sign ] . append (... | How many rectangles can be formed from a set of points |
19,868 | def cut_nodes_edges ( graph ) : n = len ( graph ) time = 0 num = [ None ] * n low = [ n ] * n father = [ None ] * n critical_childs = [ 0 ] * n times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] if t... | Bi - connected components |
19,869 | def cut_nodes_edges2 ( graph ) : N = len ( graph ) assert N <= 5000 recursionlimit = getrecursionlimit ( ) setrecursionlimit ( max ( recursionlimit , N + 42 ) ) edges = set ( ( i , j ) for i in range ( N ) for j in graph [ i ] if i <= j ) nodes = set ( ) NOT = - 2 FIN = - 3 marked = [ NOT ] * N def DFS ( n , prof = 0 )... | Bi - connected components alternative recursive implementation |
19,870 | def area ( p ) : A = 0 for i in range ( len ( p ) ) : A += p [ i - 1 ] [ 0 ] * p [ i ] [ 1 ] - p [ i ] [ 0 ] * p [ i - 1 ] [ 1 ] return A / 2. | Area of a polygone |
19,871 | def is_simple ( polygon ) : n = len ( polygon ) order = list ( range ( n ) ) order . sort ( key = lambda i : polygon [ i ] ) rank_to_y = list ( set ( p [ 1 ] for p in polygon ) ) rank_to_y . sort ( ) y_to_rank = { y : rank for rank , y in enumerate ( rank_to_y ) } S = RangeMinQuery ( [ 0 ] * len ( rank_to_y ) ) last_y ... | Test if a rectilinear polygon is is_simple |
19,872 | def closest_points ( S ) : shuffle ( S ) assert len ( S ) >= 2 p = S [ 0 ] q = S [ 1 ] d = dist ( p , q ) while d > 0 : r = improve ( S , d ) if r : d , p , q = r else : break return p , q | Closest pair of points |
19,873 | def longest_increasing_subsequence ( x ) : n = len ( x ) p = [ None ] * n h = [ None ] b = [ float ( '-inf' ) ] for i in range ( n ) : if x [ i ] > b [ - 1 ] : p [ i ] = h [ - 1 ] h . append ( i ) b . append ( x [ i ] ) else : k = bisect_left ( b , x [ i ] ) h [ k ] = i b [ k ] = x [ i ] p [ i ] = h [ k - 1 ] q = h [ -... | Longest increasing subsequence |
19,874 | def dfs_recursive ( graph , node , seen ) : seen [ node ] = True for neighbor in graph [ node ] : if not seen [ neighbor ] : dfs_recursive ( graph , neighbor , seen ) | DFS detect connected component recursive implementation |
19,875 | def dfs_iterative ( graph , start , seen ) : seen [ start ] = True to_visit = [ start ] while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if not seen [ neighbor ] : seen [ neighbor ] = True to_visit . append ( neighbor ) | DFS detect connected component iterative implementation |
19,876 | def dfs_tree ( graph , start = 0 ) : to_visit = [ start ] prec = [ None ] * len ( graph ) while to_visit : node = to_visit . pop ( ) for neighbor in graph [ node ] : if prec [ neighbor ] is None : prec [ neighbor ] = node to_visit . append ( neighbor ) return prec | DFS build DFS tree in unweighted graph |
19,877 | def find_cycle ( graph ) : n = len ( graph ) prec = [ None ] * n for u in range ( n ) : if prec [ u ] is None : S = [ u ] prec [ u ] = u while S : u = S . pop ( ) for v in graph [ u ] : if v != prec [ u ] : if prec [ v ] is not None : cycle = [ v , u ] while u != prec [ v ] and u != prec [ u ] : u = prec [ u ] cycle . ... | find a cycle in an undirected graph |
19,878 | def arithm_expr_eval ( cell , expr ) : if isinstance ( expr , tuple ) : ( left , op , right ) = expr lval = arithm_expr_eval ( cell , left ) rval = arithm_expr_eval ( cell , right ) if op == '+' : return lval + rval if op == '-' : return lval - rval if op == '*' : return lval * rval if op == '/' : return lval // rval e... | Evaluates a given expression |
19,879 | def arithm_expr_parse ( line ) : vals = [ ] ops = [ ] for tok in line + [ ';' ] : if tok in priority : while ( tok != '(' and ops and priority [ ops [ - 1 ] ] >= priority [ tok ] ) : right = vals . pop ( ) left = vals . pop ( ) vals . append ( ( left , ops . pop ( ) , right ) ) if tok == ')' : ops . pop ( ) else : ops ... | Constructs an arithmetic expression tree |
19,880 | def _alternate ( u , bigraph , visitU , visitV , matchV ) : visitU [ u ] = True for v in bigraph [ u ] : if not visitV [ v ] : visitV [ v ] = True assert matchV [ v ] is not None _alternate ( matchV [ v ] , bigraph , visitU , visitV , matchV ) | extend alternating tree from free vertex u . visitU visitV marks all vertices covered by the tree . |
19,881 | def bipartite_vertex_cover ( bigraph ) : V = range ( len ( bigraph ) ) matchV = max_bipartite_matching ( bigraph ) matchU = [ None for u in V ] for v in V : if matchV [ v ] is not None : matchU [ matchV [ v ] ] = v visitU = [ False for u in V ] visitV = [ False for v in V ] for u in V : if matchU [ u ] is None : _alter... | Bipartite minimum vertex cover by Koenig s theorem |
19,882 | def union_rectangles ( R ) : if R == [ ] : return 0 X = [ ] Y = [ ] for j in range ( len ( R ) ) : ( x1 , y1 , x2 , y2 ) = R [ j ] assert x1 <= x2 and y1 <= y2 X . append ( x1 ) X . append ( x2 ) Y . append ( ( y1 , + 1 , j ) ) Y . append ( ( y2 , - 1 , j ) ) X . sort ( ) Y . sort ( ) X2i = { X [ i ] : i for i in range... | Area of union of rectangles |
19,883 | def read ( filename ) : formula = [ ] for line in open ( filename , 'r' ) : line = line . strip ( ) if line [ 0 ] == "#" : continue lit = line . split ( ":-" ) if len ( lit ) == 1 : posvar = lit [ 0 ] negvars = [ ] else : assert len ( lit ) == 2 posvar = lit [ 0 ] . strip ( ) if posvar == '' : posvar = None negvars = l... | reads a Horn SAT formula from a text file |
19,884 | def horn_sat ( formula ) : CLAUSES = range ( len ( formula ) ) score = [ 0 for c in CLAUSES ] posvar_in_clause = [ None for c in CLAUSES ] clauses_with_negvar = defaultdict ( set ) for c in CLAUSES : posvar , negvars = formula [ c ] score [ c ] = len ( set ( negvars ) ) posvar_in_clause [ c ] = posvar for v in negvars ... | Solving a HORN Sat formula |
19,885 | def dinic ( graph , capacity , source , target ) : assert source != target add_reverse_arcs ( graph , capacity ) Q = deque ( ) total = 0 n = len ( graph ) flow = [ [ 0 ] * n for u in range ( n ) ] while True : Q . appendleft ( source ) lev = [ None ] * n lev [ source ] = 0 while Q : u = Q . pop ( ) for v in graph [ u ]... | Maximum flow by Dinic |
19,886 | def pop ( self ) : root = self . heap [ 1 ] del self . rank [ root ] x = self . heap . pop ( ) if self : self . heap [ 1 ] = x self . rank [ x ] = 1 self . down ( 1 ) return root | Remove and return smallest element |
19,887 | def update ( self , old , new ) : i = self . rank [ old ] del self . rank [ old ] self . heap [ i ] = new self . rank [ new ] = i if old < new : self . down ( i ) else : self . up ( i ) | Replace an element in the heap |
19,888 | def kruskal ( graph , weight ) : uf = UnionFind ( len ( graph ) ) edges = [ ] for u in range ( len ( graph ) ) : for v in graph [ u ] : edges . append ( ( weight [ u ] [ v ] , u , v ) ) edges . sort ( ) mst = [ ] for w , u , v in edges : if uf . union ( u , v ) : mst . append ( ( u , v ) ) return mst | Minimum spanning tree by Kruskal |
19,889 | def union ( self , x , y ) : repr_x = self . find ( x ) repr_y = self . find ( y ) if repr_x == repr_y : return False if self . rank [ repr_x ] == self . rank [ repr_y ] : self . rank [ repr_x ] += 1 self . up [ repr_y ] = repr_x elif self . rank [ repr_x ] > self . rank [ repr_y ] : self . up [ repr_y ] = repr_x else ... | Merges part that contain x and part containing y |
19,890 | def insert ( self , anchor ) : self . prec = anchor . prec self . succ = anchor self . succ . prec = self self . prec . succ = self | insert list item before anchor |
19,891 | def append ( self , item ) : if not self . items : self . items = item item . insert ( self . items ) | add item to the end of the item list |
19,892 | def remove ( self ) : DoubleLinkedListItem . remove ( self ) if self . succ is self : self . theclass . items = None elif self . theclass . items is self : self . theclass . items = self . succ | remove item from its class |
19,893 | def tolist ( self ) : return [ [ x . val for x in theclass . items ] for theclass in self . classes ] | produce a list representation of the partition |
19,894 | def order ( self ) : return [ x . val for theclass in self . classes for x in theclass . items ] | Produce a flatten list of the partition ordered by classes |
19,895 | def eratosthene ( n ) : P = [ True ] * n answ = [ 2 ] for i in range ( 3 , n , 2 ) : if P [ i ] : answ . append ( i ) for j in range ( 2 * i , n , i ) : P [ j ] = False return answ | Prime numbers by sieve of Eratosthene |
19,896 | def _augment ( graph , capacity , flow , source , target ) : n = len ( graph ) A = [ 0 ] * n augm_path = [ None ] * n Q = deque ( ) Q . append ( source ) augm_path [ source ] = source A [ source ] = float ( 'inf' ) while Q : u = Q . popleft ( ) for v in graph [ u ] : cuv = capacity [ u ] [ v ] residual = cuv - flow [ u... | find a shortest augmenting path |
19,897 | def edmonds_karp ( graph , capacity , source , target ) : add_reverse_arcs ( graph , capacity ) V = range ( len ( graph ) ) flow = [ [ 0 for v in V ] for u in V ] while True : augm_path , delta = _augment ( graph , capacity , flow , source , target ) if delta == 0 : break v = target while v != source : u = augm_path [ ... | Maximum flow by Edmonds - Karp |
19,898 | def gauss_jordan ( A , x , b ) : n = len ( x ) m = len ( b ) assert len ( A ) == m and len ( A [ 0 ] ) == n S = [ ] for i in range ( m ) : S . append ( A [ i ] [ : ] + [ b [ i ] ] ) S . append ( list ( range ( n ) ) ) k = diagonalize ( S , n , m ) if k < m : for i in range ( k , m ) : if not is_zero ( S [ i ] [ n ] ) :... | Linear equation system Ax = b by Gauss - Jordan |
19,899 | def rabin_karp_matching ( s , t ) : hash_s = 0 hash_t = 0 len_s = len ( s ) len_t = len ( t ) last_pos = pow ( DOMAIN , len_t - 1 ) % PRIME if len_s < len_t : return - 1 for i in range ( len_t ) : hash_s = ( DOMAIN * hash_s + ord ( s [ i ] ) ) % PRIME hash_t = ( DOMAIN * hash_t + ord ( t [ i ] ) ) % PRIME for i in rang... | Find a substring by Rabin - Karp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.