idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
47,400
def group_statistics ( self , group , selected_meta , stat_code = 'mean' ) : values = self . get_values ( group , selected_meta ) if stat_code == 'mean' : res = statistics . mean ( values ) elif stat_code == 'variance' : res = statistics . variance ( values ) elif stat_code == 'std' : res = statistics . stdev ( values ...
Provides statistics of a group based on the meta data selected .
47,401
def tf ( cluster ) : counts = dict ( ) words = cluster . split ( ' ' ) for word in words : counts [ word ] = counts . get ( word , 0 ) + 1 return counts
Computes the term frequency and stores it as a dictionary
47,402
def visualize_cloud_of_words ( dictionary , image_path = None ) : from PIL import Image if image_path is not None : mask = np . array ( Image . open ( image_path ) ) wc = WordCloud ( mask = mask , background_color = 'white' , width = 1600 , height = 1200 , prefer_horizontal = 0.8 ) wc = wc . generate_from_frequencies (...
Renders the cloud of words representation for a given dictionary of frequencies
47,403
def cloud_of_words ( path_to_bog , cluster_no , image_path = None ) : dictionary = GenometricSpace . best_descriptive_meta_dict ( path_to_bog , cluster_no ) GenometricSpace . visualize_cloud_of_words ( dictionary , image_path )
Draws the cloud of words representation
47,404
def from_pandas ( regs , meta = None , chr_name = None , start_name = None , stop_name = None , strand_name = None , sample_name = None ) : regs = check_regs ( regs , chr_name , start_name , stop_name , strand_name , sample_name ) regs = to_gmql_regions ( regs ) if meta is not None : if not check_meta ( meta , regs ) :...
Creates a GDataframe from a pandas dataframe of region and a pandas dataframe of metadata
47,405
def check_regs ( region_df , chr_name = None , start_name = None , stop_name = None , strand_name = None , sample_name = None ) : if sample_name is None : region_df . index = np . repeat ( default_id_sample , len ( region_df ) ) else : region_df = search_column ( region_df , id_sample_aliases , id_sample_types , 'id_sa...
Modifies a region dataframe to be coherent with the GMQL data model
47,406
def to_dataset_files ( self , local_path = None , remote_path = None ) : return FrameToGMQL . to_dataset_files ( self , path_local = local_path , path_remote = remote_path )
Save the GDataframe to a local or remote location
47,407
def to_GMQLDataset ( self , local_path = None , remote_path = None ) : local = None remote = None if ( local_path is None ) and ( remote_path is None ) : local = TempFileManager . get_new_dataset_tmp_folder ( ) if local_path is not None : local = local_path if remote_path is not None : remote = remote_path self . to_da...
Converts the GDataframe in a GMQLDataset for later local or remote computation
47,408
def project_meta ( self , attributes ) : if not isinstance ( attributes , list ) : raise TypeError ( 'attributes must be a list' ) meta_to_project = self . meta [ attributes ] . applymap ( lambda l : ", " . join ( l ) ) new_regs = self . regs . merge ( meta_to_project , left_index = True , right_index = True ) return G...
Projects the specified metadata attributes to new region fields
47,409
def to_matrix ( self , index_regs = None , index_meta = None , columns_regs = None , columns_meta = None , values_regs = None , values_meta = None , ** kwargs ) : index_regs = index_regs if index_regs is not None else [ ] index_meta = index_meta if index_meta is not None else [ ] columns_regs = columns_regs if columns_...
Transforms the GDataframe to a pivot matrix having as index and columns the ones specified . This function is a wrapper around the pivot_table function of Pandas .
47,410
def charts_slug_get ( self , slug , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . charts_slug_get_with_http_info ( slug , ** kwargs ) else : ( data ) = self . charts_slug_get_with_http_info ( slug , ** kwargs ) return data
Chart A Chart is chosen by Pollster editors . One example is \ Obama job approval - Democrats \ . It is always based upon a single Question . Users should strongly consider basing their analysis on Questions instead . Charts are derived data ; Pollster editors publish them and change them as editorial priorities change...
47,411
def polls_get ( self , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . polls_get_with_http_info ( ** kwargs ) else : ( data ) = self . polls_get_with_http_info ( ** kwargs ) return data
Polls A Poll on Pollster is a collection of questions and responses published by a reputable survey house . This endpoint provides raw data from the survey house plus Pollster - provided metadata about each question . Pollster editors don t include every question when they enter Polls and they don t necessarily enter e...
47,412
def polls_slug_get ( self , slug , ** kwargs ) : kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . polls_slug_get_with_http_info ( slug , ** kwargs ) else : ( data ) = self . polls_slug_get_with_http_info ( slug , ** kwargs ) return data
Poll A Poll on Pollster is a collection of questions and responses published by a reputable survey house . This endpoint provides raw data from the survey house plus Pollster - provided metadata about each question . Pollster editors don t include every question when they enter Polls and they don t necessarily enter ev...
47,413
def flatpage ( request , url ) : if not url . startswith ( '/' ) : url = '/' + url language = request . LANGUAGE_CODE language_prefix = '/%s' % language language_db_field = language . replace ( '-' , '_' ) if url . startswith ( language_prefix ) : url = url [ len ( language_prefix ) : ] kwargs = { '{0}__{1}' . format (...
Public interface to the flat page view .
47,414
def render_flatpage ( request , f ) : if f . registration_required and not request . user . is_authenticated ( ) : from django . contrib . auth . views import redirect_to_login return redirect_to_login ( request . path ) if f . template_name : t = loader . select_template ( ( f . template_name , DEFAULT_TEMPLATE ) ) el...
Internal interface to the flat page view .
47,415
def pidfile ( self ) : return os . path . abspath ( os . path . expandvars ( os . path . expanduser ( self . _pidfile , ) , ) , )
Get the absolute path of the pidfile .
47,416
def SQRT ( argument ) : if isinstance ( argument , MetaField ) : return argument . _unary_expression ( "SQRT" ) elif isinstance ( argument , RegField ) : return argument . _unary_expression ( "SQRT" ) else : raise TypeError ( "You have to give as input a RegField (dataset.field)" "or a MetaField (dataset['field']" )
Computes the square matrix of the argument
47,417
def login ( ) : from . RemoteConnection . RemoteManager import RemoteManager global __remote_manager , __session_manager logger = logging . getLogger ( ) remote_address = get_remote_address ( ) res = __session_manager . get_session ( remote_address ) if res is None : warnings . warn ( "There is no active session for ad...
Enables the user to login to the remote GMQL service . If both username and password are None the user will be connected as guest .
47,418
def main ( idle ) : while True : LOG . debug ( "Sleeping for {0} seconds." . format ( idle ) ) time . sleep ( idle )
Any normal python logic which runs a loop . Can take arguments .
47,419
def step ( self ) : message = self . get_message ( ) if message is None : self . sleep ( self . idle_time ) return None self . dispatch ( message ) self . sleep ( 0 )
Grab a new message and dispatch it to the handler .
47,420
def init_app ( self , app = None ) : config = getattr ( app , 'config' , app ) self . team_id = config . get ( 'TEAM_ID' )
Initialize application configuration
47,421
def validate ( self , command , token , team_id , method ) : if ( team_id , command ) not in self . _commands : raise SlackError ( 'Command {0} is not found in team {1}' . format ( command , team_id ) ) func , _token , methods , kwargs = self . _commands [ ( team_id , command ) ] if method not in methods : raise SlackE...
Validate request queries with registerd commands
47,422
def response ( self , text , response_type = 'ephemeral' , attachments = None ) : from flask import jsonify if attachments is None : attachments = [ ] data = { 'response_type' : response_type , 'text' : text , 'attachments' : attachments , } return jsonify ( ** data )
Return a response with json format
47,423
def pid ( self ) : try : with open ( self . pidfile , 'r' ) as pidfile : try : pid = int ( pidfile . read ( ) . strip ( ) ) except ValueError : return None try : os . kill ( pid , 0 ) except OSError as e : if e . errno == errno . EPERM : return pid elif e . errno == errno . ESRCH : return None LOG . exception ( "os.kil...
Get the pid which represents a daemonized process .
47,424
def pid ( self , pidnum ) : try : with open ( self . pidfile , "w+" ) as pidfile : pidfile . write ( "{0}\n" . format ( pidnum ) ) except IOError : LOG . exception ( "Failed to write pidfile {0})." . format ( self . pidfile ) ) sys . exit ( exit . PIDFILE_INACCESSIBLE )
Set the pid for a running process .
47,425
def pid ( self ) : try : os . remove ( self . pidfile ) except IOError : if not os . path . isfile ( self . pidfile ) : return None LOG . exception ( "Failed to clear pidfile {0})." . format ( self . pidfile ) ) sys . exit ( exit . PIDFILE_INACCESSIBLE )
Stop managing the current pid .
47,426
def pool ( self ) : self . _pool = self . _pool or gevent . pool . Pool ( size = self . pool_size ) return self . _pool
Get an gevent pool used to dispatch requests .
47,427
def set_essid ( interface , essid ) : interface = _get_bytes ( interface ) essid = _get_bytes ( essid ) wrq = ffi . new ( 'struct iwreq*' ) with iwlib_socket ( ) as sock : if essid . lower ( ) in ( b'off' , b'any' ) : wrq . u . essid . flags = 0 essid = b'' elif essid . lower ( ) == b'on' : buf = ffi . new ( 'char []' ...
Set the ESSID of a given interface
47,428
def ensure_data ( ) : if not os . path . exists ( GARUDA_DIR ) : os . makedirs ( GARUDA_DIR ) Path ( f'{GARUDA_DIR}/__init__.py' ) . touch ( )
Ensure that the Garuda directory and files
47,429
def protoc_arguments ( ) : proto_include = resource_filename ( 'grpc_tools' , '_proto' ) return [ protoc . __file__ , '-I' , GARUDA_DIR , f'--python_out={GARUDA_DIR}' , f'--grpc_python_out={GARUDA_DIR}' , GARUDA_PROTO_PATH , f'-I{proto_include}' ]
Construct protobuf compiler arguments
47,430
def fix_grpc_import ( ) : with open ( GARUDA_GRPC_PATH , 'r' ) as f : filedata = f . read ( ) filedata = filedata . replace ( 'import garuda_pb2 as garuda__pb2' , f'import {GARUDA_DIR}.garuda_pb2 as garuda__pb2' ) with open ( GARUDA_GRPC_PATH , 'w' ) as f : f . write ( filedata )
Snippet to fix the gRPC import path
47,431
def write_average_score_row ( fp , score_name , scores ) : row = "--" + score_name + "--" fp . write ( row ) for vector in scores : row = list ( vector ) row = [ str ( score ) for score in row ] row = "\n" + "\t" . join ( row ) fp . write ( row )
Simple utility function that writes an average score row in a file designated by a file pointer .
47,432
def catch_errors ( f ) : @ functools . wraps ( f ) def wrapper ( self , request , * args , ** kwargs ) : try : return f ( self , request , * args , ** kwargs ) except exceptions . CertificateExpired : self . message_user ( request , _ ( 'The AFIP Taxpayer certificate has expired.' ) , messages . ERROR , ) except except...
Catches specific errors in admin actions and shows a friendly error .
47,433
def augmented_tf_idf ( attribute_matrix ) : number_of_documents = attribute_matrix . shape [ 0 ] max_term_frequencies = np . ones ( number_of_documents , dtype = np . float64 ) idf_array = np . ones ( attribute_matrix . shape [ 1 ] , dtype = np . float64 ) attribute_matrix = attribute_matrix . tocsc ( ) for j in range ...
Performs augmented TF - IDF normalization on a bag - of - words vector representation of data .
47,434
def get_file_row_generator ( file_path , separator , encoding = None ) : with open ( file_path , encoding = encoding ) as file_object : for line in file_object : words = line . strip ( ) . split ( separator ) yield words
Reads an separated value file row by row .
47,435
def store_pickle ( file_path , data ) : pkl_file = open ( file_path , 'wb' ) pickle . dump ( data , pkl_file ) pkl_file . close ( )
Pickle some data to a given path .
47,436
def load_pickle ( file_path ) : pkl_file = open ( file_path , 'rb' ) data = pickle . load ( pkl_file ) pkl_file . close ( ) return data
Unpickle some data from a given path .
47,437
def makeServoIDPacket ( curr_id , new_id ) : pkt = Packet . makeWritePacket ( curr_id , xl320 . XL320_ID , [ new_id ] ) return pkt
Given the current ID returns a packet to set the servo to a new ID
47,438
def normalize_rows ( features ) : features = features . tocsr ( ) features = normalize ( features , norm = "l2" ) return features
This performs row normalization to 1 of community embedding features .
47,439
def normalize_columns ( features ) : features = features . tocsc ( ) for j in range ( features . shape [ 1 ] ) : document_frequency = features . getcol ( j ) . data . size if document_frequency > 1 : features . data [ features . indptr [ j ] : features . indptr [ j + 1 ] ] = features . data [ features . indptr [ j ] : ...
This performs column normalization of community embedding features .
47,440
def pagerank_lazy_push ( s , r , w_i , a_i , push_node , rho , lazy ) : A = rho * r [ push_node ] B = ( 1 - rho ) * ( 1 - lazy ) * r [ push_node ] C = ( 1 - rho ) * lazy * ( r [ push_node ] ) s [ push_node ] += A r [ push_node ] = C r [ a_i ] += B * w_i
Performs a random step with a self - loop .
47,441
def includeme ( config ) : settings = config . get_settings ( ) authz_class = settings . get ( "multiauth.authorization_policy" , "pyramid.authorization.ACLAuthorizationPolicy" ) authz_policy = config . maybe_dotted ( authz_class ) ( ) config . set_authorization_policy ( authz_policy ) groupfinder = settings . get ( "m...
Include pyramid_multiauth into a pyramid configurator .
47,442
def get_policy_definitions ( settings ) : policy_definitions = { } for name in settings : if not name . startswith ( "multiauth.policy." ) : continue value = settings [ name ] name = name [ len ( "multiauth.policy." ) : ] policy_name , setting_name = name . split ( "." , 1 ) if policy_name not in policy_definitions : p...
Find all multiauth policy definitions from the settings dict .
47,443
def load_file ( filename ) : if filename in ( 'stdin' , '-' , None ) : instances = [ i for i in gc . get_objects ( ) if isinstance ( i , pycodestyle . Checker ) or isinstance ( i , pep8 . Checker ) ] if len ( instances ) != 1 : raise ValueError ( 'Expected only 1 instance of pycodestyle.Checker, got {0} instead.' . for...
Read file to memory .
47,444
def ignore ( code ) : if code in Main . options [ 'ignore' ] : return True if any ( c in code for c in Main . options [ 'ignore' ] ) : return True return False
Should this code be ignored .
47,445
def add_options ( cls , parser ) : parser . add_option ( '--show-pydocstyle' , action = 'store_true' , help = 'show explanation of each PEP 257 error' ) parser . config_options . append ( 'show-pydocstyle' )
Add options to flake8 .
47,446
def parse_options ( cls , options ) : cls . options [ 'explain' ] = bool ( options . show_pydocstyle ) cls . options [ 'ignore' ] = options . ignore config = pydocstyle . RawConfigParser ( ) for file_name in pydocstyle . ConfigurationParser . PROJECT_CONFIG_FILES : if config . read ( os . path . join ( os . path . absp...
Read parsed options from flake8 .
47,447
def run ( self ) : pydocstyle . Error . explain = self . options [ 'explain' ] filename , source = load_file ( self . filename ) for error in pydocstyle . PEP257Checker ( ) . check_source ( source , filename ) : if not hasattr ( error , 'code' ) or ignore ( error . code ) : continue lineno = error . line offset = 0 exp...
Run analysis on a single file .
47,448
def numbers ( self ) : numstring = '{:011d}{:02d}{:04d}{}{}' . format ( self . _receipt . point_of_sales . owner . cuit , int ( self . _receipt . receipt_type . code ) , self . _receipt . point_of_sales . number , self . _receipt . validation . cae , self . _receipt . validation . cae_expiration . strftime ( '%Y%m%d' )...
Returns the barcode s number without the verification digit .
47,449
def verification_digit ( numbers ) : a = sum ( numbers [ : : 2 ] ) b = a * 3 c = sum ( numbers [ 1 : : 2 ] ) d = b + c e = d % 10 if e == 0 : return e return 10 - e
Returns the verification digit for a given numbre .
47,450
def full_number ( self ) : return '{}{}' . format ( '' . join ( str ( n ) for n in self . numbers ) , ReceiptBarcodeGenerator . verification_digit ( self . numbers ) , )
Returns the full number including the verification digit .
47,451
def write_screen_name_to_topics ( filepath , user_label_matrix , node_to_id , id_to_name , label_to_lemma , lemma_to_keyword , separator = "," ) : user_label_matrix = spsp . coo_matrix ( user_label_matrix ) shape = user_label_matrix . shape nnz = user_label_matrix . getnnz ( ) row = user_label_matrix . row col = user_l...
Writes a user name and associated topic names per row .
47,452
def sweep ( port , rate , ID , retry = 3 ) : if port == 'dummy' : s = ServoSerial ( port , rate , fake = True ) else : s = ServoSerial ( port , rate ) if ID < 0 : ID = xl320 . XL320_BROADCAST_ADDR try : s . open ( ) except SerialException as e : print ( '-' * 40 ) print ( sys . argv [ 0 ] , ':' ) print ( e ) exit ( 1 )...
Sends a ping packet to ID s from 0 to maximum and prints out any returned messages .
47,453
def calculate_epsilon_effective ( rho , epsilon , seed_degree , neighbor_degrees , mean_degree ) : neighborhood_degree = neighbor_degrees . mean ( ) epsilon_effective = ( epsilon * np . log ( 1 + seed_degree ) ) / np . log ( 1 + neighborhood_degree ) epsilon_effective_maximum = np . max ( 1 / ( seed_degree * neighbor_d...
Semi - automatic effective epsilon threshold calculation .
47,454
def arcte_with_lazy_pagerank ( adjacency_matrix , rho , epsilon , number_of_threads = None ) : adjacency_matrix = sparse . csr_matrix ( adjacency_matrix ) number_of_nodes = adjacency_matrix . shape [ 0 ] if number_of_threads is None : number_of_threads = get_threads_number ( ) if number_of_threads == 1 : rw_transition ...
Extracts local community features for all graph nodes based on the partitioning of node - centric similarity vectors .
47,455
def get_folds_generator ( node_label_matrix , labelled_node_indices , number_of_categories , dataset_memory_folder , percentage , number_of_folds = 10 ) : number_of_labeled_nodes = labelled_node_indices . size training_set_size = int ( np . ceil ( percentage * number_of_labeled_nodes / 100 ) ) fold_file_path = dataset_...
Read or form and store the seed nodes for training and testing .
47,456
def generate_folds ( node_label_matrix , labelled_node_indices , number_of_categories , percentage , number_of_folds = 10 ) : number_of_labeled_nodes = labelled_node_indices . size training_set_size = int ( np . ceil ( percentage * number_of_labeled_nodes / 100 ) ) train_list = list ( ) test_list = list ( ) for trial i...
Form the seed nodes for training and testing .
47,457
def form_node_label_prediction_matrix ( y_pred , y_test ) : number_of_test_nodes = y_pred . shape [ 0 ] true_number_of_labels = np . squeeze ( y_test . sum ( axis = 1 ) ) index = np . argsort ( y_pred , axis = 1 ) row = np . empty ( y_test . getnnz ( ) , dtype = np . int64 ) col = np . empty ( y_test . getnnz ( ) , dty...
Given the discriminator distances this function forms the node - label prediction matrix .
47,458
def calculate_measures ( y_pred , y_test ) : y_pred = y_pred . toarray ( ) y_test = y_test . toarray ( ) macro_precision , macro_recall , macro_F1 , macro_support = precision_recall_fscore_support ( y_test , y_pred , beta = 1.0 , average = "macro" ) micro_precision , micro_recall , micro_F1 , micro_support = precision_...
Calculates the F - scores and F - score averages given a classification result and a ground truth .
47,459
def decode ( buff ) : pp = list ( map ( ord , buff ) ) if 0 == len ( pp ) == 1 : pp = [ ] return pp
Transforms the raw buffer data read in into a list of bytes
47,460
def write ( self , pkt ) : self . setRTS ( self . DD_WRITE ) self . flushInput ( ) pkt = bytearray ( pkt ) pkt = bytes ( pkt ) num = self . serial . write ( pkt ) return num
This is a simple serial write command . It toggles the RTS pin and formats all of the data into bytes before it writes .
47,461
def sendPkt ( self , pkt , retry = 5 , sleep_time = 0.01 ) : for cnt in range ( retry ) : self . serial . flushInput ( ) self . write ( pkt ) ans = self . read ( ) if ans : return ans else : time . sleep ( sleep_time ) return None
Sends a packet and waits for a return . If no return is given then it resends the packet . If an error occurs it also resends the packet .
47,462
def scipy_sparse_to_csv ( filepath , matrix , separator = "," , directed = False , numbering = "matlab" ) : matrix = spsp . coo_matrix ( matrix ) shape = matrix . shape nnz = matrix . getnnz ( ) if numbering == "matlab" : row = matrix . row + 1 col = matrix . col + 1 data = matrix . data elif numbering == "c" : row = m...
Writes sparse matrix in separated value format .
47,463
def publish ( build ) : build . packages . install ( "wheel" ) build . packages . install ( "twine" ) build . executables . run ( [ "python" , "setup.py" , "sdist" , "bdist_wheel" , "--universal" , "--release" ] ) build . executables . run ( [ "twine" , "upload" , "dist/*" ] )
publish the package itself
47,464
def fast_approximate_personalized_pagerank ( s , r , w_i , a_i , out_degree , in_degree , seed_node , rho = 0.2 , epsilon = 0.00001 ) : r [ seed_node ] = 1.0 pushable = deque ( ) pushable . append ( seed_node ) push_node = pushable . popleft ( ) pagerank_limit_push ( s , r , w_i [ push_node ] , a_i [ push_node ] , push...
Calculates the approximate personalized PageRank starting from a seed node without self - loops .
47,465
def lazy_approximate_personalized_pagerank ( s , r , w_i , a_i , out_degree , in_degree , seed_node , rho = 0.2 , epsilon = 0.00001 , laziness_factor = 0.5 ) : r [ seed_node ] = 1.0 pushable = deque ( ) pushable . append ( seed_node ) push_node = pushable . popleft ( ) pagerank_lazy_push ( s , r , w_i [ push_node ] , a...
Calculates the approximate personalized PageRank starting from a seed node with self - loops .
47,466
def read_matlab_features ( array_paths , number_of_nodes , dimensionality ) : file_row_gen = get_file_row_generator ( array_paths [ 0 ] , "\t" ) data = list ( ) append_data = data . append for file_row in file_row_gen : append_data ( float ( file_row [ 0 ] ) ) file_row_gen = get_file_row_generator ( array_paths [ 1 ] ,...
Returns a sparse feature matrix as calculated by a Matlab routine .
47,467
def community_neighbors ( c_j , reverse_index_rows , unavailable_communities , unavailable_communities_counter ) : indices = list ( ) extend = indices . extend for node in c_j : extend ( reverse_index_rows [ node ] ) indices = np . array ( indices ) indices = np . setdiff1d ( indices , unavailable_communities [ : unava...
Finds communities with shared nodes to a seed community . Called by mroc .
47,468
def jaccard ( c_1 , c_2 ) : nom = np . intersect1d ( c_1 , c_2 ) . size denom = np . union1d ( c_1 , c_2 ) . size return nom / denom
Calculates the Jaccard similarity between two sets of nodes . Called by mroc .
47,469
def louvain ( adjacency_matrix ) : adjacency_matrix = nx . from_scipy_sparse_matrix ( adjacency_matrix , create_using = nx . Graph ( ) ) tree = community . generate_dendogram ( adjacency_matrix , part_init = None ) row = list ( ) col = list ( ) append_row = row . append append_col = col . append community_counter = 0 f...
Performs community embedding using the LOUVAIN method .
47,470
def laplacian_eigenmaps ( adjacency_matrix , k ) : laplacian = get_normalized_laplacian ( adjacency_matrix ) try : eigenvalues , eigenvectors = spla . eigsh ( laplacian , k = k , which = 'SM' , return_eigenvectors = True ) except spla . ArpackNoConvergence as e : print ( "ARPACK has not converged." ) eigenvalue = e . e...
Performs spectral graph embedding using the graph symmetric normalized Laplacian matrix .
47,471
def replicator_eigenmaps ( adjacency_matrix , k ) : number_of_nodes = adjacency_matrix . shape [ 0 ] max_eigenvalue = spla . eigsh ( adjacency_matrix , k = 1 , which = 'LM' , return_eigenvectors = False ) eye_matrix = sparse . eye ( number_of_nodes , number_of_nodes , dtype = np . float64 ) eye_matrix = eye_matrix . to...
Performs spectral graph embedding on the centrality reweighted adjacency matrix
47,472
def base_communities ( adjacency_matrix ) : number_of_nodes = adjacency_matrix . shape [ 0 ] adjacency_matrix = adjacency_matrix . tocsr ( ) adjacency_matrix = adjacency_matrix . transpose ( ) features = sparse . csr_matrix ( sparse . eye ( number_of_nodes , number_of_nodes ) ) + adjacency_matrix . tocsr ( ) features =...
Forms the community indicator normalized feature matrix for any graph .
47,473
def create_key ( file_ ) : pkey = crypto . PKey ( ) pkey . generate_key ( crypto . TYPE_RSA , 2048 ) file_ . write ( crypto . dump_privatekey ( crypto . FILETYPE_PEM , pkey ) ) file_ . flush ( )
Create a key and save it into file_ .
47,474
def create_csr ( key_file , organization_name , common_name , serial_number , file_ ) : key = crypto . load_privatekey ( crypto . FILETYPE_PEM , key_file . read ( ) ) req = crypto . X509Req ( ) subj = req . get_subject ( ) subj . O = organization_name subj . CN = common_name subj . serialNumber = serial_number req . se...
Create a CSR for a key and save it into file .
47,475
def model_fit ( X_train , y_train , svm_hardness , fit_intercept , number_of_threads , classifier_type = "LinearSVC" ) : if classifier_type == "LinearSVC" : if X_train . shape [ 0 ] > X_train . shape [ 1 ] : dual = False else : dual = True model = OneVsRestClassifier ( LinearSVC ( C = svm_hardness , random_state = 0 , ...
Fits a Linear Support Vector Classifier to the labelled graph - based features using the LIBLINEAR library .
47,476
def meta_model_fit ( X_train , y_train , svm_hardness , fit_intercept , number_of_threads , regressor_type = "LinearSVR" ) : if regressor_type == "LinearSVR" : if X_train . shape [ 0 ] > X_train . shape [ 1 ] : dual = False else : dual = True model = LinearSVR ( C = svm_hardness , random_state = 0 , dual = dual , fit_i...
Trains meta - labeler for predicting number of labels for each user .
47,477
def weigh_users ( X_test , model , classifier_type = "LinearSVC" ) : if classifier_type == "LinearSVC" : decision_weights = model . decision_function ( X_test ) elif classifier_type == "LogisticRegression" : decision_weights = model . predict_proba ( X_test ) elif classifier_type == "RandomForest" : if issparse ( X_tes...
Uses a trained model and the unlabelled features to produce a user - to - label distance matrix .
47,478
def get_client ( service_name , sandbox = False ) : key = ( service_name . lower ( ) , sandbox , ) try : if key not in cached_clients : cached_clients [ key ] = Client ( wsdls [ key ] , transport = transport ) return cached_clients [ key ] except KeyError : raise ValueError ( 'Unknown service name, {}' . format ( servi...
Returns a client for a given service .
47,479
def extract ( cls , extractor , typ ) : schema = { "title" : typ . __name__ , "type" : "object" , "properties" : { } , "required" : [ ] } for attribute in attr . fields ( typ ) : details = cls . _extract_attribute ( extractor , attribute ) if details . is_required : schema [ "required" ] . append ( details . name ) sch...
take an attrs based class and convert it to jsonschema .
47,480
def prettyPrintPacket ( ctrl_table ) : print ( '---------------------------------------' ) print ( "{:.<29} {}" . format ( 'id' , ctrl_table [ 'id' ] ) ) ctrl_table . pop ( 'id' ) for key , value in ctrl_table . items ( ) : print ( "{:.<29} {}" . format ( key , value ) )
This will pretty print out a packet s fields .
47,481
def write ( fname , data ) : try : with open ( fname , 'w' ) as f : json . dump ( data , f ) except IOError : raise Exception ( 'Could not open {0!s} for writing' . format ( ( fname ) ) )
Writes a Json file
47,482
def makePacket ( ID , instr , reg = None , params = None ) : pkt = [ ] pkt += [ 0xFF , 0xFF , 0xFD ] pkt += [ 0x00 ] pkt += [ ID ] pkt += [ 0x00 , 0x00 ] pkt += [ instr ] if reg : pkt += le ( reg ) if params : pkt += params length = le ( len ( pkt ) - 5 ) pkt [ 5 ] = length [ 0 ] pkt [ 6 ] = length [ 1 ] crc = crc16 ( ...
This makes a generic packet .
47,483
def makeControlModePacket ( ID , mode ) : pkt = makeWritePacket ( ID , xl320 . XL320_CONTROL_MODE , le ( mode ) ) return pkt
Sets the xl - 320 to either servo or wheel mode
47,484
def makeBaudRatePacket ( ID , rate ) : if rate not in [ 0 , 1 , 2 , 3 ] : raise Exception ( 'Packet.makeBaudRatePacket: wrong rate {}' . format ( rate ) ) pkt = makeWritePacket ( ID , xl320 . XL320_BAUD_RATE , [ rate ] ) return pkt
Set baud rate of servo .
47,485
def makeSyncAnglePacket ( info ) : addr = le ( xl320 . XL320_GOAL_POSITION ) data = [ ] data . append ( addr [ 0 ] ) data . append ( addr [ 1 ] ) data . append ( 2 ) data . append ( 0 ) for pkt in info : data . append ( pkt [ 0 ] ) angle = le ( int ( pkt [ 1 ] / 300 * 1023 ) ) data . append ( angle [ 0 ] ) data . appen...
Write sync angle information to servos .
47,486
def makeBulkAnglePacket ( info ) : addr = le ( xl320 . XL320_GOAL_POSITION ) data = [ ] for pkt in info : data . append ( pkt [ 0 ] ) data . append ( addr [ 0 ] ) data . append ( addr [ 1 ] ) data . append ( 2 ) data . append ( 0 ) angle = le ( int ( pkt [ 1 ] / 300 * 1023 ) ) data . append ( angle [ 0 ] ) data . appen...
Write bulk angle information to servos .
47,487
def findPkt ( pkt ) : ret = [ ] while len ( pkt ) - 10 >= 0 : if pkt [ 0 : 4 ] != [ 0xFF , 0xFF , 0xFD , 0x00 ] : pkt . pop ( 0 ) continue length = ( pkt [ 6 ] << 8 ) + pkt [ 5 ] crc_pos = 5 + length pkt_crc = pkt [ crc_pos : crc_pos + 2 ] crc = le ( crc16 ( pkt [ : crc_pos ] ) ) if pkt_crc == crc : pkt_end = crc_pos +...
Search through a string of binary for a valid xl320 package .
47,488
def populate_all ( ) : ReceiptType . objects . populate ( ) ConceptType . objects . populate ( ) DocumentType . objects . populate ( ) VatType . objects . populate ( ) TaxType . objects . populate ( ) CurrencyType . objects . populate ( )
Fetch and store all metadata from the AFIP .
47,489
def first_currency ( ) : ct = CurrencyType . objects . filter ( code = 'PES' ) . first ( ) if ct : return ct . pk
Returns the id for the first currency
47,490
def populate ( self , ticket = None ) : ticket = ticket or AuthTicket . objects . get_any_active ( 'wsfe' ) client = clients . get_client ( 'wsfe' , ticket . owner . is_sandboxed ) service = getattr ( client . service , self . __service_name ) response_xml = service ( serializers . serialize_ticket ( ticket ) ) check_r...
Populate the database with types retrieved from the AFIP .
47,491
def certificate_object ( self ) : if not self . certificate : return None self . certificate . seek ( 0 ) return crypto . parse_certificate ( self . certificate . read ( ) )
Returns the certificate as an OpenSSL object
47,492
def get_certificate_expiration ( self ) : datestring = self . certificate_object . get_notAfter ( ) . decode ( ) dt = datetime . strptime ( datestring , '%Y%m%d%H%M%SZ' ) return dt . replace ( tzinfo = timezone . utc )
Gets the certificate expiration from the certificate
47,493
def generate_key ( self , force = False ) : if self . key and not force : logger . warning ( 'Tried to generate key for a taxpayer that already had one' ) return False with NamedTemporaryFile ( suffix = '.key' ) as file_ : crypto . create_key ( file_ ) self . key = File ( file_ , name = '{}.key' . format ( uuid . uuid4...
Creates a key file for this TaxPayer
47,494
def generate_csr ( self , basename = 'djangoafip' ) : csr = BytesIO ( ) crypto . create_csr ( self . key . file , self . name , '{}{}' . format ( basename , int ( datetime . now ( ) . timestamp ( ) ) ) , 'CUIT {}' . format ( self . cuit ) , csr , ) csr . seek ( 0 ) return csr
Creates a CSR for this TaxPayer s key
47,495
def create_ticket ( self , service ) : ticket = AuthTicket ( owner = self , service = service ) ticket . authorize ( ) return ticket
Create an AuthTicket for a given service .
47,496
def get_ticket ( self , service ) : return self . auth_tickets . filter ( expires__gt = datetime . now ( timezone . utc ) , service = service ) . last ( )
Return an existing AuthTicket for a given service .
47,497
def fetch_points_of_sales ( self , ticket = None ) : ticket = ticket or self . get_or_create_ticket ( 'wsfe' ) client = clients . get_client ( 'wsfe' , self . is_sandboxed ) response = client . service . FEParamGetPtosVenta ( serializers . serialize_ticket ( ticket ) , ) check_response ( response ) results = [ ] for po...
Fetch all point of sales objects .
47,498
def logo_as_data_uri ( self ) : _ , ext = os . path . splitext ( self . logo . file . name ) with open ( self . logo . file . name , 'rb' ) as f : data = base64 . b64encode ( f . read ( ) ) return 'data:image/{};base64,{}' . format ( ext [ 1 : ] , data . decode ( ) )
This TaxPayer s logo as a data uri .
47,499
def authorize ( self ) : request = self . __create_request_xml ( ) request = self . __sign_request ( request ) request = b64encode ( request ) . decode ( ) client = clients . get_client ( 'wsaa' , self . owner . is_sandboxed ) try : raw_response = client . service . loginCms ( request ) except Fault as e : if str ( e )...
Send this ticket to AFIP for authorization .