repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
infobloxopen/infoblox-client
infoblox_client/object_manager.py
InfobloxObjectManager.create_ip_range
def create_ip_range(self, network_view, start_ip, end_ip, network, disable, range_extattrs): """Creates IPRange or fails if already exists.""" return obj.IPRange.create(self.connector, network_view=network_view, ...
python
def create_ip_range(self, network_view, start_ip, end_ip, network, disable, range_extattrs): """Creates IPRange or fails if already exists.""" return obj.IPRange.create(self.connector, network_view=network_view, ...
Creates IPRange or fails if already exists.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L103-L113
infobloxopen/infoblox-client
infoblox_client/object_manager.py
InfobloxObjectManager.network_exists
def network_exists(self, network_view, cidr): """Deprecated, use get_network() instead.""" LOG.warning( "DEPRECATION WARNING! Using network_exists() is deprecated " "and to be removed in next releases. " "Use get_network() or objects.Network.search instead") n...
python
def network_exists(self, network_view, cidr): """Deprecated, use get_network() instead.""" LOG.warning( "DEPRECATION WARNING! Using network_exists() is deprecated " "and to be removed in next releases. " "Use get_network() or objects.Network.search instead") n...
Deprecated, use get_network() instead.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L128-L137
infobloxopen/infoblox-client
infoblox_client/object_manager.py
InfobloxObjectManager.delete_objects_associated_with_a_record
def delete_objects_associated_with_a_record(self, name, view, delete_list): """Deletes records associated with record:a or record:aaaa.""" search_objects = {} if 'record:cname' in delete_list: search_objects['record:cname'] = 'canonical' if 'record:txt' in delete_list: ...
python
def delete_objects_associated_with_a_record(self, name, view, delete_list): """Deletes records associated with record:a or record:aaaa.""" search_objects = {} if 'record:cname' in delete_list: search_objects['record:cname'] = 'canonical' if 'record:txt' in delete_list: ...
Deletes records associated with record:a or record:aaaa.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L453-L470
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector._parse_options
def _parse_options(self, options): """Copy needed options to self""" attributes = ('host', 'wapi_version', 'username', 'password', 'ssl_verify', 'http_request_timeout', 'max_retries', 'http_pool_connections', 'http_pool_maxsize', 'silent_...
python
def _parse_options(self, options): """Copy needed options to self""" attributes = ('host', 'wapi_version', 'username', 'password', 'ssl_verify', 'http_request_timeout', 'max_retries', 'http_pool_connections', 'http_pool_maxsize', 'silent_...
Copy needed options to self
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L89-L115
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector._parse_reply
def _parse_reply(request): """Tries to parse reply from NIOS. Raises exception with content if reply is not in json format """ try: return jsonutils.loads(request.content) except ValueError: raise ib_ex.InfobloxConnectionError(reason=request.content)
python
def _parse_reply(request): """Tries to parse reply from NIOS. Raises exception with content if reply is not in json format """ try: return jsonutils.loads(request.content) except ValueError: raise ib_ex.InfobloxConnectionError(reason=request.content)
Tries to parse reply from NIOS. Raises exception with content if reply is not in json format
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L212-L220
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector.get_object
def get_object(self, obj_type, payload=None, return_fields=None, extattrs=None, force_proxy=False, max_results=None, paging=False): """Retrieve a list of Infoblox objects of type 'obj_type' Some get requests like 'ipv4address' should be always proxied to GM...
python
def get_object(self, obj_type, payload=None, return_fields=None, extattrs=None, force_proxy=False, max_results=None, paging=False): """Retrieve a list of Infoblox objects of type 'obj_type' Some get requests like 'ipv4address' should be always proxied to GM...
Retrieve a list of Infoblox objects of type 'obj_type' Some get requests like 'ipv4address' should be always proxied to GM on Hellfire If request is cloud and proxy is not forced yet, then plan to do 2 request: - the first one is not proxied to GM - the second is proxied...
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L231-L293
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector.create_object
def create_object(self, obj_type, payload, return_fields=None): """Create an Infoblox object of type 'obj_type' Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send ...
python
def create_object(self, obj_type, payload, return_fields=None): """Create an Infoblox object of type 'obj_type' Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send ...
Create an Infoblox object of type 'obj_type' Args: obj_type (str): Infoblox object type, e.g. 'network', 'range', etc. payload (dict): Payload with data to send return_fields (list): List of fields to be returned Returns...
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L345-L387
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector.update_object
def update_object(self, ref, payload, return_fields=None): """Update an Infoblox object Args: ref (str): Infoblox object reference payload (dict): Payload with data to send Returns: The object reference of the updated object Raises: I...
python
def update_object(self, ref, payload, return_fields=None): """Update an Infoblox object Args: ref (str): Infoblox object reference payload (dict): Payload with data to send Returns: The object reference of the updated object Raises: I...
Update an Infoblox object Args: ref (str): Infoblox object reference payload (dict): Payload with data to send Returns: The object reference of the updated object Raises: InfobloxException
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L424-L453
infobloxopen/infoblox-client
infoblox_client/connector.py
Connector.delete_object
def delete_object(self, ref, delete_arguments=None): """Remove an Infoblox object Args: ref (str): Object reference delete_arguments (dict): Extra delete arguments Returns: The object reference of the removed object Raises: I...
python
def delete_object(self, ref, delete_arguments=None): """Remove an Infoblox object Args: ref (str): Object reference delete_arguments (dict): Extra delete arguments Returns: The object reference of the removed object Raises: I...
Remove an Infoblox object Args: ref (str): Object reference delete_arguments (dict): Extra delete arguments Returns: The object reference of the removed object Raises: InfobloxException
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L456-L485
infobloxopen/infoblox-client
infoblox_client/objects.py
BaseObject._remap_fields
def _remap_fields(cls, kwargs): """Map fields from kwargs into dict acceptable by NIOS""" mapped = {} for key in kwargs: if key in cls._remap: mapped[cls._remap[key]] = kwargs[key] else: mapped[key] = kwargs[key] return mapped
python
def _remap_fields(cls, kwargs): """Map fields from kwargs into dict acceptable by NIOS""" mapped = {} for key in kwargs: if key in cls._remap: mapped[cls._remap[key]] = kwargs[key] else: mapped[key] = kwargs[key] return mapped
Map fields from kwargs into dict acceptable by NIOS
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L87-L95
infobloxopen/infoblox-client
infoblox_client/objects.py
EA.from_dict
def from_dict(cls, eas_from_nios): """Converts extensible attributes from the NIOS reply.""" if not eas_from_nios: return return cls({name: cls._process_value(ib_utils.try_value_to_bool, eas_from_nios[name]['value']) fo...
python
def from_dict(cls, eas_from_nios): """Converts extensible attributes from the NIOS reply.""" if not eas_from_nios: return return cls({name: cls._process_value(ib_utils.try_value_to_bool, eas_from_nios[name]['value']) fo...
Converts extensible attributes from the NIOS reply.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L141-L147
infobloxopen/infoblox-client
infoblox_client/objects.py
EA.to_dict
def to_dict(self): """Converts extensible attributes into the format suitable for NIOS.""" return {name: {'value': self._process_value(str, value)} for name, value in self._ea_dict.items() if not (value is None or value == "" or value == [])}
python
def to_dict(self): """Converts extensible attributes into the format suitable for NIOS.""" return {name: {'value': self._process_value(str, value)} for name, value in self._ea_dict.items() if not (value is None or value == "" or value == [])}
Converts extensible attributes into the format suitable for NIOS.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L149-L153
infobloxopen/infoblox-client
infoblox_client/objects.py
EA._process_value
def _process_value(func, value): """Applies processing method for value or each element in it. :param func: method to be called with value :param value: value to process :return: if 'value' is list/tupe, returns iterable with func results, else func result is returned ...
python
def _process_value(func, value): """Applies processing method for value or each element in it. :param func: method to be called with value :param value: value to process :return: if 'value' is list/tupe, returns iterable with func results, else func result is returned ...
Applies processing method for value or each element in it. :param func: method to be called with value :param value: value to process :return: if 'value' is list/tupe, returns iterable with func results, else func result is returned
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L156-L166
infobloxopen/infoblox-client
infoblox_client/objects.py
InfobloxObject.from_dict
def from_dict(cls, connector, ip_dict): """Build dict fields as SubObjects if needed. Checks if lambda for building object from dict exists. _global_field_processing and _custom_field_processing rules are checked. """ mapping = cls._global_field_processing.copy() ...
python
def from_dict(cls, connector, ip_dict): """Build dict fields as SubObjects if needed. Checks if lambda for building object from dict exists. _global_field_processing and _custom_field_processing rules are checked. """ mapping = cls._global_field_processing.copy() ...
Build dict fields as SubObjects if needed. Checks if lambda for building object from dict exists. _global_field_processing and _custom_field_processing rules are checked.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L243-L256
infobloxopen/infoblox-client
infoblox_client/objects.py
InfobloxObject.field_to_dict
def field_to_dict(self, field): """Read field value and converts to dict if possible""" value = getattr(self, field) if isinstance(value, (list, tuple)): return [self.value_to_dict(val) for val in value] return self.value_to_dict(value)
python
def field_to_dict(self, field): """Read field value and converts to dict if possible""" value = getattr(self, field) if isinstance(value, (list, tuple)): return [self.value_to_dict(val) for val in value] return self.value_to_dict(value)
Read field value and converts to dict if possible
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L262-L267
infobloxopen/infoblox-client
infoblox_client/objects.py
InfobloxObject.to_dict
def to_dict(self, search_fields=None): """Builds dict without None object fields""" fields = self._fields if search_fields == 'update': fields = self._search_for_update_fields elif search_fields == 'all': fields = self._all_searchable_fields elif search_fi...
python
def to_dict(self, search_fields=None): """Builds dict without None object fields""" fields = self._fields if search_fields == 'update': fields = self._search_for_update_fields elif search_fields == 'all': fields = self._all_searchable_fields elif search_fi...
Builds dict without None object fields
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L269-L284
infobloxopen/infoblox-client
infoblox_client/objects.py
InfobloxObject.fetch
def fetch(self, only_ref=False): """Fetch object from NIOS by _ref or searchfields Update existent object with fields returned from NIOS Return True on successful object fetch """ if self.ref: reply = self.connector.get_object( self.ref, return_fields...
python
def fetch(self, only_ref=False): """Fetch object from NIOS by _ref or searchfields Update existent object with fields returned from NIOS Return True on successful object fetch """ if self.ref: reply = self.connector.get_object( self.ref, return_fields...
Fetch object from NIOS by _ref or searchfields Update existent object with fields returned from NIOS Return True on successful object fetch
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L378-L399
infobloxopen/infoblox-client
infoblox_client/objects.py
HostRecord._ip_setter
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips): """Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ...
python
def _ip_setter(self, ipaddr_name, ipaddrs_name, ips): """Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ...
Setter for ip fields Accept as input string or list of IP instances. String case: only ipvXaddr is going to be filled, that is enough to perform host record search using ip List of IP instances case: ipvXaddrs is going to be filled with ips content, ...
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L527-L554
infobloxopen/infoblox-client
infoblox_client/objects.py
FixedAddressV6.mac
def mac(self, mac): """Set mac and duid fields To have common interface with FixedAddress accept mac address and set duid as a side effect. 'mac' was added to _shadow_fields to prevent sending it out over wapi. """ self._mac = mac if mac: self.duid = ...
python
def mac(self, mac): """Set mac and duid fields To have common interface with FixedAddress accept mac address and set duid as a side effect. 'mac' was added to _shadow_fields to prevent sending it out over wapi. """ self._mac = mac if mac: self.duid = ...
Set mac and duid fields To have common interface with FixedAddress accept mac address and set duid as a side effect. 'mac' was added to _shadow_fields to prevent sending it out over wapi.
https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L821-L832
cf-platform-eng/tile-generator
tile_generator/template.py
render_property
def render_property(property): """Render a property for bosh manifest, according to its type.""" # This ain't the prettiest thing, but it should get the job done. # I don't think we have anything more elegant available at bosh-manifest-generation time. # See https://docs.pivotal.io/partners/product-template-referen...
python
def render_property(property): """Render a property for bosh manifest, according to its type.""" # This ain't the prettiest thing, but it should get the job done. # I don't think we have anything more elegant available at bosh-manifest-generation time. # See https://docs.pivotal.io/partners/product-template-referen...
Render a property for bosh manifest, according to its type.
https://github.com/cf-platform-eng/tile-generator/blob/56b602334edb38639bc7e01b1e9e68e43f9e6828/tile_generator/template.py#L152-L170
h2non/filetype.py
filetype/match.py
match
def match(obj, matchers=TYPES): """ Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ buf...
python
def match(obj, matchers=TYPES): """ Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type. """ buf...
Matches the given input againts the available file type matchers. Args: obj: path to file, bytes or bytearray. Returns: Type instance if type matches. Otherwise None. Raises: TypeError: if obj is not a supported type.
https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/match.py#L14-L34
h2non/filetype.py
filetype/utils.py
signature
def signature(array): """ Returns the first 262 bytes of the given bytearray as part of the file header signature. Args: array: bytearray to extract the header signature. Returns: First 262 bytes of the file content as bytearray type. """ length = len(array) index = _NU...
python
def signature(array): """ Returns the first 262 bytes of the given bytearray as part of the file header signature. Args: array: bytearray to extract the header signature. Returns: First 262 bytes of the file content as bytearray type. """ length = len(array) index = _NU...
Returns the first 262 bytes of the given bytearray as part of the file header signature. Args: array: bytearray to extract the header signature. Returns: First 262 bytes of the file content as bytearray type.
https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/utils.py#L21-L35
h2non/filetype.py
filetype/utils.py
get_bytes
def get_bytes(obj): """ Infers the input type and reads the first 262 bytes, returning a sliced bytearray. Args: obj: path to readable, file, bytes or bytearray. Returns: First 262 bytes of the file content as bytearray type. Raises: TypeError: if obj is not a supporte...
python
def get_bytes(obj): """ Infers the input type and reads the first 262 bytes, returning a sliced bytearray. Args: obj: path to readable, file, bytes or bytearray. Returns: First 262 bytes of the file content as bytearray type. Raises: TypeError: if obj is not a supporte...
Infers the input type and reads the first 262 bytes, returning a sliced bytearray. Args: obj: path to readable, file, bytes or bytearray. Returns: First 262 bytes of the file content as bytearray type. Raises: TypeError: if obj is not a supported type.
https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/utils.py#L38-L72
h2non/filetype.py
filetype/filetype.py
get_type
def get_type(mime=None, ext=None): """ Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None. ...
python
def get_type(mime=None, ext=None): """ Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None. ...
Returns the file type instance searching by MIME type or file extension. Args: ext: file extension string. E.g: jpg, png, mp4, mp3 mime: MIME string. E.g: image/jpeg, video/mpeg Returns: The matched file type instance. Otherwise None.
https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/filetype.py#L67-L82
python-beaver/python-beaver
beaver/worker/tail.py
Tail.open
def open(self, encoding=None): """Opens the file with the appropriate call""" try: if IS_GZIPPED_FILE.search(self._filename): _file = gzip.open(self._filename, 'rb') else: if encoding: _file = io.open(self._filename, 'r', encodi...
python
def open(self, encoding=None): """Opens the file with the appropriate call""" try: if IS_GZIPPED_FILE.search(self._filename): _file = gzip.open(self._filename, 'rb') else: if encoding: _file = io.open(self._filename, 'r', encodi...
Opens the file with the appropriate call
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L79-L96
python-beaver/python-beaver
beaver/worker/tail.py
Tail.close
def close(self): """Closes all currently open file pointers""" if not self.active: return self.active = False if self._file: self._file.close() self._sincedb_update_position(force_update=True) if self._current_event: event = '\n'....
python
def close(self): """Closes all currently open file pointers""" if not self.active: return self.active = False if self._file: self._file.close() self._sincedb_update_position(force_update=True) if self._current_event: event = '\n'....
Closes all currently open file pointers
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L98-L111
python-beaver/python-beaver
beaver/worker/tail.py
Tail._buffer_extract
def _buffer_extract(self, data): """ Extract takes an arbitrary string of input data and returns an array of tokenized entities, provided there were any available to extract. This makes for easy processing of datagrams using a pattern like: tokenizer.extract(data).map { |enti...
python
def _buffer_extract(self, data): """ Extract takes an arbitrary string of input data and returns an array of tokenized entities, provided there were any available to extract. This makes for easy processing of datagrams using a pattern like: tokenizer.extract(data).map { |enti...
Extract takes an arbitrary string of input data and returns an array of tokenized entities, provided there were any available to extract. This makes for easy processing of datagrams using a pattern like: tokenizer.extract(data).map { |entity| Decode(entity) }.each do ...
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L130-L184
python-beaver/python-beaver
beaver/worker/tail.py
Tail._ensure_file_is_good
def _ensure_file_is_good(self, current_time): """Every N seconds, ensures that the file we are tailing is the file we expect to be tailing""" if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval: return self._last_file_mapping_up...
python
def _ensure_file_is_good(self, current_time): """Every N seconds, ensures that the file we are tailing is the file we expect to be tailing""" if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval: return self._last_file_mapping_up...
Every N seconds, ensures that the file we are tailing is the file we expect to be tailing
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L197-L232
python-beaver/python-beaver
beaver/worker/tail.py
Tail._run_pass
def _run_pass(self): """Read lines from a file and performs a callback against them""" while True: try: data = self._file.read(4096) except IOError, e: if e.errno == errno.ESTALE: self.active = False return F...
python
def _run_pass(self): """Read lines from a file and performs a callback against them""" while True: try: data = self._file.read(4096) except IOError, e: if e.errno == errno.ESTALE: self.active = False return F...
Read lines from a file and performs a callback against them
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L234-L273
python-beaver/python-beaver
beaver/worker/tail.py
Tail._sincedb_init
def _sincedb_init(self): """Initializes the sincedb schema in an sqlite db""" if not self._sincedb_path: return if not os.path.exists(self._sincedb_path): self._log_debug('initializing sincedb sqlite schema') conn = sqlite3.connect(self._sincedb_path, isolati...
python
def _sincedb_init(self): """Initializes the sincedb schema in an sqlite db""" if not self._sincedb_path: return if not os.path.exists(self._sincedb_path): self._log_debug('initializing sincedb sqlite schema') conn = sqlite3.connect(self._sincedb_path, isolati...
Initializes the sincedb schema in an sqlite db
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L381-L396
python-beaver/python-beaver
beaver/worker/tail.py
Tail._sincedb_update_position
def _sincedb_update_position(self, lines=0, force_update=False): """Retrieves the starting position from the sincedb sql db for a given file Returns a boolean representing whether or not it updated the record """ if not self._sincedb_path: return False self._line_cou...
python
def _sincedb_update_position(self, lines=0, force_update=False): """Retrieves the starting position from the sincedb sql db for a given file Returns a boolean representing whether or not it updated the record """ if not self._sincedb_path: return False self._line_cou...
Retrieves the starting position from the sincedb sql db for a given file Returns a boolean representing whether or not it updated the record
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L398-L441
python-beaver/python-beaver
beaver/worker/tail.py
Tail._sincedb_start_position
def _sincedb_start_position(self): """Retrieves the starting position from the sincedb sql db for a given file """ if not self._sincedb_path: return None self._sincedb_init() self._log_debug('retrieving start_position from sincedb') conn = sqlite3.con...
python
def _sincedb_start_position(self): """Retrieves the starting position from the sincedb sql db for a given file """ if not self._sincedb_path: return None self._sincedb_init() self._log_debug('retrieving start_position from sincedb') conn = sqlite3.con...
Retrieves the starting position from the sincedb sql db for a given file
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L443-L463
python-beaver/python-beaver
beaver/worker/tail.py
Tail._update_file
def _update_file(self, seek_to_end=True): """Open the file for tailing""" try: self.close() self._file = self.open() except IOError: pass else: if not self._file: return self.active = True try: ...
python
def _update_file(self, seek_to_end=True): """Open the file for tailing""" try: self.close() self._file = self.open() except IOError: pass else: if not self._file: return self.active = True try: ...
Open the file for tailing
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L465-L492
python-beaver/python-beaver
beaver/worker/tail.py
Tail.tail
def tail(self, fname, encoding, window, position=None): """Read last N lines from file fname.""" if window <= 0: raise ValueError('invalid window %r' % window) encodings = ENCODINGS if encoding: encodings = [encoding] + ENCODINGS for enc in encodings: ...
python
def tail(self, fname, encoding, window, position=None): """Read last N lines from file fname.""" if window <= 0: raise ValueError('invalid window %r' % window) encodings = ENCODINGS if encoding: encodings = [encoding] + ENCODINGS for enc in encodings: ...
Read last N lines from file fname.
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L494-L515
python-beaver/python-beaver
beaver/transports/__init__.py
create_transport
def create_transport(beaver_config, logger): """Creates and returns a transport object""" transport_str = beaver_config.get('transport') if '.' not in transport_str: # allow simple names like 'redis' to load a beaver built-in transport module_path = 'beaver.transports.%s_transport' % transpo...
python
def create_transport(beaver_config, logger): """Creates and returns a transport object""" transport_str = beaver_config.get('transport') if '.' not in transport_str: # allow simple names like 'redis' to load a beaver built-in transport module_path = 'beaver.transports.%s_transport' % transpo...
Creates and returns a transport object
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/__init__.py#L4-L22
python-beaver/python-beaver
beaver/worker/tail_manager.py
TailManager.listdir
def listdir(self): """HACK around not having a beaver_config stanza TODO: Convert this to a glob""" ls = os.listdir(self._folder) return [x for x in ls if os.path.splitext(x)[1][1:] == "log"]
python
def listdir(self): """HACK around not having a beaver_config stanza TODO: Convert this to a glob""" ls = os.listdir(self._folder) return [x for x in ls if os.path.splitext(x)[1][1:] == "log"]
HACK around not having a beaver_config stanza TODO: Convert this to a glob
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail_manager.py#L34-L38
python-beaver/python-beaver
beaver/worker/tail_manager.py
TailManager.update_files
def update_files(self): """Ensures all files are properly loaded. Detects new files, file removals, file rotation, and truncation. On non-linux platforms, it will also manually reload the file for tailing. Note that this hack is necessary because EOF is cached on BSD systems. """...
python
def update_files(self): """Ensures all files are properly loaded. Detects new files, file removals, file rotation, and truncation. On non-linux platforms, it will also manually reload the file for tailing. Note that this hack is necessary because EOF is cached on BSD systems. """...
Ensures all files are properly loaded. Detects new files, file removals, file rotation, and truncation. On non-linux platforms, it will also manually reload the file for tailing. Note that this hack is necessary because EOF is cached on BSD systems.
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail_manager.py#L85-L125
python-beaver/python-beaver
beaver/worker/tail_manager.py
TailManager.close
def close(self, signalnum=None, frame=None): self._running = False """Closes all currently open Tail objects""" self._log_debug("Closing all tail objects") self._active = False for fid in self._tails: self._tails[fid].close() for n in range(0,self._number_of_c...
python
def close(self, signalnum=None, frame=None): self._running = False """Closes all currently open Tail objects""" self._log_debug("Closing all tail objects") self._active = False for fid in self._tails: self._tails[fid].close() for n in range(0,self._number_of_c...
Closes all currently open Tail objects
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail_manager.py#L127-L138
python-beaver/python-beaver
beaver/utils.py
eglob
def eglob(path, exclude=None): """Like glob.glob, but supports "/path/**/{a,b,c}.txt" lookup""" fi = itertools.chain.from_iterable paths = list(fi(glob2.iglob(d) for d in expand_paths(path))) if exclude: cached_regex = cached_regices.get(exclude, None) if not cached_regex: ca...
python
def eglob(path, exclude=None): """Like glob.glob, but supports "/path/**/{a,b,c}.txt" lookup""" fi = itertools.chain.from_iterable paths = list(fi(glob2.iglob(d) for d in expand_paths(path))) if exclude: cached_regex = cached_regices.get(exclude, None) if not cached_regex: ca...
Like glob.glob, but supports "/path/**/{a,b,c}.txt" lookup
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L134-L144
python-beaver/python-beaver
beaver/utils.py
expand_paths
def expand_paths(path): """When given a path with brackets, expands it to return all permutations of the path with expanded brackets, similar to ant. >>> expand_paths('../{a,b}/{c,d}') ['../a/c', '../a/d', '../b/c', '../b/d'] >>> expand_paths('../{a,b}/{a,b}.py') ['../a/a.py', '....
python
def expand_paths(path): """When given a path with brackets, expands it to return all permutations of the path with expanded brackets, similar to ant. >>> expand_paths('../{a,b}/{c,d}') ['../a/c', '../a/d', '../b/c', '../b/d'] >>> expand_paths('../{a,b}/{a,b}.py') ['../a/a.py', '....
When given a path with brackets, expands it to return all permutations of the path with expanded brackets, similar to ant. >>> expand_paths('../{a,b}/{c,d}') ['../a/c', '../a/d', '../b/c', '../b/d'] >>> expand_paths('../{a,b}/{a,b}.py') ['../a/a.py', '../a/b.py', '../b/a.py', '../b/b...
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L147-L171
python-beaver/python-beaver
beaver/utils.py
multiline_merge
def multiline_merge(lines, current_event, re_after, re_before): """ Merge multi-line events based. Some event (like Python trackback or Java stracktrace) spawn on multiple line. This method will merge them using two regular expression: regex_after and regex_before. If a line match ...
python
def multiline_merge(lines, current_event, re_after, re_before): """ Merge multi-line events based. Some event (like Python trackback or Java stracktrace) spawn on multiple line. This method will merge them using two regular expression: regex_after and regex_before. If a line match ...
Merge multi-line events based. Some event (like Python trackback or Java stracktrace) spawn on multiple line. This method will merge them using two regular expression: regex_after and regex_before. If a line match re_after, it will be merged with next line. If a line match re_...
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L180-L210
python-beaver/python-beaver
beaver/ssh_tunnel.py
create_ssh_tunnel
def create_ssh_tunnel(beaver_config, logger=None): """Returns a BeaverSshTunnel object if the current config requires us to""" if not beaver_config.use_ssh_tunnel(): return None logger.info("Proxying transport using through local ssh tunnel") return BeaverSshTunnel(beaver_config, logger=logger)
python
def create_ssh_tunnel(beaver_config, logger=None): """Returns a BeaverSshTunnel object if the current config requires us to""" if not beaver_config.use_ssh_tunnel(): return None logger.info("Proxying transport using through local ssh tunnel") return BeaverSshTunnel(beaver_config, logger=logger)
Returns a BeaverSshTunnel object if the current config requires us to
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L10-L16
python-beaver/python-beaver
beaver/ssh_tunnel.py
BeaverSubprocess.poll
def poll(self): """Poll attached subprocess until it is available""" if self._subprocess is not None: self._subprocess.poll() time.sleep(self._beaver_config.get('subprocess_poll_sleep'))
python
def poll(self): """Poll attached subprocess until it is available""" if self._subprocess is not None: self._subprocess.poll() time.sleep(self._beaver_config.get('subprocess_poll_sleep'))
Poll attached subprocess until it is available
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L43-L48
python-beaver/python-beaver
beaver/ssh_tunnel.py
BeaverSubprocess.close
def close(self): """Close child subprocess""" if self._subprocess is not None: os.killpg(self._subprocess.pid, signal.SIGTERM) self._subprocess = None
python
def close(self): """Close child subprocess""" if self._subprocess is not None: os.killpg(self._subprocess.pid, signal.SIGTERM) self._subprocess = None
Close child subprocess
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L50-L54
python-beaver/python-beaver
beaver/transports/mqtt_transport.py
MqttTransport.callback
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
python
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
publishes lines one by one to the given topic
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/mqtt_transport.py#L33-L49
python-beaver/python-beaver
beaver/unicode_dammit.py
_to_unicode
def _to_unicode(self, data, encoding, errors='strict'): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'): ...
python
def _to_unicode(self, data, encoding, errors='strict'): '''Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'): ...
Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/unicode_dammit.py#L38-L59
python-beaver/python-beaver
beaver/transports/stomp_transport.py
StompTransport.callback
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings...
python
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings...
publishes lines one by one to the given topic
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/stomp_transport.py#L21-L42
python-beaver/python-beaver
beaver/transports/stomp_transport.py
StompTransport.reconnect
def reconnect(self): """Allows reconnection from when a handled TransportException is thrown""" try: self.conn.close() except Exception,e: self.logger.warn(e) self.createConnection() return True
python
def reconnect(self): """Allows reconnection from when a handled TransportException is thrown""" try: self.conn.close() except Exception,e: self.logger.warn(e) self.createConnection() return True
Allows reconnection from when a handled TransportException is thrown
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/stomp_transport.py#L64-L74
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport._check_connections
def _check_connections(self): """Checks if all configured redis servers are reachable""" for server in self._servers: if self._is_reachable(server): server['down_until'] = 0 else: server['down_until'] = time.time() + 5
python
def _check_connections(self): """Checks if all configured redis servers are reachable""" for server in self._servers: if self._is_reachable(server): server['down_until'] = 0 else: server['down_until'] = time.time() + 5
Checks if all configured redis servers are reachable
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L38-L45
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport._is_reachable
def _is_reachable(self, server): """Checks if the given redis server is reachable""" try: server['redis'].ping() return True except UserWarning: self._logger.warn('Cannot reach redis server: ' + server['url']) except Exception: self._logge...
python
def _is_reachable(self, server): """Checks if the given redis server is reachable""" try: server['redis'].ping() return True except UserWarning: self._logger.warn('Cannot reach redis server: ' + server['url']) except Exception: self._logge...
Checks if the given redis server is reachable
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L47-L58
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport.invalidate
def invalidate(self): """Invalidates the current transport and disconnects all redis connections""" super(RedisTransport, self).invalidate() for server in self._servers: server['redis'].connection_pool.disconnect() return False
python
def invalidate(self): """Invalidates the current transport and disconnects all redis connections""" super(RedisTransport, self).invalidate() for server in self._servers: server['redis'].connection_pool.disconnect() return False
Invalidates the current transport and disconnects all redis connections
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L63-L69
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport.callback
def callback(self, filename, lines, **kwargs): """Sends log lines to redis servers""" self._logger.debug('Redis transport called') timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] namespaces = self._beaver_config.g...
python
def callback(self, filename, lines, **kwargs): """Sends log lines to redis servers""" self._logger.debug('Redis transport called') timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] namespaces = self._beaver_config.g...
Sends log lines to redis servers
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L71-L112
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport._get_next_server
def _get_next_server(self): """Returns a valid redis server or raises a TransportException""" current_try = 0 max_tries = len(self._servers) while current_try < max_tries: server_index = self._raise_server_index() server = self._servers[server_index] ...
python
def _get_next_server(self): """Returns a valid redis server or raises a TransportException""" current_try = 0 max_tries = len(self._servers) while current_try < max_tries: server_index = self._raise_server_index() server = self._servers[server_index] ...
Returns a valid redis server or raises a TransportException
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L114-L144
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport._raise_server_index
def _raise_server_index(self): """Round robin magic: Raises the current redis server index and returns it""" self._current_server_index = (self._current_server_index + 1) % len(self._servers) return self._current_server_index
python
def _raise_server_index(self): """Round robin magic: Raises the current redis server index and returns it""" self._current_server_index = (self._current_server_index + 1) % len(self._servers) return self._current_server_index
Round robin magic: Raises the current redis server index and returns it
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L146-L151
python-beaver/python-beaver
beaver/transports/redis_transport.py
RedisTransport.valid
def valid(self): """Returns whether or not the transport can send data to any redis server""" valid_servers = 0 for server in self._servers: if server['down_until'] <= time.time(): valid_servers += 1 return valid_servers > 0
python
def valid(self): """Returns whether or not the transport can send data to any redis server""" valid_servers = 0 for server in self._servers: if server['down_until'] <= time.time(): valid_servers += 1 return valid_servers > 0
Returns whether or not the transport can send data to any redis server
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L154-L162
python-beaver/python-beaver
beaver/transports/kafka_transport.py
KafkaTransport.callback
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
python
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
publishes lines one by one to the given topic
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/kafka_transport.py#L52-L79
python-beaver/python-beaver
beaver/transports/base_transport.py
BaseTransport.format
def format(self, filename, line, timestamp, **kwargs): """Returns a formatted log line""" line = unicode(line.encode("utf-8"), "utf-8", errors="ignore") formatter = self._beaver_config.get_field('format', filename) if formatter not in self._formatters: formatter = self._defau...
python
def format(self, filename, line, timestamp, **kwargs): """Returns a formatted log line""" line = unicode(line.encode("utf-8"), "utf-8", errors="ignore") formatter = self._beaver_config.get_field('format', filename) if formatter not in self._formatters: formatter = self._defau...
Returns a formatted log line
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L117-L142
python-beaver/python-beaver
beaver/transports/base_transport.py
BaseTransport.get_timestamp
def get_timestamp(self, **kwargs): """Retrieves the timestamp for a given set of data""" timestamp = kwargs.get('timestamp') if not timestamp: now = datetime.datetime.utcnow() timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z" ...
python
def get_timestamp(self, **kwargs): """Retrieves the timestamp for a given set of data""" timestamp = kwargs.get('timestamp') if not timestamp: now = datetime.datetime.utcnow() timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z" ...
Retrieves the timestamp for a given set of data
https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L144-L151
gqmelo/exec-wrappers
exec_wrappers/create_wrappers.py
_make_executable
def _make_executable(path): """Make the file at path executable.""" os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
python
def _make_executable(path): """Make the file at path executable.""" os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
Make the file at path executable.
https://github.com/gqmelo/exec-wrappers/blob/0faf892a103cf03d005f1dbdc71ca52d279b4e3b/exec_wrappers/create_wrappers.py#L300-L302
cmap/cmapPy
cmapPy/pandasGEXpress/subset.py
build_parser
def build_parser(): """Build argument parser.""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Required args parser.add_argument("--in_path", "-i", required=True, help="file p...
python
def build_parser(): """Build argument parser.""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Required args parser.add_argument("--in_path", "-i", required=True, help="file p...
Build argument parser.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L28-L49
cmap/cmapPy
cmapPy/pandasGEXpress/subset.py
subset_main
def subset_main(args): """ Separate method from main() in order to make testing easier and to enable command-line access. """ # Read in each of the command line arguments rid = _read_arg(args.rid) cid = _read_arg(args.cid) exclude_rid = _read_arg(args.exclude_rid) exclude_cid = _read_arg(ar...
python
def subset_main(args): """ Separate method from main() in order to make testing easier and to enable command-line access. """ # Read in each of the command line arguments rid = _read_arg(args.rid) cid = _read_arg(args.cid) exclude_rid = _read_arg(args.exclude_rid) exclude_cid = _read_arg(ar...
Separate method from main() in order to make testing easier and to enable command-line access.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L59-L91
cmap/cmapPy
cmapPy/pandasGEXpress/subset.py
_read_arg
def _read_arg(arg): """ If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None) """ # If arg is None, just return it...
python
def _read_arg(arg): """ If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None) """ # If arg is None, just return it...
If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None)
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L94-L121
cmap/cmapPy
cmapPy/math/fast_cov.py
fast_cov
def fast_cov(x, y=None, destination=None): """calculate the covariance matrix for the columns of x (MxN), or optionally, the covariance matrix between the columns of x and and the columns of y (MxP). (In the language of statistics, the columns are variables, the rows are observations). Args: x...
python
def fast_cov(x, y=None, destination=None): """calculate the covariance matrix for the columns of x (MxN), or optionally, the covariance matrix between the columns of x and and the columns of y (MxP). (In the language of statistics, the columns are variables, the rows are observations). Args: x...
calculate the covariance matrix for the columns of x (MxN), or optionally, the covariance matrix between the columns of x and and the columns of y (MxP). (In the language of statistics, the columns are variables, the rows are observations). Args: x (numpy array-like) MxN in shape y (numpy ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/fast_cov.py#L9-L41
cmap/cmapPy
cmapPy/set_io/gmt.py
read
def read(file_path): """ Read a gmt file at the path specified by file_path. Args: file_path (string): path to gmt file Returns: gmt (GMT object): list of dicts, where each dict corresponds to one line of the GMT file """ # Read in file actual_file_path = os.path.e...
python
def read(file_path): """ Read a gmt file at the path specified by file_path. Args: file_path (string): path to gmt file Returns: gmt (GMT object): list of dicts, where each dict corresponds to one line of the GMT file """ # Read in file actual_file_path = os.path.e...
Read a gmt file at the path specified by file_path. Args: file_path (string): path to gmt file Returns: gmt (GMT object): list of dicts, where each dict corresponds to one line of the GMT file
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L24-L73
cmap/cmapPy
cmapPy/set_io/gmt.py
verify_gmt_integrity
def verify_gmt_integrity(gmt): """ Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None """ # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identif...
python
def verify_gmt_integrity(gmt): """ Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None """ # Verify that set ids are unique set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt] assert len(set(set_ids)) == len(set_ids), ( "Set identif...
Make sure that set ids are unique. Args: gmt (GMT object): list of dicts Returns: None
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L76-L90
cmap/cmapPy
cmapPy/set_io/gmt.py
write
def write(gmt, out_path): """ Write a GMT to a text file. Args: gmt (GMT object): list of dicts out_path (string): output path Returns: None """ with open(out_path, 'w') as f: for _, each_dict in enumerate(gmt): f.write(each_dict[SET_IDENTIFIER_FIELD] +...
python
def write(gmt, out_path): """ Write a GMT to a text file. Args: gmt (GMT object): list of dicts out_path (string): output path Returns: None """ with open(out_path, 'w') as f: for _, each_dict in enumerate(gmt): f.write(each_dict[SET_IDENTIFIER_FIELD] +...
Write a GMT to a text file. Args: gmt (GMT object): list of dicts out_path (string): output path Returns: None
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L93-L109
cmap/cmapPy
cmapPy/pandasGEXpress/diff_gctoo.py
diff_gctoo
def diff_gctoo(gctoo, plate_control=True, group_field='pert_type', group_val='ctl_vehicle', diff_method="robust_z", upper_diff_thresh=10, lower_diff_thresh=-10): ''' Converts a matrix of values (e.g. gene expression, viability, etc.) into a matrix of differential values. Args: df (pandas...
python
def diff_gctoo(gctoo, plate_control=True, group_field='pert_type', group_val='ctl_vehicle', diff_method="robust_z", upper_diff_thresh=10, lower_diff_thresh=-10): ''' Converts a matrix of values (e.g. gene expression, viability, etc.) into a matrix of differential values. Args: df (pandas...
Converts a matrix of values (e.g. gene expression, viability, etc.) into a matrix of differential values. Args: df (pandas df): data to make diff_gctoo plate_control (bool): True means calculate diff_gctoo using plate control. False means vehicle control. group_field (string): Metadata fiel...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/diff_gctoo.py#L18-L84
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
parse
def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ Primary method of script. Reads in path to a gctx file and parses into GCToo object. Input: Mandatory: - gctx_file_path (...
python
def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ Primary method of script. Reads in path to a gctx file and parses into GCToo object. Input: Mandatory: - gctx_file_path (...
Primary method of script. Reads in path to a gctx file and parses into GCToo object. Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not (see Note belo...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L23-L126
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
check_and_order_id_inputs
def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df): """ Makes sure that (if entered) id inputs entered are of one type (string id or index) Input: - rid (list or None): if not None, a list of rids - ridx (list or None): if not None, a list of indexes - cid ...
python
def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df): """ Makes sure that (if entered) id inputs entered are of one type (string id or index) Input: - rid (list or None): if not None, a list of rids - ridx (list or None): if not None, a list of indexes - cid ...
Makes sure that (if entered) id inputs entered are of one type (string id or index) Input: - rid (list or None): if not None, a list of rids - ridx (list or None): if not None, a list of indexes - cid (list or None): if not None, a list of cids - cidx (list or None): if not None, a l...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L129-L148
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
check_id_idx_exclusivity
def check_id_idx_exclusivity(id, idx): """ Makes sure user didn't provide both ids and idx values to subset by. Input: - id (list or None): if not None, a list of string id names - idx (list or None): if not None, a list of integer id indexes Output: - a tuple: first element is...
python
def check_id_idx_exclusivity(id, idx): """ Makes sure user didn't provide both ids and idx values to subset by. Input: - id (list or None): if not None, a list of string id names - idx (list or None): if not None, a list of integer id indexes Output: - a tuple: first element is...
Makes sure user didn't provide both ids and idx values to subset by. Input: - id (list or None): if not None, a list of string id names - idx (list or None): if not None, a list of integer id indexes Output: - a tuple: first element is subset type, second is subset content
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L151-L172
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
get_ordered_idx
def get_ordered_idx(id_type, id_list, meta_df): """ Gets index values corresponding to ids to subset and orders them. Input: - id_type (str): either "id", "idx" or None - id_list (list): either a list of indexes or id names Output: - a sorted list of indexes to subset a dimension...
python
def get_ordered_idx(id_type, id_list, meta_df): """ Gets index values corresponding to ids to subset and orders them. Input: - id_type (str): either "id", "idx" or None - id_list (list): either a list of indexes or id names Output: - a sorted list of indexes to subset a dimension...
Gets index values corresponding to ids to subset and orders them. Input: - id_type (str): either "id", "idx" or None - id_list (list): either a list of indexes or id names Output: - a sorted list of indexes to subset a dimension by
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L219-L236
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
parse_metadata_df
def parse_metadata_df(dim, meta_group, convert_neg_666): """ Reads in all metadata from .gctx file to pandas DataFrame with proper GCToo specifications. Input: - dim (str): Dimension of metadata; either "row" or "column" - meta_group (HDF5 group): Group from which to read metadata values...
python
def parse_metadata_df(dim, meta_group, convert_neg_666): """ Reads in all metadata from .gctx file to pandas DataFrame with proper GCToo specifications. Input: - dim (str): Dimension of metadata; either "row" or "column" - meta_group (HDF5 group): Group from which to read metadata values...
Reads in all metadata from .gctx file to pandas DataFrame with proper GCToo specifications. Input: - dim (str): Dimension of metadata; either "row" or "column" - meta_group (HDF5 group): Group from which to read metadata values - convert_neg_666 (bool): whether to convert "-666" values t...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L239-L284
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
replace_666
def replace_666(meta_df, convert_neg_666): """ Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df """ if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan)...
python
def replace_666(meta_df, convert_neg_666): """ Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df """ if convert_neg_666: out_df = meta_df.replace([-666, "-666", -666.0], np.nan)...
Replace -666, -666.0, and optionally "-666". Args: meta_df (pandas df): convert_neg_666 (bool): Returns: out_df (pandas df): updated meta_df
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L287-L299
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
set_metadata_index_and_column_names
def set_metadata_index_and_column_names(dim, meta_df): """ Sets index and column names to GCTX convention. Input: - dim (str): Dimension of metadata to read. Must be either "row" or "col" - meta_df (pandas.DataFrame): data frame corresponding to metadata fields of dimension speci...
python
def set_metadata_index_and_column_names(dim, meta_df): """ Sets index and column names to GCTX convention. Input: - dim (str): Dimension of metadata to read. Must be either "row" or "col" - meta_df (pandas.DataFrame): data frame corresponding to metadata fields of dimension speci...
Sets index and column names to GCTX convention. Input: - dim (str): Dimension of metadata to read. Must be either "row" or "col" - meta_df (pandas.DataFrame): data frame corresponding to metadata fields of dimension specified. Output: None
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L302-L317
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
parse_data_df
def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta): """ Parses in data_df from hdf5, subsetting if specified. Input: -data_dset (h5py dset): HDF5 dataset from which to read data_df -ridx (list): list of indexes to subset from data_df (may be all of them if no subsettin...
python
def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta): """ Parses in data_df from hdf5, subsetting if specified. Input: -data_dset (h5py dset): HDF5 dataset from which to read data_df -ridx (list): list of indexes to subset from data_df (may be all of them if no subsettin...
Parses in data_df from hdf5, subsetting if specified. Input: -data_dset (h5py dset): HDF5 dataset from which to read data_df -ridx (list): list of indexes to subset from data_df (may be all of them if no subsetting) -cidx (list): list of indexes to subset from data_df ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L320-L345
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
get_column_metadata
def get_column_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only column metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num...
python
def get_column_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only column metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num...
Opens .gctx file and returns only column metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num Output: - col_meta (pandas DataFrame): a DataFrame of all col...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L348-L368
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
get_row_metadata
def get_row_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only row metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num ...
python
def get_row_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only row metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num ...
Opens .gctx file and returns only row metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num Output: - row_meta (pandas DataFrame): a DataFrame of all row me...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L371-L391
cmap/cmapPy
cmapPy/pandasGEXpress/GCToo.py
multi_index_df_to_component_dfs
def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"): """ Convert a multi-index df into 3 component dfs. """ # Id level of the multiindex will become the index rids = list(multi_index_df.index.get_level_values(rid)) cids = list(multi_index_df.columns.get_level_values(cid)) # I...
python
def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"): """ Convert a multi-index df into 3 component dfs. """ # Id level of the multiindex will become the index rids = list(multi_index_df.index.get_level_values(rid)) cids = list(multi_index_df.columns.get_level_values(cid)) # I...
Convert a multi-index df into 3 component dfs.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L222-L284
cmap/cmapPy
cmapPy/pandasGEXpress/GCToo.py
GCToo.check_df
def check_df(self, df): """ Verifies that df is a pandas DataFrame instance and that its index and column values are unique. """ if isinstance(df, pd.DataFrame): if not df.index.is_unique: repeats = df.index[df.index.duplicated()].values ...
python
def check_df(self, df): """ Verifies that df is a pandas DataFrame instance and that its index and column values are unique. """ if isinstance(df, pd.DataFrame): if not df.index.is_unique: repeats = df.index[df.index.duplicated()].values ...
Verifies that df is a pandas DataFrame instance and that its index and column values are unique.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L125-L145
cmap/cmapPy
cmapPy/pandasGEXpress/GCToo.py
GCToo.id_match_check
def id_match_check(self, data_df, meta_df, dim): """ Verifies that id values match between: - row case: index of data_df & index of row metadata - col case: columns of data_df & index of column metadata """ if dim == "row": if len(data_df.index) == len...
python
def id_match_check(self, data_df, meta_df, dim): """ Verifies that id values match between: - row case: index of data_df & index of row metadata - col case: columns of data_df & index of column metadata """ if dim == "row": if len(data_df.index) == len...
Verifies that id values match between: - row case: index of data_df & index of row metadata - col case: columns of data_df & index of column metadata
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L147-L168
cmap/cmapPy
cmapPy/pandasGEXpress/GCToo.py
GCToo.assemble_multi_index_df
def assemble_multi_index_df(self): """Assembles three component dataframes into a multiindex dataframe. Sets the result to self.multi_index_df. IMPORTANT: Cross-section ("xs") is the best command for selecting data. Be sure to use the flag "drop_level=False" with this command, or...
python
def assemble_multi_index_df(self): """Assembles three component dataframes into a multiindex dataframe. Sets the result to self.multi_index_df. IMPORTANT: Cross-section ("xs") is the best command for selecting data. Be sure to use the flag "drop_level=False" with this command, or...
Assembles three component dataframes into a multiindex dataframe. Sets the result to self.multi_index_df. IMPORTANT: Cross-section ("xs") is the best command for selecting data. Be sure to use the flag "drop_level=False" with this command, or else the dataframe that is returned will not ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L188-L219
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gct.py
parse
def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ The main method. Args: - file_path (string): full path to gct(x) file you want to parse - convert_neg_666 (bool): whether to c...
python
def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ The main method. Args: - file_path (string): full path to gct(x) file you want to parse - convert_neg_666 (bool): whether to c...
The main method. Args: - file_path (string): full path to gct(x) file you want to parse - convert_neg_666 (bool): whether to convert -666 values to numpy.nan (see Note below for more details). Default = False. - rid (list of strings): list of row ids to specifically keep from gc...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gct.py#L82-L160
cmap/cmapPy
cmapPy/clue_api_client/gene_queries.py
are_genes_in_api
def are_genes_in_api(my_clue_api_client, gene_symbols): """determine if genes are present in the API Args: my_clue_api_client: gene_symbols: collection of gene symbols to query the API with Returns: set of the found gene symbols """ if len(gene_symbols) > 0: query_gene_sym...
python
def are_genes_in_api(my_clue_api_client, gene_symbols): """determine if genes are present in the API Args: my_clue_api_client: gene_symbols: collection of gene symbols to query the API with Returns: set of the found gene symbols """ if len(gene_symbols) > 0: query_gene_sym...
determine if genes are present in the API Args: my_clue_api_client: gene_symbols: collection of gene symbols to query the API with Returns: set of the found gene symbols
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/clue_api_client/gene_queries.py#L13-L34
cmap/cmapPy
cmapPy/pandasGEXpress/write_gct.py
write
def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"): """Write a gctoo object to a gct file. Args: gctoo (gctoo object) out_fname (string): filename for output gct file data_null (string): how to represent missing values in the...
python
def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"): """Write a gctoo object to a gct file. Args: gctoo (gctoo object) out_fname (string): filename for output gct file data_null (string): how to represent missing values in the...
Write a gctoo object to a gct file. Args: gctoo (gctoo object) out_fname (string): filename for output gct file data_null (string): how to represent missing values in the data (default = "NaN") metadata_null (string): how to represent missing values in the metadata (default = "-666"...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L16-L51
cmap/cmapPy
cmapPy/pandasGEXpress/write_gct.py
write_version_and_dims
def write_version_and_dims(version, dims, f): """Write first two lines of gct file. Args: version (string): 1.3 by default dims (list of strings): length = 4 f (file handle): handle of output file Returns: nothing """ f.write(("#" + version + "\n")) f.write((dims...
python
def write_version_and_dims(version, dims, f): """Write first two lines of gct file. Args: version (string): 1.3 by default dims (list of strings): length = 4 f (file handle): handle of output file Returns: nothing """ f.write(("#" + version + "\n")) f.write((dims...
Write first two lines of gct file. Args: version (string): 1.3 by default dims (list of strings): length = 4 f (file handle): handle of output file Returns: nothing
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L54-L65
cmap/cmapPy
cmapPy/pandasGEXpress/write_gct.py
write_top_half
def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null): """ Write the top half of the gct file: top-left filler values, row metadata headers, and top-right column metadata. Args: f (file handle): handle for output file row_metadata_df (pandas df) col_met...
python
def write_top_half(f, row_metadata_df, col_metadata_df, metadata_null, filler_null): """ Write the top half of the gct file: top-left filler values, row metadata headers, and top-right column metadata. Args: f (file handle): handle for output file row_metadata_df (pandas df) col_met...
Write the top half of the gct file: top-left filler values, row metadata headers, and top-right column metadata. Args: f (file handle): handle for output file row_metadata_df (pandas df) col_metadata_df (pandas df) metadata_null (string): how to represent missing values in the m...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L68-L102
cmap/cmapPy
cmapPy/pandasGEXpress/write_gct.py
write_bottom_half
def write_bottom_half(f, row_metadata_df, data_df, data_null, data_float_format, metadata_null): """ Write the bottom half of the gct file: row metadata and data. Args: f (file handle): handle for output file row_metadata_df (pandas df) data_df (pandas df) data_null (string): ho...
python
def write_bottom_half(f, row_metadata_df, data_df, data_null, data_float_format, metadata_null): """ Write the bottom half of the gct file: row metadata and data. Args: f (file handle): handle for output file row_metadata_df (pandas df) data_df (pandas df) data_null (string): ho...
Write the bottom half of the gct file: row metadata and data. Args: f (file handle): handle for output file row_metadata_df (pandas df) data_df (pandas df) data_null (string): how to represent missing values in the data metadata_null (string): how to represent missing values...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L105-L139
cmap/cmapPy
cmapPy/pandasGEXpress/write_gct.py
append_dims_and_file_extension
def append_dims_and_file_extension(fname, data_df): """Append dimensions and file extension to output filename. N.B. Dimensions are cols x rows. Args: fname (string): output filename data_df (pandas df) Returns: out_fname (string): output filename with matrix dims and .gct appen...
python
def append_dims_and_file_extension(fname, data_df): """Append dimensions and file extension to output filename. N.B. Dimensions are cols x rows. Args: fname (string): output filename data_df (pandas df) Returns: out_fname (string): output filename with matrix dims and .gct appen...
Append dimensions and file extension to output filename. N.B. Dimensions are cols x rows. Args: fname (string): output filename data_df (pandas df) Returns: out_fname (string): output filename with matrix dims and .gct appended
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L142-L161
cmap/cmapPy
cmapPy/math/robust_zscore.py
robust_zscore
def robust_zscore(mat, ctrl_mat=None, min_mad=0.1): ''' Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs (e.g. vehicle control) min_mad (float): M...
python
def robust_zscore(mat, ctrl_mat=None, min_mad=0.1): ''' Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs (e.g. vehicle control) min_mad (float): M...
Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs (e.g. vehicle control) min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/robust_zscore.py#L24-L58
cmap/cmapPy
cmapPy/pandasGEXpress/gct2gctx.py
gct2gctx_main
def gct2gctx_main(args): """ Separate from main() in order to make command-line tool. """ in_gctoo = parse_gct.parse(args.filename, convert_neg_666=False) if args.output_filepath is None: basename = os.path.basename(args.filename) out_name = os.path.splitext(basename)[0] + ".gctx" else...
python
def gct2gctx_main(args): """ Separate from main() in order to make command-line tool. """ in_gctoo = parse_gct.parse(args.filename, convert_neg_666=False) if args.output_filepath is None: basename = os.path.basename(args.filename) out_name = os.path.splitext(basename)[0] + ".gctx" else...
Separate from main() in order to make command-line tool.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/gct2gctx.py#L48-L76
cmap/cmapPy
cmapPy/pandasGEXpress/parse.py
parse
def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ Identifies whether file_path corresponds to a .gct or .gctx file and calls the correct corresponding parse method. Input: Mandator...
python
def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False): """ Identifies whether file_path corresponds to a .gct or .gctx file and calls the correct corresponding parse method. Input: Mandator...
Identifies whether file_path corresponds to a .gct or .gctx file and calls the correct corresponding parse method. Input: Mandatory: - gct(x)_file_path (str): full path to gct(x) file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to numpy...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse.py#L21-L75
cmap/cmapPy
cmapPy/math/agg_wt_avg.py
get_upper_triangle
def get_upper_triangle(correlation_matrix): ''' Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid ...
python
def get_upper_triangle(correlation_matrix): ''' Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid ...
Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid is the row index, cid is the column index, c...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L17-L41
cmap/cmapPy
cmapPy/math/agg_wt_avg.py
calculate_weights
def calculate_weights(correlation_matrix, min_wt): ''' Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicat...
python
def calculate_weights(correlation_matrix, min_wt): ''' Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicat...
Calculate a weight for each profile based on its correlation to other replicates. Negative correlations are clipped to 0, and weights are clipped to be min_wt at the least. Args: correlation_matrix (pandas df): Correlations between all replicates min_wt (float): Minimum raw weight when calculating ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L44-L72
cmap/cmapPy
cmapPy/math/agg_wt_avg.py
agg_wt_avg
def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'): ''' Aggregate a set of replicate profiles into a single signature using a weighted average. Args: mat (pandas df): a matrix of replicate profiles, where the columns are samples and the rows are features; columns correspond to the ...
python
def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'): ''' Aggregate a set of replicate profiles into a single signature using a weighted average. Args: mat (pandas df): a matrix of replicate profiles, where the columns are samples and the rows are features; columns correspond to the ...
Aggregate a set of replicate profiles into a single signature using a weighted average. Args: mat (pandas df): a matrix of replicate profiles, where the columns are samples and the rows are features; columns correspond to the replicates of a single perturbagen min_wt (float): Minimum ra...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L75-L118
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
concat_main
def concat_main(args): """ Separate method from main() in order to make testing easier and to enable command-line access. """ # Get files directly if args.input_filepaths is not None: files = args.input_filepaths # Or find them else: files = get_file_list(args.file_wildcard) ...
python
def concat_main(args): """ Separate method from main() in order to make testing easier and to enable command-line access. """ # Get files directly if args.input_filepaths is not None: files = args.input_filepaths # Or find them else: files = get_file_list(args.file_wildcard) ...
Separate method from main() in order to make testing easier and to enable command-line access.
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L106-L155
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
get_file_list
def get_file_list(wildcard): """ Search for files to be concatenated. Currently very basic, but could expand to be more sophisticated. Args: wildcard (regular expression string) Returns: files (list of full file paths) """ files = glob.glob(os.path.expanduser(wildcard)) re...
python
def get_file_list(wildcard): """ Search for files to be concatenated. Currently very basic, but could expand to be more sophisticated. Args: wildcard (regular expression string) Returns: files (list of full file paths) """ files = glob.glob(os.path.expanduser(wildcard)) re...
Search for files to be concatenated. Currently very basic, but could expand to be more sophisticated. Args: wildcard (regular expression string) Returns: files (list of full file paths)
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L158-L170
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
hstack
def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False): """ Horizontally concatenate gctoos. Args: gctoos (list of gctoo objects) remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos error_...
python
def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False): """ Horizontally concatenate gctoos. Args: gctoos (list of gctoo objects) remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos error_...
Horizontally concatenate gctoos. Args: gctoos (list of gctoo objects) remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos error_report_file (string): path to write file containing error report indicating problems that occurred during hsta...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L173-L224
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
assemble_common_meta
def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file): """ Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_r...
python
def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file): """ Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_r...
Assemble the common metadata dfs together. Both indices are sorted. Fields that are not in all the dfs are dropped. Args: common_meta_dfs (list of pandas dfs) fields_to_remove (list of strings): fields to be removed from the common metadata because they don't agree across files ...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L279-L312
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
build_common_all_meta_df
def build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields): """ concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely ( remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta...
python
def build_common_all_meta_df(common_meta_dfs, fields_to_remove, remove_all_metadata_fields): """ concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely ( remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta...
concatenate the entries in common_meta_dfs, removing columns selectively (fields_to_remove) or entirely ( remove_all_metadata_fields=True; in this case, effectively just merges all the indexes in common_meta_dfs). Returns 2 dataframes (in a tuple): the first has duplicates removed, the second does not...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L315-L367
cmap/cmapPy
cmapPy/pandasGEXpress/concat.py
build_mismatched_common_meta_report
def build_mismatched_common_meta_report(common_meta_df_shapes, sources, all_meta_df, all_meta_df_with_dups): """ Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: ...
python
def build_mismatched_common_meta_report(common_meta_df_shapes, sources, all_meta_df, all_meta_df_with_dups): """ Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: ...
Generate a report (dataframe) that indicates for the common metadata that does not match across the common metadata which source file had which of the different mismatch values Args: common_meta_df_shapes: list of tuples that are the shapes of the common meta dataframes sources: list of th...
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L370-L420