output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Adds a key to the bot s data structures.
Make a summary of the following Python 3 code def add_api_key(key, value): if key is None or key == "": logger.error("Key cannot be empty") if value is None or value == "": logger.error("Value cannot be empty") from .. import datatools data = datatools.get_data() if "keys" not in...
As a Python code composer, you craft elegant and concise scripts.
def success(channel, title, datapacks): """ Creates an embed UI containing the help message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed datapacks (list): The hex value Returns: ui (ui_embed.UI): The embed...
Can you create a Python 3 function that creates an embed UI containing the help message
You are a Python code analyst, evaluating scripts for potential improvements.
def http_exception(channel, title): """ Creates an embed UI containing the 'too long' error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed Returns: ui (ui_embed.UI): The embed UI object """ # Create...
Write a Python 3 function that can create an embed UI containing the too long error message
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_or_create_config(path, prompt=True): """ Get or create a Tarbell configuration directory. """ dirname = os.path.dirname(path) filename = os.path.basename(path) try: os.makedirs(dirname) except OSError: pass try: with open(path, 'r+') as f: i...
Write a Python 3 script for getting or create a Tarbell configuration file.
You are a Python code architect, reviewing and designing scalable and efficient code
def _setup_google_spreadsheets(settings, path, prompt=True): """ Set up a Google spreadsheet. """ ret = {} if prompt: use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ") if use.lower() != "y" and use != "": return settings dirname = os.path.dirname...
Implement a function in Python 3 to set up a Google spreadsheet.
You are a Python code architect, reviewing and designing scalable and efficient code
def _setup_s3(settings, path, prompt=True): """ Prompt user to set up Amazon S3. """ ret = {'default_s3_buckets': {}, 's3_credentials': settings.get('s3_credentials', {})} if prompt: use = raw_input("\nWould you like to set up Amazon S3? [Y/n] ") if use.lower() != "y" and use != "":...
Write a Python 3 script for prompting user to set up Amazon S3.
As a Python code translator, you convert algorithms and pseudocode into Python.
Setup Tarbell project path.
Can you tell what is the following Python 3 function doing def _setup_tarbell_project_path(settings, path, prompt=True): default_path = os.path.expanduser(os.path.join("~", "tarbell")) projects_path = raw_input("\nWhat is your Tarbell projects path? [Default: {0}, 'none' to skip] ".format(default_path)) if ...
As a Python code composer, you craft elegant and concise scripts.
Add some (hardcoded) default templates.
Given the following Python 3 function, write the documentation def _setup_default_templates(settings, path, prompt=True): project_templates = [{ "name": "Basic Bootstrap 3 template", "url": "https://github.com/tarbell-project/tarbell-template", }, { "name": "Searchable map template", ...
As a Python code analyst, you investigate and solve complex coding mysteries
Wrap puts to avoid getting called twice by Werkzeug reloader.
Can you generate the documentation for the following Python 3 function def puts(s='', newline=True, stream=STDOUT): if not is_werkzeug_process(): try: return _puts(s, newline, stream) except UnicodeEncodeError: return _puts(s.encode(sys.stdout.encoding), newline, stream)
You are a Python code generator, capable of creating scripts from specifications.
Get from a list with an optional default value.
Can you generate a brief explanation for the following Python 3 code def list_get(l, idx, default=None): try: if l[idx]: return l[idx] else: return default except IndexError: return default
As a Python code translator, you convert algorithms and pseudocode into Python.
Split a string into a list of sentences.
Can you tell what is the following Python 3 function doing def split_sentences(s, pad=0): sentences = [] for index, sentence in enumerate(s.split('. ')): padding = '' if index > 0: padding = ' ' * (pad + 1) if sentence.endswith('.'): sentence = sentence[:-1] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def ensure_directory(path): """ Ensure directory exists for a given file path. """ dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname)
Can you implement a function in Python 3 that ensures that the directory exists for a given file path.
You are a Python code architect, reviewing and designing scalable and efficient code
Add a stream to the SRTP session applying the given policy to the stream.
Can you generate the documentation for the following Python 3 function def add_stream(self, policy): _srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy))
As a Python code composer, you craft elegant and concise scripts.
def remove_stream(self, ssrc): """ Remove the stream with the given `ssrc` from the SRTP session. :param ssrc: :class:`int` """ _srtp_assert(lib.srtp_remove_stream(self._srtp[0], htonl(ssrc)))
How would you code a function in Python 3 to remove the stream with the given ssrc from the SRTP session.
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts Excel file contents into Tarbell worksheet data
Can you generate a brief explanation for the following Python 3 code def process_xlsx(content): data = {} workbook = xlrd.open_workbook(file_contents=content) worksheets = [w for w in workbook.sheet_names() if not w.startswith('_')] for worksheet_name in worksheets: if worksheet_name.startswith(...
As a Python code translator, you convert algorithms and pseudocode into Python.
Copy values from the global namespace into the data.
Given the following Python 3 function, write the documentation def copy_global_values(data): for k, v in data['values'].items(): if not data.get(k): data[k] = v else: puts("There is both a worksheet and a " "value named '{0}'. The worksheet data " ...
You are a Python code architect, reviewing and designing scalable and efficient code
Make headers from worksheet
Given the following Python 3 function, write the documentation def make_headers(worksheet): headers = {} cell_idx = 0 while cell_idx < worksheet.ncols: cell_type = worksheet.cell_type(0, cell_idx) if cell_type == 1: header = slughifi(worksheet.cell_value(0, cell_idx)) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Make data from a worksheet.
Here you have a function in Python 3, explain what it does def make_worksheet_data(headers, worksheet): data = [] row_idx = 1 while row_idx < worksheet.nrows: cell_idx = 0 row_dict = {} while cell_idx < worksheet.ncols: cell_type = worksheet.cell_type(row_idx, cell_idx) ...
As a python code expert, you are capable of creating scripts from specifications.
def never_cache_preview(self, response): """ Ensure preview is never cached """ response.cache_control.max_age = 0 response.cache_control.no_cache = True response.cache_control.must_revalidate = True response.cache_control.no_store = True return response
Can you write a function in Python 3 where it ensures preview is never cached
You are a Python code architect, reviewing and designing scalable and efficient code
def call_hook(self, hook, *args, **kwargs): """ Calls each registered hook """ for function in self.hooks[hook]: function.__call__(*args, **kwargs)
Can you write a function in Python 3 where it calls each registered hook
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the base module for the current project.
Given the following Python 3 function, write the documentation def _get_base(self, path): base = None # Slightly ugly DRY violation for backwards compatibility with old # "_base" convention if os.path.isdir(os.path.join(path, "_blueprint")): base_dir = os.path.join(path, "_b...
You are a Python code generator, capable of creating scripts from specifications.
def load_project(self, path): """ Load a Tarbell project """ base = self._get_base(path) filename, pathname, description = imp.find_module('tarbell_config', [path]) project = imp.load_module('project', filename, pathname, description) try: self.key =...
Can you write a function in Python 3 where it loads a Tarbell project and return a dictionary of the project s attributes.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _resolve_path(self, path): """ Resolve static file paths """ filepath = None mimetype = None for root, dirs, files in self.filter_files(self.path): # Does it exist in error path? error_path = os.path.join(os.path.dirname(os.path.abspath(__file...
Implement a function in Python 3 to resolve static file paths
You are a Python code architect, reviewing and designing scalable and efficient code
Serve site context as JSON. Useful for debugging.
Given the following Python 3 function, write the documentation def data_json(self, extra_context=None, publish=False): if not self.project.CREATE_JSON: # nothing to see here, but the right mimetype return jsonify() if not self.data: # this sets site.data by spreadshe...
You are a Python code generator, capable of creating scripts from specifications.
def preview(self, path=None, extra_context=None, publish=False): """ Serve up a project path """ try: self.call_hook("preview", self) if path is None: path = 'index.html' # Detect files filepath, mimetype = self._resolve_p...
Can you write a function in Python 3 where it serves up a project path and return a response.
You are a Python code generator, capable of creating scripts from specifications.
def get_context(self, publish=False): """ Use optional CONTEXT_SOURCE_FILE setting to determine data source. Return the parsed data. Can be an http|https url or local file. Supports csv and excel files. """ context = self.project.DEFAULT_CONTEXT try: ...
Write a Python 3 script to return the parsed data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_context_from_xlsx(self): """ Get context from an Excel file """ if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE): resp = requests.get(self.project.CONTEXT_SOURCE_FILE) content = resp.content else: try: ...
Write a Python 3 script for getting context from an Excel file
You are a Python code architect, reviewing and designing scalable and efficient code
def get_context_from_csv(self): """ Open CONTEXT_SOURCE_FILE, parse and return a context """ if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE): data = requests.get(self.project.CONTEXT_SOURCE_FILE) reader = csv.reader( data.iter_li...
Write a Python 3 script for parsing and return a context from the CONTEXT_SOURCE_FILE
As a python code expert, you are capable of creating scripts from specifications.
Wrap getting context from Google sheets in a simple caching mechanism.
Can you generate a brief explanation for the following Python 3 code def get_context_from_gdoc(self): try: start = int(time.time()) if not self.data or start > self.expires: self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY) end = int(ti...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a Jinja2 context from a Google spreadsheet.
Can you generate a brief explanation for the following Python 3 code def _get_context_from_gdoc(self, key): try: content = self.export_xlsx(key) data = process_xlsx(content) if 'values' in data: data = copy_global_values(data) return data e...
You are a Python code analyst, evaluating scripts for potential improvements.
def export_xlsx(self, key): """ Download xlsx version of spreadsheet. """ spreadsheet_file = self.client.files().get(fileId=key).execute() links = spreadsheet_file.get('exportLinks') downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.shee...
How would you implement a function in Python 3 that downloads xlsx version of spreadsheet.
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_static_site(self, output_root=None, extra_context=None): """ Bake out static site """ self.app.config['BUILD_PATH'] = output_root # use this hook for registering URLs to freeze self.call_hook("generate", self, output_root, extra_context) if output_r...
Write a Python 3 function that can generate a static site for the current application.
As a Python code analyst, you investigate and solve complex coding mysteries
def filter_files(self, path): """ Exclude files based on blueprint and project configuration as well as hidden files. """ excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.' for root, dirs, files in os.walk(path, topdown=True): dirs[:]...
Write a Python 3 script to filter files based on blueprint and project configuration as well as hidden files.
As a python code expert, you are capable of creating scripts from specifications.
def find_files(self): """ Find all file paths for publishing, yield (urlname, kwargs) """ # yield blueprint paths first if getattr(self, 'blueprint_name', None): for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES): ...
Write a Python 3 function that can find all files for publishing yield urlname kwargs
As a Python code analyst, you investigate and solve complex coding mysteries
def deploy_to_s3(self): """ Deploy a directory to an s3 bucket. """ self.tempdir = tempfile.mkdtemp('s3deploy') for keyname, absolute_path in self.find_file_paths(): self.s3_upload(keyname, absolute_path) shutil.rmtree(self.tempdir, True) return True
Write a Python 3 function for deploying a directory to an s3 bucket.
You are a Python code architect, reviewing and designing scalable and efficient code
Upload a file to s3
Make a summary of the following Python 3 code def s3_upload(self, keyname, absolute_path): mimetype = mimetypes.guess_type(absolute_path) options = {'Content-Type': mimetype[0]} if mimetype[0] is not None and mimetype[0].startswith('text/'): upload = open(absolute_path, 'rb') ...
As a Python code translator, you convert algorithms and pseudocode into Python.
A generator function that recursively finds all files in the upload directory.
Make a summary of the following Python 3 code def find_file_paths(self): paths = [] for root, dirs, files in os.walk(self.directory, topdown=True): rel_path = os.path.relpath(root, self.directory) for f in files: if rel_path == '.': path = (f, ...
As a python code expert, you are capable of creating scripts from specifications.
Get drive API client based on settings.
How would you explain what the following Python 3 function does def get_drive_api(): settings = Settings() if settings.credentials: return get_drive_api_from_file(settings.credentials_path) if settings.client_secrets: return get_drive_api_from_client_secrets(settings.client_secrets_path)
You are a Python code analyst, evaluating scripts for potential improvements.
def get_drive_api_from_client_secrets(path, reset_creds=False): """ Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API ...
Write a Python 3 function that can read the client secrets file if available and authorizes them.
You are a Python code analyst, evaluating scripts for potential improvements.
Get drive API from file.
Explain what the following Python 3 code does def get_drive_api_from_file(path): f = open(path) credentials = client.OAuth2Credentials.from_json(f.read()) return _get_drive_api(credentials)
As a python code expert, you are capable of creating scripts from specifications.
def _get_drive_api(credentials): """ For a given set of credentials, return a drive API object. """ http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('drive', 'v2', http=http) service.credentials = credentials # duck punch service obj. with credentials ...
Write a Python 3 function for returning a drive API object for a given set of credentials.
You are a Python code generator, capable of creating scripts from specifications.
Install a project template.
Here you have a function in Python 3, explain what it does def tarbell_install_blueprint(command, args): with ensure_settings(command, args) as settings: name = None error = None template_url = args.get(0) matches = [template for template in settings.config["project_templates"] if te...
As a Python code translator, you convert algorithms and pseudocode into Python.
def tarbell_list_templates(command, args): """ List available Tarbell blueprints. """ with ensure_settings(command, args) as settings: puts("\nAvailable project templates\n") _list_templates(settings) puts("")
Write a Python 3 function for listing available Tarbell templates.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new Tarbell project.
Here you have a function in Python 3, explain what it does def tarbell_newproject(command, args): with ensure_settings(command, args) as settings: # Set it up and make the directory name = _get_project_name(args) puts("Creating {0}".format(colored.cyan(name))) path = _get_path(name, ...
As a Python code composer, you craft elegant and concise scripts.
def tarbell_serve(command, args): """ Serve the current Tarbell project. """ with ensure_project(command, args) as site: with ensure_settings(command, args) as settings: address = list_get(args, 0, "").split(":") ip = list_get(address, 0, settings.config['default_server_i...
Write a Python 3 function that can serve the current Tarbell project.
As a Python code translator, you convert algorithms and pseudocode into Python.
Switch to a project.
Can you generate a brief explanation for the following Python 3 code def tarbell_switch(command, args): with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) ...
You are a Python code generator, capable of creating scripts from specifications.
def tarbell_update(command, args): """ Update the current tarbell project. """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: puts("Updating to latest blueprint\n") git = sh.git.bake(_cwd=site.base.base_dir) # stash then pull put...
Write a Python 3 function for updating the current tarbell project.
As a python code expert, you are capable of creating scripts from specifications.
def tarbell_spreadsheet(command, args): """ Open context spreadsheet """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: try: # First, try to get the Google Spreadsheet URL spreadsheet_url = _google_spreadsheet_url(site.project.SPRE...
How would you implement a function in Python 3 that opens a context spreadsheet with the specified settings and project.
You are a Python code generator, capable of creating scripts from specifications.
def _context_source_file_url(path_or_url): """ Returns a URL for a remote or local context CSV file """ if path_or_url.startswith('http'): # Remote CSV. Just return the URL return path_or_url if path_or_url.startswith('/'): # Absolute path return "file://" + path_or_...
Can you create a Python 3 function that returns a URL for a remote or local context CSV file
As a python code expert, you are capable of creating scripts from specifications.
Helper to create a new project.
Here you have a function in Python 3, explain what it does def _newproject(command, path, name, settings): key = None title = _get_project_title() template = _get_template(settings) # Init repo git = sh.git.bake(_cwd=path) puts(git.init()) if template.get("url"): # Create submodule...
As a python code expert, you are capable of creating scripts from specifications.
def _install_requirements(path): """ Install a blueprint's requirements.txt """ locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path] success = True for location in locations: try: with open(os.path.join(location, "requirements.txt")): ...
How would you implement a function in Python 3 that installs a blueprint s requirements. txt
You are a Python code generator, capable of creating scripts from specifications.
def _clean_suffix(string, suffix): """ If string endswith the suffix, remove it. Else leave it alone. """ suffix_len = len(suffix) if len(string) < suffix_len: # the string param was shorter than the suffix raise ValueError("A suffix can not be bigger than string argument.") if ...
Write a Python 3 function that can remove the suffix from the string and returns the string.
As a python code expert, you are capable of creating scripts from specifications.
Generate a project path.
Make a summary of the following Python 3 code def _get_path(name, settings, mkdir=True): default_projects_path = settings.config.get("projects_path") path = None if default_projects_path: path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name...
You are a Python code analyst, evaluating scripts for potential improvements.
Make a directory or bail.
Can you generate the documentation for the following Python 3 function def _mkdir(path): try: os.mkdir(path) except OSError as e: if e.errno == 17: show_error("ABORTING: Directory {0} already exists.".format(path)) else: show_error("ABORTING: OSError {0}".format(e...
You are a Python code generator, capable of creating scripts from specifications.
Prompt user to pick a template from a list.
Given the following Python 3 function, write the documentation def _get_template(settings): puts("\nPick a template\n") template = None while not template: _list_templates(settings) index = raw_input("\nWhich template would you like to use? [1] ") if not index: index = "1...
As a python code expert, you are capable of creating scripts from specifications.
def _list_templates(settings): """ List templates from settings. """ for idx, option in enumerate(settings.config.get("project_templates"), start=1): puts(" {0!s:5} {1!s:36}".format( colored.yellow("[{0}]".format(idx)), colored.cyan(option.get("name")) )) ...
Write a Python 3 script for listing templates from settings.
You are a Python code generator, capable of creating scripts from specifications.
def _create_spreadsheet(name, title, path, settings): """ Create Google spreadsheet. """ if not settings.client_secrets: return None create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ") if create and not create.lower() == "y": return puts("Not creating sp...
Create a Python 3 function to create a Google spreadsheet.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _add_user_to_file(file_id, service, user_email, perm_type='user', role='writer'): """ Grants the given set of permissions for a given file_id. service is an already-credentialed Google Drive service instance. """ new_permission = { 'value': user_email, 'type...
How would you implement a function in Python 3 that adds a user to a file in the spreadsheet.
You are a Python code analyst, evaluating scripts for potential improvements.
Copy a template from Tarbell default to the tarbell_config. py. template file.
Given the following Python 3 function, write the documentation def _copy_config_template(name, title, template, path, key, settings): puts("\nCopying configuration file") context = settings.config context.update({ "default_context": { "name": name, "ti...
You are a Python code architect, reviewing and designing scalable and efficient code
Save settings. to file.
Here you have a function in Python 3, explain what it does def save(self): with open(self.path, "w") as f: self.config["project_templates"] = list(filter(lambda template: template.get("url"), self.config["project_templates"])) yaml.dump(self.config, f, default_flow_style=False)
As a python code expert, you are capable of creating scripts from specifications.
Read the file at path.
Can you generate the documentation for the following Python 3 function def read_file(path, absolute=False, encoding='utf-8'): site = g.current_site if not absolute: path = os.path.join(site.path, path) try: return codecs.open(path, 'r', encoding).read() except IOError: return No...
You are a Python code generator, capable of creating scripts from specifications.
def render_file(context, path, absolute=False): """ Like :py:func:`read_file`, except that the file is rendered as a Jinja template using the current context. If `absolute` is True, use absolute path, otherwise path is assumed to be relative to Tarbell template root dir. For example: ...
How would you code a function in Python 3 to render a file using the current context.
As a Python code analyst, you investigate and solve complex coding mysteries
def format_date(value, format='%b %d, %Y', convert_tz=None): """ Format an Excel date or date string, returning a formatted date. To return a Python :py:class:`datetime.datetime` object, pass ``None`` as a ``format`` argument. >>> format_date(42419.82163) 'Feb. 19, 2016' .. code-block:: ht...
Write a Python 3 function for returning a formatted date string.
As a Python code composer, you craft elegant and concise scripts.
Plot a dataframe of generics and label underlying instruments which are composed of.
Can you generate a brief explanation for the following Python 3 code def plot_composition(df, intervals, axes=None): generics = df.columns if (axes is not None) and (len(axes) != len(generics)): raise ValueError("If 'axes' is not None then it must be the same " "length as 'df.c...
As a Python code composer, you craft elegant and concise scripts.
def intervals(weights): """ Extract intervals where generics are composed of different tradeable instruments. Parameters ---------- weights: DataFrame or dict A DataFrame or dictionary of DataFrames with columns representing generics and a MultiIndex of date and contract. Values...
How would you implement a function in Python 3 that extracts intervals where generics are composed of different tradeable instruments.
As a Python code translator, you convert algorithms and pseudocode into Python.
Synchronizes the Router DB with the EOS.
Explain what the following Python 3 code does def synchronize(self): LOG.info(_LI('Syncing Neutron Router DB <-> EOS')) routers, router_interfaces = self.get_routers_and_interfaces() expected_vrfs = set() if self._use_vrf: expected_vrfs.update(self.driver._arista_router_name(...
As a Python code composer, you craft elegant and concise scripts.
def create_router(self, context, router): """Create a new router entry in DB, and create it Arista HW.""" # Add router to the DB new_router = super(AristaL3ServicePlugin, self).create_router( context, router) # create router on the Arista Hw try: ...
Can you create a Python 3 function that creates a new router entry in DB and create it Arista HW.
You are a Python code generator, capable of creating scripts from specifications.
def update_router(self, context, router_id, router): """Update an existing router in DB, and update it in Arista HW.""" # Read existing router record from DB original_router = self.get_router(context, router_id) # Update router DB new_router = super(AristaL3ServicePlugin, self)....
Implement a function in Python 3 to update an existing router in DB and update it in Arista HW.
You are a Python code architect, reviewing and designing scalable and efficient code
Delete an existing router from Arista HW and from the DB.
Make a summary of the following Python 3 code def delete_router(self, context, router_id): router = self.get_router(context, router_id) # Delete router on the Arista Hw try: self.driver.delete_router(context, router_id, router) except Exception as e: LOG.error(_...
You are a Python code generator, capable of creating scripts from specifications.
Add a subnet of a network to an existing router.
Can you tell what is the following Python 3 function doing def add_router_interface(self, context, router_id, interface_info): new_router = super(AristaL3ServicePlugin, self).add_router_interface( context, router_id, interface_info) core = directory.get_plugin() # Get network info...
As a Python code composer, you craft elegant and concise scripts.
def remove_router_interface(self, context, router_id, interface_info): """Remove a subnet of a network from an existing router.""" router_to_del = ( super(AristaL3ServicePlugin, self).remove_router_interface( context, router_id, interface_info...
Can you implement a function in Python 3 that removes a subnet of a network from an existing router.
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize switch endpoints for switch communication
Make a summary of the following Python 3 code def initialize_switch_endpoints(self): self._switches = {} self._port_group_info = {} self._validate_config() for s in cfg.CONF.ml2_arista.switch_info: switch_ip, switch_user, switch_pass = s.split(":") if switch_pass ...
As a python code expert, you are capable of creating scripts from specifications.
Log an error if any switches don t support dynamic ACLs.
Given the following Python 3 function, write the documentation def _check_dynamic_acl_support(self): cmds = ['ip access-list openstack-test dynamic', 'no ip access-list openstack-test'] for switch_ip, switch_client in self._switches.items(): try: self.run_open...
You are a Python code generator, capable of creating scripts from specifications.
def _validate_config(self): """Ensure at least one switch is configured""" if len(cfg.CONF.ml2_arista.get('switch_info')) < 1: msg = _('Required option - when "sec_group_support" is enabled, ' 'at least one switch must be specified ') LOG.exception(msg) ...
Can you write a function in Python 3 where it ensures at least one switch is configured
You are a Python code analyst, evaluating scripts for potential improvements.
Execute a list of commands on Arista switch and send them to the Arista server.
Can you generate a brief explanation for the following Python 3 code def run_openstack_sg_cmds(self, commands, switch): if not switch: LOG.exception("No client found for switch") return [] if len(commands) == 0: return [] command_start = ['enable', 'configure'...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _run_eos_cmds(self, commands, switch): """Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the ...
Write a Python 3 script for executing a list of commands on Arista switch and return the result of the command.
As a python code expert, you are capable of creating scripts from specifications.
def _get_switchports(profile): """Return list of (switch_ip, interface) tuples from local_link_info""" switchports = [] if profile.get('local_link_information'): for link in profile['local_link_information']: if 'switch_info' in link and 'port_id' in link: ...
Implement a function in Python 3 to return list of switch_ip and interface tuples from local_link_info
As a python code expert, you are capable of creating scripts from specifications.
def _update_port_group_info(self, switches=None): """Refresh data on switch interfaces' port group membership""" if switches is None: switches = self._switches.keys() for switch_ip in switches: client = self._switches.get(switch_ip) ret = self._run_eos_cmds(['...
Write a Python 3 script to refresh data on switch interfaces port group membership
As a python code expert, you are capable of creating scripts from specifications.
Gets the interface name for a given port_id for a switch.
Explain what the following Python 3 code does def _get_port_for_acl(self, port_id, switch): all_intf_info = self._port_group_info.get(switch, {}) intf_info = all_intf_info.get(port_id, {}) member_info = intf_info.get('interfaceMembership', '') port_group_info = re.search('Member of (?P<p...
As a Python code composer, you craft elegant and concise scripts.
Checks that the rule is an IPv4 rule of a supported protocol
Make a summary of the following Python 3 code def _supported_rule(protocol, ethertype): if not protocol or protocol not in utils.SUPPORTED_SG_PROTOCOLS: return False if ethertype != n_const.IPv4: return False return True
As a python code expert, you are capable of creating scripts from specifications.
def _format_rule(self, protocol, cidr, min_port, max_port, direction): """Get EOS formatted rule""" if cidr is None: cidr = 'any' if direction == n_const.INGRESS_DIRECTION: dst_ip = 'any' src_ip = cidr elif direction == n_const.EGRESS_DIRECTION: ...
Can you implement a function in Python 3 that gets EOS formatted rule
As a Python code analyst, you investigate and solve complex coding mysteries
def _format_rules_for_eos(self, rules): """Format list of rules for EOS and sort into ingress/egress rules""" in_rules = [] eg_rules = [] for rule in rules: protocol = rule.get('protocol') cidr = rule.get('remote_ip_prefix', 'any') min_port = rule.get(...
Can you implement a function in Python 3 that formats list of rules for EOS and sort into ingress and egress rules
As a Python code composer, you craft elegant and concise scripts.
def run_cmds_on_all_switches(self, cmds): """Runs all cmds on all configured switches This helper is used for ACL and rule creation/deletion as ACLs and rules must exist on all switches. """ for switch in self._switches.values(): self.run_openstack_sg_cmds(cmds, swit...
Write a Python 3 script to run all cmds on all configured switches
As a Python code analyst, you investigate and solve complex coding mysteries
Applies cmds to appropriate switches This will run only the set of cmds that are specified for a switch on that switch.
How would you explain what the following Python 3 function does def run_per_switch_cmds(self, switch_cmds): for switch_ip, cmds in switch_cmds.items(): switch = self._switches.get(switch_ip) self.run_openstack_sg_cmds(cmds, switch)
You are a Python code analyst, evaluating scripts for potential improvements.
Get set of switches referenced in a port binding profile
Make a summary of the following Python 3 code def _get_switches(self, profile): switchports = self._get_switchports(profile) switches = set([switchport[0] for switchport in switchports]) return switches
As a python code expert, you are capable of creating scripts from specifications.
Returns the list of commands to create a security group.
Make a summary of the following Python 3 code def get_create_security_group_commands(self, sg_id, sg_rules): cmds = [] in_rules, eg_rules = self._format_rules_for_eos(sg_rules) cmds.append("ip access-list %s dynamic" % self._acl_name(sg_id, n_const.INGRESS_DIRECTION)) ...
You are a Python code generator, capable of creating scripts from specifications.
def get_delete_security_group_commands(self, sg_id): """Commands for deleting ACL""" cmds = [] cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const.INGRESS_DIRECTION)) cmds.append("no ip access-list %s" % self._acl_name(sg_id, n_const...
Can you write a function in Python 3 where it returns the list of commands to delete a security group
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the list of commands to remove a rule from an existing security group
Here you have a function in Python 3, explain what it does def get_delete_security_group_rule_commands(self, sg_id, sg_rule): return self._get_rule_cmds(sg_id, sg_rule, delete=True)
You are a Python code generator, capable of creating scripts from specifications.
Helper method for getting the list of commands for an interface ACL apply or remove.
Make a summary of the following Python 3 code def _get_interface_commands(self, sg_id, profile, delete=False): rule_prefix = "" if delete: rule_prefix = "no " switch_cmds = {} switchports = self._get_switchports(profile) for switch_ip, intf in switchports: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the list of commands to remove ACL from interface
How would you explain what the following Python 3 function does def get_remove_security_group_commands(self, sg_id, profile): return self._get_interface_commands(sg_id, profile, delete=True)
You are a Python code generator, capable of creating scripts from specifications.
Parse the ACLs and rules and return a dict of rule sets.
Explain what the following Python 3 code does def _parse_acl_config(self, acl_config): parsed_acls = dict() for acl in acl_config['aclList']: parsed_acls[acl['name']] = set() for rule in acl['sequence']: parsed_acls[acl['name']].add(rule['text']) return pa...
As a Python code composer, you craft elegant and concise scripts.
Parse the config file for the ACL bindings.
Can you tell what is the following Python 3 function doing def _parse_binding_config(self, binding_config): parsed_bindings = set() for acl in binding_config['aclList']: for intf in acl['configuredIngressIntfs']: parsed_bindings.add((intf['name'], acl['name'], ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_dynamic_acl_info(self, switch_ip): """Retrieve ACLs, ACLs rules and interface bindings from switch""" cmds = ["enable", "show ip access-lists dynamic", "show ip access-lists summary dynamic"] switch = self._switches.get(switch_ip) _, acls, bindin...
Write a Python 3 function that can retrieve ACLs rules and interface bindings from switch
As a python code expert, you are capable of creating scripts from specifications.
def get_expected_acls(self): """Query the neutron DB for Security Groups and Rules Groups and rules are returned as a dict of rule sets: {<eos_acl1_name>: set([<eos_acl1_rules>]), <eos_acl2_name>: set([<eos_acl2_rules>]), ..., } """ security_groups = db...
Create a Python 3 function for querying the neutron DB for the expected ACLs.
As a python code expert, you are capable of creating scripts from specifications.
def get_expected_bindings(self): """Query the neutron DB for SG->switch interface bindings Bindings are returned as a dict of bindings for each switch: {<switch1>: set([(intf1, acl_name, direction), (intf2, acl_name, direction)]), <switch2>: set([(intf1, acl_na...
Can you write a function in Python 3 where it queries the neutron DB for SG - > switch interface bindings and return a dict of expected bindings for each switch.
As a Python code analyst, you investigate and solve complex coding mysteries
def adjust_bindings_for_lag(self, switch_ip, bindings): """Adjusting interface names for expected bindings where LAGs exist""" # Get latest LAG info for switch self._update_port_group_info([switch_ip]) # Update bindings to account for LAG info adjusted_bindings = set() ...
Write a Python 3 script for adjusting interface names for expected bindings where LAGs exist
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_sync_acl_cmds(self, switch_acls, expected_acls): """Returns the list of commands required synchronize switch ACLs 1. Identify unexpected ACLs and delete them 2. Iterate over expected ACLs a. Add missing ACLs + all rules b. Delete unexpected rules c. Add ...
Can you write a function in Python 3 where it returns the list of commands required synchronize switch ACLs and expected ACLs and switch rules.
You are a Python code generator, capable of creating scripts from specifications.
def get_sync_binding_cmds(self, switch_bindings, expected_bindings): """Returns the list of commands required to synchronize ACL bindings 1. Delete any unexpected bindings 2. Add any missing bindings """ switch_cmds = list() # Update any necessary switch interface ACLs ...
Can you create a Python 3 function that returns the list of commands required to synchronize the ACL bindings with the expected bindings.
As a Python code composer, you craft elegant and concise scripts.
def flatten(weights): """ Flatten weights into a long DataFrame. Parameters ---------- weights: pandas.DataFrame or dict A DataFrame of instrument weights with a MultiIndex where the top level contains pandas. Timestamps and the second level is instrument names. The columns ...
How would you implement a function in Python 3 that flattens a DataFrame of instrument weights into a long DataFrame.
You are a Python code analyst, evaluating scripts for potential improvements.
Unflattens a single - level dataframe into a single - level DataFrame.
Can you generate the documentation for the following Python 3 function def unflatten(flat_weights): if flat_weights.columns.contains("key"): weights = {} for key in flat_weights.loc[:, "key"].unique(): flt_wts = flat_weights.loc[flat_weights.loc[:, "key"] == key, :] flt_wts =...
You are a Python code generator, capable of creating scripts from specifications.