Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def prepare_metadata(devkit_archive): # Read what's necessary from the development kit. synsets, raw_valid_groundtruth = read_devkit(devkit_archive) # Mapping to take WordNet IDs to our internal 0-999 encoding. wnid_map = dict(zip((s.decode('utf8') for ...
[ "Extract dataset metadata required for HDF5 file setup.\n\n Parameters\n ----------\n devkit_archive : str or file-like object\n The filename or file-handle for the gzipped TAR archive\n containing the ILSVRC2012 development kit.\n\n Returns\n -------\n n_train : int\n The num...
Please provide a description of the function: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', nump...
[ "Read ILSVRC2012 metadata from the distributed MAT file.\n\n Parameters\n ----------\n meta_mat : str or file-like object\n The filename or file-handle for `meta.mat` from the\n ILSVRC2012 development kit.\n\n Returns\n -------\n synsets : ndarray, 1-dimensional, compound dtype\n ...
Please provide a description of the function:def extra_downloader_converter(value): if isinstance(value, six.string_types): value = value.split(" ") return value
[ "Parses extra_{downloader,converter} arguments.\n\n Parameters\n ----------\n value : iterable or str\n If the value is a string, it is split into a list using spaces\n as delimiters. Otherwise, it is returned as is.\n\n " ]
Please provide a description of the function:def multiple_paths_parser(value): if isinstance(value, six.string_types): value = value.split(os.path.pathsep) return value
[ "Parses data_path argument.\n\n Parameters\n ----------\n value : str\n a string of data paths separated by \":\".\n\n Returns\n -------\n value : list\n a list of strings indicating each data paths.\n\n " ]
Please provide a description of the function: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'] =...
[ "Add a configuration setting.\n\n Parameters\n ----------\n key : str\n The name of the configuration setting. This must be a valid\n Python attribute name i.e. alphanumeric with underscores.\n type : function\n A function such as ``float``, ``int`` or ``...
Please provide a description of the function:def send_arrays(socket, arrays, stop=False): if arrays: # The buffer protocol only works on contiguous arrays arrays = [numpy.ascontiguousarray(array) for array in arrays] if stop: headers = {'stop': True} socket.send_json(headers...
[ "Send NumPy arrays using the buffer interface and some metadata.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n The socket to send data over.\n arrays : list\n A list of :class:`numpy.ndarray` to transfer.\n stop : bool, optional\n Instead of sending a series of Num...
Please provide a description of the function: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=nump...
[ "Receive a list of NumPy arrays.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n The socket to receive the arrays on.\n\n Returns\n -------\n list\n A list of :class:`numpy.ndarray` objects.\n\n Raises\n ------\n StopIteration\n If the first JSON object r...
Please provide a description of the function: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() ...
[ "Start a data processing server.\n\n This command starts a server in the current process that performs the\n actual data processing (by retrieving data from the given data stream).\n It also starts a second process, the broker, which mediates between the\n server and the client. The broker also keeps a ...
Please provide a description of the function:def tmp_pre_commit_home() -> Generator[None, None, None]: before = os.environ.get('PRE_COMMIT_HOME') with tempfile.TemporaryDirectory() as tmpdir: os.environ['PRE_COMMIT_HOME'] = tmpdir try: yield finally: if befor...
[ "During lots of autoupdates, many repositories will be cloned into the\n pre-commit directory. This prevents leaving many MB/GB of repositories\n behind due to this autofixer. This context creates a temporary directory\n so these many repositories are automatically cleaned up.\n " ]
Please provide a description of the function:def move_images(self, image_directory): image_paths = glob(image_directory + "/**/*.png", recursive=True) for image_path in image_paths: destination = image_path.replace("\\image\\", "\\") shutil.move(image_path, destination)...
[ " Moves png-files one directory up from path/image/*.png -> path/*.png" ]
Please provide a description of the function:def create_images(raw_data_directory: str, destination_directory: str, stroke_thicknesses: List[int], canvas_width: int = None, canvas_height: int = None, staff_line...
[ "\n Creates a visual representation of the Homus Dataset by parsing all text-files and the symbols as specified\n by the parameters by drawing lines that connect the points from each stroke of each symbol.\n\n Each symbol will be drawn in the center of a fixed canvas, specified by width and hei...
Please provide a description of the function:def download_and_extract_dataset(self, destination_directory: str): if not os.path.exists(self.get_dataset_filename()): print("Downloading MUSCIMA++ Dataset...") self.download_file(self.get_dataset_download_url(), self.get_dataset_fil...
[ "\n Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset\n that were manually annotated (140 out of 1000 images).\n " ]
Please provide a description of the function:def download_and_extract_measure_annotations(self, destination_directory: str): if not os.path.exists(self.get_measure_annotation_filename()): print("Downloading MUSCIMA++ Measure Annotations...") self.download_file(self.get_measure_a...
[ "\n Downloads the annotations only of stave-measures, system-measures and staves that were extracted\n from the MUSCIMA++ dataset via the :class:`omrdatasettools.converters.MuscimaPlusPlusAnnotationConverter`.\n\n The annotations from that extraction are provided in a simple json format with on...
Please provide a description of the function: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_cr...
[ "\n Extracts all symbols from the raw XML documents and generates individual symbols from the masks\n\n :param raw_data_directory: The directory, that contains the xml-files and matching images\n :param destination_directory: The directory, in which the symbols should be generated into. One sub...
Please provide a description of the function:def get_all_xml_file_paths(self, raw_data_directory: str) -> List[str]: raw_data_directory = os.path.join(raw_data_directory, "v1.0", "data", "cropobjects_manual") xml_files = [y for x in os.walk(raw_data_directory) for y in glob(os.path.join(x[0], '...
[ " Loads all XML-files that are located in the folder.\n :param raw_data_directory: Path to the raw directory, where the MUSCIMA++ dataset was extracted to\n " ]
Please provide a description of the function: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 i...
[ "\n In-situ converts the white on black images of a directory to black on white images\n\n :param image_directory: The directory, that contains the images\n :param image_file_ending: The pattern for finding files in the image_directory\n " ]
Please provide a description of the function: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...
[ "\n Creates a visual representation of the Capitan strokes by parsing all text-files and the symbols as specified\n by the parameters by drawing lines that connect the points from each stroke of each symbol.\n\n :param raw_data_directory: The directory, that contains the raw capitan dataset\n ...
Please provide a description of the function: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_...
[ "\n Creates a visual representation of the Capitan strokes by drawing lines that connect the points\n from each stroke of each symbol.\n\n :param symbols: The list of parsed Capitan-symbols\n :param destination_directory: The directory, in which the symbols should be generated into. One ...
Please provide a description of the function:def initialize_from_string(content: str) -> 'CapitanSymbol': if content is None or content is "": return None parts = content.split(":") min_x = 100000 max_x = 0 min_y = 100000 max_y = 0 symbol_n...
[ "\n Create and initializes a new symbol from a string\n :param content: The content of a symbol as read from the text-file in the form <label>:<sequence>:<image>\n :return: The initialized symbol\n :rtype: CapitanSymbol\n " ]
Please provide a description of the function:def draw_capitan_score_bitmap(self, export_path: ExportPath) -> None: with Image.fromarray(self.image_data, mode='L') as image: image.save(export_path.get_full_path())
[ "\n Draws the 30x30 symbol into the given file\n :param export_path: The path, where the symbols should be created on disk\n " ]
Please provide a description of the function:def draw_capitan_stroke_onto_canvas(self, export_path: ExportPath, stroke_thickness: int, margin: int): width = int(self.dimensions.width + 2 * margin) height = int(self.dimensions.height + 2 * margin) offset = Point2D(self.dimensions.origin....
[ "\n Draws the symbol strokes onto a canvas\n :param export_path: The path, where the symbols should be created on disk\n :param stroke_thickness:\n :param margin:\n " ]
Please provide a description of the function: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
[ "\n Overlapping rectangles overlap both horizontally & vertically\n " ]
Please provide a description of the function: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...
[ "\n Extracts the symbols from the raw XML documents and matching images of the Audiveris OMR dataset into\n individual symbols\n\n :param raw_data_directory: The directory, that contains the xml-files and matching images\n :param destination_directory: The directory, in which the symbols...
Please provide a description of the function:def convert_csv_annotations_to_cropobject(annotations_path: str, image_path: str) -> List[CropObject]: annotations = pd.read_csv(annotations_path) image = Image.open(image_path) # type: Image.Image crop_objects = [] node_id = 0 for index, annotation...
[ "\n Converts a normalized dataset of objects into crop-objects.\n :param annotations_path: Path to the csv-file that contains bounding boxes in the following\n format for a single image:\n image_name,top,left,bottom,right,class_name,confidence\n CVC-MU...
Please provide a description of the function:def get_full_path(self, offset: int = None): stroke_thickness = "" if self.stroke_thickness is not None: stroke_thickness = "_{0}".format(self.stroke_thickness) staffline_offset = "" if offset is not None: sta...
[ "\n :return: Returns the full path that will join all fields according to the following format if no offset if provided:\n 'destination_directory'/'symbol_class'/'raw_file_name_without_extension'_'stroke_thickness'.'extension',\n e.g.: data/images/3-4-Time/1-13_3.png\n\n or with an addit...
Please provide a description of the function: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 ...
[ "\n Create and initializes a new symbol from a string\n\n :param content: The content of a symbol as read from the text-file\n :return: The initialized symbol\n :rtype: HomusSymbol\n " ]
Please provide a description of the function: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.d...
[ "\n Draws the symbol in the original size that it has plus an optional margin\n\n :param export_path: The path, where the symbols should be created on disk\n :param stroke_thickness: Pen-thickness for drawing the symbol in pixels\n :param margin: An optional margin for each symbol\n ...
Please provide a description of the function: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, ...
[ "\n Draws the symbol onto a canvas with a fixed size\n\n :param bounding_boxes: The dictionary into which the bounding-boxes will be added of each generated image\n :param export_path: The path, where the symbols should be created on disk\n :param stroke_thickness:\n :param margin...
Please provide a description of the function:def iter_detector_clss(): return iter_subclasses( os.path.dirname(os.path.abspath(__file__)), Detector, _is_abstract_detector, )
[ "Iterate over all of the detectors that are included in this sub-package.\n This is a convenience method for capturing all new Detectors that are added\n over time and it is used both by the unit tests and in the\n ``Scrubber.__init__`` method.\n " ]
Please provide a description of the function:def _iter_module_subclasses(package, module_name, base_cls): module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getmembers(module): if inspect.isclass(obj) and issubclass(obj, base_cls): yield obj
[ "inspect all modules in this directory for subclasses of inherit from\n ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709\n " ]
Please provide a description of the function:def update_locals(locals_instance, instance_iterator, *args, **kwargs): # http://stackoverflow.com/a/4526709/564709 # http://stackoverflow.com/a/511059/564709 for instance in instance_iterator(): locals_instance.update({type(instance).__name__: insta...
[ "import all of the detector classes into the local namespace to make it\n easy to do things like `import scrubadub.detectors.NameDetector` without\n having to add each new ``Detector`` or ``Filth``\n " ]
Please provide a description of the function:def clean(text, cls=None, **kwargs): cls = cls or Scrubber scrubber = cls() return scrubber.clean(text, **kwargs)
[ "Public facing function to clean ``text`` using the scrubber ``cls`` by\n replacing all personal information with ``{{PLACEHOLDERS}}``.\n " ]
Please provide a description of the function: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.\n This is a convenience method for capturing all new Filth that are added\n over time.\n " ]
Please provide a description of the function: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" ]
Please provide a description of the function: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, s...
[ "this updates the bounds, text and placeholder for the merged\n filth\n " ]
Please provide a description of the function: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()) # TODO: should add tests to mak...
[ "Add a ``Detector`` to scrubadub" ]
Please provide a description of the function:def clean(self, text, **kwargs): if sys.version_info < (3, 0): # Only in Python 2. In 3 every string is a Python 2 unicode if not isinstance(text, unicode): raise exceptions.UnicodeRequired clean_chunks = [] ...
[ "This is the master method that cleans all of the filth out of the\n dirty dirty ``text``. All keyword arguments to this function are passed\n through to the ``Filth.replace_with`` method to fine-tune how the\n ``Filth`` is cleaned.\n " ]
Please provide a description of the function:def iter_filth(self, text): # currently doing this by aggregating all_filths and then sorting # inline instead of with a Filth.__cmp__ method, which is apparently # much slower http://stackoverflow.com/a/988728/564709 # # NOTE...
[ "Iterate over the different types of filth that can exist.\n " ]
Please provide a description of the function:async def init(self, *args, dialect=None, **kwargs): self.__pool = await create_pool(*args, dialect=dialect, **kwargs)
[ "\n :param args: args for pool\n :param dialect: sqlalchemy postgres dialect\n :param kwargs: kwargs for pool\n :return: None\n " ]
Please provide a description of the function:def query(self, query, *args, prefetch=None, timeout=None): compiled_q, compiled_args = compile_query(query) query, args = compiled_q, compiled_args or args return QueryContextManager(self.pool, query, args, ...
[ "\n make a read only query. Ideal for select statements.\n This method converts the query to a prepared statement\n and uses a cursor to return the results. So you only get\n so many rows at a time. This can dramatically increase performance\n for queries that have a lot of result...
Please provide a description of the function: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.\n\n Usage::\n\n import boto3\n s3 = boto3.resource('s3')\n s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')\n\n Similar behavior as S3Transfer's download_file() method,\n except that parameters are capitalized.\n " ]
Please provide a description of the function: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': ...
[ "Download an object from S3 to a file-like object.\n\n The file-like object must be in binary mode.\n\n This is a managed transfer which will perform a multipart download in\n multiple threads if necessary.\n\n Usage::\n\n import boto3\n s3 = boto3.client('s3')\n\n with open('filena...
Please provide a description of the function: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 no...
[ "Upload a file-like object to S3.\n\n The file-like object must be in binary mode.\n\n This is a managed transfer which will perform a multipart upload in\n multiple threads if necessary.\n\n Usage::\n\n import boto3\n s3 = boto3.client('s3')\n\n with open('filename', 'rb') as data:...
Please provide a description of the function: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.\n\n Usage::\n\n import boto3\n s3 = boto3.resource('s3')\n s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')\n\n Similar behavior as S3Transfer's upload_file() method,\n except that parameters are capitalized.\n " ]
Please provide a description of the function:def load_from_definition(self, resource_name, single_resource_json_definition, service_context): logger.debug('Loading %s:%s', service_context.service_name, resource_name) # Using the loaded JSON cre...
[ "\n Loads a resource from a model, creating a new\n :py:class:`~boto3.resources.base.ServiceResource` subclass\n with the correct properties and methods, named based on the service\n and resource name, e.g. EC2.Instance.\n\n :type resource_name: string\n :param resource_nam...
Please provide a description of the function:def _create_action(factory_self, action_model, resource_name, service_context, is_load=False): # Create the action in in this closure but before the ``do_action`` # method below is invoked, which allows instances of the resourc...
[ "\n Creates a new method which makes a request to the underlying\n AWS service.\n " ]
Please provide a description of the function:def client(*args, loop=None, **kwargs): return _get_default_session(loop=loop).client(*args, **kwargs)
[ "\n Create a low-level service client by name using the default session.\n See :py:meth:`aioboto3.session.Session.client`.\n " ]
Please provide a description of the function:def resource(*args, loop=None, **kwargs): return _get_default_session(loop=loop).resource(*args, **kwargs)
[ "\n Create a resource service client by name using the default session.\n See :py:meth:`aioboto3.session.Session.resource`.\n " ]
Please provide a description of the function:async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes: raise NotImplementedError()
[ "\n Get decryption key for a given S3 object\n\n :param key: Base64 decoded version of x-amz-key-v2\n :param material_description: JSON decoded x-amz-matdesc\n :return: Raw AES key bytes\n " ]
Please provide a description of the function:async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes: if self.private_key is None: raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key') plainte...
[ "\n Get decryption key for a given S3 object\n\n :param key: Base64 decoded version of x-amz-key\n :param material_description: JSON decoded x-amz-matdesc\n :return: Raw AES key bytes\n " ]
Please provide a description of the function:async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]: if self.public_key is None: raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key') random_bytes = os.urandom(32) ...
[ "\n Get encryption key to encrypt an S3 object\n\n :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key\n " ]
Please provide a description of the function:def from_der_private_key(data: bytes, password: Optional[str] = None) -> _RSAPrivateKey: return serialization.load_der_private_key(data, password, default_backend())
[ "\n Convert private key in DER encoding to a Private key object\n\n :param data: private key bytes\n :param password: password the private key is encrypted with\n " ]
Please provide a description of the function:async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes: # So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Padding aesecb = self._cipher.decryptor() padded_re...
[ "\n Get decryption key for a given S3 object\n\n :param key: Base64 decoded version of x-amz-key\n :param material_description: JSON decoded x-amz-matdesc\n :return: Raw AES key bytes\n " ]
Please provide a description of the function:async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]: random_bytes = os.urandom(32) padder = PKCS7(AES.block_size).padder() padded_result = await self._loop.run_in_executor( None, lambda: (padder.update(ra...
[ "\n Get encryption key to encrypt an S3 object\n\n :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key\n " ]
Please provide a description of the function:async def get_object(self, Bucket: str, Key: str, **kwargs) -> dict: if self._s3_client is None: await self.setup() # Ok so if we are doing a range get. We need to align the range start/end with AES block boundaries # 92233720368...
[ "\n S3 GetObject. Takes same args as Boto3 documentation\n\n Decrypts any CSE\n\n :param Bucket: S3 Bucket\n :param Key: S3 Key (filepath)\n :return: returns same response as a normal S3 get_object\n " ]
Please provide a description of the function: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): ...
[ "\n PutObject. Takes same args as Boto3 documentation\n\n Encrypts files\n\n :param: Body: File data\n :param Bucket: S3 Bucket\n :param Key: S3 Key (filepath)\n " ]
Please provide a description of the function: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.isfi...
[ "\n Compute a 1D histogram assuming equally spaced bins.\n\n Parameters\n ----------\n x : `~numpy.ndarray`\n The position of the points to bin in the 1D histogram\n bins : int\n The number of bins\n range : iterable\n The range as a tuple of (xmin, xmax)\n weights : `~nump...
Please provide a description of the function: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')...
[ "\n Compute a 2D histogram assuming equally spaced bins.\n\n Parameters\n ----------\n x, y : `~numpy.ndarray`\n The position of the points to bin in the 2D histogram\n bins : int or iterable\n The number of bins in each dimension. If given as an integer, the same\n number of bin...
Please provide a description of the function:def to_networkx(self): return nx_util.to_networkx(self.session.get(self.__url).json())
[ "\n Return this network in NetworkX graph object.\n\n :return: Network as NetworkX graph object\n " ]
Please provide a description of the function:def to_dataframe(self, extra_edges_columns=[]): return df_util.to_dataframe( self.session.get(self.__url).json(), edges_attr_cols=extra_edges_columns )
[ "\n Return this network in pandas DataFrame.\n\n :return: Network as DataFrame. This is equivalent to SIF.\n " ]
Please provide a description of the function: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. " ]
Please provide a description of the function: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...
[ "\n Add new nodes to the network\n\n :param node_name_list: list of node names, e.g. ['a', 'b', 'c']\n :param dataframe: If True, return a pandas dataframe instead of a dict.\n :return: A dict mapping names to SUIDs for the newly-created nodes.\n " ]
Please provide a description of the function:def add_edge(self, source, target, interaction='-', directed=True, dataframe=True): new_edge = { 'source': source, 'target': target, 'interaction': interaction, 'directed': directed } return sel...
[ " Add a single edge from source to target. " ]
Please provide a description of the function:def add_edges(self, edge_list, dataframe=True): # It might be nice to have an option pass a list of dicts instead of list of tuples if not isinstance(edge_list[0], dict): edge_list = [{'source': edge_tuple[0], 't...
[ "\n Add a all edges in edge_list.\n :return: A data structure with Cytoscape SUIDs for the newly-created edges.\n :param edge_list: List of (source, target, interaction) tuples *or*\n list of dicts with 'source', 'target', 'interaction', 'direction' keys.\n :para...
Please provide a description of the function:def get_views(self): url = self.__url + 'views' return self.session.get(url).json()
[ "\n Get views as a list of SUIDs\n\n :return:\n " ]
Please provide a description of the function:def get_first_view(self, fmt='json'): url = self.__url + 'views/first' return self.session.get(url).json()
[ "\n Get a first view model as dict\n :return:\n " ]
Please provide a description of the function: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) retur...
[ "\n Diffusion will send the selected network view and its selected nodes to\n a web-based REST service to calculate network propagation. Results are\n returned and represented by columns in the node table.\n Columns are created for each execution of Diffusion and their names are\n ...
Please provide a description of the function: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[ke...
[ "\n Convert Cytoscape.js-style JSON object into NetworkX object.\n\n By default, data will be handles as a directed graph.\n " ]
Please provide a description of the function:def api(namespace=None, command="", PARAMS={}, body=None, host=HOST, port=str(PORT), version=VERSION, method="POST", verbose=VERBOSE, url=None, parse_params=True): if url: baseurl=url else: if namespace: baseurl="http://"+str(host)+"...
[ "\n General function for interacting with Cytoscape API.\n\n :param namespace: namespace where the request should be executed. eg. \"string\"\n :param commnand: command to execute. eg. \"protein query\"\n :param PARAMs: a dictionary with the parameters. Check your swagger normaly running on\n http://...
Please provide a description of the function: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", verbos...
[ "\n Launch and HTML browser in a separate window.\n\n :param wid: Window ID\n :param text: HTML text\n :param title: Window Title\n :param url: URL\n :param debug: Show debug tools. boolean\n :param verbose: print more\n " ]
Please provide a description of the function:def hide(self, wid, verbose=False): PARAMS={"id":wid} response=api(url=self.__url+"/hide?",PARAMS=PARAMS, method="GET", verbose=verbose) return response
[ "\n Hide and HTML browser in the Results Panel.\n\n :param wid: Window ID\n :param verbose: print more\n " ]
Please provide a description of the function: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=...
[ "\n Launch an HTML browser in the Results Panel.\n\n :param wid: Window ID\n :param text: HTML text\n :param title: Window Title\n :param url: URL\n :param verbose: print more\n " ]
Please provide a description of the function:def check_response(res): try: res.raise_for_status() # Alternative is res.ok except Exception as exc: # Bad response code, e.g. if adding an edge with nodes that doesn't exist try: err_info = res.json() err_msg = e...
[ " Check HTTP response and raise exception if response is not OK. " ]
Please provide a description of the function:def from_dataframe(df, source_col='source', target_col='target', interaction_col='interaction', name='From DataFrame', edge_attr_cols=[]): network = cyjs.get_empty_networ...
[ "\n Utility to convert Pandas DataFrame object into Cytoscape.js JSON\n\n :param df: Dataframe to convert.\n :param source_col: Name of source column.\n :param target_col: Name of target column.\n :param interaction_col: Name of interaction column.\n :param name: Name of network.\n :param edge_...
Please provide a description of the function: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_co...
[ "\n Utility to convert a Cytoscape dictionary into a Pandas Dataframe.\n\n :param network: Dictionary to convert.\n :param interaction: Name of interaction column.\n :param default_interaction: Default value for missing interactions.\n :param edges_attr_cols: List containing other edges' attributes t...
Please provide a description of the function: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_edge...
[ "Render network data with embedded Cytoscape.js widget.\n\n :param network: dict (required)\n The network data should be in Cytoscape.js JSON format.\n :param style: str or dict\n If str, pick one of the preset style. [default: 'default']\n If dict, it should be Cytoscape.js style CSS obj...
Please provide a description of the function:def getPanelStatus(self, panelName, verbose=None): response=api(url=self.___url+'ui/panels/'+str(panelName)+'', method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns the status of the CytoPanel specified by the `panelName` parameter.\n\n :param panelName: Name of the CytoPanel\n :param verbose: print more\n\n :returns: 200: successful operation\n " ]
Please provide a description of the function:def updateLodState(self, verbose=None): response=api(url=self.___url+'ui/lod', method="PUT", verbose=verbose) return response
[ "\n Switch between full graphics details <---> fast rendering mode.\n \n Returns a success message.\n\n :param verbose: print more\n\n :returns: 200: successful operation\n " ]
Please provide a description of the function: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,nam...
[ "\n Creates a new edge column.\n\n :param column (string, optional): Unique name of column\n :param listType (string, optional): Can be one of integer, long, double,\n or string.\n :param namespace (string, optional): Node, Edge, and Network objects\n support the de...
Please provide a description of the function: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,target...
[ "\n Returns the SUID of an edge that matches the passed parameters. If\n multiple edges are found, only one will be returned, and a warning will\n be reported in the Cytoscape Task History dialog.\n\n :param edge (string, optional): Selects an edge by name, or, if the\n parame...
Please provide a description of the function:def getNetworkViewCount(self, networkId, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/count', method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns a count of the Network Views available for the Network specified by the `networkId` parameter.\n \n Cytoscape can have multiple views per network model, but this feature is not exposed in the Cytoscape GUI. GUI access is limited to the first available view only.\n\n :param ne...
Please provide a description of the function:def getFirstImageAsPdf(self, networkId, h, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/first.pdf', PARAMS={'h':h}, method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns a PDF of the first available Network View for the Network specified by the `networkId` parameter.\n \n Default size is 600 px\n\n :param networkId: SUID of the Network\n :param h: Height of the image. Width is set automatically -- Not required, can be None\n :pa...
Please provide a description of the function:def getTableAsCsv(self, networkId, tableType, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/tables/'+str(tableType)+'.csv', method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns a CSV representation of the table specified by the `networkId` and `tableType` parameters. All column names are included in the first row.\n\n :param networkId: SUID of the network containing the table\n :param tableType: Table type\n :param verbose: print more\n\n :re...
Please provide a description of the function:def putNetworkVisualPropBypass(self, networkId, viewId, visualProperty, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/network/'+str(visualProperty)+'/bypass', method="PUT", body=body, verbose=verbose) ...
[ "\n Bypasses the Visual Style of the Network with the Visual Property specificed by the `visualProperty`, `viewId`, and `networkId` parameters.\n \n Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](http://chianti.ucsd.edu/cytoscape-3.6.1/API/...
Please provide a description of the function:def deleteNetworkVisualProp(self, networkId, viewId, visualProperty, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/network/'+str(visualProperty)+'/bypass', method="DELETE", verbose=verbose) return res...
[ "\n Deletes the bypass Visual Property specificed by the `visualProperty`, `viewId`, and `networkId` parameters. When this is done, the Visual Property will be defined by the Visual Style\n \n Additional details on common Visual Properties can be found in the [Basic Visual Lexicon JavaDoc API](...
Please provide a description of the function:def setCurrentNetwork(self, body, verbose=None): response=api(url=self.___url+'networks/currentNetwork', method="PUT", body=body, verbose=verbose) return response
[ "\n Sets the current network.\n\n :param body: SUID of the Network -- Not required, can be None\n :param verbose: print more\n\n :returns: 200: successful operation\n " ]
Please provide a description of the function:def createNetworkFromSelected(self, networkId, title, verbose=None): PARAMS=set_param(['networkId','title'],[networkId,title]) response=api(url=self.___url+'networks/'+str(networkId)+'', PARAMS=PARAMS, method="POST", verbose=verbose) return ...
[ "\n Creates new sub-network from current selection, with the name specified by the `title` parameter.\n \n Returns the SUID of the new sub-network.\n\n :param networkId: SUID of the network containing the selected nodes and edges\n :param title: Name for the new sub-network -- Not...
Please provide a description of the function:def updateTable(self, networkId, tableType, body, class_, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/tables/'+str(tableType)+'', method="PUT", body=body, verbose=verbose) return response
[ "\n Updates the table specified by the `tableType` and `networkId` parameters. New columns will be created if they do not exist in the target table.\n \n Current limitations:\n * Numbers are handled as Double\n * List column is not supported in this version\n\n :param netw...
Please provide a description of the function:def getSingleVisualPropertyValue(self, networkId, viewId, objectType, objectId, visualProperty, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/'+str(objectType)+'/'+str(objectId)+'/'+str(visualProperty)+'', me...
[ "\n Gets the Visual Property specificed by the `visualProperty` parameter for the node or edge specified by the `objectId` parameter in the Network View specified by the `viewId` and `networkId` parameters.\n \n Additional details on common Visual Properties can be found in the [Basic Visual Le...
Please provide a description of the function:def updateViews(self, networkId, viewId, objectType, bypass, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/'+str(objectType)+'', method="PUT", body=body, verbose=verbose) return response
[ "\n Updates multiple node or edge Visual Properties as defined by the `objectType` parameter, in the Network View specified by the `viewId` and `networkId` parameters.\n \n Examples of Visual Properties:\n \n ```\n {\n \"visualProperty\": \"NODE_BORDER_WIDTH\",\n ...
Please provide a description of the function:def getViews(self, networkId, viewId, objectType, visualProperty, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/'+str(objectType)+'', PARAMS={'visualProperty':visualProperty}, method="H", verbose=verbose, par...
[ "\n Returns a list of all Visual Property values for the Visual Property specified by the `visualProperty` and `objectType` parameters, in the Network View specified by the `viewId` and `networkId` parameters.\n \n Additional details on common Visual Properties can be found in the [Basic Visual...
Please provide a description of the function:def updateColumnName(self, networkId, tableType, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/tables/'+str(tableType)+'/columns', method="PUT", body=body, verbose=verbose) return response
[ "\n Renames an existing column in the table specified by the `tableType` and `networkId` parameters.\n\n :param networkId: SUID of the network containing the table\n :param tableType: Table Type\n :param body: Old and new column name\n :param verbose: print more\n\n :return...
Please provide a description of the function:def getEdgeDirected(self, networkId, edgeId, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/edges/'+str(edgeId)+'/isDirected', method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns true if the edge specified by the `edgeId` and `networkId` parameters is directed.\n\n :param networkId: SUID of the network containing the edge\n :param edgeId: SUID of the edge\n :param verbose: print more\n\n :returns: 200: successful operation\n " ]
Please provide a description of the function:def putSingleVisualPropertyValueBypass(self, networkId, viewId, objectType, objectId, visualProperty, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/views/'+str(viewId)+'/'+str(objectType)+'/'+str(objectId)+'/'+str(visualProp...
[ "\n Bypasses the Visual Style of the object specified by the `objectId` and `objectType` parameters, in the Network View specified by the `viewId` and `networkId` parameters. The Visual Property included in the message body will be used instead of the definition provided by the Visual Style.\n \n ...
Please provide a description of the function:def deleteNode(self, networkId, nodeId, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/nodes/'+str(nodeId)+'', method="DELETE", verbose=verbose) return response
[ "\n Deletes the node specified by the `nodeId` and `networkId` parameters.\n\n :param networkId: SUID of the network containing the node.\n :param nodeId: SUID of the node\n :param verbose: print more\n\n :returns: default: successful operation\n " ]
Please provide a description of the function:def setSelectedEdges(self, networkId, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/edges/selected', method="PUT", body=body, verbose=verbose) return response
[ "\n Sets as selected the edges specified by the `suids` and `networkId` parameters.\n \n Returns a list of selected SUIDs.\n\n :param networkId: SUID of the network containing the edges\n :param body: Array of edge SUIDs to select -- Not required, can be None\n :param verbo...
Please provide a description of the function:def deleteGroup(self, networkId, groupNodeId, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/groups/'+str(groupNodeId)+'', method="DELETE", verbose=verbose) return response
[ "\n Deletes the group specified by the `groupNodeId` and `networkId` parameters. The nodes and edges that the group contained will remain present in the network, however the node used to identify the Group will be deleted.\n\n :param networkId: SUID of the Network\n :param groupNodeId: SUID of ...
Please provide a description of the function:def getGroup(self, networkId, groupNodeId, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/groups/'+str(groupNodeId)+'', method="GET", verbose=verbose, parse_params=False) return response
[ "\n Returns the group specified by the `groupNodeId` and `networkId` parameters.\n\n :param networkId: SUID of the Network\n :param groupNodeId: SUID of the Node representing the Group\n :param verbose: print more\n\n :returns: 200: successful operation\n " ]
Please provide a description of the function:def updateColumnValues(self, networkId, tableType, columnName, default, body, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/tables/'+str(tableType)+'/columns/'+str(columnName)+'', method="PUT", body=body, verbose=verbose) ...
[ "\n Sets the values for cells in the table specified by the `tableType` and `networkId` parameters.\n \n If the 'default` parameter is not specified, the message body should consist of key-value pairs with which to set values.\n \n If the `default` parameter is specified, its valu...
Please provide a description of the function:def deleteColumn(self, networkId, tableType, columnName, verbose=None): response=api(url=self.___url+'networks/'+str(networkId)+'/tables/'+str(tableType)+'/columns/'+str(columnName)+'', method="DELETE", verbose=verbose) return response
[ "\n Deletes the column specified by the `columnName` parameter from the table speficied by the `tableType` and `networkId` parameters.\n\n :param networkId: SUID of the network containing the table from which to delete the column\n :param tableType: Table Type from which to delete the column\n ...