idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
244,800
def verify_axis_labels ( self , expected , actual , source_name ) : if not getattr ( self , '_checked_axis_labels' , False ) : self . _checked_axis_labels = defaultdict ( bool ) if not self . _checked_axis_labels [ source_name ] : if actual is None : log . warning ( "%s instance could not verify (missing) axis " "expec...
Verify that axis labels for a given source are as expected .
244,801
def get_data ( self , request = None ) : if request is None : raise ValueError data = [ [ ] for _ in self . sources ] for i in range ( request ) : try : for source_data , example in zip ( data , next ( self . child_epoch_iterator ) ) : source_data . append ( example ) except StopIteration : if not self . strictness and...
Get data from the dataset .
244,802
def _producer_wrapper ( f , port , addr = 'tcp://127.0.0.1' ) : try : context = zmq . Context ( ) socket = context . socket ( zmq . PUSH ) socket . connect ( ':' . join ( [ addr , str ( port ) ] ) ) f ( socket ) finally : context . destroy ( )
A shim that sets up a socket and starts the producer callable .
244,803
def _spawn_producer ( f , port , addr = 'tcp://127.0.0.1' ) : process = Process ( target = _producer_wrapper , args = ( f , port , addr ) ) process . start ( ) return process
Start a process that sends results on a PUSH socket .
244,804
def producer_consumer ( producer , consumer , addr = 'tcp://127.0.0.1' , port = None , context = None ) : context_created = False if context is None : context_created = True context = zmq . Context ( ) try : consumer_socket = context . socket ( zmq . PULL ) if port is None : port = consumer_socket . bind_to_random_port...
A producer - consumer pattern .
244,805
def convert_dogs_vs_cats ( directory , output_directory , output_filename = 'dogs_vs_cats.hdf5' ) : output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_path , mode = 'w' ) dtype = h5py . special_dtype ( vlen = numpy . dtype ( 'uint8' ) ) hdf_features = h5file . create_dat...
Converts the Dogs vs . Cats dataset to HDF5 .
244,806
def main ( args = None ) : built_in_datasets = dict ( downloaders . all_downloaders ) if fuel . config . extra_downloaders : for name in fuel . config . extra_downloaders : extra_datasets = dict ( importlib . import_module ( name ) . all_downloaders ) if any ( key in built_in_datasets for key in extra_datasets . keys (...
Entry point for fuel - download script .
244,807
def fill_subparser ( subparser ) : filenames = [ 'train-images-idx3-ubyte.gz' , 'train-labels-idx1-ubyte.gz' , 't10k-images-idx3-ubyte.gz' , 't10k-labels-idx1-ubyte.gz' ] urls = [ 'http://yann.lecun.com/exdb/mnist/' + f for f in filenames ] subparser . set_defaults ( urls = urls , filenames = filenames ) return default...
Sets up a subparser to download the MNIST dataset files .
244,808
def main ( args = None ) : parser = argparse . ArgumentParser ( description = 'Extracts metadata from a Fuel-converted HDF5 file.' ) parser . add_argument ( "filename" , help = "HDF5 file to analyze" ) args = parser . parse_args ( ) with h5py . File ( args . filename , 'r' ) as h5file : interface_version = h5file . att...
Entry point for fuel - info script .
244,809
def convert_silhouettes ( size , directory , output_directory , output_filename = None ) : if size not in ( 16 , 28 ) : raise ValueError ( 'size must be 16 or 28' ) if output_filename is None : output_filename = 'caltech101_silhouettes{}.hdf5' . format ( size ) output_file = os . path . join ( output_directory , output...
Convert the CalTech 101 Silhouettes Datasets .
244,810
def cross_validation ( scheme_class , num_examples , num_folds , strict = True , ** kwargs ) : if strict and num_examples % num_folds != 0 : raise ValueError ( ( "{} examples are not divisible in {} evenly-sized " + "folds. To allow this, have a look at the " + "`strict` argument." ) . format ( num_examples , num_folds...
Return pairs of schemes to be used for cross - validation .
244,811
def main ( args = None ) : built_in_datasets = dict ( converters . all_converters ) if fuel . config . extra_converters : for name in fuel . config . extra_converters : extra_datasets = dict ( importlib . import_module ( name ) . all_converters ) if any ( key in built_in_datasets for key in extra_datasets . keys ( ) ) ...
Entry point for fuel - convert script .
244,812
def refresh_lock ( lock_file ) : unique_id = '%s_%s_%s' % ( os . getpid ( ) , '' . join ( [ str ( random . randint ( 0 , 9 ) ) for i in range ( 10 ) ] ) , hostname ) try : lock_write = open ( lock_file , 'w' ) lock_write . write ( unique_id + '\n' ) lock_write . close ( ) except Exception : while get_lock . n_lock > 0 ...
Refresh an existing lock .
244,813
def get_lock ( lock_dir , ** kw ) : if not hasattr ( get_lock , 'n_lock' ) : get_lock . n_lock = 0 if not hasattr ( get_lock , 'lock_is_enabled' ) : get_lock . lock_is_enabled = True get_lock . lock_dir = lock_dir get_lock . unlocker = Unlocker ( get_lock . lock_dir ) else : if lock_dir != get_lock . lock_dir : assert ...
Obtain lock on compilation directory .
244,814
def release_lock ( ) : get_lock . n_lock -= 1 assert get_lock . n_lock >= 0 if get_lock . lock_is_enabled and get_lock . n_lock == 0 : get_lock . start_time = None get_lock . unlocker . unlock ( )
Release lock on compilation directory .
244,815
def release_readlock ( lockdir_name ) : if os . path . exists ( lockdir_name ) and os . path . isdir ( lockdir_name ) : os . rmdir ( lockdir_name )
Release a previously obtained readlock .
244,816
def get_readlock ( pid , path ) : timestamp = int ( time . time ( ) * 1e6 ) lockdir_name = "%s.readlock.%i.%i" % ( path , pid , timestamp ) os . mkdir ( lockdir_name ) atexit . register ( release_readlock , lockdir_name = lockdir_name )
Obtain a readlock on a file .
244,817
def unlock ( self ) : try : self . os . remove ( self . os . path . join ( self . tmp_dir , 'lock' ) ) except Exception : pass try : self . os . rmdir ( self . tmp_dir ) except Exception : pass
Remove current lock .
244,818
def filename_from_url ( url , path = None ) : r = requests . get ( url , stream = True ) if 'Content-Disposition' in r . headers : filename = re . findall ( r'filename=([^;]+)' , r . headers [ 'Content-Disposition' ] ) [ 0 ] . strip ( '"\"' ) else : filename = os . path . basename ( urllib . parse . urlparse ( url ) . ...
Parses a URL to determine a file name .
244,819
def download ( url , file_handle , chunk_size = 1024 ) : r = requests . get ( url , stream = True ) total_length = r . headers . get ( 'content-length' ) if total_length is None : maxval = UnknownLength else : maxval = int ( total_length ) name = file_handle . name with progress_bar ( name = name , maxval = maxval ) as...
Downloads a given URL to a specific file .
244,820
def default_downloader ( directory , urls , filenames , url_prefix = None , clear = False ) : for i , url in enumerate ( urls ) : filename = filenames [ i ] if not filename : filename = filename_from_url ( url ) if not filename : raise ValueError ( "no filename available for URL '{}'" . format ( url ) ) filenames [ i ]...
Downloads or clears files from URLs and filenames .
244,821
def find_in_data_path ( filename ) : for path in config . data_path : path = os . path . expanduser ( os . path . expandvars ( path ) ) file_path = os . path . join ( path , filename ) if os . path . isfile ( file_path ) : return file_path raise IOError ( "{} not found in Fuel's data path" . format ( filename ) )
Searches for a file within Fuel s data path .
244,822
def lazy_property_factory ( lazy_property ) : def lazy_property_getter ( self ) : if not hasattr ( self , '_' + lazy_property ) : self . load ( ) if not hasattr ( self , '_' + lazy_property ) : raise ValueError ( "{} wasn't loaded" . format ( lazy_property ) ) return getattr ( self , '_' + lazy_property ) def lazy_prop...
Create properties that perform lazy loading of attributes .
244,823
def do_not_pickle_attributes ( * lazy_properties ) : r def wrap_class ( cls ) : if not hasattr ( cls , 'load' ) : raise ValueError ( "no load method implemented" ) for lazy_property in lazy_properties : setattr ( cls , lazy_property , property ( * lazy_property_factory ( lazy_property ) ) ) if not hasattr ( cls , '__ge...
r Decorator to assign non - pickable properties .
244,824
def sorted_fancy_indexing ( indexable , request ) : if len ( request ) > 1 : indices = numpy . argsort ( request ) data = numpy . empty ( shape = ( len ( request ) , ) + indexable . shape [ 1 : ] , dtype = indexable . dtype ) data [ indices ] = indexable [ numpy . array ( request ) [ indices ] , ... ] else : data = ind...
Safe fancy indexing .
244,825
def slice_to_numerical_args ( slice_ , num_examples ) : start = slice_ . start if slice_ . start is not None else 0 stop = slice_ . stop if slice_ . stop is not None else num_examples step = slice_ . step if slice_ . step is not None else 1 return start , stop , step
Translate a slice s attributes into numerical attributes .
244,826
def get_list_representation ( self ) : if self . is_list : return self . list_or_slice else : return self [ list ( range ( self . num_examples ) ) ]
Returns this subset s representation as a list of indices .
244,827
def index_within_subset ( self , indexable , subset_request , sort_indices = False ) : if isinstance ( subset_request , numbers . Integral ) : request , = self [ [ subset_request ] ] else : request = self [ subset_request ] if isinstance ( request , numbers . Integral ) or hasattr ( request , 'step' ) : return indexabl...
Index an indexable object within the context of this subset .
244,828
def num_examples ( self ) : if self . is_list : return len ( self . list_or_slice ) else : start , stop , step = self . slice_to_numerical_args ( self . list_or_slice , self . original_num_examples ) return stop - start
The number of examples this subset spans .
244,829
def get_epoch_iterator ( self , ** kwargs ) : if not self . _fresh_state : self . next_epoch ( ) else : self . _fresh_state = False return super ( DataStream , self ) . get_epoch_iterator ( ** kwargs )
Get an epoch iterator for the data stream .
244,830
def fill_subparser ( subparser ) : sets = [ 'train' , 'valid' , 'test' ] urls = [ 'http://www.cs.toronto.edu/~larocheh/public/datasets/' + 'binarized_mnist/binarized_mnist_{}.amat' . format ( s ) for s in sets ] filenames = [ 'binarized_mnist_{}.amat' . format ( s ) for s in sets ] subparser . set_defaults ( urls = url...
Sets up a subparser to download the binarized MNIST dataset files .
244,831
def download ( directory , youtube_id , clear = False ) : filepath = os . path . join ( directory , '{}.m4a' . format ( youtube_id ) ) if clear : os . remove ( filepath ) return if not PAFY_AVAILABLE : raise ImportError ( "pafy is required to download YouTube videos" ) url = 'https://www.youtube.com/watch?v={}' . forma...
Download the audio of a YouTube video .
244,832
def fill_subparser ( subparser ) : subparser . add_argument ( '--youtube-id' , type = str , required = True , help = ( "The YouTube ID of the video from which to extract audio, " "usually an 11-character string." ) ) return download
Sets up a subparser to download audio of YouTube videos .
244,833
def convert_youtube_audio ( directory , output_directory , youtube_id , channels , sample , output_filename = None ) : input_file = os . path . join ( directory , '{}.m4a' . format ( youtube_id ) ) wav_filename = '{}.wav' . format ( youtube_id ) wav_file = os . path . join ( directory , wav_filename ) ffmpeg_not_availa...
Converts downloaded YouTube audio to HDF5 format .
244,834
def fill_subparser ( subparser ) : subparser . add_argument ( '--youtube-id' , type = str , required = True , help = ( "The YouTube ID of the video from which to extract audio, " "usually an 11-character string." ) ) subparser . add_argument ( '--channels' , type = int , default = 1 , help = ( "The number of audio chan...
Sets up a subparser to convert YouTube audio files .
244,835
def convert_ilsvrc2012 ( directory , output_directory , output_filename = 'ilsvrc2012.hdf5' , shuffle_seed = config . default_seed ) : devkit_path = os . path . join ( directory , DEVKIT_ARCHIVE ) train , valid , test = [ os . path . join ( directory , fn ) for fn in IMAGE_TARS ] n_train , valid_groundtruth , n_test , ...
Converter for data from the ILSVRC 2012 competition .
244,836
def fill_subparser ( subparser ) : subparser . add_argument ( "--shuffle-seed" , help = "Seed to use for randomizing order of the " "training set on disk." , default = config . default_seed , type = int , required = False ) return convert_ilsvrc2012
Sets up a subparser to convert the ILSVRC2012 dataset files .
244,837
def read_metadata_mat_file ( meta_mat ) : mat = loadmat ( meta_mat , squeeze_me = True ) synsets = mat [ 'synsets' ] new_dtype = numpy . dtype ( [ ( 'ILSVRC2012_ID' , numpy . int16 ) , ( 'WNID' , ( 'S' , max ( map ( len , synsets [ 'WNID' ] ) ) ) ) , ( 'wordnet_height' , numpy . int8 ) , ( 'gloss' , ( 'S' , max ( map (...
Read ILSVRC2012 metadata from the distributed MAT file .
244,838
def multiple_paths_parser ( value ) : if isinstance ( value , six . string_types ) : value = value . split ( os . path . pathsep ) return value
Parses data_path argument .
244,839
def add_config ( self , key , type_ , default = NOT_SET , env_var = None ) : self . config [ key ] = { 'type' : type_ } if env_var is not None : self . config [ key ] [ 'env_var' ] = env_var if default is not NOT_SET : self . config [ key ] [ 'default' ] = default
Add a configuration setting .
244,840
def send_arrays ( socket , arrays , stop = False ) : if arrays : arrays = [ numpy . ascontiguousarray ( array ) for array in arrays ] if stop : headers = { 'stop' : True } socket . send_json ( headers ) else : headers = [ header_data_from_array_1_0 ( array ) for array in arrays ] socket . send_json ( headers , zmq . SN...
Send NumPy arrays using the buffer interface and some metadata .
244,841
def recv_arrays ( socket ) : headers = socket . recv_json ( ) if 'stop' in headers : raise StopIteration arrays = [ ] for header in headers : data = socket . recv ( copy = False ) buf = buffer_ ( data ) array = numpy . frombuffer ( buf , dtype = numpy . dtype ( header [ 'descr' ] ) ) array . shape = header [ 'shape' ] ...
Receive a list of NumPy arrays .
244,842
def start_server ( data_stream , port = 5557 , hwm = 10 ) : logging . basicConfig ( level = 'INFO' ) context = zmq . Context ( ) socket = context . socket ( zmq . PUSH ) socket . set_hwm ( hwm ) socket . bind ( 'tcp://*:{}' . format ( port ) ) it = data_stream . get_epoch_iterator ( ) logger . info ( 'server started' )...
Start a data processing server .
244,843
def create_images ( raw_data_directory : str , destination_directory : str , stroke_thicknesses : List [ int ] , canvas_width : int = None , canvas_height : int = None , staff_line_spacing : int = 14 , staff_line_vertical_offsets : List [ int ] = None , random_position_on_canvas : bool = False ) -> dict : all_symbol_fi...
Creates a visual representation of the Homus Dataset by parsing all text - files and the symbols as specified by the parameters by drawing lines that connect the points from each stroke of each symbol .
244,844
def extract_and_render_all_symbol_masks ( self , raw_data_directory : str , destination_directory : str ) : print ( "Extracting Symbols from Muscima++ Dataset..." ) xml_files = self . get_all_xml_file_paths ( raw_data_directory ) crop_objects = self . load_crop_objects_from_xml_files ( xml_files ) self . render_masks_o...
Extracts all symbols from the raw XML documents and generates individual symbols from the masks
244,845
def invert_images ( self , image_directory : str , image_file_ending : str = "*.bmp" ) : image_paths = [ y for x in os . walk ( image_directory ) for y in glob ( os . path . join ( x [ 0 ] , image_file_ending ) ) ] for image_path in tqdm ( image_paths , desc = "Inverting all images in directory {0}" . format ( image_di...
In - situ converts the white on black images of a directory to black on white images
244,846
def create_capitan_images ( self , raw_data_directory : str , destination_directory : str , stroke_thicknesses : List [ int ] ) -> None : symbols = self . load_capitan_symbols ( raw_data_directory ) self . draw_capitan_stroke_images ( symbols , destination_directory , stroke_thicknesses ) self . draw_capitan_score_imag...
Creates a visual representation of the Capitan strokes by parsing all text - files and the symbols as specified by the parameters by drawing lines that connect the points from each stroke of each symbol .
244,847
def draw_capitan_stroke_images ( self , symbols : List [ CapitanSymbol ] , destination_directory : str , stroke_thicknesses : List [ int ] ) -> None : total_number_of_symbols = len ( symbols ) * len ( stroke_thicknesses ) output = "Generating {0} images with {1} symbols in {2} different stroke thicknesses ({3})" . form...
Creates a visual representation of the Capitan strokes by drawing lines that connect the points from each stroke of each symbol .
244,848
def overlap ( r1 : 'Rectangle' , r2 : 'Rectangle' ) : h_overlaps = ( r1 . left <= r2 . right ) and ( r1 . right >= r2 . left ) v_overlaps = ( r1 . bottom >= r2 . top ) and ( r1 . top <= r2 . bottom ) return h_overlaps and v_overlaps
Overlapping rectangles overlap both horizontally & vertically
244,849
def extract_symbols ( self , raw_data_directory : str , destination_directory : str ) : print ( "Extracting Symbols from Audiveris OMR Dataset..." ) all_xml_files = [ y for x in os . walk ( raw_data_directory ) for y in glob ( os . path . join ( x [ 0 ] , '*.xml' ) ) ] all_image_files = [ y for x in os . walk ( raw_dat...
Extracts the symbols from the raw XML documents and matching images of the Audiveris OMR dataset into individual symbols
244,850
def initialize_from_string ( content : str ) -> 'HomusSymbol' : if content is None or content is "" : return None lines = content . splitlines ( ) min_x = sys . maxsize max_x = 0 min_y = sys . maxsize max_y = 0 symbol_name = lines [ 0 ] strokes = [ ] for stroke_string in lines [ 1 : ] : stroke = [ ] for point_string in...
Create and initializes a new symbol from a string
244,851
def draw_into_bitmap ( self , export_path : ExportPath , stroke_thickness : int , margin : int = 0 ) -> None : self . draw_onto_canvas ( export_path , stroke_thickness , margin , self . dimensions . width + 2 * margin , self . dimensions . height + 2 * margin )
Draws the symbol in the original size that it has plus an optional margin
244,852
def draw_onto_canvas ( self , export_path : ExportPath , stroke_thickness : int , margin : int , destination_width : int , destination_height : int , staff_line_spacing : int = 14 , staff_line_vertical_offsets : List [ int ] = None , bounding_boxes : dict = None , random_position_on_canvas : bool = False ) -> None : wi...
Draws the symbol onto a canvas with a fixed size
244,853
def update_locals ( locals_instance , instance_iterator , * args , ** kwargs ) : for instance in instance_iterator ( ) : locals_instance . update ( { type ( instance ) . __name__ : instance . __class__ } )
import all of the detector classes into the local namespace to make it easy to do things like import scrubadub . detectors . NameDetector without having to add each new Detector or Filth
244,854
def iter_filth_clss ( ) : return iter_subclasses ( os . path . dirname ( os . path . abspath ( __file__ ) ) , Filth , _is_abstract_filth , )
Iterate over all of the filths that are included in this sub - package . This is a convenience method for capturing all new Filth that are added over time .
244,855
def iter_filths ( ) : for filth_cls in iter_filth_clss ( ) : if issubclass ( filth_cls , RegexFilth ) : m = next ( re . finditer ( r"\s+" , "fake pattern string" ) ) yield filth_cls ( m ) else : yield filth_cls ( )
Iterate over all instances of filth
244,856
def _update_content ( self , other_filth ) : if self . end < other_filth . beg or other_filth . end < self . beg : raise exceptions . FilthMergeError ( "a_filth goes from [%s, %s) and b_filth goes from [%s, %s)" % ( self . beg , self . end , other_filth . beg , other_filth . end ) ) if self . beg < other_filth . beg : ...
this updates the bounds text and placeholder for the merged filth
244,857
def add_detector ( self , detector_cls ) : if not issubclass ( detector_cls , detectors . base . Detector ) : raise TypeError ( ( '"%(detector_cls)s" is not a subclass of Detector' ) % locals ( ) ) name = detector_cls . filth_cls . type if name in self . _detectors : raise KeyError ( ( 'can not add Detector "%(name)s"-...
Add a Detector to scrubadub
244,858
def clean ( self , text , ** kwargs ) : if sys . version_info < ( 3 , 0 ) : if not isinstance ( text , unicode ) : raise exceptions . UnicodeRequired clean_chunks = [ ] filth = Filth ( ) for next_filth in self . iter_filth ( text ) : clean_chunks . append ( text [ filth . end : next_filth . beg ] ) clean_chunks . appen...
This is the master method that cleans all of the filth out of the dirty dirty text . All keyword arguments to this function are passed through to the Filth . replace_with method to fine - tune how the Filth is cleaned .
244,859
def iter_filth ( self , text ) : all_filths = [ ] for detector in self . _detectors . values ( ) : for filth in detector . iter_filth ( text ) : if not isinstance ( filth , Filth ) : raise TypeError ( 'iter_filth must always yield Filth' ) all_filths . append ( filth ) all_filths . sort ( key = lambda f : ( f . beg , -...
Iterate over the different types of filth that can exist .
244,860
async def download_file ( self , Bucket , Key , Filename , ExtraArgs = None , Callback = None , Config = None ) : with open ( Filename , 'wb' ) as open_file : await download_fileobj ( self , Bucket , Key , open_file , ExtraArgs = ExtraArgs , Callback = Callback , Config = Config )
Download an S3 object to a file .
244,861
async def download_fileobj ( self , Bucket , Key , Fileobj , ExtraArgs = None , Callback = None , Config = None ) : try : resp = await self . get_object ( Bucket = Bucket , Key = Key ) except ClientError as err : if err . response [ 'Error' ] [ 'Code' ] == 'NoSuchKey' : raise ClientError ( { 'Error' : { 'Code' : '404' ...
Download an object from S3 to a file - like object .
244,862
async def upload_fileobj ( self , Fileobj : BinaryIO , Bucket : str , Key : str , ExtraArgs : Optional [ Dict [ str , Any ] ] = None , Callback : Optional [ Callable [ [ int ] , None ] ] = None , Config : Optional [ S3TransferConfig ] = None ) : if not ExtraArgs : ExtraArgs = { } multipart_chunksize = 8388608 if Config...
Upload a file - like object to S3 .
244,863
async def upload_file ( self , Filename , Bucket , Key , ExtraArgs = None , Callback = None , Config = None ) : with open ( Filename , 'rb' ) as open_file : await upload_fileobj ( self , open_file , Bucket , Key , ExtraArgs = ExtraArgs , Callback = Callback , Config = Config )
Upload a file to an S3 object .
244,864
def _create_action ( factory_self , action_model , resource_name , service_context , is_load = False ) : action = AIOServiceAction ( action_model , factory = factory_self , service_context = service_context ) if is_load : async def do_action ( self , * args , ** kwargs ) : response = await action . async_call ( self , ...
Creates a new method which makes a request to the underlying AWS service .
244,865
def from_der_private_key ( data : bytes , password : Optional [ str ] = None ) -> _RSAPrivateKey : return serialization . load_der_private_key ( data , password , default_backend ( ) )
Convert private key in DER encoding to a Private key object
244,866
async def get_object ( self , Bucket : str , Key : str , ** kwargs ) -> dict : if self . _s3_client is None : await self . setup ( ) _range = kwargs . get ( 'Range' ) actual_range_start = None desired_range_start = None desired_range_end = None if _range : range_match = RANGE_REGEX . match ( _range ) if not range_match...
S3 GetObject . Takes same args as Boto3 documentation
244,867
async def put_object ( self , Body : Union [ bytes , IO ] , Bucket : str , Key : str , Metadata : Dict = None , ** kwargs ) : if self . _s3_client is None : await self . setup ( ) if hasattr ( Body , 'read' ) : if inspect . iscoroutinefunction ( Body . read ) : Body = await Body . read ( ) else : Body = Body . read ( )...
PutObject . Takes same args as Boto3 documentation
244,868
def histogram1d ( x , bins , range , weights = None ) : nx = bins if not np . isscalar ( bins ) : raise TypeError ( 'bins should be an integer' ) xmin , xmax = range if not np . isfinite ( xmin ) : raise ValueError ( "xmin should be finite" ) if not np . isfinite ( xmax ) : raise ValueError ( "xmax should be finite" ) ...
Compute a 1D histogram assuming equally spaced bins .
244,869
def histogram2d ( x , y , bins , range , weights = None ) : if isinstance ( bins , numbers . Integral ) : nx = ny = bins else : nx , ny = bins if not np . isscalar ( nx ) or not np . isscalar ( ny ) : raise TypeError ( 'bins should be an iterable of two integers' ) ( xmin , xmax ) , ( ymin , ymax ) = range if not np . ...
Compute a 2D histogram assuming equally spaced bins .
244,870
def to_networkx ( self ) : return nx_util . to_networkx ( self . session . get ( self . __url ) . json ( ) )
Return this network in NetworkX graph object .
244,871
def to_dataframe ( self , extra_edges_columns = [ ] ) : return df_util . to_dataframe ( self . session . get ( self . __url ) . json ( ) , edges_attr_cols = extra_edges_columns )
Return this network in pandas DataFrame .
244,872
def add_node ( self , node_name , dataframe = False ) : if node_name is None : return None return self . add_nodes ( [ node_name ] , dataframe = dataframe )
Add a single node to the network .
244,873
def add_nodes ( self , node_name_list , dataframe = False ) : res = self . session . post ( self . __url + 'nodes' , data = json . dumps ( node_name_list ) , headers = HEADERS ) check_response ( res ) nodes = res . json ( ) if dataframe : return pd . DataFrame ( nodes ) . set_index ( [ 'SUID' ] ) else : return { node [...
Add new nodes to the network
244,874
def add_edge ( self , source , target , interaction = '-' , directed = True , dataframe = True ) : new_edge = { 'source' : source , 'target' : target , 'interaction' : interaction , 'directed' : directed } return self . add_edges ( [ new_edge ] , dataframe = dataframe )
Add a single edge from source to target .
244,875
def get_views ( self ) : url = self . __url + 'views' return self . session . get ( url ) . json ( )
Get views as a list of SUIDs
244,876
def diffuse_advanced ( self , heatColumnName = None , time = None , verbose = False ) : PARAMS = set_param ( [ "heatColumnName" , "time" ] , [ heatColumnName , time ] ) response = api ( url = self . __url + "/diffuse_advanced" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Diffusion will send the selected network view and its selected nodes to a web - based REST service to calculate network propagation . Results are returned and represented by columns in the node table . Columns are created for each execution of Diffusion and their names are returned in the response .
244,877
def to_networkx ( cyjs , directed = True ) : if directed : g = nx . MultiDiGraph ( ) else : g = nx . MultiGraph ( ) network_data = cyjs [ DATA ] if network_data is not None : for key in network_data . keys ( ) : g . graph [ key ] = network_data [ key ] nodes = cyjs [ ELEMENTS ] [ NODES ] edges = cyjs [ ELEMENTS ] [ EDG...
Convert Cytoscape . js - style JSON object into NetworkX object .
244,878
def dialog ( self = None , wid = None , text = None , title = None , url = None , debug = False , verbose = False ) : PARAMS = set_param ( [ "id" , "text" , "title" , "url" , "debug" ] , [ wid , text , title , url , debug ] ) response = api ( url = self . __url + "/dialog?" , PARAMS = PARAMS , method = "GET" , verbose ...
Launch and HTML browser in a separate window .
244,879
def hide ( self , wid , verbose = False ) : PARAMS = { "id" : wid } response = api ( url = self . __url + "/hide?" , PARAMS = PARAMS , method = "GET" , verbose = verbose ) return response
Hide and HTML browser in the Results Panel .
244,880
def show ( self , wid = None , text = None , title = None , url = None , verbose = False ) : PARAMS = { } for p , v in zip ( [ "id" , "text" , "title" , "url" ] , [ wid , text , title , url ] ) : if v : PARAMS [ p ] = v response = api ( url = self . __url + "/show?" , PARAMS = PARAMS , method = "GET" , verbose = verbos...
Launch an HTML browser in the Results Panel .
244,881
def check_response ( res ) : try : res . raise_for_status ( ) except Exception as exc : try : err_info = res . json ( ) err_msg = err_info [ 'message' ] except ValueError : err_msg = res . text [ : 40 ] except KeyError : err_msg = res . text [ : 40 ] + ( "(No 'message' in err_info dict: %s" % list ( err_info . keys ( )...
Check HTTP response and raise exception if response is not OK .
244,882
def from_dataframe ( df , source_col = 'source' , target_col = 'target' , interaction_col = 'interaction' , name = 'From DataFrame' , edge_attr_cols = [ ] ) : network = cyjs . get_empty_network ( name = name ) nodes = set ( ) if edge_attr_cols is None : edge_attr_cols = [ ] for index , row in df . iterrows ( ) : s = ro...
Utility to convert Pandas DataFrame object into Cytoscape . js JSON
244,883
def to_dataframe ( network , interaction = 'interaction' , default_interaction = '-' , edges_attr_cols = [ ] ) : edges = network [ 'elements' ] [ 'edges' ] if edges_attr_cols is None : edges_attr_cols = [ ] edges_attr_cols = sorted ( edges_attr_cols ) network_array = [ ] valid_extra_cols = set ( ) for edge in edges : e...
Utility to convert a Cytoscape dictionary into a Pandas Dataframe .
244,884
def render ( network , style = DEF_STYLE , layout_algorithm = DEF_LAYOUT , background = DEF_BACKGROUND_COLOR , height = DEF_HEIGHT , width = DEF_WIDTH , style_file = STYLE_FILE , def_nodes = DEF_NODES , def_edges = DEF_EDGES ) : from jinja2 import Template from IPython . core . display import display , HTML STYLES = se...
Render network data with embedded Cytoscape . js widget .
244,885
def create_attribute ( self , column = None , listType = None , namespace = None , network = None , atype = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "column" , "listType" , "namespace" , "network" , "type" ] , [ column , listType , namespace , netw...
Creates a new edge column .
244,886
def get ( self , edge = None , network = None , sourceNode = None , targetNode = None , atype = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "edge" , "network" , "sourceNode" , "targetNode" , "type" ] , [ edge , network , sourceNode , targetNode , atyp...
Returns the SUID of an edge that matches the passed parameters . If multiple edges are found only one will be returned and a warning will be reported in the Cytoscape Task History dialog .
244,887
def add_edge ( self , isDirected = None , name = None , network = None , sourceName = None , targetName = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "isDirected" , "name" , "network" , "sourceName" , "targetName" ] , [ isDirected , name , network , s...
Add a new edge between two existing nodes in a network . The names of the nodes must be specified and much match the value in the name column for each node .
244,888
def create ( self , edgeList = None , excludeEdges = None , networkName = None , nodeList = None , source = None , verbose = False ) : network = check_network ( self , source , verbose = verbose ) PARAMS = set_param ( [ "edgeList" , "excludeEdges" , "networkName" , "nodeList" , "source" ] , [ edgeList , excludeEdges , ...
Create a new network from a list of nodes and edges in an existing source network . The SUID of the network and view are returned .
244,889
def create_empty ( self , name = None , renderers = None , RootNetworkList = None , verbose = False ) : PARAMS = set_param ( [ "name" , "renderers" , "RootNetworkList" ] , [ name , renderers , RootNetworkList ] ) response = api ( url = self . __url + "/create empty" , PARAMS = PARAMS , method = "POST" , verbose = verbo...
Create a new empty network . The new network may be created as part of an existing network collection or a new network collection .
244,890
def list ( self , verbose = False ) : response = api ( url = self . __url + "/list" , method = "POST" , verbose = verbose ) return response
List all of the networks in the current session .
244,891
def list_attributes ( self , namespace = None , network = None , verbose = False ) : network = check_network ( self , network , verbose = verbose ) PARAMS = set_param ( [ "namespace" , "network" ] , [ namespace , network ] ) response = api ( url = self . __url + "/list attributes" , PARAMS = PARAMS , method = "POST" , ...
Returns a list of column names assocated with a network .
244,892
def rename ( self , name = None , sourceNetwork = None , verbose = False ) : sourceNetwork = check_network ( self , sourceNetwork , verbose = verbose ) PARAMS = set_param ( [ "name" , "sourceNetwork" ] , [ name , sourceNetwork ] ) response = api ( url = self . __url + "/rename" , PARAMS = PARAMS , method = "POST" , ver...
Rename an existing network . The SUID of the network is returned
244,893
def new ( self , verbose = False ) : response = api ( url = self . __url + "/new" , verbose = verbose ) return response
Destroys the current session and creates a new empty one .
244,894
def open ( self , session_file = None , session_url = None , verbose = False ) : PARAMS = set_param ( [ "file" , "url" ] , [ session_file , session_url ] ) response = api ( url = self . __url + "/open" , PARAMS = PARAMS , verbose = verbose ) return response
Opens a session from a local file or URL .
244,895
def save ( self , session_file , verbose = False ) : PARAMS = { "file" : session_file } response = api ( url = self . __url + "/save" , PARAMS = PARAMS , verbose = verbose ) return response
Saves the current session to an existing file which will be replaced . If this is a new session that has not been saved yet use save as instead .
244,896
def apply ( self , styles = None , verbose = False ) : PARAMS = set_param ( [ "styles" ] , [ styles ] ) response = api ( url = self . __url + "/apply" , PARAMS = PARAMS , method = "POST" , verbose = verbose ) return response
Applies the specified style to the selected views and returns the SUIDs of the affected views .
244,897
def create_style ( self , title = None , defaults = None , mappings = None , verbose = VERBOSE ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if defaults : defaults_ = [ ] for d in de...
Creates a new visual style
244,898
def update_style ( self , title = None , defaults = None , mappings = None , verbose = False ) : u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if defaults : defaults_ = [ ] for d in defa...
Updates a visual style
244,899
def simple_defaults ( self , defaults_dic ) : defaults = [ ] for d in defaults_dic . keys ( ) : dic = { } dic [ "visualProperty" ] = d dic [ "value" ] = defaults_dic [ d ] defaults . append ( dic ) return defaults
Simplifies defaults .