text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collapse_spaces(text): """Remove newlines, tabs and multiple spaces with single spaces."""
if not isinstance(text, six.string_types): return text return COLLAPSE_RE.sub(WS, text).strip(WS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False, encoding_default='utf-8', encoding=None, replace_categories=UNICODE_CATEGORIES): """The main normalization function for text. This will take a string and apply a set of transformations to it so that it can be processed more easily afterwards. Arguments: * ``lowercase``: not very mysterious. * ``collapse``: replace multiple whitespace-like characters with a single whitespace. This is especially useful with category replacement which can lead to a lot of whitespace. * ``decompose``: apply a unicode normalization (NFKD) to separate simple characters and their diacritics. * ``replace_categories``: This will perform a replacement of whole classes of unicode characters (e.g. symbols, marks, numbers) with a given character. It is used to replace any non-text elements of the input string. """
text = stringify(text, encoding_default=encoding_default, encoding=encoding) if text is None: return if lowercase: # Yeah I made a Python package for this. text = text.lower() if ascii: # A stricter form of transliteration that leaves only ASCII # characters. text = ascii_text(text) elif latinize: # Perform unicode-based transliteration, e.g. of cyricllic # or CJK scripts into latin. text = latinize_text(text) if text is None: return # Perform unicode category-based character replacement. This is # used to filter out whole classes of characters, such as symbols, # punctuation, or whitespace-like characters. text = category_replace(text, replace_categories) if collapse: # Remove consecutive whitespace. text = collapse_spaces(text) return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slugify(text, sep='-'): """A simple slug generator."""
text = stringify(text) if text is None: return None text = text.replace(sep, WS) text = normalize(text, ascii=True) if text is None: return None return text.replace(WS, sep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def latinize_text(text, ascii=False): """Transliterate the given text to the latin script. This attempts to convert a given text to latin script using the closest match of characters vis a vis the original script. """
if text is None or not isinstance(text, six.string_types) or not len(text): return text if ascii: if not hasattr(latinize_text, '_ascii'): # Transform to latin, separate accents, decompose, remove # symbols, compose, push to ASCII latinize_text._ascii = Transliterator.createInstance('Any-Latin; NFKD; [:Symbol:] Remove; [:Nonspacing Mark:] Remove; NFKC; Accents-Any; Latin-ASCII') # noqa return latinize_text._ascii.transliterate(text) if not hasattr(latinize_text, '_tr'): latinize_text._tr = Transliterator.createInstance('Any-Latin') return latinize_text._tr.transliterate(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ascii_text(text): """Transliterate the given text and make sure it ends up as ASCII."""
text = latinize_text(text, ascii=True) if isinstance(text, six.text_type): text = text.encode('ascii', 'ignore').decode('ascii') return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self): """Return default message for this element """
if self.code != 200: for code in self.response_codes: if code.code == self.code: return code.message raise ValueError("Unknown response code \"%s\" in \"%s\"." % (self.code, self.name)) return "OK"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_sample(self): """Return default value for the element """
if self.type not in Object.Types or self.type is Object.Types.type: return self.type_object.get_sample() else: return self.get_object().get_sample()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Main function to run command """
configParser = FileParser() logging.config.dictConfig( configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml')) ) ApiDoc().main()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_config(self): """return command's configuration from call's arguments """
options = self.parser.parse_args() if options.config is None and options.input is None: self.parser.print_help() sys.exit(2) if options.config is not None: configFactory = ConfigFactory() config = configFactory.load_from_file(options.config) else: config = ConfigObject() if options.input is not None: config["input"]["locations"] = [str(x) for x in options.input] if options.arguments is not None: config["input"]["arguments"] = dict((x.partition("=")[0], x.partition("=")[2]) for x in options.arguments) if options.output is not None: config["output"]["location"] = options.output if options.no_validate is not None: config["input"]["validate"] = not options.no_validate if options.dry_run is not None: self.dry_run = options.dry_run if options.watch is not None: self.watch = options.watch if options.traceback is not None: self.traceback = options.traceback if options.quiet is not None: self.logger.setLevel(logging.WARNING) if options.silence is not None: logging.disable(logging.CRITICAL) configService = ConfigService() configService.validate(config) self.config = config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _watch_refresh_source(self, event): """Refresh sources then templates """
self.logger.info("Sources changed...") try: self.sources = self._get_sources() self._render_template(self.sources) except: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _watch_refresh_template(self, event): """Refresh template's contents """
self.logger.info("Template changed...") try: self._render_template(self.sources) except: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_property(attribute, type): """Add a property to a class """
def decorator(cls): """Decorator """ private = "_" + attribute def getAttr(self): """Property getter """ if getattr(self, private) is None: setattr(self, private, type()) return getattr(self, private) def setAttr(self, value): """Property setter """ setattr(self, private, value) setattr(cls, attribute, property(getAttr, setAttr)) setattr(cls, private, None) return cls return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_files(self, input_files, output_file): """Combine the input files to a big output file"""
# we assume that all the input files have the same charset with open(output_file, mode='wb') as out: for input_file in input_files: out.write(open(input_file, mode='rb').read())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_extends(self, target, extends, inherit_key="inherit", inherit=False): """Merge extended dicts """
if isinstance(target, dict): if inherit and inherit_key in target and not to_boolean(target[inherit_key]): return if not isinstance(extends, dict): raise ValueError("Unable to merge: Dictionnary expected") for key in extends: if key not in target: target[str(key)] = extends[key] else: self.merge_extends(target[key], extends[key], inherit_key, True) elif isinstance(target, list): if not isinstance(extends, list): raise ValueError("Unable to merge: List expected") target += extends
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_sources(self, datas): """Merge sources files """
datas = [data for data in datas if data is not None] if len(datas) == 0: raise ValueError("Data missing") if len(datas) == 1: return datas[0] if isinstance(datas[0], list): if len([x for x in datas if not isinstance(x, list)]) > 0: raise TypeError("Unable to merge: List expected") base = [] for x in datas: base = base + x return base if isinstance(datas[0], dict): if len([x for x in datas if not isinstance(x, dict)]) > 0: raise TypeError("Unable to merge: Dictionnary expected") result = {} for element in datas: for key in element: if key in result: result[key] = self.merge_sources([result[key], element[key]]) else: result[key] = element[key] return result if len([x for x in datas if isinstance(x, (dict, list))]) > 0: raise TypeError("Unable to merge: List not expected") raise ValueError("Unable to merge: Conflict")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_configs(self, config, datas): """Merge configs files """
if not isinstance(config, dict) or len([x for x in datas if not isinstance(x, dict)]) > 0: raise TypeError("Unable to merge: Dictionnary expected") for key, value in config.items(): others = [x[key] for x in datas if key in x] if len(others) > 0: if isinstance(value, dict): config[key] = self.merge_configs(value, others) else: config[key] = others[-1] return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_dictionary(self, datas): """Return a populated object Configuration from dictionnary datas """
configuration = ObjectConfiguration() if "uri" in datas: configuration.uri = str(datas["uri"]) if "title" in datas: configuration.title = str(datas["title"]) if "description" in datas: configuration.description = str(datas["description"]) return configuration
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_name_and_dictionary(self, name, datas): """Return a populated object Parameter from dictionary datas """
parameter = ObjectParameter() self.set_common_datas(parameter, name, datas) if "optional" in datas: parameter.optional = to_boolean(datas["optional"]) if "type" in datas: parameter.type = str(datas["type"]) if "generic" in datas: parameter.generic = to_boolean(datas["generic"]) return parameter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, sources): """Validate the format of sources """
if not isinstance(sources, Root): raise Exception("Source object expected") parameters = self.get_uri_with_missing_parameters(sources) for parameter in parameters: logging.getLogger().warn('Missing parameter "%s" in uri of method "%s" in versions "%s"' % (parameter["name"], parameter["method"], parameter["version"]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, config): """Validate that the source file is ok """
if not isinstance(config, ConfigObject): raise Exception("Config object expected") if config["output"]["componants"] not in ("local", "remote", "embedded", "without"): raise ValueError("Unknown componant \"%s\"." % config["output"]["componants"]) if config["output"]["layout"] not in ("default", "content-only"): raise ValueError("Unknown layout \"%s\"." % config["output"]["layout"]) if config["input"]["locations"] is not None: unknown_locations = [x for x in config["input"]["locations"] if not os.path.exists(x)] if len(unknown_locations) > 0: raise ValueError( "Location%s \"%s\" does not exists" % ("s" if len(unknown_locations) > 1 else "", ("\" and \"").join(unknown_locations)) ) config["input"]["locations"] = [os.path.realpath(x) for x in config["input"]["locations"]] if config["input"]["arguments"] is not None: if not isinstance(config["input"]["arguments"], dict): raise ValueError( "Sources arguments \"%s\" are not a dict" % config["input"]["arguments"] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_template_from_config(self, config): """Retrieve a template path from the config object """
if config["output"]["template"] == "default": return os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'template', 'default.html' ) else: return os.path.abspath(config["output"]["template"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_dictionary(self, datas): """Return a populated object ResponseCode from dictionary datas """
if "code" not in datas: raise ValueError("A response code must contain a code in \"%s\"." % repr(datas)) code = ObjectResponseCode() self.set_common_datas(code, str(datas["code"]), datas) code.code = int(datas["code"]) if "message" in datas: code.message = str(datas["message"]) elif code.code in self.default_messages.keys(): code.message = self.default_messages[code.code] if "generic" in datas: code.generic = to_boolean(datas["generic"]) return code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_handler(self, path, handler): """Add a path in watch queue """
self.signatures[path] = self.get_path_signature(path) self.handlers[path] = handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_path_signature(self, path): """generate a unique signature for file contained in path """
if not os.path.exists(path): return None if os.path.isdir(path): merge = {} for root, dirs, files in os.walk(path): for name in files: full_name = os.path.join(root, name) merge[full_name] = os.stat(full_name) return merge else: return os.stat(path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self): """Check if a file is changed """
for (path, handler) in self.handlers.items(): current_signature = self.signatures[path] new_signature = self.get_path_signature(path) if new_signature != current_signature: self.signatures[path] = new_signature handler.on_change(Event(path))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_name_and_dictionary(self, name, datas): """Return a populated object Category from dictionary datas """
category = ObjectCategory(name) self.set_common_datas(category, name, datas) if "order" in datas: category.order = int(datas["order"]) return category
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_from_file(self, file_path, format=None): """Return dict from a file config """
if format is None: base_name, file_extension = os.path.splitext(file_path) if file_extension in (".yaml", ".yml"): format = "yaml" elif file_extension in (".json"): format = "json" else: raise ValueError("Config file \"%s\" undetermined" % file_extension) if format == "yaml": return yaml.load(open(file_path), Loader=yaml.CSafeLoader if yaml.__with_libyaml__ else yaml.SafeLoader) elif format == "json": return json.load(open(file_path)) else: raise ValueError("Format \"%s\" unknwon" % format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_all_from_directory(self, directory_path): """Return a list of dict from a directory containing files """
datas = [] for root, folders, files in os.walk(directory_path): for f in files: datas.append(self.load_from_file(os.path.join(root, f))) return datas
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_repr(obj): """Represent instance of a class as JSON. """
def serialize(obj): """Recursively walk object's hierarchy. """ if obj is None: return None if isinstance(obj, Enum): return str(obj) if isinstance(obj, (bool, int, float, str)): return obj if isinstance(obj, dict): obj = obj.copy() for key in sorted(obj.keys()): obj[key] = serialize(obj[key]) return obj if isinstance(obj, list): return [serialize(item) for item in obj] if isinstance(obj, tuple): return tuple(serialize([item for item in obj])) if hasattr(obj, '__dict__'): return serialize(obj.__dict__) return repr(obj) return json.dumps(serialize(obj))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_root(self, root_source): """Return a populated Object Root from dictionnary datas """
root_dto = ObjectRoot() root_dto.configuration = root_source.configuration root_dto.versions = [Version(x) for x in root_source.versions.values()] for version in sorted(root_source.versions.values()): hydrator = Hydrator(version, root_source.versions, root_source.versions[version.name].types) for method in version.methods.values(): hydrator.hydrate_method(root_dto, root_source, method) for type in version.types.values(): hydrator.hydrate_type(root_dto, root_source, type) self.define_changes_status(root_dto) return root_dto
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_common_datas(self, element, name, datas): """Populated common data for an element from dictionnary datas """
element.name = str(name) if "description" in datas: element.description = str(datas["description"]).strip() if isinstance(element, Sampleable) and element.sample is None and "sample" in datas: element.sample = str(datas["sample"]).strip() if isinstance(element, Displayable): if "display" in datas: element.display = to_boolean(datas["display"]) if "label" in datas: element.label = datas["label"] else: element.label = element.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_dictionary_of_element_from_dictionary(self, property_name, datas): """Populate a dictionary of elements """
response = {} if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], collections.Iterable): for key, value in datas[property_name].items(): response[key] = self.create_from_name_and_dictionary(key, value) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_list_of_element_from_dictionary(self, property_name, datas): """Populate a list of elements """
response = [] if property_name in datas and datas[property_name] is not None and isinstance(datas[property_name], list): for value in datas[property_name]: response.append(self.create_from_dictionary(value)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_enum(self, property, enum, datas): """Factory enum type """
str_property = str(datas[property]).lower() if str_property not in enum: raise ValueError("Unknow enum \"%s\" for \"%s\"." % (str_property, property)) return enum(str_property)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_from_config(self, config): """Create a template object file defined in the config object """
configService = ConfigService() template = TemplateService() template.output = config["output"]["location"] template_file = configService.get_template_from_config(config) template.input = os.path.basename(template_file) template.env = Environment(loader=FileSystemLoader(os.path.dirname(template_file))) return template
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy(self, id_networkv4): """Deploy network in equipments and set column 'active = 1' in tables redeipv4 :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output """
data = dict() uri = 'api/networkv4/%s/equipments/' % id_networkv4 return super(ApiNetworkIPv4, self).post(uri, data=data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_by_id(self, id_networkv4): """Get IPv4 network :param id_networkv4: ID for NetworkIPv4 :return: IPv4 Network """
uri = 'api/networkv4/%s/' % id_networkv4 return super(ApiNetworkIPv4, self).get(uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, environment_vip=None): """List IPv4 networks :param environment_vip: environment vip to filter :return: IPv4 Networks """
uri = 'api/networkv4/?' if environment_vip: uri += 'environment_vip=%s' % environment_vip return super(ApiNetworkIPv4, self).get(uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def undeploy(self, id_networkv4): """Remove deployment of network in equipments and set column 'active = 0' in tables redeipv4 ] :param id_networkv4: ID for NetworkIPv4 :return: Equipments configuration output """
uri = 'api/networkv4/%s/equipments/' % id_networkv4 return super(ApiNetworkIPv4, self).delete(uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_vip_ip(self, ip, environment_vip): """ Check available ip in environment vip """
uri = 'api/ipv4/ip/%s/environment-vip/%s/' % (ip, environment_vip) return super(ApiNetworkIPv4, self).get(uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete network-ipv4's by their ids :param ids: Identifiers of network-ipv4's :return: None """
url = build_uri_with_ids('api/v3/networkv4/%s/', ids) return super(ApiNetworkIPv4, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, networkipv4s): """ Method to update network-ipv4's :param networkipv4s: List containing network-ipv4's desired to updated :return: None """
data = {'networks': networkipv4s} networkipv4s_ids = [str(networkipv4.get('id')) for networkipv4 in networkipv4s] return super(ApiNetworkIPv4, self).put('api/v3/networkv4/%s/' % ';'.join(networkipv4s_ids), data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, networkipv4s): """ Method to create network-ipv4's :param networkipv4s: List containing networkipv4's desired to be created on database :return: None """
data = {'networks': networkipv4s} return super(ApiNetworkIPv4, self).post('api/v3/networkv4/', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, name): """Inserts a new Division Dc and returns its identifier. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: Dictionary with the following structure: :: {'division_dc': {'id': < id_division_dc >}} :raise InvalidParameterError: Name is null and invalid. :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
division_dc_map = dict() division_dc_map['name'] = name code, xml = self.submit( {'division_dc': division_dc_map}, 'POST', 'divisiondc/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alterar(self, id_divisiondc, name): """Change Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :param name: Division Dc name. String with a minimum 2 and maximum of 80 characters :return: None :raise InvalidParameterError: The identifier of Division Dc or name is null and invalid. :raise NomeDivisaoDcDuplicadoError: There is already a registered Division Dc with the value of name. :raise DivisaoDcNaoExisteError: Division Dc not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_divisiondc): raise InvalidParameterError( u'The identifier of Division Dc is invalid or was not informed.') url = 'divisiondc/' + str(id_divisiondc) + '/' division_dc_map = dict() division_dc_map['name'] = name code, xml = self.submit({'division_dc': division_dc_map}, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remover(self, id_divisiondc): """Remove Division Dc from by the identifier. :param id_divisiondc: Identifier of the Division Dc. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Division Dc is null and invalid. :raise DivisaoDcNaoExisteError: Division Dc not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_divisiondc): raise InvalidParameterError( u'The identifier of Division Dc is invalid or was not informed.') url = 'divisiondc/' + str(id_divisiondc) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search object types based on extends search. :param search: Dict containing QuerySets to find object types. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing object types """
return super(ApiObjectType, self).get(self.prepare_url('api/v3/object-type/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert_vlan( self, environment_id, name, number, description, acl_file, acl_file_v6, network_ipv4, network_ipv6, vrf=None): """Create new VLAN :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :param network_ipv4: responsible for generating a network attribute ipv4 automatically. :param network_ipv6: responsible for generating a network attribute ipv6 automatically. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'ativada': < ativada > 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, } } :raise VlanError: VLAN name already exists, VLAN name already exists, DC division of the environment invalid or does not exist VLAN number available. :raise VlanNaoExisteError: VLAN not found. :raise AmbienteNaoExisteError: Environment not registered. :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(environment_id): raise InvalidParameterError(u'Environment id is none or invalid.') if not is_valid_int_param(number): raise InvalidParameterError(u'Vlan number is none or invalid') vlan_map = dict() vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['acl_file'] = acl_file vlan_map['acl_file_v6'] = acl_file_v6 vlan_map['number'] = number vlan_map['network_ipv4'] = network_ipv4 vlan_map['network_ipv6'] = network_ipv6 vlan_map['vrf'] = vrf code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/insert/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_vlan( self, environment_id, name, number, description, acl_file, acl_file_v6, id_vlan): """Edit a VLAN :param id_vlan: ID for Vlan :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :param number: Number of Vlan :param acl_file: Acl IPv4 File name to VLAN. :param acl_file_v6: Acl IPv6 File name to VLAN. :return: None :raise VlanError: VLAN name already exists, DC division of the environment invalid or there is no VLAN number available. :raise VlanNaoExisteError: VLAN not found. :raise AmbienteNaoExisteError: Environment not registered. :raise InvalidParameterError: Name of Vlan and/or the identifier of the Environment is null or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') if not is_valid_int_param(environment_id): raise InvalidParameterError(u'Environment id is none or invalid.') if not is_valid_int_param(number): raise InvalidParameterError(u'Vlan number is none or invalid') vlan_map = dict() vlan_map['vlan_id'] = id_vlan vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['acl_file'] = acl_file vlan_map['acl_file_v6'] = acl_file_v6 vlan_map['number'] = number code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/edit/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_vlan(self, id_vlan): """ Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None """
vlan_map = dict() vlan_map['vlan_id'] = id_vlan code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allocate_without_network(self, environment_id, name, description, vrf=None): """Create new VLAN without add NetworkIPv4. :param environment_id: ID for Environment. :param name: The name of VLAN. :param description: Some description to VLAN. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada > } } :raise VlanError: Duplicate name of VLAN, division DC of Environment not found/invalid or VLAN number not available. :raise AmbienteNaoExisteError: Environment not found. :raise InvalidParameterError: Some parameter was invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
vlan_map = dict() vlan_map['environment_id'] = environment_id vlan_map['name'] = name vlan_map['description'] = description vlan_map['vrf'] = vrf code, xml = self.submit({'vlan': vlan_map}, 'POST', 'vlan/no-network/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verificar_permissao(self, id_vlan, nome_equipamento, nome_interface): """Check if there is communication permission for VLAN to trunk. Run script 'configurador'. The "stdout" key value of response dictionary is 1(one) if VLAN has permission, or 0(zero), otherwise. :param id_vlan: VLAN identifier. :param nome_equipamento: Equipment name. :param nome_interface: Interface name. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise VlanNaoExisteError: VLAN does not exist. :raise InvalidParameterError: VLAN id is none or invalid. :raise InvalidParameterError: Equipment name and/or interface name is invalid or none. :raise EquipamentoNaoExisteError: Equipment does not exist. :raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface. :raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment. :raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/check/' vlan_map = dict() vlan_map['nome'] = nome_equipamento vlan_map['nome_interface'] = nome_interface code, xml = self.submit({'equipamento': vlan_map}, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buscar(self, id_vlan): """Get VLAN by its identifier. :param id_vlan: VLAN identifier. :return: Following dictionary: :: {'vlan': {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_ambiente': < id_ambiente >, 'id_tipo_rede': < id_tipo_rede >, 'rede_oct1': < rede_oct1 >, 'rede_oct2': < rede_oct2 >, 'rede_oct3': < rede_oct3 >, 'rede_oct4': < rede_oct4 >, 'bloco': < bloco >, 'mascara_oct1': < mascara_oct1 >, 'mascara_oct2': < mascara_oct2 >, 'mascara_oct3': < mascara_oct3 >, 'mascara_oct4': < mascara_oct4 >, 'broadcast': < broadcast >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'ativada': < ativada >} OR {'id': < id_vlan >, 'nome': < nome_vlan >, 'num_vlan': < num_vlan >, 'id_tipo_rede': < id_tipo_rede >, 'id_ambiente': < id_ambiente >, 'bloco1': < bloco1 >, 'bloco2': < bloco2 >, 'bloco3': < bloco3 >, 'bloco4': < bloco4 >, 'bloco5': < bloco5 >, 'bloco6': < bloco6 >, 'bloco7': < bloco7 >, 'bloco8': < bloco8 >, 'bloco': < bloco >, 'mask_bloco1': < mask_bloco1 >, 'mask_bloco2': < mask_bloco2 >, 'mask_bloco3': < mask_bloco3 >, 'mask_bloco4': < mask_bloco4 >, 'mask_bloco5': < mask_bloco5 >, 'mask_bloco6': < mask_bloco6 >, 'mask_bloco7': < mask_bloco7 >, 'mask_bloco8': < mask_bloco8 >, 'broadcast': < broadcast >, 'descricao': < descricao >, 'acl_file_name': < acl_file_name >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'acl_valida_v6': < acl_valida_v6 >, 'ativada': < ativada >}} :raise VlanNaoExisteError: VLAN does not exist. :raise InvalidParameterError: VLAN id is none or invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Vlan id is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/' code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listar_permissao(self, nome_equipamento, nome_interface): """List all VLANS having communication permission to trunk from a port in switch. Run script 'configurador'. :: The value of 'stdout' key of return dictionary can have a list of numbers or number intervals of VLAN´s, comma separated. Examples of possible returns of 'stdout' below: :param nome_equipamento: Equipment name. :param nome_interface: Interface name. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise InvalidParameterError: Equipment name and/or interface name is invalid or none. :raise EquipamentoNaoExisteError: Equipment does not exist. :raise LigacaoFrontInterfaceNaoExisteError: There is no interface on front link of informed interface. :raise InterfaceNaoExisteError: Interface does not exist or is not associated to equipment. :raise LigacaoFrontNaoTerminaSwitchError: Interface does not have switch connected. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. :raise ScriptError: Failed to run the script. """
vlan_map = dict() vlan_map['nome'] = nome_equipamento vlan_map['nome_interface'] = nome_interface code, xml = self.submit({'equipamento': vlan_map}, 'PUT', 'vlan/list/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def apply_acl(self, equipments, vlan, environment, network): '''Apply the file acl in equipments :param equipments: list of equipments :param vlan: Vvlan :param environment: Environment :param network: v4 or v6 :raise Exception: Failed to apply acl :return: True case Apply and sysout of script ''' vlan_map = dict() vlan_map['equipments'] = equipments vlan_map['vlan'] = vlan vlan_map['environment'] = environment vlan_map['network'] = network url = 'vlan/apply/acl/' code, xml = self.submit({'vlan': vlan_map}, 'POST', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm_vlan(self, number_net, id_environment_vlan, ip_version=None): """Checking if the vlan insert need to be confirmed :param number_net: Filter by vlan number column :param id_environment_vlan: Filter by environment ID related :param ip_version: Ip version for checking :return: True is need confirmation, False if no need :raise AmbienteNaoExisteError: Ambiente não cadastrado. :raise InvalidParameterError: Invalid ID for VLAN. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
url = 'vlan/confirm/' + \ str(number_net) + '/' + id_environment_vlan + '/' + str(ip_version) code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_number_available(self, id_environment, num_vlan, id_vlan): """Checking if environment has a number vlan available :param id_environment: Identifier of environment :param num_vlan: Vlan number :param id_vlan: Vlan indentifier (False if inserting a vlan) :return: True is has number available, False if hasn't :raise AmbienteNaoExisteError: Ambiente não cadastrado. :raise InvalidParameterError: Invalid ID for VLAN. :raise VlanNaoExisteError: VLAN not found. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
url = 'vlan/check_number_available/' + \ str(id_environment) + '/' + str(num_vlan) + '/' + str(id_vlan) code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validar(self, id_vlan): """Validates ACL - IPv4 of VLAN from its identifier. Assigns 1 to 'acl_valida'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :raise VlanNaoExisteError: Vlan not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'The identifier of Vlan is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/validate/' + IP_VERSION.IPv4[0] + '/' code, xml = self.submit(None, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_ipv6(self, id_vlan): """Validates ACL - IPv6 of VLAN from its identifier. Assigns 1 to 'acl_valida_v6'. :param id_vlan: Identifier of the Vlan. Integer value and greater than zero. :return: None :raise InvalidParameterError: Vlan identifier is null and invalid. :raise VlanNaoExisteError: Vlan not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'The identifier of Vlan is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/validate/' + IP_VERSION.IPv6[0] + '/' code, xml = self.submit(None, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, id_vlan): """Remove a VLAN by your primary key. Execute script to remove VLAN :param id_vlan: ID for VLAN. :return: Following dictionary: :: {‘sucesso’: {‘codigo’: < codigo >, ‘descricao’: {'stdout':< stdout >, 'stderr':< stderr >}}} :raise InvalidParameterError: Identifier of the VLAN is invalid. :raise VlanNaoExisteError: VLAN not found. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'Parameter id_vlan is invalid. Value: ' + id_vlan) url = 'vlan/' + str(id_vlan) + '/remove/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deallocate(self, id_vlan): """Deallocate all relationships between Vlan. :param id_vlan: Identifier of the VLAN. Integer value and greater than zero. :return: None :raise InvalidParameterError: VLAN identifier is null and invalid. :raise VlanError: VLAN is active. :raise VlanNaoExisteError: VLAN not found. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_vlan): raise InvalidParameterError( u'The identifier of Vlan is invalid or was not informed.') url = 'vlan/' + str(id_vlan) + '/deallocate/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_script_acl(self, id_vlan, network_type): '''Generate the script acl :param id_vlan: Vlan Id :param network_type: v4 or v6 :raise InvalidValueError: Attrs invalids. :raise XMLError: Networkapi failed to generate the XML response. :raise VlanACLDuplicatedError: ACL name duplicate. :raise VlanNotFoundError: Vlan not registered. :return: Following dictionary: :: {'vlan': { 'id': < id >, 'nome': '< nome >', 'num_vlan': < num_vlan >, 'descricao': < descricao > 'acl_file_name': < acl_file_name >, 'ativada': < ativada >, 'acl_valida': < acl_valida >, 'acl_file_name_v6': < acl_file_name_v6 >, 'redeipv6': < redeipv6 >, 'acl_valida_v6': < acl_valida_v6 >, 'redeipv4': < redeipv4 >, 'ambiente': < ambiente >, }} ''' vlan_map = dict() vlan_map['id_vlan'] = id_vlan vlan_map['network_type'] = network_type url = 'vlan/create/script/acl/' code, xml = self.submit({'vlan': vlan_map}, 'POST', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, id_user, id_group): """Create a relationship between User and Group. :param id_user: Identifier of the User. Integer value and greater than zero. :param id_group: Identifier of the Group. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'user_group': {'id': < id_user_group >}} :raise InvalidParameterError: The identifier of User or Group is null and invalid. :raise GrupoUsuarioNaoExisteError: UserGroup not registered. :raise UsuarioNaoExisteError: User not registered. :raise UsuarioGrupoError: User already registered in the group. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_user): raise InvalidParameterError( u'The identifier of User is invalid or was not informed.') if not is_valid_int_param(id_group): raise InvalidParameterError( u'The identifier of Group is invalid or was not informed.') url = 'usergroup/user/' + \ str(id_user) + '/ugroup/' + str(id_group) + '/associate/' code, xml = self.submit(None, 'PUT', url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search neighbors based on extends search. :param search: Dict containing QuerySets to find neighbors. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing neighbors """
return super(ApiV4Neighbor, self).get(self.prepare_url( 'api/v4/neighbor/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete neighbors by their id's :param ids: Identifiers of neighbors :return: None """
url = build_uri_with_ids('api/v4/neighbor/%s/', ids) return super(ApiV4Neighbor, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, neighbors): """ Method to update neighbors :param neighbors: List containing neighbors desired to updated :return: None """
data = {'neighbors': neighbors} neighbors_ids = [str(env.get('id')) for env in neighbors] return super(ApiV4Neighbor, self).put('api/v4/neighbor/%s/' % ';'.join(neighbors_ids), data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, neighbors): """ Method to create neighbors :param neighbors: List containing neighbors desired to be created on database :return: None """
data = {'neighbors': neighbors} return super(ApiV4Neighbor, self).post('api/v4/neighbor/', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_access(self, id_access): """Get Equipment Access by id. :return: Dictionary with following: :: {'equipamento_acesso': {'id_equipamento': < id_equipamento >, 'fqdn': < fqdn >, 'user': < user >, 'pass': < pass >, 'id_tipo_acesso': < id_tipo_acesso >, 'enable_pass': < enable_pass >}} """
if not is_valid_int_param(id_access): raise InvalidParameterError(u'Equipment Access ID is invalid.') url = 'equipamentoacesso/id/' + str(id_access) + '/' code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_by_equip(self, name): """ List all equipment access by equipment name :return: Dictionary with the following structure: :: {‘equipamento_acesso’:[ {'id': <id_equiptos_access>, 'equipamento': <id_equip>, 'fqdn': <fqdn>, 'user': <user>, 'password': <pass> 'tipo_acesso': <id_tipo_acesso>, 'enable_pass': <enable_pass> }]} :raise InvalidValueError: Invalid parameter. :raise EquipamentoNotFoundError: Equipment name not found in database. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
equip_access_map = dict() equip_access_map['name'] = name code, xml = self.submit( {"equipamento_acesso": equip_access_map}, 'POST', 'equipamentoacesso/name/') key = 'equipamento_acesso' return get_list_map(self.response(code, xml, [key]), key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir( self, id_equipamento, fqdn, user, password, id_tipo_acesso, enable_pass): """Add new relationship between equipment and access type and returns its id. :param id_equipamento: Equipment identifier. :param fqdn: Equipment FQDN. :param user: User. :param password: Password. :param id_tipo_acesso: Access Type identifier. :param enable_pass: Enable access. :return: Dictionary with the following: {‘equipamento_acesso’: {‘id’: < id >}} :raise EquipamentoNaoExisteError: Equipment doesn't exist. :raise TipoAcessoNaoExisteError: Access Type doesn't exist. :raise EquipamentoAcessoError: Equipment and access type already associated. :raise InvalidParameterError: The parameters equipment id, fqdn, user, password or access type id are invalid or none. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
equipamento_acesso_map = dict() equipamento_acesso_map['id_equipamento'] = id_equipamento equipamento_acesso_map['fqdn'] = fqdn equipamento_acesso_map['user'] = user equipamento_acesso_map['pass'] = password equipamento_acesso_map['id_tipo_acesso'] = id_tipo_acesso equipamento_acesso_map['enable_pass'] = enable_pass code, xml = self.submit( {'equipamento_acesso': equipamento_acesso_map}, 'POST', 'equipamentoacesso/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_by_id( self, id_equip_acesso, id_tipo_acesso, fqdn, user, password, enable_pass): """Edit access type, fqdn, user, password and enable_pass of the relationship of equipment and access type. :param id_tipo_acesso: Access type identifier. :param id_equip_acesso: Equipment identifier. :param fqdn: Equipment FQDN. :param user: User. :param password: Password. :param enable_pass: Enable access. :return: None :raise InvalidParameterError: The parameters fqdn, user, password or access type id are invalid or none. :raise EquipamentoAcessoNaoExisteError: Equipment access type relationship doesn't exist. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_tipo_acesso): raise InvalidParameterError( u'Access type id is invalid or not informed.') equipamento_acesso_map = dict() equipamento_acesso_map['fqdn'] = fqdn equipamento_acesso_map['user'] = user equipamento_acesso_map['pass'] = password equipamento_acesso_map['enable_pass'] = enable_pass equipamento_acesso_map['id_tipo_acesso'] = id_tipo_acesso equipamento_acesso_map['id_equip_acesso'] = id_equip_acesso url = 'equipamentoacesso/edit/' code, xml = self.submit( {'equipamento_acesso': equipamento_acesso_map}, 'POST', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remover(self, id_tipo_acesso, id_equipamento): """Removes relationship between equipment and access type. :param id_equipamento: Equipment identifier. :param id_tipo_acesso: Access type identifier. :return: None :raise EquipamentoNaoExisteError: Equipment doesn't exist. :raise EquipamentoAcessoNaoExisteError: Relationship between equipment and access type doesn't exist. :raise InvalidParameterError: Equipment and/or access type id is/are invalid. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_tipo_acesso): raise InvalidParameterError(u'Access type id is invalid.') if not is_valid_int_param(id_equipamento): raise InvalidParameterError(u'Equipment id is invalid.') url = 'equipamentoacesso/' + \ str(id_equipamento) + '/' + str(id_tipo_acesso) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self, pools): """ Remove Pools Running Script And Update to Not Created :param ids: List of ids :return: None on success :raise ScriptRemovePoolException :raise InvalidIdPoolException :raise NetworkAPIException """
data = dict() data["pools"] = pools uri = "api/pools/v2/" return self.delete(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, pools): """ Create Pools Running Script And Update to Created :param pools: List of pools :return: None on success :raise PoolDoesNotExistException :raise ScriptCreatePoolException :raise InvalidIdPoolException :raise NetworkAPIException """
data = dict() data["pools"] = pools uri = "api/pools/v2/" return self.put(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable(self, ids): """ Enable Pool Members Running Script :param ids: List of ids :return: None on success :raise PoolMemberDoesNotExistException :raise InvalidIdPoolMemberException :raise ScriptEnablePoolException :raise NetworkAPIException """
data = dict() data["ids"] = ids uri = "api/pools/enable/" return self.post(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable(self, ids): """ Disable Pool Members Running Script :param ids: List of ids :return: None on success :raise PoolMemberDoesNotExistException :raise InvalidIdPoolMemberException :raise ScriptDisablePoolException :raise NetworkAPIException """
data = dict() data["ids"] = ids uri = "api/pools/disable/" return self.post(uri, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search object group permissions based on extends search. :param search: Dict containing QuerySets to find object group permissions. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing object group permissions """
return super(ApiObjectGroupPermission, self).get(self.prepare_url('api/v3/object-group-perm/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete object group permissions by their ids :param ids: Identifiers of object group permissions :return: None """
url = build_uri_with_ids('api/v3/object-group-perm/%s/', ids) return super(ApiObjectGroupPermission, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, ogps): """ Method to update object group permissions :param ogps: List containing object group permissions desired to updated :return: None """
data = {'ogps': ogps} ogps_ids = [str(ogp.get('id')) for ogp in ogps] return super(ApiObjectGroupPermission, self).put('api/v3/object-group-perm/%s/' % ';'.join(ogps_ids), data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, ogps): """ Method to create object group permissions :param ogps: List containing vrf desired to be created on database :return: None """
data = {'ogps': ogps} return super(ApiObjectGroupPermission, self).post('api/v3/object-group-perm/', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, id_equipment, id_script): """Inserts a new Related Equipment with Script and returns its identifier :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :param id_script: Identifier of the Script. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'equipamento_roteiro': {'id': < id_equipment_script >}} :raise InvalidParameterError: The identifier of Equipment or Script is null and invalid. :raise RoteiroNaoExisteError: Script not registered. :raise EquipamentoNaoExisteError: Equipment not registered. :raise EquipamentoRoteiroError: Equipment is already associated with the script. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response """
equipment_script_map = dict() equipment_script_map['id_equipment'] = id_equipment equipment_script_map['id_script'] = id_script code, xml = self.submit( {'equipment_script': equipment_script_map}, 'POST', 'equipmentscript/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search vrf's based on extends search. :param search: Dict containing QuerySets to find vrf's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing vrf's """
return super(ApiVrf, self).get(self.prepare_url('api/v3/vrf/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None """
url = build_uri_with_ids('api/v3/vrf/%s/', ids) return super(ApiVrf, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, vrfs): """ Method to update vrf's :param vrfs: List containing vrf's desired to updated :return: None """
data = {'vrfs': vrfs} vrfs_ids = [str(vrf.get('id')) for vrf in vrfs] return super(ApiVrf, self).put('api/v3/vrf/%s/' % ';'.join(vrfs_ids), data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, vrfs): """ Method to create vrf's :param vrfs: List containing vrf's desired to be created on database :return: None """
data = {'vrfs': vrfs} return super(ApiVrf, self).post('api/v3/vrf/', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, name): """Inserts a new Equipment Type and returns its identifier :param name: Equipment Type name. String with a minimum 3 and maximum of 100 characters :return: Dictionary with the following structure: :: {'tipo_equipamento': {'id': < id_equipment_ype >}} :raise InvalidParameterError: Name is null and invalid. :raise EquipamentoError: There is already a registered Equipment Type with the value of name. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response """
equipment_type_map = dict() equipment_type_map['name'] = name url = 'equipmenttype/' code, xml = self.submit( {'equipment_type': equipment_type_map}, 'POST', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, id_equipment, id_environment, is_router=0): """Inserts a new Related Equipment with Environment and returns its identifier :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :param id_environment: Identifier of the Environment. Integer value and greater than zero. :param is_router: Identifier of the Environment. Boolean value. :return: Dictionary with the following structure: :: {'equipamento_ambiente': {'id': < id_equipment_environment >}} :raise InvalidParameterError: The identifier of Equipment or Environment is null and invalid. :raise AmbienteNaoExisteError: Environment not registered. :raise EquipamentoNaoExisteError: Equipment not registered. :raise EquipamentoAmbienteError: Equipment is already associated with the Environment. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
equipment_environment_map = dict() equipment_environment_map['id_equipamento'] = id_equipment equipment_environment_map['id_ambiente'] = id_environment equipment_environment_map['is_router'] = is_router code, xml = self.submit( {'equipamento_ambiente': equipment_environment_map}, 'POST', 'equipamentoambiente/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, name): """Inserts a new Group L3 and returns its identifier. :param name: Group L3 name. String with a minimum 2 and maximum of 80 characters :return: Dictionary with the following structure: :: {'group_l3': {'id': < id_group_l3 >}} :raise InvalidParameterError: Name is null and invalid. :raise NomeGrupoL3DuplicadoError: There is already a registered Group L3 with the value of name. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
group_l3_map = dict() group_l3_map['name'] = name code, xml = self.submit({'group_l3': group_l3_map}, 'POST', 'groupl3/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alterar(self, id_groupl3, name): """Change Group L3 from by the identifier. :param id_groupl3: Identifier of the Group L3. Integer value and greater than zero. :param name: Group L3 name. String with a minimum 2 and maximum of 80 characters :return: None :raise InvalidParameterError: The identifier of Group L3 or name is null and invalid. :raise NomeGrupoL3DuplicadoError: There is already a registered Group L3 with the value of name. :raise GrupoL3NaoExisteError: Group L3 not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_groupl3): raise InvalidParameterError( u'The identifier of Group L3 is invalid or was not informed.') url = 'groupl3/' + str(id_groupl3) + '/' group_l3_map = dict() group_l3_map['name'] = name code, xml = self.submit({'groupl3': group_l3_map}, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remover(self, id_groupl3): """Remove Group L3 from by the identifier. :param id_groupl3: Identifier of the Group L3. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Group L3 is null and invalid. :raise GrupoL3NaoExisteError: Group L3 not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_groupl3): raise InvalidParameterError( u'The identifier of Group L3 is invalid or was not informed.') url = 'groupl3/' + str(id_groupl3) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_full_url(self, parsed_url): """ Returns url path with querystring """
full_path = parsed_url.path if parsed_url.query: full_path = '%s?%s' % (full_path, parsed_url.query) return full_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, **kwargs): """ Method to search Virtual Interfaces based on extends search. :param search: Dict containing QuerySets to find Virtual Interfaces. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing Virtual Interfaces """
return super(ApiV4VirtualInterface, self).get(self.prepare_url( 'api/v4/virtual-interface/', kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, ids): """ Method to delete Virtual Interfaces by their id's :param ids: Identifiers of Virtual Interfaces :return: None """
url = build_uri_with_ids('api/v4/virtual-interface/%s/', ids) return super(ApiV4VirtualInterface, self).delete(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, virtual_interfaces): """ Method to update Virtual Interfaces :param Virtual Interfaces: List containing Virtual Interfaces desired to updated :return: None """
data = {'virtual_interfaces': virtual_interfaces} virtual_interfaces_ids = [str(env.get('id')) for env in virtual_interfaces] return super(ApiV4VirtualInterface, self).put\ ('api/v4/virtual-interface/%s/' % ';'.join(virtual_interfaces_ids), data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, virtual_interfaces): """ Method to create Virtual Interfaces :param Virtual Interfaces: List containing Virtual Interfaces desired to be created on database :return: None """
data = {'virtual_interfaces': virtual_interfaces} return super(ApiV4VirtualInterface, self).post\ ('api/v4/virtual-interface/', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, id_ugroup): """Search Group User by its identifier. :param id_ugroup: Identifier of the Group User. Integer value and greater than zero. :return: Following dictionary: :: {‘user_group’: {'escrita': < escrita >, 'nome': < nome >, 'exclusao': < exclusao >, 'edicao': < edicao >, 'id': < id >, 'leitura': < leitura >}} :raise InvalidParameterError: Group User identifier is none or invalid. :raise GrupoUsuarioNaoExisteError: Group User not registered. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """
if not is_valid_int_param(id_ugroup): raise InvalidParameterError( u'The identifier of Group User is invalid or was not informed.') url = 'ugroup/get/' + str(id_ugroup) + '/' code, xml = self.submit(None, 'GET', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inserir(self, name, read, write, edit, remove): """Insert new user group and returns its identifier. :param name: User group's name. :param read: If user group has read permission ('S' ou 'N'). :param write: If user group has write permission ('S' ou 'N'). :param edit: If user group has edit permission ('S' ou 'N'). :param remove: If user group has remove permission ('S' ou 'N'). :return: Dictionary with structure: {'user_group': {'id': < id >}} :raise InvalidParameterError: At least one of the parameters is invalid or none.. :raise NomeGrupoUsuarioDuplicadoError: User group name already exists. :raise ValorIndicacaoPermissaoInvalidoError: Read, write, edit or remove value is invalid. :raise DataBaseError: Networkapi failed to access database. :raise XMLError: Networkapi fails generating response XML. """
ugroup_map = dict() ugroup_map['nome'] = name ugroup_map['leitura'] = read ugroup_map['escrita'] = write ugroup_map['edicao'] = edit ugroup_map['exclusao'] = remove code, xml = self.submit({'user_group': ugroup_map}, 'POST', 'ugroup/') return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alterar(self, id_user_group, name, read, write, edit, remove): """Edit user group data from its identifier. :param id_user_group: User group id. :param name: User group name. :param read: If user group has read permission ('S' ou 'N'). :param write: If user group has write permission ('S' ou 'N'). :param edit: If user group has edit permission ('S' ou 'N'). :param remove: If user group has remove permission ('S' ou 'N'). :return: None :raise NomeGrupoUsuarioDuplicadoError: User group name already exists. :raise ValorIndicacaoPermissaoInvalidoError: Read, write, edit or remove value is invalid. :raise GrupoUsuarioNaoExisteError: User Group not found. :raise InvalidParameterError: At least one of the parameters is invalid or none. :raise DataBaseError: Networkapi failed to access database. :raise XMLError: Networkapi fails generating response XML. """
if not is_valid_int_param(id_user_group): raise InvalidParameterError( u'Invalid or inexistent user group id.') url = 'ugroup/' + str(id_user_group) + '/' ugroup_map = dict() ugroup_map['nome'] = name ugroup_map['leitura'] = read ugroup_map['escrita'] = write ugroup_map['edicao'] = edit ugroup_map['exclusao'] = remove code, xml = self.submit({'user_group': ugroup_map}, 'PUT', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remover(self, id_user_group): """Removes a user group by its id. :param id_user_group: User Group's identifier. Valid integer greater than zero. :return: None :raise GrupoUsuarioNaoExisteError: User Group not found. :raise InvalidParameterError: User Group id is invalid or none. :raise DataBaseError: Networkapi failed to access database. :raise XMLError: Networkapi fails generating response XML. """
if not is_valid_int_param(id_user_group): raise InvalidParameterError( u'Invalid or inexistent user group id.') url = 'ugroup/' + str(id_user_group) + '/' code, xml = self.submit(None, 'DELETE', url) return self.response(code, xml)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_environment(self, environment_ids): """ Method to get environment """
uri = 'api/v3/environment/%s/' % environment_ids return super(ApiEnvironment, self).get(uri)