id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,800
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_hdfs_ha
def disable_hdfs_ha(self, active_name, secondary_name, start_dependent_services=True, deploy_client_configs=True, disable_quorum_storage=False): """ Disable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use disable_nn_ha instead. @param active_name: Name of the NameNode to keep. @param secondary_name: Name of (existing) SecondaryNameNode to link to remaining NameNode. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param disable_quorum_storage: whether to disable Quorum-based Storage. Available since API v2. Quorum-based Storage will be disabled for all nameservices that have Quorum-based Storage enabled. @return: Reference to the submitted command. """ args = dict( activeName = active_name, secondaryName = secondary_name, startDependentServices = start_dependent_services, deployClientConfigs = deploy_client_configs, ) version = self._get_resource_root().version if version < 2: if disable_quorum_storage: raise AttributeError("Quorum-based Storage requires at least API version 2 available in Cloudera Manager 4.1.") else: args['disableQuorumStorage'] = disable_quorum_storage return self._cmd('hdfsDisableHa', data=args)
python
def disable_hdfs_ha(self, active_name, secondary_name, start_dependent_services=True, deploy_client_configs=True, disable_quorum_storage=False): args = dict( activeName = active_name, secondaryName = secondary_name, startDependentServices = start_dependent_services, deployClientConfigs = deploy_client_configs, ) version = self._get_resource_root().version if version < 2: if disable_quorum_storage: raise AttributeError("Quorum-based Storage requires at least API version 2 available in Cloudera Manager 4.1.") else: args['disableQuorumStorage'] = disable_quorum_storage return self._cmd('hdfsDisableHa', data=args)
[ "def", "disable_hdfs_ha", "(", "self", ",", "active_name", ",", "secondary_name", ",", "start_dependent_services", "=", "True", ",", "deploy_client_configs", "=", "True", ",", "disable_quorum_storage", "=", "False", ")", ":", "args", "=", "dict", "(", "activeName"...
Disable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use disable_nn_ha instead. @param active_name: Name of the NameNode to keep. @param secondary_name: Name of (existing) SecondaryNameNode to link to remaining NameNode. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param disable_quorum_storage: whether to disable Quorum-based Storage. Available since API v2. Quorum-based Storage will be disabled for all nameservices that have Quorum-based Storage enabled. @return: Reference to the submitted command.
[ "Disable", "high", "availability", "for", "an", "HDFS", "NameNode", ".", "This", "command", "is", "no", "longer", "supported", "with", "API", "v6", "onwards", ".", "Use", "disable_nn_ha", "instead", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L886-L918
232,801
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enable_hdfs_auto_failover
def enable_hdfs_auto_failover(self, nameservice, active_fc_name, standby_fc_name, zk_service): """ Enable auto-failover for an HDFS nameservice. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param nameservice: Nameservice for which to enable auto-failover. @param active_fc_name: Name of failover controller to create for active node. @param standby_fc_name: Name of failover controller to create for stand-by node. @param zk_service: ZooKeeper service to use. @return: Reference to the submitted command. """ version = self._get_resource_root().version args = dict( nameservice = nameservice, activeFCName = active_fc_name, standByFCName = standby_fc_name, zooKeeperService = dict( clusterName = zk_service.clusterRef.clusterName, serviceName = zk_service.name, ), ) return self._cmd('hdfsEnableAutoFailover', data=args)
python
def enable_hdfs_auto_failover(self, nameservice, active_fc_name, standby_fc_name, zk_service): version = self._get_resource_root().version args = dict( nameservice = nameservice, activeFCName = active_fc_name, standByFCName = standby_fc_name, zooKeeperService = dict( clusterName = zk_service.clusterRef.clusterName, serviceName = zk_service.name, ), ) return self._cmd('hdfsEnableAutoFailover', data=args)
[ "def", "enable_hdfs_auto_failover", "(", "self", ",", "nameservice", ",", "active_fc_name", ",", "standby_fc_name", ",", "zk_service", ")", ":", "version", "=", "self", ".", "_get_resource_root", "(", ")", ".", "version", "args", "=", "dict", "(", "nameservice",...
Enable auto-failover for an HDFS nameservice. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param nameservice: Nameservice for which to enable auto-failover. @param active_fc_name: Name of failover controller to create for active node. @param standby_fc_name: Name of failover controller to create for stand-by node. @param zk_service: ZooKeeper service to use. @return: Reference to the submitted command.
[ "Enable", "auto", "-", "failover", "for", "an", "HDFS", "nameservice", ".", "This", "command", "is", "no", "longer", "supported", "with", "API", "v6", "onwards", ".", "Use", "enable_nn_ha", "instead", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L920-L943
232,802
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enable_hdfs_ha
def enable_hdfs_ha(self, active_name, active_shared_path, standby_name, standby_shared_path, nameservice, start_dependent_services=True, deploy_client_configs=True, enable_quorum_storage=False): """ Enable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param active_name: name of active NameNode. @param active_shared_path: shared edits path for active NameNode. Ignored if Quorum-based Storage is being enabled. @param standby_name: name of stand-by NameNode. @param standby_shared_path: shared edits path for stand-by NameNode. Ignored if Quourm Journal is being enabled. @param nameservice: nameservice for the HA pair. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param enable_quorum_storage: whether to enable Quorum-based Storage. Available since API v2. Quorum-based Storage will be enabled for all nameservices except those configured with NFS High Availability. @return: Reference to the submitted command. """ version = self._get_resource_root().version args = dict( activeName = active_name, standByName = standby_name, nameservice = nameservice, startDependentServices = start_dependent_services, deployClientConfigs = deploy_client_configs, ) if enable_quorum_storage: if version < 2: raise AttributeError("Quorum-based Storage is not supported prior to Cloudera Manager 4.1.") else: args['enableQuorumStorage'] = enable_quorum_storage else: if active_shared_path is None or standby_shared_path is None: raise AttributeError("Active and standby shared paths must be specified if not enabling Quorum-based Storage") args['activeSharedEditsPath'] = active_shared_path args['standBySharedEditsPath'] = standby_shared_path return self._cmd('hdfsEnableHa', data=args)
python
def enable_hdfs_ha(self, active_name, active_shared_path, standby_name, standby_shared_path, nameservice, start_dependent_services=True, deploy_client_configs=True, enable_quorum_storage=False): version = self._get_resource_root().version args = dict( activeName = active_name, standByName = standby_name, nameservice = nameservice, startDependentServices = start_dependent_services, deployClientConfigs = deploy_client_configs, ) if enable_quorum_storage: if version < 2: raise AttributeError("Quorum-based Storage is not supported prior to Cloudera Manager 4.1.") else: args['enableQuorumStorage'] = enable_quorum_storage else: if active_shared_path is None or standby_shared_path is None: raise AttributeError("Active and standby shared paths must be specified if not enabling Quorum-based Storage") args['activeSharedEditsPath'] = active_shared_path args['standBySharedEditsPath'] = standby_shared_path return self._cmd('hdfsEnableHa', data=args)
[ "def", "enable_hdfs_ha", "(", "self", ",", "active_name", ",", "active_shared_path", ",", "standby_name", ",", "standby_shared_path", ",", "nameservice", ",", "start_dependent_services", "=", "True", ",", "deploy_client_configs", "=", "True", ",", "enable_quorum_storage...
Enable high availability for an HDFS NameNode. This command is no longer supported with API v6 onwards. Use enable_nn_ha instead. @param active_name: name of active NameNode. @param active_shared_path: shared edits path for active NameNode. Ignored if Quorum-based Storage is being enabled. @param standby_name: name of stand-by NameNode. @param standby_shared_path: shared edits path for stand-by NameNode. Ignored if Quourm Journal is being enabled. @param nameservice: nameservice for the HA pair. @param start_dependent_services: whether to re-start dependent services. @param deploy_client_configs: whether to re-deploy client configurations. @param enable_quorum_storage: whether to enable Quorum-based Storage. Available since API v2. Quorum-based Storage will be enabled for all nameservices except those configured with NFS High Availability. @return: Reference to the submitted command.
[ "Enable", "high", "availability", "for", "an", "HDFS", "NameNode", ".", "This", "command", "is", "no", "longer", "supported", "with", "API", "v6", "onwards", ".", "Use", "enable_nn_ha", "instead", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L945-L988
232,803
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_nn_ha
def disable_nn_ha(self, active_name, snn_host_id, snn_check_point_dir_list, snn_name=None): """ Disable high availability with automatic failover for an HDFS NameNode. @param active_name: Name of the NamdeNode role that is going to be active after High Availability is disabled. @param snn_host_id: Id of the host where the new SecondaryNameNode will be created. @param snn_check_point_dir_list : List of directories used for checkpointing by the new SecondaryNameNode. @param snn_name: Name of the new SecondaryNameNode role (Optional). @return: Reference to the submitted command. @since: API v6 """ args = dict( activeNnName = active_name, snnHostId = snn_host_id, snnCheckpointDirList = snn_check_point_dir_list, snnName = snn_name ) return self._cmd('hdfsDisableNnHa', data=args, api_version=6)
python
def disable_nn_ha(self, active_name, snn_host_id, snn_check_point_dir_list, snn_name=None): args = dict( activeNnName = active_name, snnHostId = snn_host_id, snnCheckpointDirList = snn_check_point_dir_list, snnName = snn_name ) return self._cmd('hdfsDisableNnHa', data=args, api_version=6)
[ "def", "disable_nn_ha", "(", "self", ",", "active_name", ",", "snn_host_id", ",", "snn_check_point_dir_list", ",", "snn_name", "=", "None", ")", ":", "args", "=", "dict", "(", "activeNnName", "=", "active_name", ",", "snnHostId", "=", "snn_host_id", ",", "snnC...
Disable high availability with automatic failover for an HDFS NameNode. @param active_name: Name of the NamdeNode role that is going to be active after High Availability is disabled. @param snn_host_id: Id of the host where the new SecondaryNameNode will be created. @param snn_check_point_dir_list : List of directories used for checkpointing by the new SecondaryNameNode. @param snn_name: Name of the new SecondaryNameNode role (Optional). @return: Reference to the submitted command. @since: API v6
[ "Disable", "high", "availability", "with", "automatic", "failover", "for", "an", "HDFS", "NameNode", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1047-L1067
232,804
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enable_jt_ha
def enable_jt_ha(self, new_jt_host_id, force_init_znode=True, zk_service_name=None, new_jt_name=None, fc1_name=None, fc2_name=None): """ Enable high availability for a MR JobTracker. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If MapReduce service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @param new_jt_host_id: id of the host where the second JobTracker will be added. @param force_init_znode: Initialize the ZNode used for auto-failover even if it already exists. This can happen if JobTracker HA was enabled before and then disabled. Disable operation doesn't delete this ZNode. Defaults to true. @param new_jt_name: Name of the second JobTracker role to be created. @param fc1_name: Name of the Failover Controller role that is co-located with the existing JobTracker. @param fc2_name: Name of the Failover Controller role that is co-located with the new JobTracker. @return: Reference to the submitted command. @since: API v5 """ args = dict( newJtHostId = new_jt_host_id, forceInitZNode = force_init_znode, zkServiceName = zk_service_name, newJtRoleName = new_jt_name, fc1RoleName = fc1_name, fc2RoleName = fc2_name ) return self._cmd('enableJtHa', data=args)
python
def enable_jt_ha(self, new_jt_host_id, force_init_znode=True, zk_service_name=None, new_jt_name=None, fc1_name=None, fc2_name=None): args = dict( newJtHostId = new_jt_host_id, forceInitZNode = force_init_znode, zkServiceName = zk_service_name, newJtRoleName = new_jt_name, fc1RoleName = fc1_name, fc2RoleName = fc2_name ) return self._cmd('enableJtHa', data=args)
[ "def", "enable_jt_ha", "(", "self", ",", "new_jt_host_id", ",", "force_init_znode", "=", "True", ",", "zk_service_name", "=", "None", ",", "new_jt_name", "=", "None", ",", "fc1_name", "=", "None", ",", "fc2_name", "=", "None", ")", ":", "args", "=", "dict"...
Enable high availability for a MR JobTracker. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If MapReduce service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @param new_jt_host_id: id of the host where the second JobTracker will be added. @param force_init_znode: Initialize the ZNode used for auto-failover even if it already exists. This can happen if JobTracker HA was enabled before and then disabled. Disable operation doesn't delete this ZNode. Defaults to true. @param new_jt_name: Name of the second JobTracker role to be created. @param fc1_name: Name of the Failover Controller role that is co-located with the existing JobTracker. @param fc2_name: Name of the Failover Controller role that is co-located with the new JobTracker. @return: Reference to the submitted command. @since: API v5
[ "Enable", "high", "availability", "for", "a", "MR", "JobTracker", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1069-L1100
232,805
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_jt_ha
def disable_jt_ha(self, active_name): """ Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be removed. @return: Reference to the submitted command. """ args = dict( activeName = active_name, ) return self._cmd('disableJtHa', data=args)
python
def disable_jt_ha(self, active_name): args = dict( activeName = active_name, ) return self._cmd('disableJtHa', data=args)
[ "def", "disable_jt_ha", "(", "self", ",", "active_name", ")", ":", "args", "=", "dict", "(", "activeName", "=", "active_name", ",", ")", "return", "self", ".", "_cmd", "(", "'disableJtHa'", ",", "data", "=", "args", ")" ]
Disable high availability for a MR JobTracker active-standby pair. @param active_name: name of the JobTracker that will be active after the disable operation. The other JobTracker and Failover Controllers will be removed. @return: Reference to the submitted command.
[ "Disable", "high", "availability", "for", "a", "MR", "JobTracker", "active", "-", "standby", "pair", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1102-L1114
232,806
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enable_rm_ha
def enable_rm_ha(self, new_rm_host_id, zk_service_name=None): """ Enable high availability for a YARN ResourceManager. @param new_rm_host_id: id of the host where the second ResourceManager will be added. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If YARN service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @return: Reference to the submitted command. @since: API v6 """ args = dict( newRmHostId = new_rm_host_id, zkServiceName = zk_service_name ) return self._cmd('enableRmHa', data=args)
python
def enable_rm_ha(self, new_rm_host_id, zk_service_name=None): args = dict( newRmHostId = new_rm_host_id, zkServiceName = zk_service_name ) return self._cmd('enableRmHa', data=args)
[ "def", "enable_rm_ha", "(", "self", ",", "new_rm_host_id", ",", "zk_service_name", "=", "None", ")", ":", "args", "=", "dict", "(", "newRmHostId", "=", "new_rm_host_id", ",", "zkServiceName", "=", "zk_service_name", ")", "return", "self", ".", "_cmd", "(", "...
Enable high availability for a YARN ResourceManager. @param new_rm_host_id: id of the host where the second ResourceManager will be added. @param zk_service_name: Name of the ZooKeeper service to use for auto-failover. If YARN service depends on a ZooKeeper service then that ZooKeeper service will be used for auto-failover and in that case this parameter can be omitted. @return: Reference to the submitted command. @since: API v6
[ "Enable", "high", "availability", "for", "a", "YARN", "ResourceManager", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1116-L1133
232,807
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_rm_ha
def disable_rm_ha(self, active_name): """ Disable high availability for a YARN ResourceManager active-standby pair. @param active_name: name of the ResourceManager that will be active after the disable operation. The other ResourceManager will be removed. @return: Reference to the submitted command. @since: API v6 """ args = dict( activeName = active_name ) return self._cmd('disableRmHa', data=args)
python
def disable_rm_ha(self, active_name): args = dict( activeName = active_name ) return self._cmd('disableRmHa', data=args)
[ "def", "disable_rm_ha", "(", "self", ",", "active_name", ")", ":", "args", "=", "dict", "(", "activeName", "=", "active_name", ")", "return", "self", ".", "_cmd", "(", "'disableRmHa'", ",", "data", "=", "args", ")" ]
Disable high availability for a YARN ResourceManager active-standby pair. @param active_name: name of the ResourceManager that will be active after the disable operation. The other ResourceManager will be removed. @return: Reference to the submitted command. @since: API v6
[ "Disable", "high", "availability", "for", "a", "YARN", "ResourceManager", "active", "-", "standby", "pair", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1135-L1148
232,808
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enable_oozie_ha
def enable_oozie_ha(self, new_oozie_server_host_ids, new_oozie_server_role_names=None, zk_service_name=None, load_balancer_host_port=None): """ Enable high availability for Oozie. @param new_oozie_server_host_ids: List of IDs of the hosts on which new Oozie Servers will be added. @param new_oozie_server_role_names: List of names of the new Oozie Servers. This is an optional argument, but if provided, it should match the length of host IDs provided. @param zk_service_name: Name of the ZooKeeper service that will be used for Oozie HA. This is an optional parameter if the Oozie to ZooKeeper dependency is already set. @param load_balancer_host_port: Address and port of the load balancer used for Oozie HA. This is an optional parameter if this config is already set. @return: Reference to the submitted command. @since: API v6 """ args = dict( newOozieServerHostIds = new_oozie_server_host_ids, newOozieServerRoleNames = new_oozie_server_role_names, zkServiceName = zk_service_name, loadBalancerHostPort = load_balancer_host_port ) return self._cmd('oozieEnableHa', data=args, api_version=6)
python
def enable_oozie_ha(self, new_oozie_server_host_ids, new_oozie_server_role_names=None, zk_service_name=None, load_balancer_host_port=None): args = dict( newOozieServerHostIds = new_oozie_server_host_ids, newOozieServerRoleNames = new_oozie_server_role_names, zkServiceName = zk_service_name, loadBalancerHostPort = load_balancer_host_port ) return self._cmd('oozieEnableHa', data=args, api_version=6)
[ "def", "enable_oozie_ha", "(", "self", ",", "new_oozie_server_host_ids", ",", "new_oozie_server_role_names", "=", "None", ",", "zk_service_name", "=", "None", ",", "load_balancer_host_port", "=", "None", ")", ":", "args", "=", "dict", "(", "newOozieServerHostIds", "...
Enable high availability for Oozie. @param new_oozie_server_host_ids: List of IDs of the hosts on which new Oozie Servers will be added. @param new_oozie_server_role_names: List of names of the new Oozie Servers. This is an optional argument, but if provided, it should match the length of host IDs provided. @param zk_service_name: Name of the ZooKeeper service that will be used for Oozie HA. This is an optional parameter if the Oozie to ZooKeeper dependency is already set. @param load_balancer_host_port: Address and port of the load balancer used for Oozie HA. This is an optional parameter if this config is already set. @return: Reference to the submitted command. @since: API v6
[ "Enable", "high", "availability", "for", "Oozie", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1150-L1174
232,809
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.disable_oozie_ha
def disable_oozie_ha(self, active_name): """ Disable high availability for Oozie @param active_name: Name of the Oozie Server that will be active after High Availability is disabled. @return: Reference to the submitted command. @since: API v6 """ args = dict( activeName = active_name ) return self._cmd('oozieDisableHa', data=args, api_version=6)
python
def disable_oozie_ha(self, active_name): args = dict( activeName = active_name ) return self._cmd('oozieDisableHa', data=args, api_version=6)
[ "def", "disable_oozie_ha", "(", "self", ",", "active_name", ")", ":", "args", "=", "dict", "(", "activeName", "=", "active_name", ")", "return", "self", ".", "_cmd", "(", "'oozieDisableHa'", ",", "data", "=", "args", ",", "api_version", "=", "6", ")" ]
Disable high availability for Oozie @param active_name: Name of the Oozie Server that will be active after High Availability is disabled. @return: Reference to the submitted command. @since: API v6
[ "Disable", "high", "availability", "for", "Oozie" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1176-L1188
232,810
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.failover_hdfs
def failover_hdfs(self, active_name, standby_name, force=False): """ Initiate a failover of an HDFS NameNode HA pair. This will make the given stand-by NameNode active, and vice-versa. @param active_name: name of currently active NameNode. @param standby_name: name of NameNode currently in stand-by. @param force: whether to force failover. @return: Reference to the submitted command. """ params = { "force" : "true" and force or "false" } args = { ApiList.LIST_KEY : [ active_name, standby_name ] } return self._cmd('hdfsFailover', data=[ active_name, standby_name ], params = { "force" : "true" and force or "false" })
python
def failover_hdfs(self, active_name, standby_name, force=False): params = { "force" : "true" and force or "false" } args = { ApiList.LIST_KEY : [ active_name, standby_name ] } return self._cmd('hdfsFailover', data=[ active_name, standby_name ], params = { "force" : "true" and force or "false" })
[ "def", "failover_hdfs", "(", "self", ",", "active_name", ",", "standby_name", ",", "force", "=", "False", ")", ":", "params", "=", "{", "\"force\"", ":", "\"true\"", "and", "force", "or", "\"false\"", "}", "args", "=", "{", "ApiList", ".", "LIST_KEY", ":...
Initiate a failover of an HDFS NameNode HA pair. This will make the given stand-by NameNode active, and vice-versa. @param active_name: name of currently active NameNode. @param standby_name: name of NameNode currently in stand-by. @param force: whether to force failover. @return: Reference to the submitted command.
[ "Initiate", "a", "failover", "of", "an", "HDFS", "NameNode", "HA", "pair", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1190-L1204
232,811
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.roll_edits_hdfs
def roll_edits_hdfs(self, nameservice=None): """ Roll the edits of an HDFS NameNode or Nameservice. @param nameservice: Nameservice whose edits should be rolled. Required only with a federated HDFS. @return: Reference to the submitted command. @since: API v3 """ args = dict() if nameservice: args['nameservice'] = nameservice return self._cmd('hdfsRollEdits', data=args)
python
def roll_edits_hdfs(self, nameservice=None): args = dict() if nameservice: args['nameservice'] = nameservice return self._cmd('hdfsRollEdits', data=args)
[ "def", "roll_edits_hdfs", "(", "self", ",", "nameservice", "=", "None", ")", ":", "args", "=", "dict", "(", ")", "if", "nameservice", ":", "args", "[", "'nameservice'", "]", "=", "nameservice", "return", "self", ".", "_cmd", "(", "'hdfsRollEdits'", ",", ...
Roll the edits of an HDFS NameNode or Nameservice. @param nameservice: Nameservice whose edits should be rolled. Required only with a federated HDFS. @return: Reference to the submitted command. @since: API v3
[ "Roll", "the", "edits", "of", "an", "HDFS", "NameNode", "or", "Nameservice", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1235-L1248
232,812
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.sync_hue_db
def sync_hue_db(self, *servers): """ Synchronize the Hue server's database. @param servers: Name of Hue Server roles to synchronize. Not required starting with API v10. @return: List of submitted commands. """ actual_version = self._get_resource_root().version if actual_version < 10: return self._role_cmd('hueSyncDb', servers) return self._cmd('hueSyncDb', api_version=10)
python
def sync_hue_db(self, *servers): actual_version = self._get_resource_root().version if actual_version < 10: return self._role_cmd('hueSyncDb', servers) return self._cmd('hueSyncDb', api_version=10)
[ "def", "sync_hue_db", "(", "self", ",", "*", "servers", ")", ":", "actual_version", "=", "self", ".", "_get_resource_root", "(", ")", ".", "version", "if", "actual_version", "<", "10", ":", "return", "self", ".", "_role_cmd", "(", "'hueSyncDb'", ",", "serv...
Synchronize the Hue server's database. @param servers: Name of Hue Server roles to synchronize. Not required starting with API v10. @return: List of submitted commands.
[ "Synchronize", "the", "Hue", "server", "s", "database", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1337-L1349
232,813
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.enter_maintenance_mode
def enter_maintenance_mode(self): """ Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2 """ cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(_get_service(self._get_resource_root(), self._path())) return cmd
python
def enter_maintenance_mode(self): cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(_get_service(self._get_resource_root(), self._path())) return cmd
[ "def", "enter_maintenance_mode", "(", "self", ")", ":", "cmd", "=", "self", ".", "_cmd", "(", "'enterMaintenanceMode'", ")", "if", "cmd", ".", "success", ":", "self", ".", "_update", "(", "_get_service", "(", "self", ".", "_get_resource_root", "(", ")", ",...
Put the service in maintenance mode. @return: Reference to the completed command. @since: API v2
[ "Put", "the", "service", "in", "maintenance", "mode", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1412-L1422
232,814
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.create_replication_schedule
def create_replication_schedule(self, start_time, end_time, interval_unit, interval, paused, arguments, alert_on_start=False, alert_on_success=False, alert_on_fail=False, alert_on_abort=False): """ Create a new replication schedule for this service. The replication argument type varies per service type. The following types are recognized: - HDFS: ApiHdfsReplicationArguments - Hive: ApiHiveReplicationArguments @type start_time: datetime.datetime @param start_time: The time at which the schedule becomes active and first executes. @type end_time: datetime.datetime @param end_time: The time at which the schedule will expire. @type interval_unit: str @param interval_unit: The unit of time the `interval` represents. Ex. MINUTE, HOUR, DAY. See the server documentation for a full list of values. @type interval: int @param interval: The number of time units to wait until triggering the next replication. @type paused: bool @param paused: Should the schedule be paused? Useful for on-demand replication. @param arguments: service type-specific arguments for the replication job. @param alert_on_start: whether to generate alerts when the job is started. @param alert_on_success: whether to generate alerts when the job succeeds. @param alert_on_fail: whether to generate alerts when the job fails. @param alert_on_abort: whether to generate alerts when the job is aborted. @return: The newly created schedule. @since: API v3 """ schedule = ApiReplicationSchedule(self._get_resource_root(), startTime=start_time, endTime=end_time, intervalUnit=interval_unit, interval=interval, paused=paused, alertOnStart=alert_on_start, alertOnSuccess=alert_on_success, alertOnFail=alert_on_fail, alertOnAbort=alert_on_abort) if self.type == 'HDFS': if isinstance(arguments, ApiHdfsCloudReplicationArguments): schedule.hdfsCloudArguments = arguments elif isinstance(arguments, ApiHdfsReplicationArguments): schedule.hdfsArguments = arguments else: raise TypeError, 'Unexpected type for HDFS replication argument.' elif self.type == 'HIVE': if not isinstance(arguments, ApiHiveReplicationArguments): raise TypeError, 'Unexpected type for Hive replication argument.' schedule.hiveArguments = arguments else: raise TypeError, 'Replication is not supported for service type ' + self.type return self._post("replications", ApiReplicationSchedule, True, [schedule], api_version=3)[0]
python
def create_replication_schedule(self, start_time, end_time, interval_unit, interval, paused, arguments, alert_on_start=False, alert_on_success=False, alert_on_fail=False, alert_on_abort=False): schedule = ApiReplicationSchedule(self._get_resource_root(), startTime=start_time, endTime=end_time, intervalUnit=interval_unit, interval=interval, paused=paused, alertOnStart=alert_on_start, alertOnSuccess=alert_on_success, alertOnFail=alert_on_fail, alertOnAbort=alert_on_abort) if self.type == 'HDFS': if isinstance(arguments, ApiHdfsCloudReplicationArguments): schedule.hdfsCloudArguments = arguments elif isinstance(arguments, ApiHdfsReplicationArguments): schedule.hdfsArguments = arguments else: raise TypeError, 'Unexpected type for HDFS replication argument.' elif self.type == 'HIVE': if not isinstance(arguments, ApiHiveReplicationArguments): raise TypeError, 'Unexpected type for Hive replication argument.' schedule.hiveArguments = arguments else: raise TypeError, 'Replication is not supported for service type ' + self.type return self._post("replications", ApiReplicationSchedule, True, [schedule], api_version=3)[0]
[ "def", "create_replication_schedule", "(", "self", ",", "start_time", ",", "end_time", ",", "interval_unit", ",", "interval", ",", "paused", ",", "arguments", ",", "alert_on_start", "=", "False", ",", "alert_on_success", "=", "False", ",", "alert_on_fail", "=", ...
Create a new replication schedule for this service. The replication argument type varies per service type. The following types are recognized: - HDFS: ApiHdfsReplicationArguments - Hive: ApiHiveReplicationArguments @type start_time: datetime.datetime @param start_time: The time at which the schedule becomes active and first executes. @type end_time: datetime.datetime @param end_time: The time at which the schedule will expire. @type interval_unit: str @param interval_unit: The unit of time the `interval` represents. Ex. MINUTE, HOUR, DAY. See the server documentation for a full list of values. @type interval: int @param interval: The number of time units to wait until triggering the next replication. @type paused: bool @param paused: Should the schedule be paused? Useful for on-demand replication. @param arguments: service type-specific arguments for the replication job. @param alert_on_start: whether to generate alerts when the job is started. @param alert_on_success: whether to generate alerts when the job succeeds. @param alert_on_fail: whether to generate alerts when the job fails. @param alert_on_abort: whether to generate alerts when the job is aborted. @return: The newly created schedule. @since: API v3
[ "Create", "a", "new", "replication", "schedule", "for", "this", "service", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1484-L1535
232,815
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.update_replication_schedule
def update_replication_schedule(self, schedule_id, schedule): """ Update a replication schedule. @param schedule_id: The id of the schedule to update. @param schedule: The modified schedule. @return: The updated replication schedule. @since: API v3 """ return self._put("replications/%s" % schedule_id, ApiReplicationSchedule, data=schedule, api_version=3)
python
def update_replication_schedule(self, schedule_id, schedule): return self._put("replications/%s" % schedule_id, ApiReplicationSchedule, data=schedule, api_version=3)
[ "def", "update_replication_schedule", "(", "self", ",", "schedule_id", ",", "schedule", ")", ":", "return", "self", ".", "_put", "(", "\"replications/%s\"", "%", "schedule_id", ",", "ApiReplicationSchedule", ",", "data", "=", "schedule", ",", "api_version", "=", ...
Update a replication schedule. @param schedule_id: The id of the schedule to update. @param schedule: The modified schedule. @return: The updated replication schedule. @since: API v3
[ "Update", "a", "replication", "schedule", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1569-L1579
232,816
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.get_replication_command_history
def get_replication_command_history(self, schedule_id, limit=20, offset=0, view=None): """ Retrieve a list of commands for a replication schedule. @param schedule_id: The id of the replication schedule. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands executed for a replication schedule. @since: API v4 """ params = { 'limit': limit, 'offset': offset, } if view: params['view'] = view return self._get("replications/%s/history" % schedule_id, ApiReplicationCommand, True, params=params, api_version=4)
python
def get_replication_command_history(self, schedule_id, limit=20, offset=0, view=None): params = { 'limit': limit, 'offset': offset, } if view: params['view'] = view return self._get("replications/%s/history" % schedule_id, ApiReplicationCommand, True, params=params, api_version=4)
[ "def", "get_replication_command_history", "(", "self", ",", "schedule_id", ",", "limit", "=", "20", ",", "offset", "=", "0", ",", "view", "=", "None", ")", ":", "params", "=", "{", "'limit'", ":", "limit", ",", "'offset'", ":", "offset", ",", "}", "if"...
Retrieve a list of commands for a replication schedule. @param schedule_id: The id of the replication schedule. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands executed for a replication schedule. @since: API v4
[ "Retrieve", "a", "list", "of", "commands", "for", "a", "replication", "schedule", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1581-L1601
232,817
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.trigger_replication_schedule
def trigger_replication_schedule(self, schedule_id, dry_run=False): """ Trigger replication immediately. Start and end dates on the schedule will be ignored. @param schedule_id: The id of the schedule to trigger. @param dry_run: Whether to execute a dry run. @return: The command corresponding to the replication job. @since: API v3 """ return self._post("replications/%s/run" % schedule_id, ApiCommand, params=dict(dryRun=dry_run), api_version=3)
python
def trigger_replication_schedule(self, schedule_id, dry_run=False): return self._post("replications/%s/run" % schedule_id, ApiCommand, params=dict(dryRun=dry_run), api_version=3)
[ "def", "trigger_replication_schedule", "(", "self", ",", "schedule_id", ",", "dry_run", "=", "False", ")", ":", "return", "self", ".", "_post", "(", "\"replications/%s/run\"", "%", "schedule_id", ",", "ApiCommand", ",", "params", "=", "dict", "(", "dryRun", "=...
Trigger replication immediately. Start and end dates on the schedule will be ignored. @param schedule_id: The id of the schedule to trigger. @param dry_run: Whether to execute a dry run. @return: The command corresponding to the replication job. @since: API v3
[ "Trigger", "replication", "immediately", ".", "Start", "and", "end", "dates", "on", "the", "schedule", "will", "be", "ignored", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1603-L1615
232,818
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.get_snapshot_policies
def get_snapshot_policies(self, view=None): """ Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6 """ return self._get("snapshots/policies", ApiSnapshotPolicy, True, params=view and dict(view=view) or None, api_version=6)
python
def get_snapshot_policies(self, view=None): return self._get("snapshots/policies", ApiSnapshotPolicy, True, params=view and dict(view=view) or None, api_version=6)
[ "def", "get_snapshot_policies", "(", "self", ",", "view", "=", "None", ")", ":", "return", "self", ".", "_get", "(", "\"snapshots/policies\"", ",", "ApiSnapshotPolicy", ",", "True", ",", "params", "=", "view", "and", "dict", "(", "view", "=", "view", ")", ...
Retrieve a list of snapshot policies. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: A list of snapshot policies. @since: API v6
[ "Retrieve", "a", "list", "of", "snapshot", "policies", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1627-L1636
232,819
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.get_snapshot_policy
def get_snapshot_policy(self, name, view=None): """ Retrieve a single snapshot policy. @param name: The name of the snapshot policy to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: The requested snapshot policy. @since: API v6 """ return self._get("snapshots/policies/%s" % name, ApiSnapshotPolicy, params=view and dict(view=view) or None, api_version=6)
python
def get_snapshot_policy(self, name, view=None): return self._get("snapshots/policies/%s" % name, ApiSnapshotPolicy, params=view and dict(view=view) or None, api_version=6)
[ "def", "get_snapshot_policy", "(", "self", ",", "name", ",", "view", "=", "None", ")", ":", "return", "self", ".", "_get", "(", "\"snapshots/policies/%s\"", "%", "name", ",", "ApiSnapshotPolicy", ",", "params", "=", "view", "and", "dict", "(", "view", "=",...
Retrieve a single snapshot policy. @param name: The name of the snapshot policy to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: The requested snapshot policy. @since: API v6
[ "Retrieve", "a", "single", "snapshot", "policy", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1638-L1648
232,820
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.update_snapshot_policy
def update_snapshot_policy(self, name, policy): """ Update a snapshot policy. @param name: The name of the snapshot policy to update. @param policy: The modified snapshot policy. @return: The updated snapshot policy. @since: API v6 """ return self._put("snapshots/policies/%s" % name, ApiSnapshotPolicy, data=policy, api_version=6)
python
def update_snapshot_policy(self, name, policy): return self._put("snapshots/policies/%s" % name, ApiSnapshotPolicy, data=policy, api_version=6)
[ "def", "update_snapshot_policy", "(", "self", ",", "name", ",", "policy", ")", ":", "return", "self", ".", "_put", "(", "\"snapshots/policies/%s\"", "%", "name", ",", "ApiSnapshotPolicy", ",", "data", "=", "policy", ",", "api_version", "=", "6", ")" ]
Update a snapshot policy. @param name: The name of the snapshot policy to update. @param policy: The modified snapshot policy. @return: The updated snapshot policy. @since: API v6
[ "Update", "a", "snapshot", "policy", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1660-L1670
232,821
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiService.get_snapshot_command_history
def get_snapshot_command_history(self, name, limit=20, offset=0, view=None): """ Retrieve a list of commands triggered by a snapshot policy. @param name: The name of the snapshot policy. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands triggered by a snapshot policy. @since: API v6 """ params = { 'limit': limit, 'offset': offset, } if view: params['view'] = view return self._get("snapshots/policies/%s/history" % name, ApiSnapshotCommand, True, params=params, api_version=6)
python
def get_snapshot_command_history(self, name, limit=20, offset=0, view=None): params = { 'limit': limit, 'offset': offset, } if view: params['view'] = view return self._get("snapshots/policies/%s/history" % name, ApiSnapshotCommand, True, params=params, api_version=6)
[ "def", "get_snapshot_command_history", "(", "self", ",", "name", ",", "limit", "=", "20", ",", "offset", "=", "0", ",", "view", "=", "None", ")", ":", "params", "=", "{", "'limit'", ":", "limit", ",", "'offset'", ":", "offset", ",", "}", "if", "view"...
Retrieve a list of commands triggered by a snapshot policy. @param name: The name of the snapshot policy. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'export_redacted'. @return: List of commands triggered by a snapshot policy. @since: API v6
[ "Retrieve", "a", "list", "of", "commands", "triggered", "by", "a", "snapshot", "policy", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1672-L1691
232,822
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiServiceSetupInfo.set_config
def set_config(self, config): """ Set the service configuration. @param config: A dictionary of config key/value """ if self.config is None: self.config = { } self.config.update(config_to_api_list(config))
python
def set_config(self, config): if self.config is None: self.config = { } self.config.update(config_to_api_list(config))
[ "def", "set_config", "(", "self", ",", "config", ")", ":", "if", "self", ".", "config", "is", "None", ":", "self", ".", "config", "=", "{", "}", "self", ".", "config", ".", "update", "(", "config_to_api_list", "(", "config", ")", ")" ]
Set the service configuration. @param config: A dictionary of config key/value
[ "Set", "the", "service", "configuration", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1940-L1948
232,823
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiServiceSetupInfo.add_role_type_info
def add_role_type_info(self, role_type, config): """ Add a role type setup info. @param role_type: Role type @param config: A dictionary of role type configuration """ rt_config = config_to_api_list(config) rt_config['roleType'] = role_type if self.config is None: self.config = { } if not self.config.has_key(ROLETYPES_CFG_KEY): self.config[ROLETYPES_CFG_KEY] = [ ] self.config[ROLETYPES_CFG_KEY].append(rt_config)
python
def add_role_type_info(self, role_type, config): rt_config = config_to_api_list(config) rt_config['roleType'] = role_type if self.config is None: self.config = { } if not self.config.has_key(ROLETYPES_CFG_KEY): self.config[ROLETYPES_CFG_KEY] = [ ] self.config[ROLETYPES_CFG_KEY].append(rt_config)
[ "def", "add_role_type_info", "(", "self", ",", "role_type", ",", "config", ")", ":", "rt_config", "=", "config_to_api_list", "(", "config", ")", "rt_config", "[", "'roleType'", "]", "=", "role_type", "if", "self", ".", "config", "is", "None", ":", "self", ...
Add a role type setup info. @param role_type: Role type @param config: A dictionary of role type configuration
[ "Add", "a", "role", "type", "setup", "info", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1950-L1964
232,824
cloudera/cm_api
python/src/cm_api/endpoints/services.py
ApiServiceSetupInfo.add_role_info
def add_role_info(self, role_name, role_type, host_id, config=None): """ Add a role info. The role will be created along with the service setup. @param role_name: Role name @param role_type: Role type @param host_id: The host where the role should run @param config: (Optional) A dictionary of role config values """ if self.roles is None: self.roles = [ ] api_config_list = config is not None and config_to_api_list(config) or None self.roles.append({ 'name' : role_name, 'type' : role_type, 'hostRef' : { 'hostId' : host_id }, 'config' : api_config_list })
python
def add_role_info(self, role_name, role_type, host_id, config=None): if self.roles is None: self.roles = [ ] api_config_list = config is not None and config_to_api_list(config) or None self.roles.append({ 'name' : role_name, 'type' : role_type, 'hostRef' : { 'hostId' : host_id }, 'config' : api_config_list })
[ "def", "add_role_info", "(", "self", ",", "role_name", ",", "role_type", ",", "host_id", ",", "config", "=", "None", ")", ":", "if", "self", ".", "roles", "is", "None", ":", "self", ".", "roles", "=", "[", "]", "api_config_list", "=", "config", "is", ...
Add a role info. The role will be created along with the service setup. @param role_name: Role name @param role_type: Role type @param host_id: The host where the role should run @param config: (Optional) A dictionary of role config values
[ "Add", "a", "role", "info", ".", "The", "role", "will", "be", "created", "along", "with", "the", "service", "setup", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1966-L1982
232,825
cloudera/cm_api
python/src/cm_api/endpoints/hosts.py
create_host
def create_host(resource_root, host_id, name, ipaddr, rack_id=None): """ Create a host @param resource_root: The root Resource object. @param host_id: Host id @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None @return: An ApiHost object """ apihost = ApiHost(resource_root, host_id, name, ipaddr, rack_id) return call(resource_root.post, HOSTS_PATH, ApiHost, True, data=[apihost])[0]
python
def create_host(resource_root, host_id, name, ipaddr, rack_id=None): apihost = ApiHost(resource_root, host_id, name, ipaddr, rack_id) return call(resource_root.post, HOSTS_PATH, ApiHost, True, data=[apihost])[0]
[ "def", "create_host", "(", "resource_root", ",", "host_id", ",", "name", ",", "ipaddr", ",", "rack_id", "=", "None", ")", ":", "apihost", "=", "ApiHost", "(", "resource_root", ",", "host_id", ",", "name", ",", "ipaddr", ",", "rack_id", ")", "return", "ca...
Create a host @param resource_root: The root Resource object. @param host_id: Host id @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None @return: An ApiHost object
[ "Create", "a", "host" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/hosts.py#L25-L36
232,826
cloudera/cm_api
python/src/cm_api/endpoints/hosts.py
get_all_hosts
def get_all_hosts(resource_root, view=None): """ Get all hosts @param resource_root: The root Resource object. @return: A list of ApiHost objects. """ return call(resource_root.get, HOSTS_PATH, ApiHost, True, params=view and dict(view=view) or None)
python
def get_all_hosts(resource_root, view=None): return call(resource_root.get, HOSTS_PATH, ApiHost, True, params=view and dict(view=view) or None)
[ "def", "get_all_hosts", "(", "resource_root", ",", "view", "=", "None", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "HOSTS_PATH", ",", "ApiHost", ",", "True", ",", "params", "=", "view", "and", "dict", "(", "view", "=", "view", "...
Get all hosts @param resource_root: The root Resource object. @return: A list of ApiHost objects.
[ "Get", "all", "hosts" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/hosts.py#L47-L54
232,827
cloudera/cm_api
python/src/cm_api/endpoints/hosts.py
ApiHost.enter_maintenance_mode
def enter_maintenance_mode(self): """ Put the host in maintenance mode. @return: Reference to the completed command. @since: API v2 """ cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(get_host(self._get_resource_root(), self.hostId)) return cmd
python
def enter_maintenance_mode(self): cmd = self._cmd('enterMaintenanceMode') if cmd.success: self._update(get_host(self._get_resource_root(), self.hostId)) return cmd
[ "def", "enter_maintenance_mode", "(", "self", ")", ":", "cmd", "=", "self", ".", "_cmd", "(", "'enterMaintenanceMode'", ")", "if", "cmd", ".", "success", ":", "self", ".", "_update", "(", "get_host", "(", "self", ".", "_get_resource_root", "(", ")", ",", ...
Put the host in maintenance mode. @return: Reference to the completed command. @since: API v2
[ "Put", "the", "host", "in", "maintenance", "mode", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/hosts.py#L161-L171
232,828
cloudera/cm_api
python/src/cm_api/endpoints/hosts.py
ApiHost.migrate_roles
def migrate_roles(self, role_names_to_migrate, destination_host_id, clear_stale_role_data): """ Migrate roles from this host to a different host. Currently, this command applies only to HDFS NameNode, JournalNode, and Failover Controller roles. In order to migrate these roles: - HDFS High Availability must be enabled, using quorum-based storage. - HDFS must not be configured to use a federated nameservice. I{B{Migrating a NameNode role requires cluster downtime.}} HDFS, along with all of its dependent services, will be stopped at the beginning of the migration process, and restarted at its conclusion. If the active NameNode is selected for migration, a manual failover will be performed before the role is migrated. The role will remain in standby mode after the migration is complete. When migrating a NameNode role, the co-located Failover Controller role must be migrated as well. The Failover Controller role name must be included in the list of role names to migrate specified in the arguments to this command (it will not be included implicitly). This command does not allow a Failover Controller role to be moved by itself, although it is possible to move a JournalNode independently. @param role_names_to_migrate: list of role names to migrate. @param destination_host_id: the id of the host to which the roles should be migrated. @param clear_stale_role_data: true to delete existing stale role data, if any. For example, when migrating a NameNode, if the destination host has stale data in the NameNode data directories (possibly because a NameNode role was previously located there), this stale data will be deleted before migrating the role. @return: Reference to the submitted command. @since: API v10 """ args = dict( roleNamesToMigrate = role_names_to_migrate, destinationHostId = destination_host_id, clearStaleRoleData = clear_stale_role_data) return self._cmd('migrateRoles', data=args, api_version=10)
python
def migrate_roles(self, role_names_to_migrate, destination_host_id, clear_stale_role_data): args = dict( roleNamesToMigrate = role_names_to_migrate, destinationHostId = destination_host_id, clearStaleRoleData = clear_stale_role_data) return self._cmd('migrateRoles', data=args, api_version=10)
[ "def", "migrate_roles", "(", "self", ",", "role_names_to_migrate", ",", "destination_host_id", ",", "clear_stale_role_data", ")", ":", "args", "=", "dict", "(", "roleNamesToMigrate", "=", "role_names_to_migrate", ",", "destinationHostId", "=", "destination_host_id", ","...
Migrate roles from this host to a different host. Currently, this command applies only to HDFS NameNode, JournalNode, and Failover Controller roles. In order to migrate these roles: - HDFS High Availability must be enabled, using quorum-based storage. - HDFS must not be configured to use a federated nameservice. I{B{Migrating a NameNode role requires cluster downtime.}} HDFS, along with all of its dependent services, will be stopped at the beginning of the migration process, and restarted at its conclusion. If the active NameNode is selected for migration, a manual failover will be performed before the role is migrated. The role will remain in standby mode after the migration is complete. When migrating a NameNode role, the co-located Failover Controller role must be migrated as well. The Failover Controller role name must be included in the list of role names to migrate specified in the arguments to this command (it will not be included implicitly). This command does not allow a Failover Controller role to be moved by itself, although it is possible to move a JournalNode independently. @param role_names_to_migrate: list of role names to migrate. @param destination_host_id: the id of the host to which the roles should be migrated. @param clear_stale_role_data: true to delete existing stale role data, if any. For example, when migrating a NameNode, if the destination host has stale data in the NameNode data directories (possibly because a NameNode role was previously located there), this stale data will be deleted before migrating the role. @return: Reference to the submitted command. @since: API v10
[ "Migrate", "roles", "from", "this", "host", "to", "a", "different", "host", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/hosts.py#L185-L229
232,829
cloudera/cm_api
nagios/cm_nagios.py
get_host_map
def get_host_map(root): ''' Gets a mapping between CM hostId and Nagios host information The key is the CM hostId The value is an object containing the Nagios hostname and host address ''' hosts_map = {} for host in root.get_all_hosts(): hosts_map[host.hostId] = {"hostname": NAGIOS_HOSTNAME_FORMAT % (host.hostname,), "address": host.ipAddress} ''' Also define "virtual hosts" for the CM clusters- they will be the hosts to which CM services are mapped ''' for cluster in root.get_all_clusters(): hosts_map[cluster.name] = {"hostname": cluster.name, "address": quote(cluster.name)} hosts_map[CM_DUMMY_HOST] = {"hostname": CM_DUMMY_HOST, "address": CM_DUMMY_HOST} return hosts_map
python
def get_host_map(root): ''' Gets a mapping between CM hostId and Nagios host information The key is the CM hostId The value is an object containing the Nagios hostname and host address ''' hosts_map = {} for host in root.get_all_hosts(): hosts_map[host.hostId] = {"hostname": NAGIOS_HOSTNAME_FORMAT % (host.hostname,), "address": host.ipAddress} ''' Also define "virtual hosts" for the CM clusters- they will be the hosts to which CM services are mapped ''' for cluster in root.get_all_clusters(): hosts_map[cluster.name] = {"hostname": cluster.name, "address": quote(cluster.name)} hosts_map[CM_DUMMY_HOST] = {"hostname": CM_DUMMY_HOST, "address": CM_DUMMY_HOST} return hosts_map
[ "def", "get_host_map", "(", "root", ")", ":", "hosts_map", "=", "{", "}", "for", "host", "in", "root", ".", "get_all_hosts", "(", ")", ":", "hosts_map", "[", "host", ".", "hostId", "]", "=", "{", "\"hostname\"", ":", "NAGIOS_HOSTNAME_FORMAT", "%", "(", ...
Gets a mapping between CM hostId and Nagios host information The key is the CM hostId The value is an object containing the Nagios hostname and host address
[ "Gets", "a", "mapping", "between", "CM", "hostId", "and", "Nagios", "host", "information" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/nagios/cm_nagios.py#L199-L218
232,830
cloudera/cm_api
nagios/cm_nagios.py
get_services
def get_services(root, hosts_map, view=None): ''' Gets a list of objects representing the Nagios services. Each object contains the Nagios hostname, service name, service display name, and service health summary. ''' services_list = [] mgmt_service = root.get_cloudera_manager().get_service() services_list.append({"hostname": CM_DUMMY_HOST, "name": mgmt_service.name, "display_name": "CM Managed Service: %s" % (mgmt_service.name,), "status": get_status(mgmt_service), "url": mgmt_service.serviceUrl, "health_summary": mgmt_service.healthSummary}) for cm_role in root.get_cloudera_manager().get_service().get_all_roles(view): services_list.append({"hostname": hosts_map[cm_role.hostRef.hostId]["hostname"], "name": cm_role.name, "display_name": "CM Management Service: %s" % (cm_role.name,), "status": get_status(cm_role), "url": cm_role.roleUrl, "health_summary": cm_role.healthSummary}) for cm_host in root.get_all_hosts(view): services_list.append({"hostname": hosts_map[cm_host.hostId]["hostname"], "name": "cm-host-%s" % (cm_host.hostname,), "display_name": "CM Managed Host: %s" % (cm_host.hostname,), "status": get_status(cm_host), "url": cm_host.hostUrl, "health_summary": cm_host.healthSummary}) for cluster in root.get_all_clusters(view): for service in cluster.get_all_services(view): services_list.append({"hostname": cluster.name, "name": service.name, "display_name": "CM Managed Service: %s" % (service.name,), "status": get_status(service), "url": service.serviceUrl, "health_summary": service.healthSummary}) for role in service.get_all_roles(view): services_list.append({"hostname": hosts_map[role.hostRef.hostId]["hostname"], "name": role.name, "display_name": "%s:%s" % (cluster.name, role.name,), "status": get_status(role), "url": role.roleUrl, "health_summary": role.healthSummary}) return services_list
python
def get_services(root, hosts_map, view=None): ''' Gets a list of objects representing the Nagios services. Each object contains the Nagios hostname, service name, service display name, and service health summary. ''' services_list = [] mgmt_service = root.get_cloudera_manager().get_service() services_list.append({"hostname": CM_DUMMY_HOST, "name": mgmt_service.name, "display_name": "CM Managed Service: %s" % (mgmt_service.name,), "status": get_status(mgmt_service), "url": mgmt_service.serviceUrl, "health_summary": mgmt_service.healthSummary}) for cm_role in root.get_cloudera_manager().get_service().get_all_roles(view): services_list.append({"hostname": hosts_map[cm_role.hostRef.hostId]["hostname"], "name": cm_role.name, "display_name": "CM Management Service: %s" % (cm_role.name,), "status": get_status(cm_role), "url": cm_role.roleUrl, "health_summary": cm_role.healthSummary}) for cm_host in root.get_all_hosts(view): services_list.append({"hostname": hosts_map[cm_host.hostId]["hostname"], "name": "cm-host-%s" % (cm_host.hostname,), "display_name": "CM Managed Host: %s" % (cm_host.hostname,), "status": get_status(cm_host), "url": cm_host.hostUrl, "health_summary": cm_host.healthSummary}) for cluster in root.get_all_clusters(view): for service in cluster.get_all_services(view): services_list.append({"hostname": cluster.name, "name": service.name, "display_name": "CM Managed Service: %s" % (service.name,), "status": get_status(service), "url": service.serviceUrl, "health_summary": service.healthSummary}) for role in service.get_all_roles(view): services_list.append({"hostname": hosts_map[role.hostRef.hostId]["hostname"], "name": role.name, "display_name": "%s:%s" % (cluster.name, role.name,), "status": get_status(role), "url": role.roleUrl, "health_summary": role.healthSummary}) return services_list
[ "def", "get_services", "(", "root", ",", "hosts_map", ",", "view", "=", "None", ")", ":", "services_list", "=", "[", "]", "mgmt_service", "=", "root", ".", "get_cloudera_manager", "(", ")", ".", "get_service", "(", ")", "services_list", ".", "append", "(",...
Gets a list of objects representing the Nagios services. Each object contains the Nagios hostname, service name, service display name, and service health summary.
[ "Gets", "a", "list", "of", "objects", "representing", "the", "Nagios", "services", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/nagios/cm_nagios.py#L237-L280
232,831
cloudera/cm_api
nagios/cm_nagios.py
submit_status_external_cmd
def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(cmd_file, 'a') as cmd_file: cmd_file.write(status_file.read()) except IOError: exit("Fatal error: Unable to write to Nagios external command file '%s'.\n" "Make sure that the file exists and is writable." % (cmd_file,))
python
def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(cmd_file, 'a') as cmd_file: cmd_file.write(status_file.read()) except IOError: exit("Fatal error: Unable to write to Nagios external command file '%s'.\n" "Make sure that the file exists and is writable." % (cmd_file,))
[ "def", "submit_status_external_cmd", "(", "cmd_file", ",", "status_file", ")", ":", "try", ":", "with", "open", "(", "cmd_file", ",", "'a'", ")", "as", "cmd_file", ":", "cmd_file", ".", "write", "(", "status_file", ".", "read", "(", ")", ")", "except", "...
Submits the status lines in the status_file to Nagios' external cmd file.
[ "Submits", "the", "status", "lines", "in", "the", "status_file", "to", "Nagios", "external", "cmd", "file", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/nagios/cm_nagios.py#L283-L291
232,832
cloudera/cm_api
python/src/cm_api/resource.py
Resource.invoke
def invoke(self, method, relpath=None, params=None, data=None, headers=None): """ Invoke an API method. @return: Raw body or JSON dictionary (if response content type is JSON). """ path = self._join_uri(relpath) resp = self._client.execute(method, path, params=params, data=data, headers=headers) try: body = resp.read() except Exception, ex: raise Exception("Command '%s %s' failed: %s" % (method, path, ex)) self._client.logger.debug( "%s Got response: %s%s" % (method, body[:32], len(body) > 32 and "..." or "")) # Is the response application/json? if len(body) != 0 and \ resp.info().getmaintype() == "application" and \ resp.info().getsubtype() == "json": try: json_dict = json.loads(body) return json_dict except Exception, ex: self._client.logger.exception('JSON decode error: %s' % (body,)) raise ex else: return body
python
def invoke(self, method, relpath=None, params=None, data=None, headers=None): path = self._join_uri(relpath) resp = self._client.execute(method, path, params=params, data=data, headers=headers) try: body = resp.read() except Exception, ex: raise Exception("Command '%s %s' failed: %s" % (method, path, ex)) self._client.logger.debug( "%s Got response: %s%s" % (method, body[:32], len(body) > 32 and "..." or "")) # Is the response application/json? if len(body) != 0 and \ resp.info().getmaintype() == "application" and \ resp.info().getsubtype() == "json": try: json_dict = json.loads(body) return json_dict except Exception, ex: self._client.logger.exception('JSON decode error: %s' % (body,)) raise ex else: return body
[ "def", "invoke", "(", "self", ",", "method", ",", "relpath", "=", "None", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ")", ":", "path", "=", "self", ".", "_join_uri", "(", "relpath", ")", "resp", "=", "self", ...
Invoke an API method. @return: Raw body or JSON dictionary (if response content type is JSON).
[ "Invoke", "an", "API", "method", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/resource.py#L63-L95
232,833
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
create_host_template
def create_host_template(resource_root, name, cluster_name): """ Create a host template. @param resource_root: The root Resource object. @param name: Host template name @param cluster_name: Cluster name @return: An ApiHostTemplate object for the created host template. @since: API v3 """ apitemplate = ApiHostTemplate(resource_root, name, []) return call(resource_root.post, HOST_TEMPLATES_PATH % (cluster_name,), ApiHostTemplate, True, data=[apitemplate], api_version=3)[0]
python
def create_host_template(resource_root, name, cluster_name): apitemplate = ApiHostTemplate(resource_root, name, []) return call(resource_root.post, HOST_TEMPLATES_PATH % (cluster_name,), ApiHostTemplate, True, data=[apitemplate], api_version=3)[0]
[ "def", "create_host_template", "(", "resource_root", ",", "name", ",", "cluster_name", ")", ":", "apitemplate", "=", "ApiHostTemplate", "(", "resource_root", ",", "name", ",", "[", "]", ")", "return", "call", "(", "resource_root", ".", "post", ",", "HOST_TEMPL...
Create a host template. @param resource_root: The root Resource object. @param name: Host template name @param cluster_name: Cluster name @return: An ApiHostTemplate object for the created host template. @since: API v3
[ "Create", "a", "host", "template", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L26-L38
232,834
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
get_host_template
def get_host_template(resource_root, name, cluster_name): """ Lookup a host template by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: An ApiHostTemplate object. @since: API v3 """ return call(resource_root.get, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, api_version=3)
python
def get_host_template(resource_root, name, cluster_name): return call(resource_root.get, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, api_version=3)
[ "def", "get_host_template", "(", "resource_root", ",", "name", ",", "cluster_name", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "HOST_TEMPLATE_PATH", "%", "(", "cluster_name", ",", "name", ")", ",", "ApiHostTemplate", ",", "api_version", ...
Lookup a host template by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: An ApiHostTemplate object. @since: API v3
[ "Lookup", "a", "host", "template", "by", "name", "in", "the", "specified", "cluster", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L40-L51
232,835
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
get_all_host_templates
def get_all_host_templates(resource_root, cluster_name="default"): """ Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3 """ return call(resource_root.get, HOST_TEMPLATES_PATH % (cluster_name,), ApiHostTemplate, True, api_version=3)
python
def get_all_host_templates(resource_root, cluster_name="default"): return call(resource_root.get, HOST_TEMPLATES_PATH % (cluster_name,), ApiHostTemplate, True, api_version=3)
[ "def", "get_all_host_templates", "(", "resource_root", ",", "cluster_name", "=", "\"default\"", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "HOST_TEMPLATES_PATH", "%", "(", "cluster_name", ",", ")", ",", "ApiHostTemplate", ",", "True", ","...
Get all host templates in a cluster. @param cluster_name: Cluster name. @return: ApiList of ApiHostTemplate objects for all host templates in a cluster. @since: API v3
[ "Get", "all", "host", "templates", "in", "a", "cluster", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L53-L62
232,836
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
delete_host_template
def delete_host_template(resource_root, name, cluster_name): """ Delete a host template identified by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: The deleted ApiHostTemplate object. @since: API v3 """ return call(resource_root.delete, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, api_version=3)
python
def delete_host_template(resource_root, name, cluster_name): return call(resource_root.delete, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, api_version=3)
[ "def", "delete_host_template", "(", "resource_root", ",", "name", ",", "cluster_name", ")", ":", "return", "call", "(", "resource_root", ".", "delete", ",", "HOST_TEMPLATE_PATH", "%", "(", "cluster_name", ",", "name", ")", ",", "ApiHostTemplate", ",", "api_versi...
Delete a host template identified by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: The deleted ApiHostTemplate object. @since: API v3
[ "Delete", "a", "host", "template", "identified", "by", "name", "in", "the", "specified", "cluster", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L64-L75
232,837
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
update_host_template
def update_host_template(resource_root, name, cluster_name, api_host_template): """ Update a host template identified by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @param api_host_template: The updated host template. @return: The updated ApiHostTemplate. @since: API v3 """ return call(resource_root.put, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, data=api_host_template, api_version=3)
python
def update_host_template(resource_root, name, cluster_name, api_host_template): return call(resource_root.put, HOST_TEMPLATE_PATH % (cluster_name, name), ApiHostTemplate, data=api_host_template, api_version=3)
[ "def", "update_host_template", "(", "resource_root", ",", "name", ",", "cluster_name", ",", "api_host_template", ")", ":", "return", "call", "(", "resource_root", ".", "put", ",", "HOST_TEMPLATE_PATH", "%", "(", "cluster_name", ",", "name", ")", ",", "ApiHostTem...
Update a host template identified by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @param api_host_template: The updated host template. @return: The updated ApiHostTemplate. @since: API v3
[ "Update", "a", "host", "template", "identified", "by", "name", "in", "the", "specified", "cluster", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L77-L89
232,838
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
ApiHostTemplate.rename
def rename(self, new_name): """ Rename a host template. @param new_name: New host template name. @return: An ApiHostTemplate object. """ update = copy.copy(self) update.name = new_name return self._do_update(update)
python
def rename(self, new_name): update = copy.copy(self) update.name = new_name return self._do_update(update)
[ "def", "rename", "(", "self", ",", "new_name", ")", ":", "update", "=", "copy", ".", "copy", "(", "self", ")", "update", ".", "name", "=", "new_name", "return", "self", ".", "_do_update", "(", "update", ")" ]
Rename a host template. @param new_name: New host template name. @return: An ApiHostTemplate object.
[ "Rename", "a", "host", "template", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L136-L144
232,839
cloudera/cm_api
python/src/cm_api/endpoints/host_templates.py
ApiHostTemplate.set_role_config_groups
def set_role_config_groups(self, role_config_group_refs): """ Updates the role config groups in a host template. @param role_config_group_refs: List of role config group refs. @return: An ApiHostTemplate object. """ update = copy.copy(self) update.roleConfigGroupRefs = role_config_group_refs return self._do_update(update)
python
def set_role_config_groups(self, role_config_group_refs): update = copy.copy(self) update.roleConfigGroupRefs = role_config_group_refs return self._do_update(update)
[ "def", "set_role_config_groups", "(", "self", ",", "role_config_group_refs", ")", ":", "update", "=", "copy", ".", "copy", "(", "self", ")", "update", ".", "roleConfigGroupRefs", "=", "role_config_group_refs", "return", "self", ".", "_do_update", "(", "update", ...
Updates the role config groups in a host template. @param role_config_group_refs: List of role config group refs. @return: An ApiHostTemplate object.
[ "Updates", "the", "role", "config", "groups", "in", "a", "host", "template", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/host_templates.py#L146-L154
232,840
cloudera/cm_api
python/examples/aws.py
list_supported_categories
def list_supported_categories(): """ Prints a list of supported external account category names. For example, "AWS" is a supported external account category name. """ categories = get_supported_categories(api) category_names = [category.name for category in categories] print ("Supported account categories by name: {0}".format( COMMA_WITH_SPACE.join(map(str, category_names))))
python
def list_supported_categories(): categories = get_supported_categories(api) category_names = [category.name for category in categories] print ("Supported account categories by name: {0}".format( COMMA_WITH_SPACE.join(map(str, category_names))))
[ "def", "list_supported_categories", "(", ")", ":", "categories", "=", "get_supported_categories", "(", "api", ")", "category_names", "=", "[", "category", ".", "name", "for", "category", "in", "categories", "]", "print", "(", "\"Supported account categories by name: {...
Prints a list of supported external account category names. For example, "AWS" is a supported external account category name.
[ "Prints", "a", "list", "of", "supported", "external", "account", "category", "names", ".", "For", "example", "AWS", "is", "a", "supported", "external", "account", "category", "name", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L73-L81
232,841
cloudera/cm_api
python/examples/aws.py
list_supported_types
def list_supported_types(category_name): """ Prints a list of supported external account type names for the given category_name. For example, "AWS_ACCESS_KEY_AUTH" is a supported external account type name for external account category "AWS". """ types = get_supported_types(api, category_name) type_names = [type.name for type in types] print ("Supported account types by name for '{0}': [{1}]".format( category_name, COMMA_WITH_SPACE.join(map(str, type_names))))
python
def list_supported_types(category_name): types = get_supported_types(api, category_name) type_names = [type.name for type in types] print ("Supported account types by name for '{0}': [{1}]".format( category_name, COMMA_WITH_SPACE.join(map(str, type_names))))
[ "def", "list_supported_types", "(", "category_name", ")", ":", "types", "=", "get_supported_types", "(", "api", ",", "category_name", ")", "type_names", "=", "[", "type", ".", "name", "for", "type", "in", "types", "]", "print", "(", "\"Supported account types by...
Prints a list of supported external account type names for the given category_name. For example, "AWS_ACCESS_KEY_AUTH" is a supported external account type name for external account category "AWS".
[ "Prints", "a", "list", "of", "supported", "external", "account", "type", "names", "for", "the", "given", "category_name", ".", "For", "example", "AWS_ACCESS_KEY_AUTH", "is", "a", "supported", "external", "account", "type", "name", "for", "external", "account", "...
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L84-L93
232,842
cloudera/cm_api
python/examples/aws.py
list_credentials_by_name
def list_credentials_by_name(type_name): """ Prints a list of available credential names for the given type_name. """ accounts = get_all_external_accounts(api, type_name) account_names = [account.name for account in accounts] print ("List of credential names for '{0}': [{1}]".format( type_name, COMMA_WITH_SPACE.join(map(str, account_names))))
python
def list_credentials_by_name(type_name): accounts = get_all_external_accounts(api, type_name) account_names = [account.name for account in accounts] print ("List of credential names for '{0}': [{1}]".format( type_name, COMMA_WITH_SPACE.join(map(str, account_names))))
[ "def", "list_credentials_by_name", "(", "type_name", ")", ":", "accounts", "=", "get_all_external_accounts", "(", "api", ",", "type_name", ")", "account_names", "=", "[", "account", ".", "name", "for", "account", "in", "accounts", "]", "print", "(", "\"List of c...
Prints a list of available credential names for the given type_name.
[ "Prints", "a", "list", "of", "available", "credential", "names", "for", "the", "given", "type_name", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L96-L103
232,843
cloudera/cm_api
python/examples/aws.py
call_s3guard_prune
def call_s3guard_prune(credential_name): """ Runs S3Guard prune command on external account associated with the given credential_name. """ # Get the AWS credential account associated with the credential account = get_external_account(api, credential_name) # Invoke the prune command for the account by its name cmd = account.external_account_cmd_by_name('S3GuardPrune') print ("Issued '{0}' command with id '{1}'".format(cmd.name, cmd.id)) print ("Waiting for command {0} to finish...".format(cmd.id)) cmd = cmd.wait() print ("Command succeeded: {0}".format(cmd.success))
python
def call_s3guard_prune(credential_name): # Get the AWS credential account associated with the credential account = get_external_account(api, credential_name) # Invoke the prune command for the account by its name cmd = account.external_account_cmd_by_name('S3GuardPrune') print ("Issued '{0}' command with id '{1}'".format(cmd.name, cmd.id)) print ("Waiting for command {0} to finish...".format(cmd.id)) cmd = cmd.wait() print ("Command succeeded: {0}".format(cmd.success))
[ "def", "call_s3guard_prune", "(", "credential_name", ")", ":", "# Get the AWS credential account associated with the credential", "account", "=", "get_external_account", "(", "api", ",", "credential_name", ")", "# Invoke the prune command for the account by its name", "cmd", "=", ...
Runs S3Guard prune command on external account associated with the given credential_name.
[ "Runs", "S3Guard", "prune", "command", "on", "external", "account", "associated", "with", "the", "given", "credential_name", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L106-L117
232,844
cloudera/cm_api
python/examples/aws.py
initialize_api
def initialize_api(args): """ Initializes the global API instance using the given arguments. @param args: arguments provided to the script. """ global api api = ApiResource(server_host=args.hostname, server_port=args.port, username=args.username, password=args.password, version=args.api_version, use_tls=args.use_tls)
python
def initialize_api(args): global api api = ApiResource(server_host=args.hostname, server_port=args.port, username=args.username, password=args.password, version=args.api_version, use_tls=args.use_tls)
[ "def", "initialize_api", "(", "args", ")", ":", "global", "api", "api", "=", "ApiResource", "(", "server_host", "=", "args", ".", "hostname", ",", "server_port", "=", "args", ".", "port", ",", "username", "=", "args", ".", "username", ",", "password", "=...
Initializes the global API instance using the given arguments. @param args: arguments provided to the script.
[ "Initializes", "the", "global", "API", "instance", "using", "the", "given", "arguments", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L129-L137
232,845
cloudera/cm_api
python/examples/aws.py
validate_api_compatibility
def validate_api_compatibility(args): """ Validates the API version. @param args: arguments provided to the script. """ if args.api_version and args.api_version < MINIMUM_SUPPORTED_API_VERSION: print("ERROR: Given API version: {0}. Minimum supported API version: {1}" .format(args.api_version, MINIMUM_SUPPORTED_API_VERSION))
python
def validate_api_compatibility(args): if args.api_version and args.api_version < MINIMUM_SUPPORTED_API_VERSION: print("ERROR: Given API version: {0}. Minimum supported API version: {1}" .format(args.api_version, MINIMUM_SUPPORTED_API_VERSION))
[ "def", "validate_api_compatibility", "(", "args", ")", ":", "if", "args", ".", "api_version", "and", "args", ".", "api_version", "<", "MINIMUM_SUPPORTED_API_VERSION", ":", "print", "(", "\"ERROR: Given API version: {0}. Minimum supported API version: {1}\"", ".", "format", ...
Validates the API version. @param args: arguments provided to the script.
[ "Validates", "the", "API", "version", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L140-L147
232,846
cloudera/cm_api
python/examples/aws.py
get_login_credentials
def get_login_credentials(args): """ Gets the login credentials from the user, if not specified while invoking the script. @param args: arguments provided to the script. """ if not args.username: args.username = raw_input("Enter Username: ") if not args.password: args.password = getpass.getpass("Enter Password: ")
python
def get_login_credentials(args): if not args.username: args.username = raw_input("Enter Username: ") if not args.password: args.password = getpass.getpass("Enter Password: ")
[ "def", "get_login_credentials", "(", "args", ")", ":", "if", "not", "args", ".", "username", ":", "args", ".", "username", "=", "raw_input", "(", "\"Enter Username: \"", ")", "if", "not", "args", ".", "password", ":", "args", ".", "password", "=", "getpass...
Gets the login credentials from the user, if not specified while invoking the script. @param args: arguments provided to the script.
[ "Gets", "the", "login", "credentials", "from", "the", "user", "if", "not", "specified", "while", "invoking", "the", "script", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L150-L159
232,847
cloudera/cm_api
python/examples/aws.py
main
def main(): """ The "main" entry that controls the flow of the script based on the provided arguments. """ setup_logging(logging.INFO) # Parse arguments parser = argparse.ArgumentParser( description="A utility to interact with AWS using Cloudera Manager.") parser.add_argument('-H', '--hostname', action='store', dest='hostname', required=True, help='The hostname of the Cloudera Manager server.') parser.add_argument('-p', action='store', dest='port', type=int, help='The port of the Cloudera Manager server. Defaults ' 'to 7180 (http) or 7183 (https).') parser.add_argument('-u', '--username', action='store', dest='username', help='Login name.') parser.add_argument('--password', action='store', dest='password', help='Login password.') parser.add_argument('--api-version', action='store', dest='api_version', type=int, default=MINIMUM_SUPPORTED_API_VERSION, help='API version to be used. Defaults to {0}.'.format( MINIMUM_SUPPORTED_API_VERSION)) parser.add_argument('--tls', action='store_const', dest='use_tls', const=True, default=False, help='Whether to use tls (https).') parser.add_argument('-c', '--show-categories', action='store_true', default=False, dest='show_categories', help='Prints a list of supported external account ' 'category names. For example, "AWS" is a supported ' 'external account category name.') parser.add_argument('-t', '--show-types', action='store', dest='category_name', help='Prints a list of supported external account type ' 'names for the given CATEGORY_NAME. For example, ' '"AWS_ACCESS_KEY_AUTH" is a supported external ' 'account type name for external account category ' '"AWS".') parser.add_argument('-n', '--show-credentials', action='store', dest='type_name', help='Prints a list of available credential names for ' 'the given TYPE_NAME.') parser.add_argument('--prune', action='store', dest='credential_name', help='Runs S3Guard prune command on external account ' 'associated with the given CREDENTIAL_NAME.') parser.add_argument('--version', action='version', version='%(prog)s 1.0') args = parser.parse_args() # Use the default port if required. if not args.port: if args.use_tls: args.port = DEFAULT_HTTPS_PORT else: args.port = DEFAULT_HTTP_PORT validate_api_compatibility(args) get_login_credentials(args) initialize_api(args) # Perform the AWS operation based on the input arguments. if args.show_categories: list_supported_categories() elif args.category_name: list_supported_types(args.category_name) elif args.type_name: list_credentials_by_name(args.type_name) elif args.credential_name: call_s3guard_prune(args.credential_name) else: print ("ERROR: No arguments given to perform any AWS operation.") parser.print_help() sys.exit(1)
python
def main(): setup_logging(logging.INFO) # Parse arguments parser = argparse.ArgumentParser( description="A utility to interact with AWS using Cloudera Manager.") parser.add_argument('-H', '--hostname', action='store', dest='hostname', required=True, help='The hostname of the Cloudera Manager server.') parser.add_argument('-p', action='store', dest='port', type=int, help='The port of the Cloudera Manager server. Defaults ' 'to 7180 (http) or 7183 (https).') parser.add_argument('-u', '--username', action='store', dest='username', help='Login name.') parser.add_argument('--password', action='store', dest='password', help='Login password.') parser.add_argument('--api-version', action='store', dest='api_version', type=int, default=MINIMUM_SUPPORTED_API_VERSION, help='API version to be used. Defaults to {0}.'.format( MINIMUM_SUPPORTED_API_VERSION)) parser.add_argument('--tls', action='store_const', dest='use_tls', const=True, default=False, help='Whether to use tls (https).') parser.add_argument('-c', '--show-categories', action='store_true', default=False, dest='show_categories', help='Prints a list of supported external account ' 'category names. For example, "AWS" is a supported ' 'external account category name.') parser.add_argument('-t', '--show-types', action='store', dest='category_name', help='Prints a list of supported external account type ' 'names for the given CATEGORY_NAME. For example, ' '"AWS_ACCESS_KEY_AUTH" is a supported external ' 'account type name for external account category ' '"AWS".') parser.add_argument('-n', '--show-credentials', action='store', dest='type_name', help='Prints a list of available credential names for ' 'the given TYPE_NAME.') parser.add_argument('--prune', action='store', dest='credential_name', help='Runs S3Guard prune command on external account ' 'associated with the given CREDENTIAL_NAME.') parser.add_argument('--version', action='version', version='%(prog)s 1.0') args = parser.parse_args() # Use the default port if required. if not args.port: if args.use_tls: args.port = DEFAULT_HTTPS_PORT else: args.port = DEFAULT_HTTP_PORT validate_api_compatibility(args) get_login_credentials(args) initialize_api(args) # Perform the AWS operation based on the input arguments. if args.show_categories: list_supported_categories() elif args.category_name: list_supported_types(args.category_name) elif args.type_name: list_credentials_by_name(args.type_name) elif args.credential_name: call_s3guard_prune(args.credential_name) else: print ("ERROR: No arguments given to perform any AWS operation.") parser.print_help() sys.exit(1)
[ "def", "main", "(", ")", ":", "setup_logging", "(", "logging", ".", "INFO", ")", "# Parse arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"A utility to interact with AWS using Cloudera Manager.\"", ")", "parser", ".", "add_argu...
The "main" entry that controls the flow of the script based on the provided arguments.
[ "The", "main", "entry", "that", "controls", "the", "flow", "of", "the", "script", "based", "on", "the", "provided", "arguments", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/examples/aws.py#L162-L235
232,848
cloudera/cm_api
python/src/cm_api/api_client.py
get_root_resource
def get_root_resource(server_host, server_port=None, username="admin", password="admin", use_tls=False, version=API_CURRENT_VERSION): """ See ApiResource. """ return ApiResource(server_host, server_port, username, password, use_tls, version)
python
def get_root_resource(server_host, server_port=None, username="admin", password="admin", use_tls=False, version=API_CURRENT_VERSION): return ApiResource(server_host, server_port, username, password, use_tls, version)
[ "def", "get_root_resource", "(", "server_host", ",", "server_port", "=", "None", ",", "username", "=", "\"admin\"", ",", "password", "=", "\"admin\"", ",", "use_tls", "=", "False", ",", "version", "=", "API_CURRENT_VERSION", ")", ":", "return", "ApiResource", ...
See ApiResource.
[ "See", "ApiResource", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/api_client.py#L392-L399
232,849
cloudera/cm_api
python/src/cm_api/api_client.py
ApiResource.create_cluster
def create_cluster(self, name, version=None, fullVersion=None): """ Create a new cluster. @param name: Cluster name. @param version: Cluster major CDH version, e.g. 'CDH5'. Ignored if fullVersion is specified. @param fullVersion: Complete CDH version, e.g. '5.1.2'. Overrides major version if both specified. @return: The created cluster. """ return clusters.create_cluster(self, name, version, fullVersion)
python
def create_cluster(self, name, version=None, fullVersion=None): return clusters.create_cluster(self, name, version, fullVersion)
[ "def", "create_cluster", "(", "self", ",", "name", ",", "version", "=", "None", ",", "fullVersion", "=", "None", ")", ":", "return", "clusters", ".", "create_cluster", "(", "self", ",", "name", ",", "version", ",", "fullVersion", ")" ]
Create a new cluster. @param name: Cluster name. @param version: Cluster major CDH version, e.g. 'CDH5'. Ignored if fullVersion is specified. @param fullVersion: Complete CDH version, e.g. '5.1.2'. Overrides major version if both specified. @return: The created cluster.
[ "Create", "a", "new", "cluster", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/api_client.py#L103-L114
232,850
cloudera/cm_api
python/src/cm_api/api_client.py
ApiResource.create_host
def create_host(self, host_id, name, ipaddr, rack_id = None): """ Create a host. @param host_id: The host id. @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None. @return: An ApiHost object """ return hosts.create_host(self, host_id, name, ipaddr, rack_id)
python
def create_host(self, host_id, name, ipaddr, rack_id = None): return hosts.create_host(self, host_id, name, ipaddr, rack_id)
[ "def", "create_host", "(", "self", ",", "host_id", ",", "name", ",", "ipaddr", ",", "rack_id", "=", "None", ")", ":", "return", "hosts", ".", "create_host", "(", "self", ",", "host_id", ",", "name", ",", "ipaddr", ",", "rack_id", ")" ]
Create a host. @param host_id: The host id. @param name: Host name @param ipaddr: IP address @param rack_id: Rack id. Default None. @return: An ApiHost object
[ "Create", "a", "host", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/api_client.py#L144-L154
232,851
cloudera/cm_api
python/src/cm_api/api_client.py
ApiResource.get_metrics
def get_metrics(self, path, from_time, to_time, metrics, view, params=None): """ Generic function for querying metrics. @param from_time: A datetime; start of the period to query (optional). @param to_time: A datetime; end of the period to query (default = now). @param metrics: List of metrics to query (default = all). @param view: View to materialize ('full' or 'summary') @param params: Other query parameters. @return: List of metrics and their readings. """ if not params: params = { } if from_time: params['from'] = from_time.isoformat() if to_time: params['to'] = to_time.isoformat() if metrics: params['metrics'] = metrics if view: params['view'] = view resp = self.get(path, params=params) return types.ApiList.from_json_dict(resp, self, types.ApiMetric)
python
def get_metrics(self, path, from_time, to_time, metrics, view, params=None): if not params: params = { } if from_time: params['from'] = from_time.isoformat() if to_time: params['to'] = to_time.isoformat() if metrics: params['metrics'] = metrics if view: params['view'] = view resp = self.get(path, params=params) return types.ApiList.from_json_dict(resp, self, types.ApiMetric)
[ "def", "get_metrics", "(", "self", ",", "path", ",", "from_time", ",", "to_time", ",", "metrics", ",", "view", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "if", "from_time", ":", "params", "[", "'from'",...
Generic function for querying metrics. @param from_time: A datetime; start of the period to query (optional). @param to_time: A datetime; end of the period to query (default = now). @param metrics: List of metrics to query (default = all). @param view: View to materialize ('full' or 'summary') @param params: Other query parameters. @return: List of metrics and their readings.
[ "Generic", "function", "for", "querying", "metrics", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/api_client.py#L263-L285
232,852
cloudera/cm_api
python/src/cm_api/api_client.py
ApiResource.query_timeseries
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False): """ Query time series. @param query: Query string. @param from_time: Start of the period to query (optional). @param to_time: End of the period to query (default = now). @return: A list of ApiTimeSeriesResponse. """ return timeseries.query_timeseries(self, query, from_time, to_time, by_post=by_post)
python
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False): return timeseries.query_timeseries(self, query, from_time, to_time, by_post=by_post)
[ "def", "query_timeseries", "(", "self", ",", "query", ",", "from_time", "=", "None", ",", "to_time", "=", "None", ",", "by_post", "=", "False", ")", ":", "return", "timeseries", ".", "query_timeseries", "(", "self", ",", "query", ",", "from_time", ",", "...
Query time series. @param query: Query string. @param from_time: Start of the period to query (optional). @param to_time: End of the period to query (default = now). @return: A list of ApiTimeSeriesResponse.
[ "Query", "time", "series", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/api_client.py#L287-L295
232,853
cloudera/cm_api
python/src/cm_api/endpoints/tools.py
echo
def echo(root_resource, message): """Have the server echo our message back.""" params = dict(message=message) return root_resource.get(ECHO_PATH, params)
python
def echo(root_resource, message): params = dict(message=message) return root_resource.get(ECHO_PATH, params)
[ "def", "echo", "(", "root_resource", ",", "message", ")", ":", "params", "=", "dict", "(", "message", "=", "message", ")", "return", "root_resource", ".", "get", "(", "ECHO_PATH", ",", "params", ")" ]
Have the server echo our message back.
[ "Have", "the", "server", "echo", "our", "message", "back", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/tools.py#L23-L26
232,854
cloudera/cm_api
python/src/cm_api/endpoints/tools.py
echo_error
def echo_error(root_resource, message): """Generate an error, but we get to set the error message.""" params = dict(message=message) return root_resource.get(ECHO_ERROR_PATH, params)
python
def echo_error(root_resource, message): params = dict(message=message) return root_resource.get(ECHO_ERROR_PATH, params)
[ "def", "echo_error", "(", "root_resource", ",", "message", ")", ":", "params", "=", "dict", "(", "message", "=", "message", ")", "return", "root_resource", ".", "get", "(", "ECHO_ERROR_PATH", ",", "params", ")" ]
Generate an error, but we get to set the error message.
[ "Generate", "an", "error", "but", "we", "get", "to", "set", "the", "error", "message", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/tools.py#L28-L31
232,855
cloudera/cm_api
python/src/cm_shell/cmps.py
ClouderaShell.service_action
def service_action(self, service, action): "Perform given action on service for the selected cluster" try: service = api.get_cluster(self.cluster).get_service(service) except ApiException: print("Service not found") return None if action == "start": service.start() if action == "restart": service.restart() if action == "stop": service.stop() return True
python
def service_action(self, service, action): "Perform given action on service for the selected cluster" try: service = api.get_cluster(self.cluster).get_service(service) except ApiException: print("Service not found") return None if action == "start": service.start() if action == "restart": service.restart() if action == "stop": service.stop() return True
[ "def", "service_action", "(", "self", ",", "service", ",", "action", ")", ":", "try", ":", "service", "=", "api", ".", "get_cluster", "(", "self", ".", "cluster", ")", ".", "get_service", "(", "service", ")", "except", "ApiException", ":", "print", "(", ...
Perform given action on service for the selected cluster
[ "Perform", "given", "action", "on", "service", "for", "the", "selected", "cluster" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_shell/cmps.py#L277-L292
232,856
cloudera/cm_api
python/src/cm_shell/cmps.py
ClouderaShell.cluster_autocomplete
def cluster_autocomplete(self, text, line, start_index, end_index): "autocomplete for the use command, obtain list of clusters first" if not self.CACHED_CLUSTERS: clusters = [cluster.name for cluster in api.get_all_clusters()] self.CACHED_CLUSTERS = clusters if text: return [cluster for cluster in self.CACHED_CLUSTERS if cluster.startswith(text)] else: return self.CACHED_CLUSTERS
python
def cluster_autocomplete(self, text, line, start_index, end_index): "autocomplete for the use command, obtain list of clusters first" if not self.CACHED_CLUSTERS: clusters = [cluster.name for cluster in api.get_all_clusters()] self.CACHED_CLUSTERS = clusters if text: return [cluster for cluster in self.CACHED_CLUSTERS if cluster.startswith(text)] else: return self.CACHED_CLUSTERS
[ "def", "cluster_autocomplete", "(", "self", ",", "text", ",", "line", ",", "start_index", ",", "end_index", ")", ":", "if", "not", "self", ".", "CACHED_CLUSTERS", ":", "clusters", "=", "[", "cluster", ".", "name", "for", "cluster", "in", "api", ".", "get...
autocomplete for the use command, obtain list of clusters first
[ "autocomplete", "for", "the", "use", "command", "obtain", "list", "of", "clusters", "first" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_shell/cmps.py#L370-L379
232,857
cloudera/cm_api
python/src/cm_shell/cmps.py
ClouderaShell.roles_autocomplete
def roles_autocomplete(self, text, line, start_index, end_index): "Return full list of roles" if '-' not in line: # Append a dash to each service, makes for faster autocompletion of # roles return [s + '-' for s in self.services_autocomplete(text, line, start_index, end_index)] else: key, role = line.split()[1].split('-', 1) if key not in self.CACHED_ROLES: service = api.get_cluster(self.cluster).get_service(key) roles = [] for t in service.get_role_types(): for r in service.get_roles_by_type(t): roles.append(r.name) self.CACHED_ROLES[key] = roles if not role: return self.CACHED_ROLES[key] else: return [r for r in self.CACHED_ROLES[key] if r.startswith(line.split()[1])]
python
def roles_autocomplete(self, text, line, start_index, end_index): "Return full list of roles" if '-' not in line: # Append a dash to each service, makes for faster autocompletion of # roles return [s + '-' for s in self.services_autocomplete(text, line, start_index, end_index)] else: key, role = line.split()[1].split('-', 1) if key not in self.CACHED_ROLES: service = api.get_cluster(self.cluster).get_service(key) roles = [] for t in service.get_role_types(): for r in service.get_roles_by_type(t): roles.append(r.name) self.CACHED_ROLES[key] = roles if not role: return self.CACHED_ROLES[key] else: return [r for r in self.CACHED_ROLES[key] if r.startswith(line.split()[1])]
[ "def", "roles_autocomplete", "(", "self", ",", "text", ",", "line", ",", "start_index", ",", "end_index", ")", ":", "if", "'-'", "not", "in", "line", ":", "# Append a dash to each service, makes for faster autocompletion of", "# roles", "return", "[", "s", "+", "'...
Return full list of roles
[ "Return", "full", "list", "of", "roles" ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_shell/cmps.py#L424-L444
232,858
cloudera/cm_api
python/src/cm_api/endpoints/events.py
query_events
def query_events(resource_root, query_str=None): """ Search for events. @param query_str: Query string. @return: A list of ApiEvent. """ params = None if query_str: params = dict(query=query_str) return call(resource_root.get, EVENTS_PATH, ApiEventQueryResult, params=params)
python
def query_events(resource_root, query_str=None): params = None if query_str: params = dict(query=query_str) return call(resource_root.get, EVENTS_PATH, ApiEventQueryResult, params=params)
[ "def", "query_events", "(", "resource_root", ",", "query_str", "=", "None", ")", ":", "params", "=", "None", "if", "query_str", ":", "params", "=", "dict", "(", "query", "=", "query_str", ")", "return", "call", "(", "resource_root", ".", "get", ",", "EVE...
Search for events. @param query_str: Query string. @return: A list of ApiEvent.
[ "Search", "for", "events", "." ]
5d2512375bd94684b4da36df9e0d9177865ffcbb
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/events.py#L23-L33
232,859
ivankorobkov/python-inject
src/inject.py
configure
def configure(config=None, bind_in_runtime=True): """Create an injector with a callable config or raise an exception when already configured.""" global _INJECTOR with _INJECTOR_LOCK: if _INJECTOR: raise InjectorException('Injector is already configured') _INJECTOR = Injector(config, bind_in_runtime=bind_in_runtime) logger.debug('Created and configured an injector, config=%s', config) return _INJECTOR
python
def configure(config=None, bind_in_runtime=True): global _INJECTOR with _INJECTOR_LOCK: if _INJECTOR: raise InjectorException('Injector is already configured') _INJECTOR = Injector(config, bind_in_runtime=bind_in_runtime) logger.debug('Created and configured an injector, config=%s', config) return _INJECTOR
[ "def", "configure", "(", "config", "=", "None", ",", "bind_in_runtime", "=", "True", ")", ":", "global", "_INJECTOR", "with", "_INJECTOR_LOCK", ":", "if", "_INJECTOR", ":", "raise", "InjectorException", "(", "'Injector is already configured'", ")", "_INJECTOR", "=...
Create an injector with a callable config or raise an exception when already configured.
[ "Create", "an", "injector", "with", "a", "callable", "config", "or", "raise", "an", "exception", "when", "already", "configured", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L95-L105
232,860
ivankorobkov/python-inject
src/inject.py
configure_once
def configure_once(config=None, bind_in_runtime=True): """Create an injector with a callable config if not present, otherwise, do nothing.""" with _INJECTOR_LOCK: if _INJECTOR: return _INJECTOR return configure(config, bind_in_runtime=bind_in_runtime)
python
def configure_once(config=None, bind_in_runtime=True): with _INJECTOR_LOCK: if _INJECTOR: return _INJECTOR return configure(config, bind_in_runtime=bind_in_runtime)
[ "def", "configure_once", "(", "config", "=", "None", ",", "bind_in_runtime", "=", "True", ")", ":", "with", "_INJECTOR_LOCK", ":", "if", "_INJECTOR", ":", "return", "_INJECTOR", "return", "configure", "(", "config", ",", "bind_in_runtime", "=", "bind_in_runtime"...
Create an injector with a callable config if not present, otherwise, do nothing.
[ "Create", "an", "injector", "with", "a", "callable", "config", "if", "not", "present", "otherwise", "do", "nothing", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L108-L114
232,861
ivankorobkov/python-inject
src/inject.py
clear_and_configure
def clear_and_configure(config=None, bind_in_runtime=True): """Clear an existing injector and create another one with a callable config.""" with _INJECTOR_LOCK: clear() return configure(config, bind_in_runtime=bind_in_runtime)
python
def clear_and_configure(config=None, bind_in_runtime=True): with _INJECTOR_LOCK: clear() return configure(config, bind_in_runtime=bind_in_runtime)
[ "def", "clear_and_configure", "(", "config", "=", "None", ",", "bind_in_runtime", "=", "True", ")", ":", "with", "_INJECTOR_LOCK", ":", "clear", "(", ")", "return", "configure", "(", "config", ",", "bind_in_runtime", "=", "bind_in_runtime", ")" ]
Clear an existing injector and create another one with a callable config.
[ "Clear", "an", "existing", "injector", "and", "create", "another", "one", "with", "a", "callable", "config", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L117-L121
232,862
ivankorobkov/python-inject
src/inject.py
autoparams
def autoparams(*selected_args): """Return a decorator that will inject args into a function using type annotations, Python >= 3.5 only. For example:: @inject.autoparams() def refresh_cache(cache: RedisCache, db: DbInterface): pass There is an option to specify which arguments we want to inject without attempts of injecting everything: For example:: @inject.autoparams('cache', 'db') def sign_up(name, email, cache, db): pass """ def autoparams_decorator(func): if sys.version_info[:2] < (3, 5): raise InjectorException('autoparams are supported from Python 3.5 onwards') full_args_spec = inspect.getfullargspec(func) annotations_items = full_args_spec.annotations.items() all_arg_names = frozenset(full_args_spec.args + full_args_spec.kwonlyargs) args_to_check = frozenset(selected_args) or all_arg_names args_annotated_types = { arg_name: annotated_type for arg_name, annotated_type in annotations_items if arg_name in args_to_check } return _ParametersInjection(**args_annotated_types)(func) return autoparams_decorator
python
def autoparams(*selected_args): def autoparams_decorator(func): if sys.version_info[:2] < (3, 5): raise InjectorException('autoparams are supported from Python 3.5 onwards') full_args_spec = inspect.getfullargspec(func) annotations_items = full_args_spec.annotations.items() all_arg_names = frozenset(full_args_spec.args + full_args_spec.kwonlyargs) args_to_check = frozenset(selected_args) or all_arg_names args_annotated_types = { arg_name: annotated_type for arg_name, annotated_type in annotations_items if arg_name in args_to_check } return _ParametersInjection(**args_annotated_types)(func) return autoparams_decorator
[ "def", "autoparams", "(", "*", "selected_args", ")", ":", "def", "autoparams_decorator", "(", "func", ")", ":", "if", "sys", ".", "version_info", "[", ":", "2", "]", "<", "(", "3", ",", "5", ")", ":", "raise", "InjectorException", "(", "'autoparams are s...
Return a decorator that will inject args into a function using type annotations, Python >= 3.5 only. For example:: @inject.autoparams() def refresh_cache(cache: RedisCache, db: DbInterface): pass There is an option to specify which arguments we want to inject without attempts of injecting everything: For example:: @inject.autoparams('cache', 'db') def sign_up(name, email, cache, db): pass
[ "Return", "a", "decorator", "that", "will", "inject", "args", "into", "a", "function", "using", "type", "annotations", "Python", ">", "=", "3", ".", "5", "only", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L169-L200
232,863
ivankorobkov/python-inject
src/inject.py
Binder.bind
def bind(self, cls, instance): """Bind a class to an instance.""" self._check_class(cls) self._bindings[cls] = lambda: instance logger.debug('Bound %s to an instance %s', cls, instance) return self
python
def bind(self, cls, instance): self._check_class(cls) self._bindings[cls] = lambda: instance logger.debug('Bound %s to an instance %s', cls, instance) return self
[ "def", "bind", "(", "self", ",", "cls", ",", "instance", ")", ":", "self", ".", "_check_class", "(", "cls", ")", "self", ".", "_bindings", "[", "cls", "]", "=", "lambda", ":", "instance", "logger", ".", "debug", "(", "'Bound %s to an instance %s'", ",", ...
Bind a class to an instance.
[ "Bind", "a", "class", "to", "an", "instance", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L226-L231
232,864
ivankorobkov/python-inject
src/inject.py
Binder.bind_to_constructor
def bind_to_constructor(self, cls, constructor): """Bind a class to a callable singleton constructor.""" self._check_class(cls) if constructor is None: raise InjectorException('Constructor cannot be None, key=%s' % cls) self._bindings[cls] = _ConstructorBinding(constructor) logger.debug('Bound %s to a constructor %s', cls, constructor) return self
python
def bind_to_constructor(self, cls, constructor): self._check_class(cls) if constructor is None: raise InjectorException('Constructor cannot be None, key=%s' % cls) self._bindings[cls] = _ConstructorBinding(constructor) logger.debug('Bound %s to a constructor %s', cls, constructor) return self
[ "def", "bind_to_constructor", "(", "self", ",", "cls", ",", "constructor", ")", ":", "self", ".", "_check_class", "(", "cls", ")", "if", "constructor", "is", "None", ":", "raise", "InjectorException", "(", "'Constructor cannot be None, key=%s'", "%", "cls", ")",...
Bind a class to a callable singleton constructor.
[ "Bind", "a", "class", "to", "a", "callable", "singleton", "constructor", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L233-L241
232,865
ivankorobkov/python-inject
src/inject.py
Binder.bind_to_provider
def bind_to_provider(self, cls, provider): """Bind a class to a callable instance provider executed for each injection.""" self._check_class(cls) if provider is None: raise InjectorException('Provider cannot be None, key=%s' % cls) self._bindings[cls] = provider logger.debug('Bound %s to a provider %s', cls, provider) return self
python
def bind_to_provider(self, cls, provider): self._check_class(cls) if provider is None: raise InjectorException('Provider cannot be None, key=%s' % cls) self._bindings[cls] = provider logger.debug('Bound %s to a provider %s', cls, provider) return self
[ "def", "bind_to_provider", "(", "self", ",", "cls", ",", "provider", ")", ":", "self", ".", "_check_class", "(", "cls", ")", "if", "provider", "is", "None", ":", "raise", "InjectorException", "(", "'Provider cannot be None, key=%s'", "%", "cls", ")", "self", ...
Bind a class to a callable instance provider executed for each injection.
[ "Bind", "a", "class", "to", "a", "callable", "instance", "provider", "executed", "for", "each", "injection", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L243-L251
232,866
ivankorobkov/python-inject
src/inject.py
Injector.get_instance
def get_instance(self, cls): """Return an instance for a class.""" binding = self._bindings.get(cls) if binding: return binding() # Try to create a runtime binding. with _BINDING_LOCK: binding = self._bindings.get(cls) if binding: return binding() if not self._bind_in_runtime: raise InjectorException('No binding was found for key=%s' % cls) if not callable(cls): raise InjectorException( 'Cannot create a runtime binding, the key is not callable, key=%s' % cls) instance = cls() self._bindings[cls] = lambda: instance logger.debug('Created a runtime binding for key=%s, instance=%s', cls, instance) return instance
python
def get_instance(self, cls): binding = self._bindings.get(cls) if binding: return binding() # Try to create a runtime binding. with _BINDING_LOCK: binding = self._bindings.get(cls) if binding: return binding() if not self._bind_in_runtime: raise InjectorException('No binding was found for key=%s' % cls) if not callable(cls): raise InjectorException( 'Cannot create a runtime binding, the key is not callable, key=%s' % cls) instance = cls() self._bindings[cls] = lambda: instance logger.debug('Created a runtime binding for key=%s, instance=%s', cls, instance) return instance
[ "def", "get_instance", "(", "self", ",", "cls", ")", ":", "binding", "=", "self", ".", "_bindings", ".", "get", "(", "cls", ")", "if", "binding", ":", "return", "binding", "(", ")", "# Try to create a runtime binding.", "with", "_BINDING_LOCK", ":", "binding...
Return an instance for a class.
[ "Return", "an", "instance", "for", "a", "class", "." ]
e2f04f91fbcfd0b38e628cbeda97bd8449038d36
https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L271-L294
232,867
theislab/anndata
anndata/readwrite/read.py
read_csv
def read_csv( filename: Union[PathLike, Iterator[str]], delimiter: Optional[str]=',', first_column_names: Optional[bool]=None, dtype: str='float32', ) -> AnnData: """Read ``.csv`` file. Same as :func:`~anndata.read_text` but with default delimiter ``','``. Parameters ---------- filename Data file. delimiter Delimiter that separates data within text file. If ``None``, will split at arbitrary number of white spaces, which is different from enforcing splitting at single white space ``' '``. first_column_names Assume the first column stores row names. dtype Numpy data type. """ return read_text(filename, delimiter, first_column_names, dtype)
python
def read_csv( filename: Union[PathLike, Iterator[str]], delimiter: Optional[str]=',', first_column_names: Optional[bool]=None, dtype: str='float32', ) -> AnnData: return read_text(filename, delimiter, first_column_names, dtype)
[ "def", "read_csv", "(", "filename", ":", "Union", "[", "PathLike", ",", "Iterator", "[", "str", "]", "]", ",", "delimiter", ":", "Optional", "[", "str", "]", "=", "','", ",", "first_column_names", ":", "Optional", "[", "bool", "]", "=", "None", ",", ...
Read ``.csv`` file. Same as :func:`~anndata.read_text` but with default delimiter ``','``. Parameters ---------- filename Data file. delimiter Delimiter that separates data within text file. If ``None``, will split at arbitrary number of white spaces, which is different from enforcing splitting at single white space ``' '``. first_column_names Assume the first column stores row names. dtype Numpy data type.
[ "Read", ".", "csv", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L16-L39
232,868
theislab/anndata
anndata/readwrite/read.py
read_umi_tools
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData: """Read a gzipped condensed count matrix from umi_tools. Parameters ---------- filename File name to read from. """ # import pandas for conversion of a dict of dicts into a matrix # import gzip to read a gzipped file :-) import gzip from pandas import DataFrame dod = {} # this will contain basically everything fh = gzip.open(fspath(filename)) header = fh.readline() # read the first line for line in fh: t = line.decode('ascii').split('\t') # gzip read bytes, hence the decoding try: dod[t[1]].update({t[0]:int(t[2])}) except KeyError: dod[t[1]] = {t[0]:int(t[2])} df = DataFrame.from_dict(dod, orient='index') # build the matrix df.fillna(value=0., inplace=True) # many NaN, replace with zeros return AnnData(np.array(df), {'obs_names': df.index}, {'var_names': df.columns}, dtype=dtype)
python
def read_umi_tools(filename: PathLike, dtype: str='float32') -> AnnData: # import pandas for conversion of a dict of dicts into a matrix # import gzip to read a gzipped file :-) import gzip from pandas import DataFrame dod = {} # this will contain basically everything fh = gzip.open(fspath(filename)) header = fh.readline() # read the first line for line in fh: t = line.decode('ascii').split('\t') # gzip read bytes, hence the decoding try: dod[t[1]].update({t[0]:int(t[2])}) except KeyError: dod[t[1]] = {t[0]:int(t[2])} df = DataFrame.from_dict(dod, orient='index') # build the matrix df.fillna(value=0., inplace=True) # many NaN, replace with zeros return AnnData(np.array(df), {'obs_names': df.index}, {'var_names': df.columns}, dtype=dtype)
[ "def", "read_umi_tools", "(", "filename", ":", "PathLike", ",", "dtype", ":", "str", "=", "'float32'", ")", "->", "AnnData", ":", "# import pandas for conversion of a dict of dicts into a matrix", "# import gzip to read a gzipped file :-)", "import", "gzip", "from", "pandas...
Read a gzipped condensed count matrix from umi_tools. Parameters ---------- filename File name to read from.
[ "Read", "a", "gzipped", "condensed", "count", "matrix", "from", "umi_tools", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L68-L94
232,869
theislab/anndata
anndata/readwrite/read.py
read_loom
def read_loom(filename: PathLike, sparse: bool = True, cleanup: bool = False, X_name: str = 'spliced', obs_names: str = 'CellID', var_names: str = 'Gene', dtype: str='float32', **kwargs) -> AnnData: """Read ``.loom``-formatted hdf5 file. This reads the whole file into memory. Beware that you have to explicitly state when you want to read the file as sparse data. Parameters ---------- filename The filename. sparse Whether to read the data matrix as sparse. cleanup: Whether to remove all obs/var keys that do not store more than one unique value. X_name: Loompy key where the data matrix is stored. obs_names: Loompy key where the observation/cell names are stored. var_names: Loompy key where the variable/gene names are stored. **kwargs: Arguments to loompy.connect """ filename = fspath(filename) # allow passing pathlib.Path objects from loompy import connect with connect(filename, 'r', **kwargs) as lc: if X_name not in lc.layers.keys(): X_name = '' X = lc.layers[X_name].sparse().T.tocsr() if sparse else lc.layers[X_name][()].T layers = OrderedDict() if X_name != '': layers['matrix'] = lc.layers[''].sparse().T.tocsr() if sparse else lc.layers[''][()].T for key in lc.layers.keys(): if key != '': layers[key] = lc.layers[key].sparse().T.tocsr() if sparse else lc.layers[key][()].T obs = dict(lc.col_attrs) if obs_names in obs.keys(): obs['obs_names'] = obs.pop(obs_names) obsm_attrs = [k for k, v in obs.items() if v.ndim > 1 and v.shape[1] > 1] obsm = {} for key in obsm_attrs: obsm[key] = obs.pop(key) var = dict(lc.row_attrs) if var_names in var.keys(): var['var_names'] = var.pop(var_names) varm_attrs = [k for k, v in var.items() if v.ndim > 1 and v.shape[1] > 1] varm = {} for key in varm_attrs: varm[key] = var.pop(key) if cleanup: for key in list(obs.keys()): if len(set(obs[key])) == 1: del obs[key] for key in list(var.keys()): if len(set(var[key])) == 1: del var[key] adata = AnnData( X, obs=obs, # not ideal: make the generator a dict... var=var, layers=layers, obsm=obsm if obsm else None, varm=varm if varm else None, dtype=dtype) return adata
python
def read_loom(filename: PathLike, sparse: bool = True, cleanup: bool = False, X_name: str = 'spliced', obs_names: str = 'CellID', var_names: str = 'Gene', dtype: str='float32', **kwargs) -> AnnData: filename = fspath(filename) # allow passing pathlib.Path objects from loompy import connect with connect(filename, 'r', **kwargs) as lc: if X_name not in lc.layers.keys(): X_name = '' X = lc.layers[X_name].sparse().T.tocsr() if sparse else lc.layers[X_name][()].T layers = OrderedDict() if X_name != '': layers['matrix'] = lc.layers[''].sparse().T.tocsr() if sparse else lc.layers[''][()].T for key in lc.layers.keys(): if key != '': layers[key] = lc.layers[key].sparse().T.tocsr() if sparse else lc.layers[key][()].T obs = dict(lc.col_attrs) if obs_names in obs.keys(): obs['obs_names'] = obs.pop(obs_names) obsm_attrs = [k for k, v in obs.items() if v.ndim > 1 and v.shape[1] > 1] obsm = {} for key in obsm_attrs: obsm[key] = obs.pop(key) var = dict(lc.row_attrs) if var_names in var.keys(): var['var_names'] = var.pop(var_names) varm_attrs = [k for k, v in var.items() if v.ndim > 1 and v.shape[1] > 1] varm = {} for key in varm_attrs: varm[key] = var.pop(key) if cleanup: for key in list(obs.keys()): if len(set(obs[key])) == 1: del obs[key] for key in list(var.keys()): if len(set(var[key])) == 1: del var[key] adata = AnnData( X, obs=obs, # not ideal: make the generator a dict... var=var, layers=layers, obsm=obsm if obsm else None, varm=varm if varm else None, dtype=dtype) return adata
[ "def", "read_loom", "(", "filename", ":", "PathLike", ",", "sparse", ":", "bool", "=", "True", ",", "cleanup", ":", "bool", "=", "False", ",", "X_name", ":", "str", "=", "'spliced'", ",", "obs_names", ":", "str", "=", "'CellID'", ",", "var_names", ":",...
Read ``.loom``-formatted hdf5 file. This reads the whole file into memory. Beware that you have to explicitly state when you want to read the file as sparse data. Parameters ---------- filename The filename. sparse Whether to read the data matrix as sparse. cleanup: Whether to remove all obs/var keys that do not store more than one unique value. X_name: Loompy key where the data matrix is stored. obs_names: Loompy key where the observation/cell names are stored. var_names: Loompy key where the variable/gene names are stored. **kwargs: Arguments to loompy.connect
[ "Read", ".", "loom", "-", "formatted", "hdf5", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L129-L199
232,870
theislab/anndata
anndata/readwrite/read.py
read_mtx
def read_mtx(filename: PathLike, dtype: str='float32') -> AnnData: """Read ``.mtx`` file. Parameters ---------- filename The filename. dtype Numpy data type. """ from scipy.io import mmread # could be rewritten accounting for dtype to be more performant X = mmread(fspath(filename)).astype(dtype) from scipy.sparse import csr_matrix X = csr_matrix(X) return AnnData(X, dtype=dtype)
python
def read_mtx(filename: PathLike, dtype: str='float32') -> AnnData: from scipy.io import mmread # could be rewritten accounting for dtype to be more performant X = mmread(fspath(filename)).astype(dtype) from scipy.sparse import csr_matrix X = csr_matrix(X) return AnnData(X, dtype=dtype)
[ "def", "read_mtx", "(", "filename", ":", "PathLike", ",", "dtype", ":", "str", "=", "'float32'", ")", "->", "AnnData", ":", "from", "scipy", ".", "io", "import", "mmread", "# could be rewritten accounting for dtype to be more performant", "X", "=", "mmread", "(", ...
Read ``.mtx`` file. Parameters ---------- filename The filename. dtype Numpy data type.
[ "Read", ".", "mtx", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L202-L217
232,871
theislab/anndata
anndata/readwrite/read.py
iter_lines
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: """ Helper for iterating only nonempty lines without line breaks""" for line in file_like: line = line.rstrip('\r\n') if line: yield line
python
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: for line in file_like: line = line.rstrip('\r\n') if line: yield line
[ "def", "iter_lines", "(", "file_like", ":", "Iterable", "[", "str", "]", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "for", "line", "in", "file_like", ":", "line", "=", "line", ".", "rstrip", "(", "'\\r\\n'", ")", "if", ...
Helper for iterating only nonempty lines without line breaks
[ "Helper", "for", "iterating", "only", "nonempty", "lines", "without", "line", "breaks" ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L258-L263
232,872
theislab/anndata
anndata/readwrite/read.py
read_zarr
def read_zarr(store): """Read from a hierarchical Zarr array store. Parameters ---------- store The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class. """ if isinstance(store, Path): store = str(store) import zarr f = zarr.open(store, mode='r') d = {} for key in f.keys(): _read_key_value_from_zarr(f, d, key) return AnnData(*AnnData._args_from_dict(d))
python
def read_zarr(store): if isinstance(store, Path): store = str(store) import zarr f = zarr.open(store, mode='r') d = {} for key in f.keys(): _read_key_value_from_zarr(f, d, key) return AnnData(*AnnData._args_from_dict(d))
[ "def", "read_zarr", "(", "store", ")", ":", "if", "isinstance", "(", "store", ",", "Path", ")", ":", "store", "=", "str", "(", "store", ")", "import", "zarr", "f", "=", "zarr", ".", "open", "(", "store", ",", "mode", "=", "'r'", ")", "d", "=", ...
Read from a hierarchical Zarr array store. Parameters ---------- store The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class.
[ "Read", "from", "a", "hierarchical", "Zarr", "array", "store", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L369-L384
232,873
theislab/anndata
anndata/readwrite/read.py
read_h5ad
def read_h5ad(filename, backed: Optional[str] = None, chunk_size: int = 6000): """Read ``.h5ad``-formatted hdf5 file. Parameters ---------- filename File name of data file. backed : {``None``, ``'r'``, ``'r+'``} If ``'r'``, load :class:`~anndata.AnnData` in ``backed`` mode instead of fully loading it into memory (`memory` mode). If you want to modify backed attributes of the AnnData object, you need to choose ``'r+'``. chunk_size Used only when loading sparse dataset that is stored as dense. Loading iterates through chunks of the dataset of this row size until it reads the whole dataset. Higher size means higher memory consumption and higher loading speed. """ if isinstance(backed, bool): # We pass `None`s through to h5py.File, and its default is “a” # (=“r+”, but create the file if it doesn’t exist) backed = 'r+' if backed else None warnings.warn( "In a future version, read_h5ad will no longer explicitly support " "boolean arguments. Specify the read mode, or leave `backed=None`.", DeprecationWarning, ) if backed: # open in backed-mode return AnnData(filename=filename, filemode=backed) else: # load everything into memory constructor_args = _read_args_from_h5ad(filename=filename, chunk_size=chunk_size) X = constructor_args[0] dtype = None if X is not None: dtype = X.dtype.name # maintain dtype, since 0.7 return AnnData(*_read_args_from_h5ad(filename=filename, chunk_size=chunk_size), dtype=dtype)
python
def read_h5ad(filename, backed: Optional[str] = None, chunk_size: int = 6000): if isinstance(backed, bool): # We pass `None`s through to h5py.File, and its default is “a” # (=“r+”, but create the file if it doesn’t exist) backed = 'r+' if backed else None warnings.warn( "In a future version, read_h5ad will no longer explicitly support " "boolean arguments. Specify the read mode, or leave `backed=None`.", DeprecationWarning, ) if backed: # open in backed-mode return AnnData(filename=filename, filemode=backed) else: # load everything into memory constructor_args = _read_args_from_h5ad(filename=filename, chunk_size=chunk_size) X = constructor_args[0] dtype = None if X is not None: dtype = X.dtype.name # maintain dtype, since 0.7 return AnnData(*_read_args_from_h5ad(filename=filename, chunk_size=chunk_size), dtype=dtype)
[ "def", "read_h5ad", "(", "filename", ",", "backed", ":", "Optional", "[", "str", "]", "=", "None", ",", "chunk_size", ":", "int", "=", "6000", ")", ":", "if", "isinstance", "(", "backed", ",", "bool", ")", ":", "# We pass `None`s through to h5py.File, and it...
Read ``.h5ad``-formatted hdf5 file. Parameters ---------- filename File name of data file. backed : {``None``, ``'r'``, ``'r+'``} If ``'r'``, load :class:`~anndata.AnnData` in ``backed`` mode instead of fully loading it into memory (`memory` mode). If you want to modify backed attributes of the AnnData object, you need to choose ``'r+'``. chunk_size Used only when loading sparse dataset that is stored as dense. Loading iterates through chunks of the dataset of this row size until it reads the whole dataset. Higher size means higher memory consumption and higher loading speed.
[ "Read", ".", "h5ad", "-", "formatted", "hdf5", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L427-L463
232,874
theislab/anndata
anndata/readwrite/read.py
_read_args_from_h5ad
def _read_args_from_h5ad( adata: AnnData = None, filename: Optional[PathLike] = None, mode: Optional[str] = None, chunk_size: int = 6000 ): """Return a tuple with the parameters for initializing AnnData. Parameters ---------- filename Defaults to the objects filename if ``None``. """ if filename is None and (adata is None or adata.filename is None): raise ValueError('Need either a filename or an AnnData object with file backing') # we need to be able to call the function without reference to self when # not reading in backed mode backed = mode is not None if filename is None and not backed: filename = adata.filename d = {} if backed: f = adata.file._file else: f = h5py.File(filename, 'r') for key in f.keys(): if backed and key in AnnData._BACKED_ATTRS: d[key] = None else: _read_key_value_from_h5(f, d, key, chunk_size=chunk_size) # backwards compat: save X with the correct name if 'X' not in d: if backed == 'r+': for key in AnnData._H5_ALIASES['X']: if key in d: del f[key] f.create_dataset('X', data=d[key]) break # backwards compat: store sparse matrices properly csr_keys = [key.replace('_csr_data', '') for key in d if '_csr_data' in key] for key in csr_keys: d = load_sparse_csr(d, key=key) if not backed: f.close() return AnnData._args_from_dict(d)
python
def _read_args_from_h5ad( adata: AnnData = None, filename: Optional[PathLike] = None, mode: Optional[str] = None, chunk_size: int = 6000 ): if filename is None and (adata is None or adata.filename is None): raise ValueError('Need either a filename or an AnnData object with file backing') # we need to be able to call the function without reference to self when # not reading in backed mode backed = mode is not None if filename is None and not backed: filename = adata.filename d = {} if backed: f = adata.file._file else: f = h5py.File(filename, 'r') for key in f.keys(): if backed and key in AnnData._BACKED_ATTRS: d[key] = None else: _read_key_value_from_h5(f, d, key, chunk_size=chunk_size) # backwards compat: save X with the correct name if 'X' not in d: if backed == 'r+': for key in AnnData._H5_ALIASES['X']: if key in d: del f[key] f.create_dataset('X', data=d[key]) break # backwards compat: store sparse matrices properly csr_keys = [key.replace('_csr_data', '') for key in d if '_csr_data' in key] for key in csr_keys: d = load_sparse_csr(d, key=key) if not backed: f.close() return AnnData._args_from_dict(d)
[ "def", "_read_args_from_h5ad", "(", "adata", ":", "AnnData", "=", "None", ",", "filename", ":", "Optional", "[", "PathLike", "]", "=", "None", ",", "mode", ":", "Optional", "[", "str", "]", "=", "None", ",", "chunk_size", ":", "int", "=", "6000", ")", ...
Return a tuple with the parameters for initializing AnnData. Parameters ---------- filename Defaults to the objects filename if ``None``.
[ "Return", "a", "tuple", "with", "the", "parameters", "for", "initializing", "AnnData", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/readwrite/read.py#L466-L513
232,875
theislab/anndata
anndata/utils.py
make_index_unique
def make_index_unique(index: pd.Index, join: str = '-'): """Makes the index unique by appending '1', '2', etc. The first occurance of a non-unique value is ignored. Parameters ---------- join The connecting string between name and integer. Examples -------- >>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', 'b', 'c']}) >>> adata2 = sc.AnnData(np.zeros((3, 2)), {'obs_names': ['d', 'b', 'b']}) >>> adata = adata1.concatenate(adata2) >>> adata.obs_names Index(['a', 'b', 'c', 'd', 'b', 'b'], dtype='object') >>> adata.obs_names_make_unique() >>> adata.obs_names Index(['a', 'b', 'c', 'd', 'b-1', 'b-2'], dtype='object') """ if index.is_unique: return index from collections import defaultdict values = index.values indices_dup = index.duplicated(keep='first') values_dup = values[indices_dup] counter = defaultdict(lambda: 0) for i, v in enumerate(values_dup): counter[v] += 1 values_dup[i] += join + str(counter[v]) values[indices_dup] = values_dup index = pd.Index(values) return index
python
def make_index_unique(index: pd.Index, join: str = '-'): if index.is_unique: return index from collections import defaultdict values = index.values indices_dup = index.duplicated(keep='first') values_dup = values[indices_dup] counter = defaultdict(lambda: 0) for i, v in enumerate(values_dup): counter[v] += 1 values_dup[i] += join + str(counter[v]) values[indices_dup] = values_dup index = pd.Index(values) return index
[ "def", "make_index_unique", "(", "index", ":", "pd", ".", "Index", ",", "join", ":", "str", "=", "'-'", ")", ":", "if", "index", ".", "is_unique", ":", "return", "index", "from", "collections", "import", "defaultdict", "values", "=", "index", ".", "value...
Makes the index unique by appending '1', '2', etc. The first occurance of a non-unique value is ignored. Parameters ---------- join The connecting string between name and integer. Examples -------- >>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', 'b', 'c']}) >>> adata2 = sc.AnnData(np.zeros((3, 2)), {'obs_names': ['d', 'b', 'b']}) >>> adata = adata1.concatenate(adata2) >>> adata.obs_names Index(['a', 'b', 'c', 'd', 'b', 'b'], dtype='object') >>> adata.obs_names_make_unique() >>> adata.obs_names Index(['a', 'b', 'c', 'd', 'b-1', 'b-2'], dtype='object')
[ "Makes", "the", "index", "unique", "by", "appending", "1", "2", "etc", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/utils.py#L15-L48
232,876
theislab/anndata
anndata/base.py
_find_corresponding_multicol_key
def _find_corresponding_multicol_key(key, keys_multicol): """Find the corresponding multicolumn key.""" for mk in keys_multicol: if key.startswith(mk) and 'of' in key: return mk return None
python
def _find_corresponding_multicol_key(key, keys_multicol): for mk in keys_multicol: if key.startswith(mk) and 'of' in key: return mk return None
[ "def", "_find_corresponding_multicol_key", "(", "key", ",", "keys_multicol", ")", ":", "for", "mk", "in", "keys_multicol", ":", "if", "key", ".", "startswith", "(", "mk", ")", "and", "'of'", "in", "key", ":", "return", "mk", "return", "None" ]
Find the corresponding multicolumn key.
[ "Find", "the", "corresponding", "multicolumn", "key", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L177-L182
232,877
theislab/anndata
anndata/base.py
_gen_keys_from_multicol_key
def _gen_keys_from_multicol_key(key_multicol, n_keys): """Generates single-column keys from multicolumn key.""" keys = [('{}{:03}of{:03}') .format(key_multicol, i+1, n_keys) for i in range(n_keys)] return keys
python
def _gen_keys_from_multicol_key(key_multicol, n_keys): keys = [('{}{:03}of{:03}') .format(key_multicol, i+1, n_keys) for i in range(n_keys)] return keys
[ "def", "_gen_keys_from_multicol_key", "(", "key_multicol", ",", "n_keys", ")", ":", "keys", "=", "[", "(", "'{}{:03}of{:03}'", ")", ".", "format", "(", "key_multicol", ",", "i", "+", "1", ",", "n_keys", ")", "for", "i", "in", "range", "(", "n_keys", ")",...
Generates single-column keys from multicolumn key.
[ "Generates", "single", "-", "column", "keys", "from", "multicolumn", "key", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L186-L190
232,878
theislab/anndata
anndata/base.py
_check_2d_shape
def _check_2d_shape(X): """Check shape of array or sparse matrix. Assure that X is always 2D: Unlike numpy we always deal with 2D arrays. """ if X.dtype.names is None and len(X.shape) != 2: raise ValueError('X needs to be 2-dimensional, not ' '{}-dimensional.'.format(len(X.shape)))
python
def _check_2d_shape(X): if X.dtype.names is None and len(X.shape) != 2: raise ValueError('X needs to be 2-dimensional, not ' '{}-dimensional.'.format(len(X.shape)))
[ "def", "_check_2d_shape", "(", "X", ")", ":", "if", "X", ".", "dtype", ".", "names", "is", "None", "and", "len", "(", "X", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'X needs to be 2-dimensional, not '", "'{}-dimensional.'", ".", "form...
Check shape of array or sparse matrix. Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.
[ "Check", "shape", "of", "array", "or", "sparse", "matrix", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L225-L232
232,879
theislab/anndata
anndata/base.py
BoundRecArr.to_df
def to_df(self) -> pd.DataFrame: """Convert to pandas dataframe.""" df = pd.DataFrame(index=RangeIndex(0, self.shape[0], name=None)) for key in self.keys(): value = self[key] for icolumn, column in enumerate(value.T): df['{}{}'.format(key, icolumn+1)] = column return df
python
def to_df(self) -> pd.DataFrame: df = pd.DataFrame(index=RangeIndex(0, self.shape[0], name=None)) for key in self.keys(): value = self[key] for icolumn, column in enumerate(value.T): df['{}{}'.format(key, icolumn+1)] = column return df
[ "def", "to_df", "(", "self", ")", "->", "pd", ".", "DataFrame", ":", "df", "=", "pd", ".", "DataFrame", "(", "index", "=", "RangeIndex", "(", "0", ",", "self", ".", "shape", "[", "0", "]", ",", "name", "=", "None", ")", ")", "for", "key", "in",...
Convert to pandas dataframe.
[ "Convert", "to", "pandas", "dataframe", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L166-L173
232,880
theislab/anndata
anndata/base.py
AnnDataFileManager.isopen
def isopen(self) -> bool: """State of backing file.""" if self._file is None: return False # try accessing the id attribute to see if the file is open return bool(self._file.id)
python
def isopen(self) -> bool: if self._file is None: return False # try accessing the id attribute to see if the file is open return bool(self._file.id)
[ "def", "isopen", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_file", "is", "None", ":", "return", "False", "# try accessing the id attribute to see if the file is open", "return", "bool", "(", "self", ".", "_file", ".", "id", ")" ]
State of backing file.
[ "State", "of", "backing", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L366-L371
232,881
theislab/anndata
anndata/base.py
AnnData.transpose
def transpose(self) -> 'AnnData': """Transpose whole object. Data matrix is transposed, observations and variables are interchanged. """ if not self.isbacked: X = self._X else: X = self.file['X'] if self.isview: raise ValueError( 'You\'re trying to transpose a view of an `AnnData`, which is currently not implemented. ' 'Call `.copy()` before transposing.') layers = {k:(v.T.tocsr() if sparse.isspmatrix_csr(v) else v.T) for (k, v) in self.layers.items(copy=False)} if sparse.isspmatrix_csr(X): return AnnData(X.T.tocsr(), self._var, self._obs, self._uns, self._varm.flipped(), self._obsm.flipped(), filename=self.filename, layers=layers, dtype=self.X.dtype.name) return AnnData(X.T, self._var, self._obs, self._uns, self._varm.flipped(), self._obsm.flipped(), filename=self.filename, layers=layers, dtype=self.X.dtype.name)
python
def transpose(self) -> 'AnnData': if not self.isbacked: X = self._X else: X = self.file['X'] if self.isview: raise ValueError( 'You\'re trying to transpose a view of an `AnnData`, which is currently not implemented. ' 'Call `.copy()` before transposing.') layers = {k:(v.T.tocsr() if sparse.isspmatrix_csr(v) else v.T) for (k, v) in self.layers.items(copy=False)} if sparse.isspmatrix_csr(X): return AnnData(X.T.tocsr(), self._var, self._obs, self._uns, self._varm.flipped(), self._obsm.flipped(), filename=self.filename, layers=layers, dtype=self.X.dtype.name) return AnnData(X.T, self._var, self._obs, self._uns, self._varm.flipped(), self._obsm.flipped(), filename=self.filename, layers=layers, dtype=self.X.dtype.name)
[ "def", "transpose", "(", "self", ")", "->", "'AnnData'", ":", "if", "not", "self", ".", "isbacked", ":", "X", "=", "self", ".", "_X", "else", ":", "X", "=", "self", ".", "file", "[", "'X'", "]", "if", "self", ".", "isview", ":", "raise", "ValueEr...
Transpose whole object. Data matrix is transposed, observations and variables are interchanged.
[ "Transpose", "whole", "object", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L1526-L1544
232,882
theislab/anndata
anndata/base.py
AnnData.copy
def copy(self, filename: Optional[PathLike] = None) -> 'AnnData': """Full copy, optionally on disk.""" if not self.isbacked: return AnnData(self._X.copy() if self._X is not None else None, self._obs.copy(), self._var.copy(), # deepcopy on DictView does not work and is unnecessary # as uns was copied already before self._uns.copy() if isinstance(self._uns, DictView) else deepcopy(self._uns), self._obsm.copy(), self._varm.copy(), raw=None if self._raw is None else self._raw.copy(), layers=self.layers.as_dict(), dtype=self._X.dtype.name if self._X is not None else 'float32') else: if filename is None: raise ValueError( 'To copy an AnnData object in backed mode, ' 'pass a filename: `.copy(filename=\'myfilename.h5ad\')`.') if self.isview: self.write(filename) else: from shutil import copyfile copyfile(self.filename, filename) return AnnData(filename=filename)
python
def copy(self, filename: Optional[PathLike] = None) -> 'AnnData': if not self.isbacked: return AnnData(self._X.copy() if self._X is not None else None, self._obs.copy(), self._var.copy(), # deepcopy on DictView does not work and is unnecessary # as uns was copied already before self._uns.copy() if isinstance(self._uns, DictView) else deepcopy(self._uns), self._obsm.copy(), self._varm.copy(), raw=None if self._raw is None else self._raw.copy(), layers=self.layers.as_dict(), dtype=self._X.dtype.name if self._X is not None else 'float32') else: if filename is None: raise ValueError( 'To copy an AnnData object in backed mode, ' 'pass a filename: `.copy(filename=\'myfilename.h5ad\')`.') if self.isview: self.write(filename) else: from shutil import copyfile copyfile(self.filename, filename) return AnnData(filename=filename)
[ "def", "copy", "(", "self", ",", "filename", ":", "Optional", "[", "PathLike", "]", "=", "None", ")", "->", "'AnnData'", ":", "if", "not", "self", ".", "isbacked", ":", "return", "AnnData", "(", "self", ".", "_X", ".", "copy", "(", ")", "if", "self...
Full copy, optionally on disk.
[ "Full", "copy", "optionally", "on", "disk", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L1564-L1587
232,883
theislab/anndata
anndata/base.py
AnnData.write_h5ad
def write_h5ad( self, filename: Optional[PathLike] = None, compression: Optional[str] = None, compression_opts: Union[int, Any] = None, force_dense: Optional[bool] = None ): """Write ``.h5ad``-formatted hdf5 file. .. note:: Setting compression to ``'gzip'`` can save disk space but will slow down writing and subsequent reading. Prior to v0.6.16, this was the default for parameter ``compression``. Generally, if you have sparse data that are stored as a dense matrix, you can dramatically improve performance and reduce disk space by converting to a :class:`~scipy.sparse.csr_matrix`:: from scipy.sparse import csr_matrix adata.X = csr_matrix(adata.X) Parameters ---------- filename Filename of data file. Defaults to backing file. compression : ``None``, {``'gzip'``, ``'lzf'``} (default: ``None``) See the h5py :ref:`dataset_compression`. compression_opts See the h5py :ref:`dataset_compression`. force_dense Write sparse data as a dense matrix. Defaults to ``True`` if object is backed, otherwise to ``False``. """ from .readwrite.write import _write_h5ad if filename is None and not self.isbacked: raise ValueError('Provide a filename!') if filename is None: filename = self.filename if force_dense is None: force_dense = self.isbacked _write_h5ad(filename, self, compression=compression, compression_opts=compression_opts, force_dense=force_dense) if self.isbacked: self.file.close()
python
def write_h5ad( self, filename: Optional[PathLike] = None, compression: Optional[str] = None, compression_opts: Union[int, Any] = None, force_dense: Optional[bool] = None ): from .readwrite.write import _write_h5ad if filename is None and not self.isbacked: raise ValueError('Provide a filename!') if filename is None: filename = self.filename if force_dense is None: force_dense = self.isbacked _write_h5ad(filename, self, compression=compression, compression_opts=compression_opts, force_dense=force_dense) if self.isbacked: self.file.close()
[ "def", "write_h5ad", "(", "self", ",", "filename", ":", "Optional", "[", "PathLike", "]", "=", "None", ",", "compression", ":", "Optional", "[", "str", "]", "=", "None", ",", "compression_opts", ":", "Union", "[", "int", ",", "Any", "]", "=", "None", ...
Write ``.h5ad``-formatted hdf5 file. .. note:: Setting compression to ``'gzip'`` can save disk space but will slow down writing and subsequent reading. Prior to v0.6.16, this was the default for parameter ``compression``. Generally, if you have sparse data that are stored as a dense matrix, you can dramatically improve performance and reduce disk space by converting to a :class:`~scipy.sparse.csr_matrix`:: from scipy.sparse import csr_matrix adata.X = csr_matrix(adata.X) Parameters ---------- filename Filename of data file. Defaults to backing file. compression : ``None``, {``'gzip'``, ``'lzf'``} (default: ``None``) See the h5py :ref:`dataset_compression`. compression_opts See the h5py :ref:`dataset_compression`. force_dense Write sparse data as a dense matrix. Defaults to ``True`` if object is backed, otherwise to ``False``.
[ "Write", ".", "h5ad", "-", "formatted", "hdf5", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L1962-L2010
232,884
theislab/anndata
anndata/base.py
AnnData.write_csvs
def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','): """Write annotation to ``.csv`` files. It is not possible to recover the full :class:`~anndata.AnnData` from the output of this function. Use :meth:`~anndata.AnnData.write` for this. Parameters ---------- dirname Name of directory to which to export. skip_data Skip the data matrix :attr:`X`. sep Separator for the data. """ from .readwrite.write import write_csvs write_csvs(dirname, self, skip_data=skip_data, sep=sep)
python
def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','): from .readwrite.write import write_csvs write_csvs(dirname, self, skip_data=skip_data, sep=sep)
[ "def", "write_csvs", "(", "self", ",", "dirname", ":", "PathLike", ",", "skip_data", ":", "bool", "=", "True", ",", "sep", ":", "str", "=", "','", ")", ":", "from", ".", "readwrite", ".", "write", "import", "write_csvs", "write_csvs", "(", "dirname", "...
Write annotation to ``.csv`` files. It is not possible to recover the full :class:`~anndata.AnnData` from the output of this function. Use :meth:`~anndata.AnnData.write` for this. Parameters ---------- dirname Name of directory to which to export. skip_data Skip the data matrix :attr:`X`. sep Separator for the data.
[ "Write", "annotation", "to", ".", "csv", "files", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2014-L2030
232,885
theislab/anndata
anndata/base.py
AnnData.write_loom
def write_loom(self, filename: PathLike, write_obsm_varm: bool = False): """Write ``.loom``-formatted hdf5 file. Parameters ---------- filename The filename. """ from .readwrite.write import write_loom write_loom(filename, self, write_obsm_varm = write_obsm_varm)
python
def write_loom(self, filename: PathLike, write_obsm_varm: bool = False): from .readwrite.write import write_loom write_loom(filename, self, write_obsm_varm = write_obsm_varm)
[ "def", "write_loom", "(", "self", ",", "filename", ":", "PathLike", ",", "write_obsm_varm", ":", "bool", "=", "False", ")", ":", "from", ".", "readwrite", ".", "write", "import", "write_loom", "write_loom", "(", "filename", ",", "self", ",", "write_obsm_varm...
Write ``.loom``-formatted hdf5 file. Parameters ---------- filename The filename.
[ "Write", ".", "loom", "-", "formatted", "hdf5", "file", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2032-L2041
232,886
theislab/anndata
anndata/base.py
AnnData.write_zarr
def write_zarr( self, store: Union[MutableMapping, PathLike], chunks: Union[bool, int, Tuple[int, ...]], ): """Write a hierarchical Zarr array store. Parameters ---------- store The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class. chunks Chunk shape. """ from .readwrite.write import write_zarr write_zarr(store, self, chunks=chunks)
python
def write_zarr( self, store: Union[MutableMapping, PathLike], chunks: Union[bool, int, Tuple[int, ...]], ): from .readwrite.write import write_zarr write_zarr(store, self, chunks=chunks)
[ "def", "write_zarr", "(", "self", ",", "store", ":", "Union", "[", "MutableMapping", ",", "PathLike", "]", ",", "chunks", ":", "Union", "[", "bool", ",", "int", ",", "Tuple", "[", "int", ",", "...", "]", "]", ",", ")", ":", "from", ".", "readwrite"...
Write a hierarchical Zarr array store. Parameters ---------- store The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class. chunks Chunk shape.
[ "Write", "a", "hierarchical", "Zarr", "array", "store", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2043-L2058
232,887
theislab/anndata
anndata/base.py
AnnData._to_dict_fixed_width_arrays
def _to_dict_fixed_width_arrays(self, var_len_str=True): """A dict of arrays that stores data and annotation. It is sufficient for reconstructing the object. """ self.strings_to_categoricals() obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str) var_rec, uns_var = df_to_records_fixed_width(self._var, var_len_str) layers = self.layers.as_dict() d = { 'X': self._X, 'obs': obs_rec, 'var': var_rec, 'obsm': self._obsm, 'varm': self._varm, 'layers': layers, # add the categories to the unstructured annotation 'uns': {**self._uns, **uns_obs, **uns_var}} if self.raw is not None: self.strings_to_categoricals(self.raw._var) var_rec, uns_var = df_to_records_fixed_width(self.raw._var, var_len_str) d['raw.X'] = self.raw.X d['raw.var'] = var_rec d['raw.varm'] = self.raw.varm d['raw.cat'] = uns_var return d
python
def _to_dict_fixed_width_arrays(self, var_len_str=True): self.strings_to_categoricals() obs_rec, uns_obs = df_to_records_fixed_width(self._obs, var_len_str) var_rec, uns_var = df_to_records_fixed_width(self._var, var_len_str) layers = self.layers.as_dict() d = { 'X': self._X, 'obs': obs_rec, 'var': var_rec, 'obsm': self._obsm, 'varm': self._varm, 'layers': layers, # add the categories to the unstructured annotation 'uns': {**self._uns, **uns_obs, **uns_var}} if self.raw is not None: self.strings_to_categoricals(self.raw._var) var_rec, uns_var = df_to_records_fixed_width(self.raw._var, var_len_str) d['raw.X'] = self.raw.X d['raw.var'] = var_rec d['raw.varm'] = self.raw.varm d['raw.cat'] = uns_var return d
[ "def", "_to_dict_fixed_width_arrays", "(", "self", ",", "var_len_str", "=", "True", ")", ":", "self", ".", "strings_to_categoricals", "(", ")", "obs_rec", ",", "uns_obs", "=", "df_to_records_fixed_width", "(", "self", ".", "_obs", ",", "var_len_str", ")", "var_r...
A dict of arrays that stores data and annotation. It is sufficient for reconstructing the object.
[ "A", "dict", "of", "arrays", "that", "stores", "data", "and", "annotation", "." ]
34f4eb63710628fbc15e7050e5efcac1d7806062
https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2239-L2266
232,888
biocommons/hgvs
hgvs/parser.py
Parser._expose_rule_functions
def _expose_rule_functions(self, expose_all_rules=False): """add parse functions for public grammar rules Defines a function for each public grammar rule, based on introspecting the grammar. For example, the `c_interval` rule is exposed as a method `parse_c_interval` and used like this:: Parser.parse_c_interval('26+2_57-3') -> Interval(...) """ def make_parse_rule_function(rule_name): "builds a wrapper function that parses a string with the specified rule" def rule_fxn(s): try: return self._grammar(s).__getattr__(rule_name)() except ometa.runtime.ParseError as exc: raise HGVSParseError("{s}: char {exc.position}: {reason}".format( s=s, exc=exc, reason=exc.formatReason())) rule_fxn.__doc__ = "parse string s using `%s' rule" % rule_name return rule_fxn exposed_rule_re = re.compile(r"hgvs_(variant|position)|(c|g|m|n|p|r)" r"_(edit|hgvs_position|interval|pos|posedit|variant)") exposed_rules = [ m.replace("rule_", "") for m in dir(self._grammar._grammarClass) if m.startswith("rule_") ] if not expose_all_rules: exposed_rules = [ rule_name for rule_name in exposed_rules if exposed_rule_re.match(rule_name) ] for rule_name in exposed_rules: att_name = "parse_" + rule_name rule_fxn = make_parse_rule_function(rule_name) self.__setattr__(att_name, rule_fxn) self._logger.debug("Exposed {n} rules ({rules})".format( n=len(exposed_rules), rules=", ".join(exposed_rules)))
python
def _expose_rule_functions(self, expose_all_rules=False): def make_parse_rule_function(rule_name): "builds a wrapper function that parses a string with the specified rule" def rule_fxn(s): try: return self._grammar(s).__getattr__(rule_name)() except ometa.runtime.ParseError as exc: raise HGVSParseError("{s}: char {exc.position}: {reason}".format( s=s, exc=exc, reason=exc.formatReason())) rule_fxn.__doc__ = "parse string s using `%s' rule" % rule_name return rule_fxn exposed_rule_re = re.compile(r"hgvs_(variant|position)|(c|g|m|n|p|r)" r"_(edit|hgvs_position|interval|pos|posedit|variant)") exposed_rules = [ m.replace("rule_", "") for m in dir(self._grammar._grammarClass) if m.startswith("rule_") ] if not expose_all_rules: exposed_rules = [ rule_name for rule_name in exposed_rules if exposed_rule_re.match(rule_name) ] for rule_name in exposed_rules: att_name = "parse_" + rule_name rule_fxn = make_parse_rule_function(rule_name) self.__setattr__(att_name, rule_fxn) self._logger.debug("Exposed {n} rules ({rules})".format( n=len(exposed_rules), rules=", ".join(exposed_rules)))
[ "def", "_expose_rule_functions", "(", "self", ",", "expose_all_rules", "=", "False", ")", ":", "def", "make_parse_rule_function", "(", "rule_name", ")", ":", "\"builds a wrapper function that parses a string with the specified rule\"", "def", "rule_fxn", "(", "s", ")", ":...
add parse functions for public grammar rules Defines a function for each public grammar rule, based on introspecting the grammar. For example, the `c_interval` rule is exposed as a method `parse_c_interval` and used like this:: Parser.parse_c_interval('26+2_57-3') -> Interval(...)
[ "add", "parse", "functions", "for", "public", "grammar", "rules" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/parser.py#L114-L153
232,889
biocommons/hgvs
hgvs/utils/context.py
format_sequence
def format_sequence(seq, start=None, end=None, group_size=3): """print seq from [start, end) in groups of size 3 6 9 12 15 | | | | | 2001 AAA BBB CCC DDD EEE """ width = 100 loc_width = 9 sep = " " body_sep = " : " start = start or 0 end = end or len(seq) bw = width - loc_width - len(body_sep) assert group_size <= bw, "group size must be less than available line width" gpl = int((bw + len(sep)) / (group_size + len(sep))) # groups per line gpl = int(gpl / 5) * 5 if gpl > 20 else gpl rpl = group_size * gpl line_fmt = "{{l:>{lw}s}}{body_sep}{{body}}".format(lw=loc_width, body_sep=body_sep) ge_fmt = "{{ge:>{gs}}}".format(gs=group_size) blocks = [] for ls in range(start, end, rpl): le = ls + rpl groups = [ ge_fmt.format(ge=str(gs + group_size)[-group_size + 1:]) for gs in range(ls, le, group_size) ] blocks += [line_fmt.format(l="", body=sep.join(groups)) + "\n"] groups = [seq[gs:min(gs + group_size, end)] for gs in range(ls, le, group_size)] blocks += [line_fmt.format(l=str(ls + 1), body=sep.join(groups)) + "\n"] blocks += ["\n"] return blocks
python
def format_sequence(seq, start=None, end=None, group_size=3): width = 100 loc_width = 9 sep = " " body_sep = " : " start = start or 0 end = end or len(seq) bw = width - loc_width - len(body_sep) assert group_size <= bw, "group size must be less than available line width" gpl = int((bw + len(sep)) / (group_size + len(sep))) # groups per line gpl = int(gpl / 5) * 5 if gpl > 20 else gpl rpl = group_size * gpl line_fmt = "{{l:>{lw}s}}{body_sep}{{body}}".format(lw=loc_width, body_sep=body_sep) ge_fmt = "{{ge:>{gs}}}".format(gs=group_size) blocks = [] for ls in range(start, end, rpl): le = ls + rpl groups = [ ge_fmt.format(ge=str(gs + group_size)[-group_size + 1:]) for gs in range(ls, le, group_size) ] blocks += [line_fmt.format(l="", body=sep.join(groups)) + "\n"] groups = [seq[gs:min(gs + group_size, end)] for gs in range(ls, le, group_size)] blocks += [line_fmt.format(l=str(ls + 1), body=sep.join(groups)) + "\n"] blocks += ["\n"] return blocks
[ "def", "format_sequence", "(", "seq", ",", "start", "=", "None", ",", "end", "=", "None", ",", "group_size", "=", "3", ")", ":", "width", "=", "100", "loc_width", "=", "9", "sep", "=", "\" \"", "body_sep", "=", "\" : \"", "start", "=", "start", "or",...
print seq from [start, end) in groups of size 3 6 9 12 15 | | | | | 2001 AAA BBB CCC DDD EEE
[ "print", "seq", "from", "[", "start", "end", ")", "in", "groups", "of", "size" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/utils/context.py#L182-L222
232,890
biocommons/hgvs
hgvs/dataproviders/ncbi.py
_stage_from_version
def _stage_from_version(version): """return "prd", "stg", or "dev" for the given version string. A value is always returned""" if version: m = re.match(r"^(?P<xyz>\d+\.\d+\.\d+)(?P<extra>.*)", version) if m: return "stg" if m.group("extra") else "prd" return "dev"
python
def _stage_from_version(version): if version: m = re.match(r"^(?P<xyz>\d+\.\d+\.\d+)(?P<extra>.*)", version) if m: return "stg" if m.group("extra") else "prd" return "dev"
[ "def", "_stage_from_version", "(", "version", ")", ":", "if", "version", ":", "m", "=", "re", ".", "match", "(", "r\"^(?P<xyz>\\d+\\.\\d+\\.\\d+)(?P<extra>.*)\"", ",", "version", ")", "if", "m", ":", "return", "\"stg\"", "if", "m", ".", "group", "(", "\"extr...
return "prd", "stg", or "dev" for the given version string. A value is always returned
[ "return", "prd", "stg", "or", "dev", "for", "the", "given", "version", "string", ".", "A", "value", "is", "always", "returned" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/ncbi.py#L25-L31
232,891
biocommons/hgvs
hgvs/dataproviders/ncbi.py
_get_ncbi_db_url
def _get_ncbi_db_url(): """returns NCBI DB URL based on environment variables and code version * if NCBI_DB_URL is set, use that * Otherwise, if _NCBI_URL_KEY is set, use that as the name of a config file entry and use the corresponding URL * Otherwise, """ if "NCBI_DB_URL" in os.environ: return os.environ["NCBI_DB_URL"] if "_NCBI_URL_KEY" in os.environ: url_key = os.environ["_NCBI_URL_KEY"] else: sdlc = _stage_from_version(hgvs.__version__) url_key = "public_{sdlc}".format(sdlc=sdlc) return hgvs.global_config['NCBI'][url_key]
python
def _get_ncbi_db_url(): if "NCBI_DB_URL" in os.environ: return os.environ["NCBI_DB_URL"] if "_NCBI_URL_KEY" in os.environ: url_key = os.environ["_NCBI_URL_KEY"] else: sdlc = _stage_from_version(hgvs.__version__) url_key = "public_{sdlc}".format(sdlc=sdlc) return hgvs.global_config['NCBI'][url_key]
[ "def", "_get_ncbi_db_url", "(", ")", ":", "if", "\"NCBI_DB_URL\"", "in", "os", ".", "environ", ":", "return", "os", ".", "environ", "[", "\"NCBI_DB_URL\"", "]", "if", "\"_NCBI_URL_KEY\"", "in", "os", ".", "environ", ":", "url_key", "=", "os", ".", "environ...
returns NCBI DB URL based on environment variables and code version * if NCBI_DB_URL is set, use that * Otherwise, if _NCBI_URL_KEY is set, use that as the name of a config file entry and use the corresponding URL * Otherwise,
[ "returns", "NCBI", "DB", "URL", "based", "on", "environment", "variables", "and", "code", "version" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/ncbi.py#L34-L52
232,892
biocommons/hgvs
hgvs/dataproviders/ncbi.py
NCBI_postgresql._get_cursor
def _get_cursor(self, n_retries=1): """Returns a context manager for obtained from a single or pooled connection, and sets the PostgreSQL search_path to the schema specified in the connection URL. Although *connections* are threadsafe, *cursors* are bound to connections and are *not* threadsafe. Do not share cursors across threads. Use this funciton like this:: with hdp._get_cursor() as cur: # your code Do not call this function outside a contextmanager. """ n_tries_rem = n_retries + 1 while n_tries_rem > 0: try: conn = self._pool.getconn() if self.pooling else self._conn # autocommit=True obviates closing explicitly conn.autocommit = True cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute("set search_path = {self.url.schema};".format(self=self)) yield cur # contextmanager executes these when context exits cur.close() if self.pooling: self._pool.putconn(conn) break except psycopg2.OperationalError: _logger.warning( "Lost connection to {url}; attempting reconnect".format(url=self.url)) if self.pooling: self._pool.closeall() self._connect() _logger.warning("Reconnected to {url}".format(url=self.url)) n_tries_rem -= 1 else: # N.B. Probably never reached raise HGVSError("Permanently lost connection to {url} ({n} retries)".format( url=self.url, n=n_retries))
python
def _get_cursor(self, n_retries=1): n_tries_rem = n_retries + 1 while n_tries_rem > 0: try: conn = self._pool.getconn() if self.pooling else self._conn # autocommit=True obviates closing explicitly conn.autocommit = True cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute("set search_path = {self.url.schema};".format(self=self)) yield cur # contextmanager executes these when context exits cur.close() if self.pooling: self._pool.putconn(conn) break except psycopg2.OperationalError: _logger.warning( "Lost connection to {url}; attempting reconnect".format(url=self.url)) if self.pooling: self._pool.closeall() self._connect() _logger.warning("Reconnected to {url}".format(url=self.url)) n_tries_rem -= 1 else: # N.B. Probably never reached raise HGVSError("Permanently lost connection to {url} ({n} retries)".format( url=self.url, n=n_retries))
[ "def", "_get_cursor", "(", "self", ",", "n_retries", "=", "1", ")", ":", "n_tries_rem", "=", "n_retries", "+", "1", "while", "n_tries_rem", ">", "0", ":", "try", ":", "conn", "=", "self", ".", "_pool", ".", "getconn", "(", ")", "if", "self", ".", "...
Returns a context manager for obtained from a single or pooled connection, and sets the PostgreSQL search_path to the schema specified in the connection URL. Although *connections* are threadsafe, *cursors* are bound to connections and are *not* threadsafe. Do not share cursors across threads. Use this funciton like this:: with hdp._get_cursor() as cur: # your code Do not call this function outside a contextmanager.
[ "Returns", "a", "context", "manager", "for", "obtained", "from", "a", "single", "or", "pooled", "connection", "and", "sets", "the", "PostgreSQL", "search_path", "to", "the", "schema", "specified", "in", "the", "connection", "URL", "." ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/dataproviders/ncbi.py#L295-L349
232,893
biocommons/hgvs
hgvs/projector.py
Projector.project_interval_forward
def project_interval_forward(self, c_interval): """ project c_interval on the source transcript to the destination transcript :param c_interval: an :class:`hgvs.interval.Interval` object on the source transcript :returns: c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript """ return self.dst_tm.g_to_c(self.src_tm.c_to_g(c_interval))
python
def project_interval_forward(self, c_interval): return self.dst_tm.g_to_c(self.src_tm.c_to_g(c_interval))
[ "def", "project_interval_forward", "(", "self", ",", "c_interval", ")", ":", "return", "self", ".", "dst_tm", ".", "g_to_c", "(", "self", ".", "src_tm", ".", "c_to_g", "(", "c_interval", ")", ")" ]
project c_interval on the source transcript to the destination transcript :param c_interval: an :class:`hgvs.interval.Interval` object on the source transcript :returns: c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript
[ "project", "c_interval", "on", "the", "source", "transcript", "to", "the", "destination", "transcript" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/projector.py#L44-L52
232,894
biocommons/hgvs
hgvs/projector.py
Projector.project_interval_backward
def project_interval_backward(self, c_interval): """ project c_interval on the destination transcript to the source transcript :param c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript :returns: c_interval: an :class:`hgvs.interval.Interval` object on the source transcript """ return self.src_tm.g_to_c(self.dst_tm.c_to_g(c_interval))
python
def project_interval_backward(self, c_interval): return self.src_tm.g_to_c(self.dst_tm.c_to_g(c_interval))
[ "def", "project_interval_backward", "(", "self", ",", "c_interval", ")", ":", "return", "self", ".", "src_tm", ".", "g_to_c", "(", "self", ".", "dst_tm", ".", "c_to_g", "(", "c_interval", ")", ")" ]
project c_interval on the destination transcript to the source transcript :param c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript :returns: c_interval: an :class:`hgvs.interval.Interval` object on the source transcript
[ "project", "c_interval", "on", "the", "destination", "transcript", "to", "the", "source", "transcript" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/projector.py#L54-L62
232,895
biocommons/hgvs
hgvs/variantmapper.py
VariantMapper._convert_edit_check_strand
def _convert_edit_check_strand(strand, edit_in): """ Convert an edit from one type to another, based on the stand and type """ if isinstance(edit_in, hgvs.edit.NARefAlt): if strand == 1: edit_out = copy.deepcopy(edit_in) else: try: # if smells like an int, do nothing # TODO: should use ref_n, right? int(edit_in.ref) ref = edit_in.ref except (ValueError, TypeError): ref = reverse_complement(edit_in.ref) edit_out = hgvs.edit.NARefAlt( ref=ref, alt=reverse_complement(edit_in.alt), ) elif isinstance(edit_in, hgvs.edit.Dup): if strand == 1: edit_out = copy.deepcopy(edit_in) else: edit_out = hgvs.edit.Dup(ref=reverse_complement(edit_in.ref)) elif isinstance(edit_in, hgvs.edit.Inv): if strand == 1: edit_out = copy.deepcopy(edit_in) else: try: int(edit_in.ref) ref = edit_in.ref except (ValueError, TypeError): ref = reverse_complement(edit_in.ref) edit_out = hgvs.edit.Inv(ref=ref) else: raise NotImplementedError("Only NARefAlt/Dup/Inv types are currently implemented") return edit_out
python
def _convert_edit_check_strand(strand, edit_in): if isinstance(edit_in, hgvs.edit.NARefAlt): if strand == 1: edit_out = copy.deepcopy(edit_in) else: try: # if smells like an int, do nothing # TODO: should use ref_n, right? int(edit_in.ref) ref = edit_in.ref except (ValueError, TypeError): ref = reverse_complement(edit_in.ref) edit_out = hgvs.edit.NARefAlt( ref=ref, alt=reverse_complement(edit_in.alt), ) elif isinstance(edit_in, hgvs.edit.Dup): if strand == 1: edit_out = copy.deepcopy(edit_in) else: edit_out = hgvs.edit.Dup(ref=reverse_complement(edit_in.ref)) elif isinstance(edit_in, hgvs.edit.Inv): if strand == 1: edit_out = copy.deepcopy(edit_in) else: try: int(edit_in.ref) ref = edit_in.ref except (ValueError, TypeError): ref = reverse_complement(edit_in.ref) edit_out = hgvs.edit.Inv(ref=ref) else: raise NotImplementedError("Only NARefAlt/Dup/Inv types are currently implemented") return edit_out
[ "def", "_convert_edit_check_strand", "(", "strand", ",", "edit_in", ")", ":", "if", "isinstance", "(", "edit_in", ",", "hgvs", ".", "edit", ".", "NARefAlt", ")", ":", "if", "strand", "==", "1", ":", "edit_out", "=", "copy", ".", "deepcopy", "(", "edit_in...
Convert an edit from one type to another, based on the stand and type
[ "Convert", "an", "edit", "from", "one", "type", "to", "another", "based", "on", "the", "stand", "and", "type" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/variantmapper.py#L457-L493
232,896
biocommons/hgvs
hgvs/assemblymapper.py
AssemblyMapper.t_to_p
def t_to_p(self, var_t): """Return a protein variant, or "non-coding" for non-coding variant types CAUTION: Unlike other x_to_y methods that always return SequenceVariant instances, this method returns a string when the variant type is ``n``. This is intended as a convenience, particularly when looping over ``relevant_transcripts``, projecting with ``g_to_t``, then desiring a protein representation for coding transcripts. """ if var_t.type == "n": return "non-coding" if var_t.type == "c": return self.c_to_p(var_t) raise HGVSInvalidVariantError("Expected a coding (c.) or non-coding (n.) variant; got " + str(var_t))
python
def t_to_p(self, var_t): if var_t.type == "n": return "non-coding" if var_t.type == "c": return self.c_to_p(var_t) raise HGVSInvalidVariantError("Expected a coding (c.) or non-coding (n.) variant; got " + str(var_t))
[ "def", "t_to_p", "(", "self", ",", "var_t", ")", ":", "if", "var_t", ".", "type", "==", "\"n\"", ":", "return", "\"non-coding\"", "if", "var_t", ".", "type", "==", "\"c\"", ":", "return", "self", ".", "c_to_p", "(", "var_t", ")", "raise", "HGVSInvalidV...
Return a protein variant, or "non-coding" for non-coding variant types CAUTION: Unlike other x_to_y methods that always return SequenceVariant instances, this method returns a string when the variant type is ``n``. This is intended as a convenience, particularly when looping over ``relevant_transcripts``, projecting with ``g_to_t``, then desiring a protein representation for coding transcripts.
[ "Return", "a", "protein", "variant", "or", "non", "-", "coding", "for", "non", "-", "coding", "variant", "types" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/assemblymapper.py#L124-L140
232,897
biocommons/hgvs
hgvs/assemblymapper.py
AssemblyMapper._fetch_AlignmentMapper
def _fetch_AlignmentMapper(self, tx_ac, alt_ac=None, alt_aln_method=None): """convenience version of VariantMapper._fetch_AlignmentMapper that derives alt_ac from transcript, assembly, and alt_aln_method used to instantiate the AssemblyMapper instance """ if alt_ac is None: alt_ac = self._alt_ac_for_tx_ac(tx_ac) if alt_aln_method is None: alt_aln_method = self.alt_aln_method return super(AssemblyMapper, self)._fetch_AlignmentMapper(tx_ac, alt_ac, alt_aln_method)
python
def _fetch_AlignmentMapper(self, tx_ac, alt_ac=None, alt_aln_method=None): if alt_ac is None: alt_ac = self._alt_ac_for_tx_ac(tx_ac) if alt_aln_method is None: alt_aln_method = self.alt_aln_method return super(AssemblyMapper, self)._fetch_AlignmentMapper(tx_ac, alt_ac, alt_aln_method)
[ "def", "_fetch_AlignmentMapper", "(", "self", ",", "tx_ac", ",", "alt_ac", "=", "None", ",", "alt_aln_method", "=", "None", ")", ":", "if", "alt_ac", "is", "None", ":", "alt_ac", "=", "self", ".", "_alt_ac_for_tx_ac", "(", "tx_ac", ")", "if", "alt_aln_meth...
convenience version of VariantMapper._fetch_AlignmentMapper that derives alt_ac from transcript, assembly, and alt_aln_method used to instantiate the AssemblyMapper instance
[ "convenience", "version", "of", "VariantMapper", ".", "_fetch_AlignmentMapper", "that", "derives", "alt_ac", "from", "transcript", "assembly", "and", "alt_aln_method", "used", "to", "instantiate", "the", "AssemblyMapper", "instance" ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/assemblymapper.py#L208-L219
232,898
biocommons/hgvs
hgvs/assemblymapper.py
AssemblyMapper._maybe_normalize
def _maybe_normalize(self, var): """normalize variant if requested, and ignore HGVSUnsupportedOperationError This is better than checking whether the variant is intronic because future UTAs will support LRG, which will enable checking intronic variants. """ if self.normalize: try: return self._norm.normalize(var) except HGVSUnsupportedOperationError as e: _logger.warning(str(e) + "; returning unnormalized variant") # fall through to return unnormalized variant return var
python
def _maybe_normalize(self, var): if self.normalize: try: return self._norm.normalize(var) except HGVSUnsupportedOperationError as e: _logger.warning(str(e) + "; returning unnormalized variant") # fall through to return unnormalized variant return var
[ "def", "_maybe_normalize", "(", "self", ",", "var", ")", ":", "if", "self", ".", "normalize", ":", "try", ":", "return", "self", ".", "_norm", ".", "normalize", "(", "var", ")", "except", "HGVSUnsupportedOperationError", "as", "e", ":", "_logger", ".", "...
normalize variant if requested, and ignore HGVSUnsupportedOperationError This is better than checking whether the variant is intronic because future UTAs will support LRG, which will enable checking intronic variants.
[ "normalize", "variant", "if", "requested", "and", "ignore", "HGVSUnsupportedOperationError", "This", "is", "better", "than", "checking", "whether", "the", "variant", "is", "intronic", "because", "future", "UTAs", "will", "support", "LRG", "which", "will", "enable", ...
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/assemblymapper.py#L221-L232
232,899
biocommons/hgvs
hgvs/alignmentmapper.py
AlignmentMapper._parse_cigar
def _parse_cigar(self, cigar): """For a given CIGAR string, return the start positions of each aligned segment in ref and tgt, and a list of CIGAR operators. """ ces = [m.groupdict() for m in cigar_re.finditer(cigar)] ref_pos = [None] * len(ces) tgt_pos = [None] * len(ces) cigar_op = [None] * len(ces) ref_cur = tgt_cur = 0 for i, ce in enumerate(ces): ref_pos[i] = ref_cur tgt_pos[i] = tgt_cur cigar_op[i] = ce["op"] step = int(ce["len"]) if ce["op"] in "=MINX": ref_cur += step if ce["op"] in "=MDX": tgt_cur += step ref_pos.append(ref_cur) tgt_pos.append(tgt_cur) return ref_pos, tgt_pos, cigar_op
python
def _parse_cigar(self, cigar): ces = [m.groupdict() for m in cigar_re.finditer(cigar)] ref_pos = [None] * len(ces) tgt_pos = [None] * len(ces) cigar_op = [None] * len(ces) ref_cur = tgt_cur = 0 for i, ce in enumerate(ces): ref_pos[i] = ref_cur tgt_pos[i] = tgt_cur cigar_op[i] = ce["op"] step = int(ce["len"]) if ce["op"] in "=MINX": ref_cur += step if ce["op"] in "=MDX": tgt_cur += step ref_pos.append(ref_cur) tgt_pos.append(tgt_cur) return ref_pos, tgt_pos, cigar_op
[ "def", "_parse_cigar", "(", "self", ",", "cigar", ")", ":", "ces", "=", "[", "m", ".", "groupdict", "(", ")", "for", "m", "in", "cigar_re", ".", "finditer", "(", "cigar", ")", "]", "ref_pos", "=", "[", "None", "]", "*", "len", "(", "ces", ")", ...
For a given CIGAR string, return the start positions of each aligned segment in ref and tgt, and a list of CIGAR operators.
[ "For", "a", "given", "CIGAR", "string", "return", "the", "start", "positions", "of", "each", "aligned", "segment", "in", "ref", "and", "tgt", "and", "a", "list", "of", "CIGAR", "operators", "." ]
4d16efb475e1802b2531a2f1c373e8819d8e533b
https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/alignmentmapper.py#L93-L113