output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def read(self): '''Execute the expression and capture its output, similar to backticks or $() in the shell. This is a wrapper around run() which captures stdout, decodes it, trims it, and returns it directly.''' result = self.stdout_capture().run() stdout_str = decode_with_univer...
Implement a function in Python 3 to execute the expression and capture its output and return it as a string.
You are a Python code architect, reviewing and designing scalable and efficient code
Equivalent to run but instead of blocking the current thread returns a WaitHandle that doesn t block until wait is called.
Can you generate the documentation for the following Python 3 function def start(self): '''Equivalent to `run`, but instead of blocking the current thread, return a WaitHandle that doesn't block until `wait` is called. This is currently implemented with a simple background thread, though in theo...
As a Python code analyst, you investigate and solve complex coding mysteries
def _exec(self, cmd, url, json_data=None): """ execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be at...
Can you write a function in Python 3 where it executes a command at the device using the RESTful API
You are a Python code architect, reviewing and designing scalable and efficient code
def set_device(self, dev): """ set the current device (that will be used for following API calls) :param dict dev: device that should be used for the API calls (can be obtained via get_devices function) """ log.debug("setting device to '{}'".format(dev))...
Write a Python 3 script for setting the current device
You are a Python code analyst, evaluating scripts for potential improvements.
def _get_widget_id(self, package_name): """ returns widget_id for given package_name does not care about multiple widget ids at the moment, just picks the first :param str package_name: package to check for :return: id of first widget which belongs to the given package_name ...
Write a Python 3 script to return the first widget id for the given package_name
You are a Python code analyst, evaluating scripts for potential improvements.
get the user details via the cloud
Can you generate the documentation for the following Python 3 function def get_user(self): log.debug("getting user information from LaMetric cloud...") _, url = CLOUD_URLS["get_user"] res = self._cloud_session.session.get(url) if res is not None: # raise an exception on error...
You are a Python code architect, reviewing and designing scalable and efficient code
get all devices that are linked to the user
How would you explain what the following Python 3 function does def get_devices(self, force_reload=False, save_devices=True): if ( (not os.path.exists(self._devices_filename)) or (force_reload is True) ): # -- load devices from LaMetric cloud -- log.debug(...
You are a Python code generator, capable of creating scripts from specifications.
save the list of devices that have been obtained from LaMetric to a local file
Make a summary of the following Python 3 code def save_devices(self): log.debug("saving devices to ''...".format(self._devices_filename)) if self._devices != []: with codecs.open(self._devices_filename, "wb", "utf-8") as f: json.dump(self._devices, f)
As a Python code translator, you convert algorithms and pseudocode into Python.
returns API version and endpoint map
Here you have a function in Python 3, explain what it does def get_endpoint_map(self): log.debug("getting end points...") cmd, url = DEVICE_URLS["get_endpoint_map"] return self._exec(cmd, url)
You are a Python code architect, reviewing and designing scalable and efficient code
def load_devices(self): """ load stored devices from the local file """ self._devices = [] if os.path.exists(self._devices_filename): log.debug( "loading devices from '{}'...".format(self._devices_filename) ) with codecs.open(se...
Create a Python 3 function to load stored devices from the local file
You are a Python code architect, reviewing and designing scalable and efficient code
def get_device_state(self): """ returns the full device state """ log.debug("getting device state...") cmd, url = DEVICE_URLS["get_device_state"] return self._exec(cmd, url)
Write a Python 3 function that can return the full device state
You are a Python code analyst, evaluating scripts for potential improvements.
sends a new notification to the device
Can you tell what is the following Python 3 function doing def send_notification( self, model, priority="warning", icon_type=None, lifetime=None ): """ sends new notification to the device :param Model model: an instance of the Model class that should be used :param str prio...
You are a Python code architect, reviewing and designing scalable and efficient code
returns the list of all notifications in queue
Can you generate a brief explanation for the following Python 3 code def get_notifications(self): log.debug("getting notifications in queue...") cmd, url = DEVICE_URLS["get_notifications_queue"] return self._exec(cmd, url)
You are a Python code generator, capable of creating scripts from specifications.
def get_current_notification(self): """ returns the current notification (i.e. the one that is visible) """ log.debug("getting visible notification...") cmd, url = DEVICE_URLS["get_current_notification"] return self._exec(cmd, url)
Write a Python 3 function for returning the current notification
You are a Python code architect, reviewing and designing scalable and efficient code
get a specific notification by given ID
Can you generate the documentation for the following Python 3 function def get_notification(self, notification_id): log.debug("getting notification '{}'...".format(notification_id)) cmd, url = DEVICE_URLS["get_notification"] return self._exec(cmd, url.replace(":id", notification_id))
As a Python code composer, you craft elegant and concise scripts.
def get_display(self): """ returns information about the display, including brightness, screensaver etc. """ log.debug("getting display information...") cmd, url = DEVICE_URLS["get_display"] return self._exec(cmd, url)
Implement a Python 3 function for returning information about the display including brightness screensaver etc.
As a python code expert, you are capable of creating scripts from specifications.
def set_display(self, brightness=100, brightness_mode="auto"): """ allows to modify display state (change brightness) :param int brightness: display brightness [0, 100] (default: 100) :param str brightness_mode: the brightness mode of the display [aut...
Create a Python 3 function to allow to change display state
As a Python code analyst, you investigate and solve complex coding mysteries
set the display s screensaver mode
Can you generate the documentation for the following Python 3 function def set_screensaver( self, mode, is_mode_enabled, start_time=None, end_time=None, is_screensaver_enabled=True ): """ set the display's screensaver mode :param str mode: mode of the screensaver ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_volume(self): """ returns the current volume """ log.debug("getting volumne...") cmd, url = DEVICE_URLS["get_volume"] return self._exec(cmd, url)
Write a Python 3 script to return the current volume
You are a Python code generator, capable of creating scripts from specifications.
def set_volume(self, volume=50): """ allows to change the volume :param int volume: volume to be set for the current device [0..100] (default: 50) """ assert(volume in range(101)) log.debug("setting volume...") cmd, url = DEVICE_URLS[...
Can you implement a function in Python 3 that allows to change the volume for the current device
As a Python code composer, you craft elegant and concise scripts.
def get_bluetooth_state(self): """ returns the bluetooth state """ log.debug("getting bluetooth state...") cmd, url = DEVICE_URLS["get_bluetooth_state"] return self._exec(cmd, url)
Can you implement a function in Python 3 that returns the bluetooth state
You are a Python code architect, reviewing and designing scalable and efficient code
allows to activate or deactivate bluetooth and change the name
Explain what the following Python 3 code does def set_bluetooth(self, active=None, name=None): assert(active is not None or name is not None) log.debug("setting bluetooth state...") cmd, url = DEVICE_URLS["set_bluetooth"] json_data = {} if name is not None: json_dat...
You are a Python code generator, capable of creating scripts from specifications.
returns the current Wi - Fi state of the device connected to
How would you explain what the following Python 3 function does def get_wifi_state(self): log.debug("getting wifi state...") cmd, url = DEVICE_URLS["get_wifi_state"] return self._exec(cmd, url)
As a Python code composer, you craft elegant and concise scripts.
gets installed apps and puts them into the available_apps list
Make a summary of the following Python 3 code def set_apps_list(self): log.debug("getting apps and setting them in the internal app list...") cmd, url = DEVICE_URLS["get_apps_list"] result = self._exec(cmd, url) self.available_apps = [ AppModel(result[app]) for ...
You are a Python code architect, reviewing and designing scalable and efficient code
Switches the app that is specified by package. Selects the first app that is found in the app list .
Given the following Python 3 function, write the documentation def switch_to_app(self, package): log.debug("switching to app '{}'...".format(package)) cmd, url = DEVICE_URLS["switch_to_app"] widget_id = self._get_widget_id(package) url = url.format('{}', package, widget_id) sel...
You are a Python code generator, capable of creating scripts from specifications.
def switch_to_next_app(self): """ switches to the next app """ log.debug("switching to next app...") cmd, url = DEVICE_URLS["switch_to_next_app"] self.result = self._exec(cmd, url)
Write a Python 3 function for switching to the next app
You are a Python code analyst, evaluating scripts for potential improvements.
def activate_widget(self, package): """ activate the widget of the given package :param str package: name of the package """ cmd, url = DEVICE_URLS["activate_widget"] # get widget id for the package widget_id = self._get_widget_id(package) url = url.form...
Write a Python 3 script for activating the widget of the given package
You are a Python code generator, capable of creating scripts from specifications.
This method is used to execute a specific action on all apps with the same package.
Can you generate a brief explanation for the following Python 3 code def _app_exec(self, package, action, params=None): # get list of possible commands from app.actions allowed_commands = [] for app in self.get_apps_list(): if app.package == package: allowed_commands ...
You are a Python code analyst, evaluating scripts for potential improvements.
def alarm_set(self, time, wake_with_radio=False): """ set the alarm clock :param str time: time of the alarm (format: %H:%M:%S) :param bool wake_with_radio: if True, radio will be used for the alarm instead of beep sound """ # TODO: c...
Write a Python 3 script for setting the alarm clock alid
As a python code expert, you are capable of creating scripts from specifications.
def countdown_set(self, duration, start_now): """ set the countdown :param str duration: :param str start_now: """ log.debug("countdown => set...") params = {'duration': duration, 'start_now': start_now} self._app_exec( "com.lametric.countdown...
Create a Python 3 function to set the countdown for a given time period
You are a Python code architect, reviewing and designing scalable and efficient code
def action(self, includes: dict, variables: dict) -> tuple: """ Call external script. :param includes: testcase's includes :param variables: variables :return: script's output """ json_args = fill_template_str(json.dumps(self.data), variables) p = subproc...
How would you implement a function in Python 3 that calls external script. :param includes: testcase's includes :param variables: variables :return: script's output
As a Python code analyst, you investigate and solve complex coding mysteries
def set_credentials(self, client_id=None, client_secret=None): """ set given credentials and reset the session """ self._client_id = client_id self._client_secret = client_secret # make sure to reset session due to credential change self._session = None
Create a Python 3 function to set credentials and reset the session
As a Python code analyst, you investigate and solve complex coding mysteries
init a new oauth2 session that is required to access the cloud
Can you tell what is the following Python 3 function doing def init_session(self, get_token=True): if (self._client_id is None) or (self._client_secret is None): sys.exit( "Please make sure to set the client id and client secret " "via the constructor, the environment...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_token(self): """ get current oauth token """ self.token = self._session.fetch_token( token_url=CLOUD_URLS["get_token"][1], client_id=self._client_id, client_secret=self._client_secret )
Can you create a Python 3 function that gets current oauth token
As a Python code translator, you convert algorithms and pseudocode into Python.
def simple_input(self, variables): """ Use this method to get simple input as python object, with all templates filled in :param variables: :return: python object """ json_args = fill_template_str(json.dumps(self.data), variables) return try_get_objects(...
Write a Python 3 script to use this method to get simple input as python object with all templates filled in
As a Python code analyst, you investigate and solve complex coding mysteries
Creates an empty configuration file based on template and saves it.
Make a summary of the following Python 3 code def create(self): if not self.exists(): # create new empyt config file based on template self.config.add_section("lametric") self.config.set("lametric", "client_id", "") self.config.set("lametric", "client_secret", "")...
You are a Python code generator, capable of creating scripts from specifications.
def save(self): """ save current config to the file """ with open(self._filename, "w") as f: self.config.write(f)
Create a Python 3 function for saving current config to the file
As a Python code translator, you convert algorithms and pseudocode into Python.
Sleep if rate limiting is required based on current time and last query.
Explain what the following Python 3 code does def rate_limit_wait(self): if self._rate_limit_dt and self._last_query is not None: dt = time.time() - self._last_query wait = self._rate_limit_dt - dt if wait > 0: time.sleep(wait)
You are a Python code architect, reviewing and designing scalable and efficient code
def route(self, arg, destination=None, waypoints=None, raw=False, **kwargs): """ Query a route. route(locations): points can be - a sequence of locations - a Shapely LineString route(origin, destination, waypoints=None) - origin and destination are a...
Create a Python 3 function to query a route from a Shapely line to a Shapely point.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a Route object from a GeoJSON dictionary.
How would you explain what the following Python 3 function does def from_geojson(cls, data): properties = data['properties'] distance = properties.pop('distance') duration = properties.pop('duration') maneuvers = [] for feature in data['features']: geom = feature['ge...
You are a Python code generator, capable of creating scripts from specifications.
Scan all paths for external modules and form key - value dict.
Given the following Python 3 function, write the documentation def prepare_modules(module_paths: list, available: dict) -> dict: indexed = {} for path in module_paths: if not os.path.exists(path) and path not in available: err = 'No such path: ' + path error(err) else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send an SSDP discovery packet to the network and collects the devices that replies to it.
Here you have a function in Python 3, explain what it does def discover_upnp_devices( self, st="upnp:rootdevice", timeout=2, mx=1, retries=1 ): """ sends an SSDP discovery packet to the network and collects the devices that replies to it. A dictionary is returned using the de...
You are a Python code generator, capable of creating scripts from specifications.
def get_filtered_devices( self, model_name, device_types="upnp:rootdevice", timeout=2 ): """ returns a dict of devices that contain the given model name """ # get list of all UPNP devices in the network upnp_devices = self.discover_upnp_devices(st=device_types) ...
How would you implement a function in Python 3 that gets a dict of devices that contain the given model name.
You are a Python code analyst, evaluating scripts for potential improvements.
A variant of multiprocessing. Pool. map that supports lazy evaluation of a single object.
Here you have a function in Python 3, explain what it does def lazy_map(data_processor, data_generator, n_cpus=1, stepsize=None): if not n_cpus: n_cpus = mp.cpu_count() elif n_cpus < 0: n_cpus = mp.cpu_count() - n_cpus if stepsize is None: stepsize = n_cpus results = [] wi...
As a python code expert, you are capable of creating scripts from specifications.
A variant of multiprocessing. Pool. imap that supports lazy evaluation of a single object.
Can you generate the documentation for the following Python 3 function def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None): if not n_cpus: n_cpus = mp.cpu_count() elif n_cpus < 0: n_cpus = mp.cpu_count() - n_cpus if stepsize is None: stepsize = n_cpus with mp...
You are a Python code generator, capable of creating scripts from specifications.
Decorator to update variables of the ArcGIS application.
How would you explain what the following Python 3 function does def update_variables(func): @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if isinstance(result, tuple): return self.process_register(result[0], result[1]) else: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _set_properties(self, data): """ set the properties of the app model by the given data dict """ for property in data.keys(): if property in vars(self): setattr(self, property, data[property])
Implement a function in Python 3 to set the properties of the app model by the given data dict
As a Python code analyst, you investigate and solve complex coding mysteries
def get_long_description(): """ get long description from README.rst file """ with codecs.open(os.path.join(here, "README.rst"), "r", "utf-8") as f: return f.read()
Implement a Python 3 function for getting long description from README. rst file
As a Python code analyst, you investigate and solve complex coding mysteries
This function parses the order_by argument and returns a list of filters for the given model and the list of orderings for the given language.
Can you tell what is the following Python 3 function doing def _parse_order_by(model, order_by): # the list of filters for the models out = [] # for each attribute we have to order by for key in order_by: # remove any whitespace key = key.strip() # if the key starts with a plus ...
You are a Python code generator, capable of creating scripts from specifications.
Creates the example directory structure necessary for a model service.
Can you generate a brief explanation for the following Python 3 code def model(model_names): # for each model name we need to create for model_name in model_names: # the template context context = { 'name': model_name, } # render the model template render_tem...
As a python code expert, you are capable of creating scripts from specifications.
def api(): """ Create the folder/directories for an ApiGateway service. """ # the template context context = { 'name': 'api', 'secret_key': random_string(32) } render_template(template='common', context=context) render_template(template='api', context=context)
Can you implement a function in Python 3 that creates the folder directories for an ApiGateway service.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create the folder directories for an Auth service.
Make a summary of the following Python 3 code def auth(): # the template context context = { 'name': 'auth', } render_template(template='common', context=context) render_template(template='auth', context=context)
You are a Python code generator, capable of creating scripts from specifications.
Creates the example directory structure necessary for a connection.
Here you have a function in Python 3, explain what it does def connection(model_connections): # for each connection group for connection_str in model_connections: # the services to connect services = connection_str.split(':') services.sort() service_name = ''.join([service.tit...
As a Python code composer, you craft elegant and concise scripts.
This function returns the conventional action designator for a given model
Make a summary of the following Python 3 code def get_model_string(model): name = model if isinstance(model, str) else model.__name__ return normalize_string(name)
You are a Python code generator, capable of creating scripts from specifications.
def start(self): """ This function starts the brokers interaction with the kafka stream """ self.loop.run_until_complete(self._consumer.start()) self.loop.run_until_complete(self._producer.start()) self._consumer_task = self.loop.create_task(self._consume_event_callba...
How would you code a function in Python 3 to start the broker interaction with the kafka stream
As a Python code composer, you craft elegant and concise scripts.
def stop(self): """ This method stops the brokers interaction with the kafka stream """ self.loop.run_until_complete(self._consumer.stop()) self.loop.run_until_complete(self._producer.stop()) # attempt try: # to cancel the service self...
Write a Python 3 script for stopping the broker interaction with the kafka stream
You are a Python code analyst, evaluating scripts for potential improvements.
This method sends a message over the kafka stream.
How would you explain what the following Python 3 function does async def send(self, payload='', action_type='', channel=None, **kwds): # use a custom channel if one was provided channel = channel or self.producer_channel # serialize the action type for the message = serialize_action(ac...
As a Python code analyst, you investigate and solve complex coding mysteries
def fields_for_model(model): """ This function returns the fields for a schema that matches the provided nautilus model. Args: model (nautilus.model.BaseModel): The model to base the field list on Returns: (dict<field_name: str, graphqlType>): A mapping of f...
Write a Python 3 script for returning the fields that are part of the provided base model that are part of the base model.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_connection_model(service): """ Create an SQL Alchemy table that connects the provides services """ # the services connected services = service._services # the mixins / base for the model bases = (BaseModel,) # the fields of the derived attributes = {model_service_name(service): f...
Create a Python 3 function to create an SQL Alchemy table that connects the provides services
As a Python code composer, you craft elegant and concise scripts.
This factory returns an action handler that creates a new instance of a specified model.
Can you generate a brief explanation for the following Python 3 code def create_handler(Model, name=None, **kwds): async def action_handler(service, action_type, payload, props, notify=True, **kwds): # if the payload represents a new instance of `Model` if action_type == get_crud_action('create', na...
You are a Python code analyst, evaluating scripts for potential improvements.
This method searches the result dictionary for the given uid.
How would you explain what the following Python 3 function does def _find_id(self, result, uid): # if the result is a list if isinstance(result, list): # if the list has a valid entry if any([self._find_id(value, uid) for value in result]): # then we're done ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a builder inserting a new block before the current block
Explain what the following Python 3 code does def add_before(self): idx = self._container.structure.index(self) return BlockBuilder(self._container, idx)
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a builder inserting a new block after the current block
Given the following Python 3 function, write the documentation def add_after(self): idx = self._container.structure.index(self) return BlockBuilder(self._container, idx+1)
You are a Python code architect, reviewing and designing scalable and efficient code
def comment(self, text, comment_prefix='#'): """Creates a comment block Args: text (str): content of comment without # comment_prefix (str): character indicating start of comment Returns: self for chaining """ comment = Comment(self._containe...
Write a Python 3 function that can create a comment block for the current object
As a python code expert, you are capable of creating scripts from specifications.
Creates a section block at the specified level.
Make a summary of the following Python 3 code def section(self, section): if not isinstance(self._container, ConfigUpdater): raise ValueError("Sections can only be added at section level!") if isinstance(section, str): # create a new section section = Section(section,...
You are a Python code analyst, evaluating scripts for potential improvements.
def space(self, newlines=1): """Creates a vertical space of newlines Args: newlines (int): number of empty lines Returns: self for chaining """ space = Space() for line in range(newlines): space.add_line('\n') self._container....
Can you write a function in Python 3 where it creates a vertical space of newlines.
As a Python code composer, you craft elegant and concise scripts.
Adds an option to the section with the specified key and value.
Can you generate the documentation for the following Python 3 function def option(self, key, value=None, **kwargs): if not isinstance(self._container, Section): raise ValueError("Options can only be added inside a section!") option = Option(key, value, container=self._container, **kwargs) ...
As a python code expert, you are capable of creating scripts from specifications.
def add_comment(self, line): """Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment """ if not isinstance(self.last_item, Comment): comment = Comment(self._structure) self._structur...
Write a Python 3 function for adding a Comment object to the section Used during initial parsing mainly is a dict with the key = value and the value = value.
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a Space object to the section Used during initial parsing mainly is a string that defines the space.
Can you tell what is the following Python 3 function doing def add_space(self, line): if not isinstance(self.last_item, Space): space = Space(self._structure) self._structure.append(space) self.last_item.add_line(line) return self
As a python code expert, you are capable of creating scripts from specifications.
Transform to dictionary Returns: dict: dictionary with same content
Make a summary of the following Python 3 code def to_dict(self): return {key: self.__getitem__(key).value for key in self.options()}
As a Python code analyst, you investigate and solve complex coding mysteries
Set an option for chaining.
Here you have a function in Python 3, explain what it does def set(self, option, value=None): option = self._container.optionxform(option) if option in self.options(): self.__getitem__(option).value = value else: self.__setitem__(option, value) return self
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the value of the option to a given list of options e. g. multi - line values
Can you generate the documentation for the following Python 3 function def set_values(self, values, separator='\n', indent=4*' '): self._updated = True self._multiline_value_joined = True self._values = values if separator == '\n': values.insert(0, '') separator =...
As a Python code translator, you convert algorithms and pseudocode into Python.
Read and parse a file.
Make a summary of the following Python 3 code def read(self, filename, encoding=None): with open(filename, encoding=encoding) as fp: self._read(fp, filename) self._filename = os.path.abspath(filename)
As a Python code composer, you craft elegant and concise scripts.
Update the read - in configuration file.
How would you explain what the following Python 3 function does def update_file(self): if self._filename is None: raise NoConfigFileReadError() with open(self._filename, 'w') as fb: self.write(fb)
As a Python code analyst, you investigate and solve complex coding mysteries
Call ConfigParser to validate config
Can you generate the documentation for the following Python 3 function def validate_format(self, **kwargs): args = dict( dict_type=self._dict, allow_no_value=self._allow_no_value, inline_comment_prefixes=self._inline_comment_prefixes, strict=self._strict, ...
As a python code expert, you are capable of creating scripts from specifications.
Add a section to the configuration.
Given the following Python 3 function, write the documentation def add_section(self, section): if section in self.sections(): raise DuplicateSectionError(section) if isinstance(section, str): # create a new section section = Section(section, container=self) el...
As a Python code composer, you craft elegant and concise scripts.
Returns list of configuration options for the named section.
Here you have a function in Python 3, explain what it does def options(self, section): if not self.has_section(section): raise NoSectionError(section) from None return self.__getitem__(section).options()
You are a Python code generator, capable of creating scripts from specifications.
def get(self, section, option): """Gets an option value for a given section. Args: section (str): section name option (str): option name Returns: :class:`Option`: Option object holding key/value pair """ if not self.has_section(section): ...
Create a Python 3 function for getting an option value for a given section.
You are a Python code generator, capable of creating scripts from specifications.
def items(self, section=_UNSET): """Return a list of (name, value) tuples for options or sections. If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_type) for each section. ...
Create a Python 3 function for returning a list of tuples for options or sections.
You are a Python code generator, capable of creating scripts from specifications.
Checks if an option exists in a given section.
Can you tell what is the following Python 3 function doing def has_option(self, section, option): if section not in self.sections(): return False else: option = self.optionxform(option) return option in self[section]
As a Python code translator, you convert algorithms and pseudocode into Python.
def set(self, section, option, value=None): """Set an option. Args: section (str): section name option (str): option name value (str): value, default None """ try: section = self.__getitem__(section) except KeyError: ra...
Create a Python 3 function for setting an option. value
As a Python code composer, you craft elegant and concise scripts.
def remove_option(self, section, option): """Remove an option. Args: section (str): section name option (str): option name Returns: bool: whether the option was actually removed """ try: section = self.__getitem__(section) ...
Write a Python 3 function for removing an option from a section.
You are a Python code analyst, evaluating scripts for potential improvements.
Removes a section from the file.
Can you tell what is the following Python 3 function doing def remove_section(self, name): existed = self.has_section(name) if existed: idx = self._get_section_idx(name) del self._structure[idx] return existed
You are a Python code generator, capable of creating scripts from specifications.
def to_dict(self): """Transform to dictionary Returns: dict: dictionary with same content """ return {sect: self.__getitem__(sect).to_dict() for sect in self.sections()}
Write a Python 3 function that can transform to dictionary Returns: dict: dictionary with same content
You are a Python code architect, reviewing and designing scalable and efficient code
This function renders the template with the given context and returns the contents of the rendered template.
Here you have a function in Python 3, explain what it does def render_template(template, out_dir='.', context=None): ''' This function renders the template desginated by the argument to the designated directory using the given context. Args: template (string) : the source templa...
As a Python code translator, you convert algorithms and pseudocode into Python.
Publish a message with the specified action_type and payload over the event system. Useful for debugging.
Here you have a function in Python 3, explain what it does def publish(type, payload): async def _produce(): # fire an action with the given values await producer.send(action_type=type, payload=payload) # notify the user that we were successful print("Successfully dispatched action w...
You are a Python code generator, capable of creating scripts from specifications.
This factory returns an action handler that deletes a new instance of the specified model from the database.
Can you tell what is the following Python 3 function doing def delete_handler(Model, name=None, **kwds): # necessary imports from nautilus.database import db async def action_handler(service, action_type, payload, props, notify=True, **kwds): # if the payload represents a new instance of `model` ...
As a Python code composer, you craft elegant and concise scripts.
This factory returns an action handler that responds to read requests by resolving the payload as graphql query against the internal schema and sending the response to the event broker.
Here you have a function in Python 3, explain what it does def read_handler(Model, name=None, **kwds): async def action_handler(service, action_type, payload, props, **kwds): # if the payload represents a new instance of `model` if action_type == get_crud_action('read', name or Model): #...
You are a Python code generator, capable of creating scripts from specifications.
This action handler factory reaturns an action handler that creates a new object that is created with the specified CRUD types and deletes the specified CRUD types.
Given the following Python 3 function, write the documentation def crud_handler(Model, name=None, **kwds): # import the necessary modules from nautilus.network.events import combine_action_handlers from . import update_handler, create_handler, delete_handler, read_handler # combine them into one handl...
You are a Python code generator, capable of creating scripts from specifications.
Publish a message with the specified action_type and payload over the event system. Useful for debugging.
Make a summary of the following Python 3 code def ask(type, payload): async def _produce(): # notify the user that we were successful print("Dispatching action with type {}...".format(type)) # fire an action with the given values response = await producer.ask(action_type=type, payloa...
As a Python code composer, you craft elegant and concise scripts.
This function walks the object tree and returns the information in a dictionary.
Here you have a function in Python 3, explain what it does async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters): # if the object has no selection set if not hasattr(obj, 'selection_set'): # yell loudly raise Value...
As a python code expert, you are capable of creating scripts from specifications.
This function returns the standard summary for mutations inputs and outputs
Given the following Python 3 function, write the documentation def summarize_mutation_io(name, type, required=False): return dict( name=name, type=type, required=required )
You are a Python code generator, capable of creating scripts from specifications.
This function returns the name of a mutation that performs the specified crud action on the given model
Can you generate a brief explanation for the following Python 3 code def crud_mutation_name(action, model): model_string = get_model_string(model) # make sure the mutation name is correctly camelcases model_string = model_string[0].upper() + model_string[1:] # return the mutation name return "{}{}"...
As a python code expert, you are capable of creating scripts from specifications.
Create the list of fields that are required for the mutation of a service.
Can you generate a brief explanation for the following Python 3 code def create_mutation_inputs(service): # grab the default list of field summaries inputs = _service_mutation_summaries(service) # make sure the pk isn't in the list inputs.remove([field for field in inputs if field['name'] == 'id'][0]) ...
As a Python code composer, you craft elegant and concise scripts.
def update_mutation_inputs(service): """ Args: service : The service being updated by the mutation Returns: (list) : a list of all of the fields availible for the service. Pk is a required field in order to filter the results """ # grab the default lis...
Write a Python 3 script for updating the list of fields that are required by the mutation for the given service.
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_mutation_inputs(service): """ Args: service : The service being deleted by the mutation Returns: ([str]): the only input for delete is the pk of the service. """ from nautilus.api.util import summarize_mutation_io # the only input for delete events is...
How would you implement a function in Python 3 that returns a list of input for delete events.
You are a Python code generator, capable of creating scripts from specifications.
This factory returns an action handler that updates a new instance of the specified model.
Explain what the following Python 3 code does def update_handler(Model, name=None, **kwds): async def action_handler(service, action_type, payload, props, notify=True, **kwds): # if the payload represents a new instance of `Model` if action_type == get_crud_action('update', name or Model): ...
You are a Python code generator, capable of creating scripts from specifications.
This function returns a graphql mutation corresponding to the provided summary.
Here you have a function in Python 3, explain what it does def graphql_mutation_from_summary(summary): # get the name of the mutation from the summary mutation_name = summary['name'] # print(summary) # the treat the "type" string as a gra input_name = mutation_name + "Input" input_fields = bui...
As a Python code composer, you craft elegant and concise scripts.
This function takes a series of ditionaries and creates an argument string for a graphql query
Can you generate a brief explanation for the following Python 3 code def arg_string_from_dict(arg_dict, **kwds): # the filters dictionary filters = { **arg_dict, **kwds, } # return the correctly formed string return ", ".join("{}: {}".format(key, json.dumps(value)) for key,value in f...
As a Python code analyst, you investigate and solve complex coding mysteries
the name of a service that manages the connection between services
Here you have a function in Python 3, explain what it does def connection_service_name(service, *args): ''' the name of a service that manages the connection between services ''' # if the service is a string if isinstance(service, str): return service return normalize_string(type(service).__nam...
As a Python code translator, you convert algorithms and pseudocode into Python.