sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def getParam(self, name=None): """ Function getParam Return a dict of parameters or a parameter value @param key: The parameter name @return RETURN: dict of parameters or a parameter value """ if 'parameters' in self.keys(): l = {x['name']: x['value'] for x i...
Function getParam Return a dict of parameters or a parameter value @param key: The parameter name @return RETURN: dict of parameters or a parameter value
entailment
def checkAndCreateClasses(self, classes): """ Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @return RETURN: boolean """ actual_classes = self['puppetclasses'].keys() for i in classes: if i not in actual...
Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @return RETURN: boolean
entailment
def checkAndCreateParams(self, params): """ Function checkAndCreateParams Check and add global parameters @param key: The parameter name @param params: The params dict @return RETURN: boolean """ actual_params = self['parameters'].keys() for k, v in param...
Function checkAndCreateParams Check and add global parameters @param key: The parameter name @param params: The params dict @return RETURN: boolean
entailment
def version_dict(version): """Turn a version string into a dict with major/minor/... info.""" match = version_re.match(str(version) or '') letters = 'alpha pre'.split() numbers = 'major minor1 minor2 minor3 alpha_ver pre_ver'.split() if match: d = match.groupdict() for letter in lett...
Turn a version string into a dict with major/minor/... info.
entailment
def get_diff(source, dest): """Get the diff between two records list in this order: - to_create - to_delete """ # First build a dict from the lists, with the ID as the key. source_dict = {record['id']: record for record in source} dest_dict = {record['id']: record for record in dest}...
Get the diff between two records list in this order: - to_create - to_delete
entailment
def object_version_choices(obj): """ Return a list of form choices for versions of this object which can be published. """ choices = BLANK_CHOICE_DASH + [(PublishAction.UNPUBLISH_CHOICE, 'Unpublish current version')] # When creating a new object in the Django admin - obj will be None if obj is ...
Return a list of form choices for versions of this object which can be published.
entailment
def manifest(self, values, *paths, filename: str = None) -> Dict: """Load a manifest file and apply template values """ filename = filename or self.filename(*paths) with open(filename, 'r') as fp: template = Template(fp.read()) return yaml.load(template.render(values)...
Load a manifest file and apply template values
entailment
def set_packet_headers(self, headers): """ Set packet header. The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet header byte sequence specified with PS_PACKETHEADER. This is mainly for information purposes, and the stream will tran...
Set packet header. The method will try to set ps_headerprotocol to inform the Xena GUI and tester how to interpret the packet header byte sequence specified with PS_PACKETHEADER. This is mainly for information purposes, and the stream will transmit the packet header bytes even if no pro...
entailment
def add_modifier(self, m_type=XenaModifierType.standard, **kwargs): """ Add modifier. :param m_type: modifier type - standard or extended. :type: xenamanager.xena_stram.ModifierType :return: newly created modifier. :rtype: xenamanager.xena_stream.XenaModifier """ ...
Add modifier. :param m_type: modifier type - standard or extended. :type: xenamanager.xena_stram.ModifierType :return: newly created modifier. :rtype: xenamanager.xena_stream.XenaModifier
entailment
def remove_modifier(self, index, m_type=XenaModifierType.standard): """ Remove modifier. :param m_type: modifier type - standard or extended. :param index: index of modifier to remove. """ if m_type == XenaModifierType.standard: current_modifiers = OrderedDict(self....
Remove modifier. :param m_type: modifier type - standard or extended. :param index: index of modifier to remove.
entailment
def modifiers(self): """ :return: dictionary {index: object} of standard modifiers. """ if not self.get_objects_by_type('modifier'): for index in range(int(self.get_attribute('ps_modifiercount'))): XenaModifier(self, index='{}/{}'.format(self.index, index)).ge...
:return: dictionary {index: object} of standard modifiers.
entailment
def xmodifiers(self): """ :return: dictionary {index: object} of extended modifiers. """ if not self.get_objects_by_type('xmodifier'): try: for index in range(int(self.get_attribute('ps_modifierextcount'))): XenaXModifier(self, index='{}/{}...
:return: dictionary {index: object} of extended modifiers.
entailment
def DRAGONS(flat=False, extras=True): """DRAGONS cosmology assumes WMAP7 + BAO + H_0 mean from Komatsu et al. (2011) ApJS 192 18K (arxiv:1001.4538v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k_0 =...
DRAGONS cosmology assumes WMAP7 + BAO + H_0 mean from Komatsu et al. (2011) ApJS 192 18K (arxiv:1001.4538v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k_0 = 0 explicitly. extras: boolean If...
entailment
def Planck_2015(flat=False, extras=True): """Planck 2015 XII: Cosmological parameters Table 4 column Planck TT, TE, EE + lowP + lensing + ext from Ade et al. (2015) A&A in press (arxiv:1502.01589v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensu...
Planck 2015 XII: Cosmological parameters Table 4 column Planck TT, TE, EE + lowP + lensing + ext from Ade et al. (2015) A&A in press (arxiv:1502.01589v1) Parameters ---------- flat: boolean If True, sets omega_lambda_0 = 1 - omega_M_0 to ensure omega_k_0 = 0 exactly. Also sets omega_k...
entailment
def add(self, dn: str, mod_list: dict) -> None: """ Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ return self._do_with_retry(lambda obj: obj.add_s(dn, mod_list))
Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
entailment
def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ return self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list))
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
entailment
def delete(self, dn: str) -> None: """ delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ return self._do_with_retry(lambda obj: obj.delete_s(dn))
delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
entailment
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ return self._do_with_retry( lambda obj: obj.rename_s(dn, new_rdn, new_base_...
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
entailment
def get_column_name(self, column_name): """ Get a column for given column name from META api. """ name = pretty_name(column_name) if column_name in self._meta.columns: column_cls = self._meta.columns[column_name] if column_cls.verbose_name: name = column_c...
Get a column for given column name from META api.
entailment
def version(self): """Software version of the current repository """ branches = self.branches() if self.info['branch'] == branches.sandbox: try: return self.software_version() except Exception as exc: raise utils.CommandError( ...
Software version of the current repository
entailment
def validate_version(self, prefix='v'): """Validate version by checking if it is a valid semantic version and its value is higher than latest github tag """ version = self.software_version() repo = self.github_repo() repo.releases.validate_tag(version, prefix) ret...
Validate version by checking if it is a valid semantic version and its value is higher than latest github tag
entailment
def skip_build(self): """Check if build should be skipped """ skip_msg = self.config.get('skip', '[ci skip]') return ( os.environ.get('CODEBUILD_BUILD_SUCCEEDING') == '0' or self.info['current_tag'] or skip_msg in self.info['head']['message'] )
Check if build should be skipped
entailment
def message(self, msg): """Send a message to third party applications """ for broker in self.message_brokers: try: broker(msg) except Exception as exc: utils.error(exc)
Send a message to third party applications
entailment
def get_kinto_records(kinto_client, bucket, collection, permissions, config=None): """Return all the kinto records for this bucket/collection.""" # Create bucket if needed try: kinto_client.create_bucket(id=bucket, if_not_exists=True) except KintoException as e: if ...
Return all the kinto records for this bucket/collection.
entailment
def add_chassis(self, chassis): """ :param ip: chassis object """ self.chassis_list[chassis] = XenaSocket(self.logger, chassis.ip, chassis.port) self.chassis_list[chassis].connect() KeepAliveThread(self.chassis_list[chassis]).start() self.send_command(chassis, 'c...
:param ip: chassis object
entailment
def send_command(self, obj, command, *arguments): """ Send command and do not parse output (except for communication errors). :param obj: requested object. :param command: command to send. :param arguments: list of command arguments. """ index_command = obj._build_index_...
Send command and do not parse output (except for communication errors). :param obj: requested object. :param command: command to send. :param arguments: list of command arguments.
entailment
def send_command_return(self, obj, command, *arguments): """ Send command and wait for single line output. """ index_command = obj._build_index_command(command, *arguments) return obj._extract_return(command, self.chassis_list[obj.chassis].sendQuery(index_command))
Send command and wait for single line output.
entailment
def send_command_return_multilines(self, obj, command, *arguments): """ Send command and wait for multiple lines output. """ index_command = obj._build_index_command(command, *arguments) return self.chassis_list[obj.chassis].sendQuery(index_command, True)
Send command and wait for multiple lines output.
entailment
def get_attribute(self, obj, attribute): """ Returns single object attribute. :param obj: requested object. :param attribute: requested attribute to query. :returns: returned value. :rtype: str """ raw_return = self.send_command_return(obj, attribute, '?') ...
Returns single object attribute. :param obj: requested object. :param attribute: requested attribute to query. :returns: returned value. :rtype: str
entailment
def get_attributes(self, obj): """ Get all object's attributes. Sends multi-parameter info/config queries and returns the result as dictionary. :param obj: requested object. :returns: dictionary of <name, value> of all attributes returned by the query. :rtype: dict of (str, str...
Get all object's attributes. Sends multi-parameter info/config queries and returns the result as dictionary. :param obj: requested object. :returns: dictionary of <name, value> of all attributes returned by the query. :rtype: dict of (str, str)
entailment
def set_attributes(self, obj, **attributes): """ Set attributes. :param obj: requested object. :param attributes: dictionary of {attribute: value} to set """ for attribute, value in attributes.items(): self.send_command(obj, attribute, value)
Set attributes. :param obj: requested object. :param attributes: dictionary of {attribute: value} to set
entailment
def get_stats(self, obj, stat_name): """ Send CLI command that returns list of integer counters. :param obj: requested object. :param stat_name: statistics command name. :return: list of counters. :rtype: list(int) """ return [int(v) for v in self.get_attribute(o...
Send CLI command that returns list of integer counters. :param obj: requested object. :param stat_name: statistics command name. :return: list of counters. :rtype: list(int)
entailment
def depth_first(self, top_down=True): """ Iterate depth-first. :: >>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode >>> root_container = UniqueTreeContainer(name="root") >>> outer_container = UniqueTreeContainer(name="outer") >...
Iterate depth-first. :: >>> from uqbar.containers import UniqueTreeContainer, UniqueTreeNode >>> root_container = UniqueTreeContainer(name="root") >>> outer_container = UniqueTreeContainer(name="outer") >>> inner_container = UniqueTreeContainer(name="inner") ...
entailment
def reserve(self, force=False): """ Reserve port. XenaManager-2G -> Reserve/Relinquish Port. :param force: True - take forcefully, False - fail if port is reserved by other user """ p_reservation = self.get_attribute('p_reservation') if p_reservation == 'RESERVED_BY_YO...
Reserve port. XenaManager-2G -> Reserve/Relinquish Port. :param force: True - take forcefully, False - fail if port is reserved by other user
entailment
def load_config(self, config_file_name): """ Load configuration file from xpc file. :param config_file_name: full path to the configuration file. """ with open(config_file_name) as f: commands = f.read().splitlines() for command in commands: if not comm...
Load configuration file from xpc file. :param config_file_name: full path to the configuration file.
entailment
def save_config(self, config_file_name): """ Save configuration file to xpc file. :param config_file_name: full path to the configuration file. """ with open(config_file_name, 'w+') as f: f.write('P_RESET\n') for line in self.send_command_return_multilines('p_fu...
Save configuration file to xpc file. :param config_file_name: full path to the configuration file.
entailment
def add_stream(self, name=None, tpld_id=None, state=XenaStreamState.enabled): """ Add stream. :param name: stream description. :param tpld_id: TPLD ID. If None the a unique value will be set. :param state: new stream state. :type state: xenamanager.xena_stream.XenaStreamState ...
Add stream. :param name: stream description. :param tpld_id: TPLD ID. If None the a unique value will be set. :param state: new stream state. :type state: xenamanager.xena_stream.XenaStreamState :return: newly created stream. :rtype: xenamanager.xena_stream.XenaStream
entailment
def read_port_stats(self): """ :return: dictionary {group name {stat name: value}}. Sea XenaPort.stats_captions. """ stats_with_captions = OrderedDict() for stat_name in self.stats_captions.keys(): stats_with_captions[stat_name] = self.read_stat(self.stat...
:return: dictionary {group name {stat name: value}}. Sea XenaPort.stats_captions.
entailment
def read_stream_stats(self): """ :return: dictionary {stream index {stat name: value}}. Sea XenaStream.stats_captions. """ stream_stats = OrderedDict() for stream in self.streams.values(): stream_stats[stream] = stream.read_stats() return stream_st...
:return: dictionary {stream index {stat name: value}}. Sea XenaStream.stats_captions.
entailment
def read_tpld_stats(self): """ :return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions. """ payloads_stats = OrderedDict() for tpld in self.tplds.values(): payloads_stats[tpld] = tpld.read_stats() return payloa...
:return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions.
entailment
def streams(self): """ :return: dictionary {id: object} of all streams. :rtype: dict of (int, xenamanager.xena_stream.XenaStream) """ if not self.get_objects_by_type('stream'): tpld_ids = [] for index in self.get_attribute('ps_indices').split(): ...
:return: dictionary {id: object} of all streams. :rtype: dict of (int, xenamanager.xena_stream.XenaStream)
entailment
def tplds(self): """ :return: dictionary {id: object} of all current tplds. :rtype: dict of (int, xenamanager.xena_port.XenaTpld) """ # As TPLDs are dynamic we must re-read them each time from the port. self.parent.del_objects_by_type('tpld') for tpld in self.get...
:return: dictionary {id: object} of all current tplds. :rtype: dict of (int, xenamanager.xena_port.XenaTpld)
entailment
def read_stats(self): """ :return: dictionary {group name {stat name: value}}. Sea XenaTpld.stats_captions. """ stats_with_captions = OrderedDict() for stat_name in self.stats_captions.keys(): stats_with_captions[stat_name] = self.read_stat(self.stats_cap...
:return: dictionary {group name {stat name: value}}. Sea XenaTpld.stats_captions.
entailment
def get_packets(self, from_index=0, to_index=None, cap_type=XenaCaptureBufferType.text, file_name=None, tshark=None): """ Get captured packets from chassis. :param from_index: index of first packet to read. :param to_index: index of last packet to read. If None - read all pa...
Get captured packets from chassis. :param from_index: index of first packet to read. :param to_index: index of last packet to read. If None - read all packets. :param cap_type: returned capture format. If pcap then file name and tshark must be provided. :param file_name: if specified, c...
entailment
def packets(self): """ :return: dictionary {id: object} of all packets. :rtype: dict of (int, xenamanager.xena_port.XenaCapturePacket) """ if not self.get_object_by_type('cappacket'): for index in range(0, self.read_stats()['packets']): XenaCapturePac...
:return: dictionary {id: object} of all packets. :rtype: dict of (int, xenamanager.xena_port.XenaCapturePacket)
entailment
def add(self, rule: ControlRule = None, *, supply: float): """ Register a new rule above a given ``supply`` threshold Registration supports a single-argument form for use as a decorator, as well as a two-argument form for direct application. Use the former for ``def`` or ``class...
Register a new rule above a given ``supply`` threshold Registration supports a single-argument form for use as a decorator, as well as a two-argument form for direct application. Use the former for ``def`` or ``class`` definitions, and the later for ``lambda`` functions and existing cal...
entailment
def s(self, *args, **kwargs) -> Partial[Stepwise]: """ Create an unbound prototype of this class, partially applying arguments .. code:: python @stepwise def control(pool: Pool, interval): return 10 pipeline = control.s(interval=20) >> pool ...
Create an unbound prototype of this class, partially applying arguments .. code:: python @stepwise def control(pool: Pool, interval): return 10 pipeline = control.s(interval=20) >> pool :note: The partial rules are sealed, and :py:meth:`~.UnboundSt...
entailment
def revisionId(self): """ revisionId differs from id, it is details of implementation use self.id :return: RevisionId """ log.warning("'RevisionId' requested, ensure that you are don't need 'id'") revision_id = self.json()['revisionId'] assert revision_id == self....
revisionId differs from id, it is details of implementation use self.id :return: RevisionId
entailment
def changeset(python_data: LdapObject, d: dict) -> Changeset: """ Generate changes object for ldap object. """ table: LdapObjectClass = type(python_data) fields = table.get_fields() changes = Changeset(fields, src=python_data, d=d) return changes
Generate changes object for ldap object.
entailment
def _db_to_python(db_data: dict, table: LdapObjectClass, dn: str) -> LdapObject: """ Convert a DbDate object to a LdapObject. """ fields = table.get_fields() python_data = table({ name: field.to_python(db_data[name]) for name, field in fields.items() if field.db_field }) pyt...
Convert a DbDate object to a LdapObject.
entailment
def _python_to_mod_new(changes: Changeset) -> Dict[str, List[List[bytes]]]: """ Convert a LdapChanges object to a modlist for add operation. """ table: LdapObjectClass = type(changes.src) fields = table.get_fields() result: Dict[str, List[List[bytes]]] = {} for name, field in fields.items(): ...
Convert a LdapChanges object to a modlist for add operation.
entailment
def _python_to_mod_modify(changes: Changeset) -> Dict[str, List[Tuple[Operation, List[bytes]]]]: """ Convert a LdapChanges object to a modlist for a modify operation. """ table: LdapObjectClass = type(changes.src) changes = changes.changes result: Dict[str, List[Tuple[Operation, List[bytes]]]] = {} ...
Convert a LdapChanges object to a modlist for a modify operation.
entailment
def search(table: LdapObjectClass, query: Optional[Q] = None, database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]: """ Search for a object of given type in the database. """ fields = table.get_fields() db_fields = { name: field for name, fie...
Search for a object of given type in the database.
entailment
def get_one(table: LdapObjectClass, query: Optional[Q] = None, database: Optional[Database] = None, base_dn: Optional[str] = None) -> LdapObject: """ Get exactly one result from the database or fail. """ results = search(table, query, database, base_dn) try: result = next(results) e...
Get exactly one result from the database or fail.
entailment
def preload(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject: """ Preload all NotLoaded fields in LdapObject. """ changes = {} # Load objects within lists. def preload_item(value: Any) -> Any: if isinstance(value, NotLoaded): return value.load(database) ...
Preload all NotLoaded fields in LdapObject.
entailment
def insert(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject: """ Insert a new python_data object in the database. """ assert isinstance(python_data, LdapObject) table: LdapObjectClass = type(python_data) # ADD NEW ENTRY empty_data = table() changes = changeset(empty_...
Insert a new python_data object in the database.
entailment
def save(changes: Changeset, database: Optional[Database] = None) -> LdapObject: """ Save all changes in a LdapChanges. """ assert isinstance(changes, Changeset) if not changes.is_valid: raise RuntimeError(f"Changeset has errors {changes.errors}.") database = get_database(database) connect...
Save all changes in a LdapChanges.
entailment
def delete(python_data: LdapObject, database: Optional[Database] = None) -> None: """ Delete a LdapObject from the database. """ dn = python_data.get_as_single('dn') assert dn is not None database = get_database(database) connection = database.connection connection.delete(dn)
Delete a LdapObject from the database.
entailment
def _get_field_by_name(table: LdapObjectClass, name: str) -> tldap.fields.Field: """ Lookup a field by its name. """ fields = table.get_fields() return fields[name]
Lookup a field by its name.
entailment
def rename(python_data: LdapObject, new_base_dn: str = None, database: Optional[Database] = None, **kwargs) -> LdapObject: """ Move/rename a LdapObject in the database. """ table = type(python_data) dn = python_data.get_as_single('dn') assert dn is not None database = get_database(databa...
Move/rename a LdapObject in the database.
entailment
def route(route_str): # decorator param """ Provides play2 likes routes, with python formatter All string fileds should be named parameters :param route_str: a route "GET /parent/{parentID}/child/{childId}{ctype}" :return: the response of requests.request """ def ilog(elapsed): # s...
Provides play2 likes routes, with python formatter All string fileds should be named parameters :param route_str: a route "GET /parent/{parentID}/child/{childId}{ctype}" :return: the response of requests.request
entailment
def play_auth(f): """ Injects cookies, into requests call over route :return: route """ def wrapper(*args, **kwargs): self = args[0] if 'cookies' in kwargs: raise AttributeError("don't set cookies explicitly") if 'auth' in kwargs: raise AttributeError...
Injects cookies, into requests call over route :return: route
entailment
def basic_auth(f): """ Injects auth, into requests call over route :return: route """ def wrapper(*args, **kwargs): self = args[0] if 'auth' in kwargs: raise AttributeError("don't set auth token explicitly") assert self.is_connected, "not connected, call router.c...
Injects auth, into requests call over route :return: route
entailment
def _list_dict(l: Iterator[str], case_insensitive: bool = False): """ return a dictionary with all items of l being the keys of the dictionary If argument case_insensitive is non-zero ldap.cidict.cidict will be used for case-insensitive string keys """ if case_insensitive: raise NotImpl...
return a dictionary with all items of l being the keys of the dictionary If argument case_insensitive is non-zero ldap.cidict.cidict will be used for case-insensitive string keys
entailment
def addModlist(entry: dict, ignore_attr_types: Optional[List[str]] = None) -> Dict[str, List[bytes]]: """Build modify list for call of method LDAPObject.add()""" ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or []))) modlist: Dict[str, List[bytes]] = {} for attrtype in entry.keys(): ...
Build modify list for call of method LDAPObject.add()
entailment
def modifyModlist( old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None, ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]: """ Build differential modify list for calling LDAPObject.modify()/modify_s() :param old_entry: Dictionary hol...
Build differential modify list for calling LDAPObject.modify()/modify_s() :param old_entry: Dictionary holding the old entry :param new_entry: Dictionary holding what the new entry should be :param ignore_attr_types: List of attribute type names to be ignored completely :param i...
entailment
def connect(tenant=None, user=None, password=None, token=None, is_public=False): """ Authenticates user and returns new platform to user. This is an entry point to start working with Qubell Api. :rtype: QubellPlatform :param str tenant: url to tenant, default taken from 'QUBELL_T...
Authenticates user and returns new platform to user. This is an entry point to start working with Qubell Api. :rtype: QubellPlatform :param str tenant: url to tenant, default taken from 'QUBELL_TENANT' :param str user: user email, default taken from 'QUBELL_USER' :param str passw...
entailment
def connect_to_another_user(self, user, password, token=None, is_public=False): """ Authenticates user with the same tenant as current platform using and returns new platform to user. :rtype: QubellPlatform :param str user: user email :param str password: user password :p...
Authenticates user with the same tenant as current platform using and returns new platform to user. :rtype: QubellPlatform :param str user: user email :param str password: user password :param str token: session token :param bool is_public: either to use public or private api (pu...
entailment
def create_organization(self, name): """ Creates new organization :rtype: Organization """ org = Organization.new(name, self._router) assert org.ready(), "Organization {} hasn't got ready after creation".format(name) return org
Creates new organization :rtype: Organization
entailment
def get_organization(self, id=None, name=None): """ Gets existing and accessible organization :rtype: Organization """ log.info("Picking organization: %s (%s)" % (name, id)) return self.organizations[id or name]
Gets existing and accessible organization :rtype: Organization
entailment
def get_or_create_organization(self, id=None, name=None): """ Gets existing or creates new organization :rtype: Organization """ if id: return self.get_organization(id) else: assert name try: return self.get_organization...
Gets existing or creates new organization :rtype: Organization
entailment
def get_backends_versions(self): """ Get backends versions :return: dict containing name of backend and version. """ # We are not always have permission, so find open. for i in range(0, len(self.organizations)): try: backends = self.organizatio...
Get backends versions :return: dict containing name of backend and version.
entailment
def make_driver(loop=None): ''' Returns a stop driver. The optional loop argument can be provided to use the driver in another loop than the default one. Parameters ----------- loop: BaseEventLoop The event loop to use instead of the default one. ''' loop = loop or asynci...
Returns a stop driver. The optional loop argument can be provided to use the driver in another loop than the default one. Parameters ----------- loop: BaseEventLoop The event loop to use instead of the default one.
entailment
def rdn_to_dn(changes: Changeset, name: str, base_dn: str) -> Changeset: """ Convert the rdn to a fully qualified DN for the specified LDAP connection. :param changes: The changes object to lookup. :param name: rdn to convert. :param base_dn: The base_dn to lookup. :return: fully qualified DN. ...
Convert the rdn to a fully qualified DN for the specified LDAP connection. :param changes: The changes object to lookup. :param name: rdn to convert. :param base_dn: The base_dn to lookup. :return: fully qualified DN.
entailment
def _stdin_(p): """Takes input from user. Works for Python 2 and 3.""" _v = sys.version[0] return input(p) if _v is '3' else raw_input(p)
Takes input from user. Works for Python 2 and 3.
entailment
def survey_loader(sur_dir=SUR_DIR, sur_file=SUR_FILE): """Loads up the given survey in the given dir.""" survey_path = os.path.join(sur_dir, sur_file) survey = None with open(survey_path) as survey_file: survey = Survey(survey_file.read()) return survey
Loads up the given survey in the given dir.
entailment
def format_choices(self): """Return the choices in string form.""" ce = enumerate(self.choices) f = lambda i, c: '%s (%d)' % (c, i+1) # apply formatter and append help token toks = [f(i,c) for i, c in ce] + ['Help (?)'] return ' '.join(toks)
Return the choices in string form.
entailment
def is_answer_valid(self, ans): """Validate user's answer against available choices.""" return ans in [str(i+1) for i in range(len(self.choices))]
Validate user's answer against available choices.
entailment
def run_question(self, question, input_func=_stdin_): """Run the given question.""" qi = '[%d/%d] ' % (self.qcount, self.qtotal) print('%s %s:' % (qi, question['label'])) while True: # ask for user input until we get a valid one ans = input_func('%s > ' % self.for...
Run the given question.
entailment
def run_section(self, name, input_func=_stdin_): """Run the given section.""" print('\nStuff %s by the license:\n' % name) section = self.survey[name] for question in section: self.run_question(question, input_func)
Run the given section.
entailment
def run(self, input_func=_stdin_): """Run the sections.""" # reset question count self.qcount = 1 for section_name in self.survey: self.run_section(section_name, input_func)
Run the sections.
entailment
def get_vector(self): """Return the vector for this survey.""" vec = {} for dim in ['forbidden', 'required', 'permitted']: if self.survey[dim] is None: continue dim_vec = map(lambda x: (x['tag'], x['answer']), self.survey[dim]) ...
Return the vector for this survey.
entailment
def update(self, span: typing.Tuple[int, int], line_type: LineType) -> None: """ Updates line types for a block's span. Args: span: First and last relative line number of a Block. line_type: The type of line to update to. Raises: ValidationError: A s...
Updates line types for a block's span. Args: span: First and last relative line number of a Block. line_type: The type of line to update to. Raises: ValidationError: A special error on collision. This prevents Flake8 from crashing because it is conve...
entailment
def check_arrange_act_spacing(self) -> typing.Generator[AAAError, None, None]: """ * When no spaces found, point error at line above act block * When too many spaces found, point error at 2nd blank line """ yield from self.check_block_spacing( LineType.arrange, ...
* When no spaces found, point error at line above act block * When too many spaces found, point error at 2nd blank line
entailment
def check_act_assert_spacing(self) -> typing.Generator[AAAError, None, None]: """ * When no spaces found, point error at line above assert block * When too many spaces found, point error at 2nd blank line """ yield from self.check_block_spacing( LineType.act, ...
* When no spaces found, point error at line above assert block * When too many spaces found, point error at 2nd blank line
entailment
def check_block_spacing( self, first_block_type: LineType, second_block_type: LineType, error_message: str, ) -> typing.Generator[AAAError, None, None]: """ Checks there is a clear single line between ``first_block_type`` and ``second_block_type``. No...
Checks there is a clear single line between ``first_block_type`` and ``second_block_type``. Note: Is tested via ``check_arrange_act_spacing()`` and ``check_act_assert_spacing()``.
entailment
def vector_distance(v1, v2): """Given 2 vectors of multiple dimensions, calculate the euclidean distance measure between them.""" dist = 0 for dim in v1: for x in v1[dim]: dd = int(v1[dim][x]) - int(v2[dim][x]) dist = dist + dd**2 return dist
Given 2 vectors of multiple dimensions, calculate the euclidean distance measure between them.
entailment
def send_command(self, command, *arguments): """ Send command with no output. :param command: command to send. :param arguments: list of command arguments. """ self.api.send_command(self, command, *arguments)
Send command with no output. :param command: command to send. :param arguments: list of command arguments.
entailment
def send_command_return(self, command, *arguments): """ Send command and wait for single line output. """ return self.api.send_command_return(self, command, *arguments)
Send command and wait for single line output.
entailment
def send_command_return_multilines(self, command, *arguments): """ Send command and wait for multiple lines output. """ return self.api.send_command_return_multilines(self, command, *arguments)
Send command and wait for multiple lines output.
entailment
def load(self, limit=9999): """ Function list Get the list of all interfaces @param key: The targeted object @param limit: The limit of items to return @return RETURN: A ForemanItem list """ subItemList = self.api.list('{}/{}/{}'.format(self.parentObjName, ...
Function list Get the list of all interfaces @param key: The targeted object @param limit: The limit of items to return @return RETURN: A ForemanItem list
entailment
def append(self, payload): """ Function __iadd__ @param payload: The payload corresponding to the object to add @return RETURN: A ForemanItem """ if self.objType.setInParentPayload: print('Error, {} is not elibible to addition, but only set' .format...
Function __iadd__ @param payload: The payload corresponding to the object to add @return RETURN: A ForemanItem
entailment
def getPayloadStruct(self, payload): """ Function getPayloadStruct @param payload: The payload structure to the object to add @return RETURN: A dict """ newSubItem = self.objType(self.api, 0, self.parentObjName, self.parentPayloadObj, self.paren...
Function getPayloadStruct @param payload: The payload structure to the object to add @return RETURN: A dict
entailment
def get_repr(expr, multiline=False): """ Build a repr string for ``expr`` from its vars and signature. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ....
Build a repr string for ``expr`` from its vars and signature. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ... self.var_args = var_args ... ...
entailment
def get_vars(expr): """ Get ``args``, ``var args`` and ``kwargs`` for an object ``expr``. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ... se...
Get ``args``, ``var args`` and ``kwargs`` for an object ``expr``. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ... self.var_args = var_args ....
entailment
def new(expr, *args, **kwargs): """ Template an object. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ... self.var_args = var_args ......
Template an object. :: >>> class MyObject: ... def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs): ... self.arg1 = arg1 ... self.arg2 = arg2 ... self.var_args = var_args ... self.foo = foo ... ...
entailment
def on_builder_inited(app): """ Hooks into Sphinx's ``builder-inited`` event. Builds out the ReST API source. """ config = app.builder.config target_directory = ( pathlib.Path(app.builder.env.srcdir) / config.uqbar_api_directory_name ) initial_source_paths: List[str] = [] ...
Hooks into Sphinx's ``builder-inited`` event. Builds out the ReST API source.
entailment
def setup(app) -> Dict[str, Any]: """ Sets up Sphinx extension. """ app.add_config_value("uqbar_api_directory_name", "api", "env") app.add_config_value("uqbar_api_document_empty_modules", False, "env") app.add_config_value("uqbar_api_document_private_members", False, "env") app.add_config_va...
Sets up Sphinx extension.
entailment
def get_glitter_app(self, glitter_app_name): """ Retrieve the Glitter App config for a specific Glitter App. """ if not self.discovered: self.discover_glitter_apps() try: glitter_app = self.glitter_apps[glitter_app_name] return glitter_app ...
Retrieve the Glitter App config for a specific Glitter App.
entailment
def discover_glitter_apps(self): """ Find all the Glitter App configurations in the current project. """ for app_name in settings.INSTALLED_APPS: module_name = '{app_name}.glitter_apps'.format(app_name=app_name) try: glitter_apps_module = import_mo...
Find all the Glitter App configurations in the current project.
entailment