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 parse_command(self, command): """Break a multi word command up into an action and its parameters """
words = shlex.split(command.lower()) return words[0], words[1:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, command): """Pass a command along with its params to a suitable handler If the command is blank, succeed silently If the command has no handle...
log.info("Dispatch on %s", command) if not command: return "OK" action, params = self.parse_command(command) log.debug("Action = %s, Params = %s", action, params) try: function = getattr(self, "do_" + action, None) if function: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_output(self, *args): """Pass a command directly to the current output processor """
if args: action, params = args[0], args[1:] log.debug("Pass %s directly to output with %s", action, params) function = getattr(self.output, "do_" + action, None) if function: function(*params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intervals_ms(self, timeout_ms): """Generate a series of interval lengths, in ms, which will add up to the number of ms in timeout_ms. If timeout_ms is None, ...
if timeout_ms is config.FOREVER: while True: yield self.try_length_ms else: whole_intervals, part_interval = divmod(timeout_ms, self.try_length_ms) for _ in range(whole_intervals): yield self.try_length_ms yield part_interv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _receive_with_timeout(self, socket, timeout_s, use_multipart=False): """Check for socket activity and either return what's received on the socket or time out...
if timeout_s is config.FOREVER: timeout_ms = config.FOREVER else: timeout_ms = int(1000 * timeout_s) poller = zmq.Poller() poller.register(socket, zmq.POLLIN) ms_so_far = 0 try: for interval_ms in self.intervals_ms(timeout_ms): ...
<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_labels(labels): """Create unique labels."""
label_u = unique_labels(labels) label_u_line = [i + "_line" for i in label_u] return label_u, label_u_line
<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_boxes_and_lines(ax, labels): """Get boxes and lines using labels as id."""
labels_u, labels_u_line = get_labels(labels) boxes = ax.findobj(mpl.text.Annotation) lines = ax.findobj(mpl.lines.Line2D) lineid_boxes = [] lineid_lines = [] for box in boxes: l = box.get_label() try: loc = labels_u.index(l) except ValueError: # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_text_boxes(ax, labels, colors, color_arrow=True): """Color text boxes. Instead of this function, one can pass annotate_kwargs and plot_kwargs to plot_l...
assert len(labels) == len(colors), \ "Equal no. of colors and lables must be given" boxes = ax.findobj(mpl.text.Annotation) box_labels = lineid_plot.unique_labels(labels) for box in boxes: l = box.get_label() try: loc = box_labels.index(l) except ValueError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def color_lines(ax, labels, colors): """Color lines. Instead of this function, one can pass annotate_kwargs and plot_kwargs to plot_line_ids function. """
assert len(labels) == len(colors), \ "Equal no. of colors and lables must be given" lines = ax.findobj(mpl.lines.Line2D) line_labels = [i + "_line" for i in lineid_plot.unique_labels(labels)] for line in lines: l = line.get_label() try: loc = line_labels.index(l) ...
<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_tool_definition(self, target): """ Returns tool specific dic or None if it does not exist for defined tool """
if target not in self.targets_mcu_list: logging.debug("Target not found in definitions") return None mcu_record = self.targets.get_mcu_record(target) if self.mcus.get_mcu_record(target) is None else self.mcus.get_mcu_record(target) try: return mcu_record['too...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_supported(self, target): """ Returns True if target is supported by definitions """
if target.lower() not in self.targets_mcu_list: logging.debug("Target not found in definitions") return False mcu_record = self.targets.get_mcu_record(target) if self.mcus.get_mcu_record(target) is None else self.mcus.get_mcu_record(target) # Look at tool specific option...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aliases_of(self, name): """ Returns other names for given real key or alias ``name``. If given a real key, returns its aliases. If given an alias, returns th...
names = [] key = name # self.aliases keys are aliases, not realkeys. Easy test to see if we # should flip around to the POV of a realkey when given an alias. if name in self.aliases: key = self.aliases[name] # Ensure the real key shows up in output. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uridefrag(uristring): """Remove an existing fragment component from a URI reference string. """
if isinstance(uristring, bytes): parts = uristring.partition(b'#') else: parts = uristring.partition(u'#') return DefragResult(parts[0], parts[2] if parts[1] else None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geturi(self): """Return the recombined version of the original URI as a string."""
fragment = self.fragment if fragment is None: return self.uri elif isinstance(fragment, bytes): return self.uri + b'#' + fragment else: return self.uri + u'#' + fragment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getfragment(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded fragment identifier, or `default` if the original URI did not conta...
fragment = self.fragment if fragment is not None: return uridecode(fragment, encoding, errors) else: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click(self, locator, params=None, timeout=None): """ Click web element. :param locator: locator tuple or WebElement instance :param params: (optional) locato...
self._click(locator, params, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alt_click(self, locator, params=None, timeout=None): """ Alt-click web element. :param locator: locator tuple or WebElement instance :param params: (optional...
self._click(locator, params, timeout, Keys.ALT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift_click(self, locator, params=None, timeout=None): """ Shift-click web element. :param locator: locator tuple or WebElement instance :param params: (opti...
self._click(locator, params, timeout, Keys.SHIFT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_click(self, locator, params=None, timeout=None): """ Presses left control or command button depending on OS, clicks and then releases control or comman...
platform = self.execute_script('return navigator.platform') multi_key = Keys.COMMAND if 'mac' in platform.lower() else Keys.LEFT_CONTROL self._click(locator, params, timeout, multi_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 shift_select(self, first_element, last_element): """ Clicks a web element and shift clicks another web element. :param first_element: WebElement instance :pa...
self.click(first_element) self.shift_click(last_element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_select(self, elements_to_select): """ Multi-select any number of elements. :param elements_to_select: list of WebElement instances :return: None """
# Click the first element first_element = elements_to_select.pop() self.click(first_element) # Click the rest for index, element in enumerate(elements_to_select, start=1): self.multi_click(element)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_from_drop_down_by_value(self, locator, value, params=None): """ Select option from drop down widget using value. :param locator: locator tuple or WebE...
from selenium.webdriver.support.ui import Select element = locator if not isinstance(element, WebElement): element = self.get_present_element(locator, params) Select(element).select_by_value(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None): """ Select option from drop down widget using text. :param ...
# Open/activate drop down self.click(drop_down_locator, params['drop_down'] if params else None) # Get options for option in self.get_present_elements(option_locator, params['option'] if params else None): if self.get_text(option) == option_text: self.click(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_from_drop_down_by_locator(self, drop_down_locator, option_locator, params=None): """ Select option from drop down widget using locator. :param drop_do...
# Open/activate drop down self.click(drop_down_locator, params['drop_down'] if params else None) # Click option in drop down self.click(option_locator, params['option'] if params else None)
<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_attribute(self, locator, attribute, params=None, timeout=None, visible=False): """ Get attribute from element based on locator with optional parameters. ...
element = locator if not isinstance(element, WebElement): element = self.get_present_element(locator, params, timeout, visible) try: return element.get_attribute(attribute) except AttributeError: msg = "Element with attribute <{}> was never located!"...
<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_text(self, locator, params=None, timeout=None, visible=True): """ Get text or value from element based on locator with optional parameters. :param locato...
element = locator if not isinstance(element, WebElement): element = self.get_present_element(locator, params, timeout, visible) if element and element.text: return element.text else: try: return element.get_attribute('value') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter_text(self, locator, text, with_click=True, with_clear=False, with_enter=False, params=None): """ Enter text into a web element. :param locator: locator...
element = locator if not isinstance(element, WebElement): element = self.get_visible_element(locator, params) if with_click: self.click(element) actions = ActionChains(self.driver) if 'explorer' in self.driver.name and "@" in str(text): acti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def erase_text(self, locator, click=True, clear=False, backspace=0, params=None): """ Various ways to erase text from web element. :param locator: locator tuple ...
element = locator if not isinstance(element, WebElement): element = self.get_visible_element(locator, params) if click: self.click(element) if clear: element.clear() if backspace: actions = ActionChains(self.driver) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drag_and_drop(self, source_element, target_element, params=None): """ Drag source element and drop at target element. Note: Target can either be a WebElement...
if not isinstance(source_element, WebElement): source_element = self.get_visible_element(source_element, params['source'] if params else None) if not isinstance(target_element, WebElement) and not isinstance(target_element, list): source_element = self.get_visible_element(target...
<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_present_element(self, locator, params=None, timeout=None, visible=False, parent=None): """ Get element present in the DOM. If timeout is 0 (zero) return ...
error_msg = "Child was never present" if parent else "Element was never present!" expected_condition = ec.visibility_of_element_located if visible else ec.presence_of_element_located return self._get(locator, expected_condition, params, timeout, error_msg, parent)
<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_visible_element(self, locator, params=None, timeout=None): """ Get element both present AND visible in the DOM. If timeout is 0 (zero) return WebElement ...
return self.get_present_element(locator, params, timeout, True)
<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_present_elements(self, locator, params=None, timeout=None, visible=False, parent=None): """ Get elements present in the DOM. If timeout is 0 (zero) retur...
error_msg = "Children were never present" if parent else "Elements were never present!" expected_condition = ec.visibility_of_all_elements_located if visible else ec.presence_of_all_elements_located return self._get(locator, expected_condition, params, timeout, error_msg, parent)
<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_visible_elements(self, locator, params=None, timeout=None): """ Get elements both present AND visible in the DOM. If timeout is 0 (zero) return WebElemen...
return self.get_present_elements(locator, params, timeout, True)
<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_present_child(self, parent, locator, params=None, timeout=None, visible=False): """ Get child-element present in the DOM. If timeout is 0 (zero) return W...
return self.get_present_element(locator, params, timeout, visible, parent=parent)
<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_visible_child(self, parent, locator, params=None, timeout=None): """ Get child-element both present AND visible in the DOM. If timeout is 0 (zero) return...
return self.get_present_child(parent, locator, params, timeout, True)
<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_present_children(self, parent, locator, params=None, timeout=None, visible=False): """ Get child-elements both present in the DOM. If timeout is 0 (zero)...
return self.get_present_elements(locator, params, timeout, visible, parent=parent)
<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_visible_children(self, parent, locator, params=None, timeout=None): """ Get child-elements both present AND visible in the DOM. If timeout is 0 (zero) re...
return self.get_present_children(parent, locator, params, timeout, True)
<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(self, locator, expected_condition, params=None, timeout=None, error_msg="", driver=None, **kwargs): """ Get elements based on locator with optional para...
from selenium.webdriver.support.ui import WebDriverWait if not isinstance(locator, WebElement): error_msg += "\nLocator of type <{}> with selector <{}> with params <{params}>".format( *locator, params=params) locator = self.__class__.get_compliant_locator(*locat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scroll_element_into_view(self, selector): """ Scrolls an element into view. :param selector: selector of element or WebElement to scroll into view :return: N...
element = selector if isinstance(element, WebElement): self.execute_script("arguments[0].scrollIntoView( true );", element) else: self.execute_script("$('{}')[0].scrollIntoView( true );".format(selector[1]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_hover(self, locator, params=None, use_js=False): """ Open a hover or popover. :param locator: locator tuple or WebElement instance :param params: (optio...
element = locator if not isinstance(element, WebElement): element = self.get_visible_element(locator, params) if use_js: self._js_hover('mouseover', element) return element actions = ActionChains(self.driver) actions.move_to_element(element)....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_hover(self, element, use_js=False): """ Close hover by moving to a set offset "away" from the element being hovered. :param element: element that trigg...
try: if use_js: self._js_hover('mouseout', element) else: actions = ActionChains(self.driver) actions.move_to_element_with_offset(element, -100, -100) actions.reset_actions() except (StaleElementReferenceException, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform_hover_action(self, locator, func, error_msg='', exceptions=None, params=None, alt_loc=None, alt_params=None, **kwargs): """ Hovers an element and per...
def _do_hover(): try: with self.hover(locator, params, alt_loc, alt_params): return func(**kwargs) except exc: return False exc = [StaleElementReferenceException] if exceptions is not None: try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hover(self, locator, params=None, use_js=False, alt_loc=None, alt_params=None): """ Context manager for hovering. Opens and closes the hover. Usage: with sel...
# Open hover element = self.open_hover(locator, params, use_js) try: yield finally: # Close hover if alt_loc: element = alt_loc if not isinstance(element, WebElement): element = self.get_visible_elem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_non_empty_text(self, locator, params=None, timeout=5): """ Wait and get elements when they're populated with any text. :param locator: locator tuple...
def _do_wait(): elements = self.get_present_elements(locator, params, timeout=0) for element in elements: if not self.get_text(element): return False return elements return ActionWait(timeout).until(_do_wait, "Element text was nev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_attribute(self, locator, attribute, value, params=None, timeout=5): """ Waits for an element attribute to get a certain value. Note: This function r...
def _do_wait(): element = self.get_present_element(locator, params) return value in self.get_attribute(element, attribute) ActionWait(timeout).until(_do_wait, "Attribute never set!")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_ajax_calls_to_complete(self, timeout=5): """ Waits until there are no active or pending ajax requests. Raises TimeoutException should silence not be...
from selenium.webdriver.support.ui import WebDriverWait WebDriverWait(self.driver, timeout).until(lambda s: s.execute_script("return jQuery.active === 0"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_ip4_broadcast_addresses(): """Yield each IP4 broadcast address, and the all-broadcast """
yield "255.255.255.255" for interface in netifaces.interfaces(): ifaddresses = netifaces.ifaddresses(interface) for family in ifaddresses: if family == netifaces.AF_INET: address_info = ifaddresses[family] for info in address_info: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_ip4_addresses(): """Find all the IP4 addresses currently bound to interfaces """
global _ip4_addresses proto = socket.AF_INET if _ip4_addresses is None: _ip4_addresses = [] # # Determine the interface for the default gateway # (if any) and, later, prioritise the INET address on # that interface. # default_gateway = netifaces.gate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_rate(phone_number, address_country_code=None, address_exception=None): """ Calculates the VAT rate based on a telephone number :param phone_number:...
if not phone_number: raise ValueError('No phone number provided') if not isinstance(phone_number, str_cls): raise ValueError('Phone number is not a string') phone_number = phone_number.strip() phone_number = re.sub('[^+0-9]', '', phone_number) if not phone_number or phone_number...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uriunsplit(parts): """Combine the elements of a five-item iterable into a URI reference's string representation. """
scheme, authority, path, query, fragment = parts if isinstance(path, bytes): result = SplitResultBytes else: result = SplitResultUnicode return result(scheme, authority, path, query, fragment).geturi()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def geturi(self): """Return the re-combined version of the original URI reference as a string. """
scheme, authority, path, query, fragment = self # RFC 3986 5.3. Component Recomposition result = [] if scheme is not None: result.extend([scheme, self.COLON]) if authority is not None: result.extend([self.SLASH, self.SLASH, authority]) result.app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getauthority(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded userinfo, host and port subcomponents of the URI authority as a th...
# TBD: (userinfo, host, port) kwargs, default string? if default is None: default = (None, None, None) elif not isinstance(default, collections.Iterable): raise TypeError('Invalid default type') elif len(default) != 3: raise ValueError('Invalid defaul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getuserinfo(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded userinfo subcomponent of the URI authority, or `default` if the ori...
userinfo = self.userinfo if userinfo is None: return default else: return uridecode(userinfo, encoding, errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getpath(self, encoding='utf-8', errors='strict'): """Return the normalized decoded URI path."""
path = self.__remove_dot_segments(self.path) return uridecode(path, encoding, errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getquery(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded query string, or `default` if the original URI reference did not conta...
query = self.query if query is None: return default else: return uridecode(query, encoding, errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getquerydict(self, sep='&', encoding='utf-8', errors='strict'): """Split the query component into individual `name=value` pairs separated by `sep` and return...
dict = collections.defaultdict(list) for name, value in self.getquerylist(sep, encoding, errors): dict[name].append(value) return dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_rate(country_code, exception_name): """ Calculates the VAT rate for a customer based on their declared country and any declared exception informati...
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') if exception_name and not isinstance(exception_name, str_cls): raise ValueError('Exception name is not None or a string') country_code = country_co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exceptions_by_country(country_code): """ Returns a list of exception names for the given country :param country_code: The two-character country code for the ...
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') country_code = country_code.upper() return EXCEPTIONS_BY_COUNTRY.get(country_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 normalize(vat_id): """ Accepts a VAT ID and normaizes it, getting rid of spaces, periods, dashes etc and converting it to upper case. :param vat_id: The VAT ...
if not vat_id: return None if not isinstance(vat_id, str_cls): raise ValueError('VAT ID is not a string') if len(vat_id) < 3: raise ValueError('VAT ID must be at least three character long') # Normalize the ID for simpler regexes vat_id = re.sub('\\s+', '', vat_id) v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_stale(msg='', exceptions=None): """ Decorator to handle stale element reference exceptions. :param msg: Error message :param exceptions: Extra excepti...
exc = [StaleElementReferenceException] if exceptions is not None: try: exc.extend(iter(exceptions)) except TypeError: # exceptions is not iterable exc.append(exceptions) exc = tuple(exc) if not msg: msg = "Could not recover from Exception(s): {}".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 wait(msg='', exceptions=None, timeout=10): """ Decorator to handle generic waiting situations. Will handle StaleElementReferenceErrors. :param msg: Error mes...
exc = [StaleElementReferenceException] if exceptions is not None: try: exc.extend(iter(exceptions)) except TypeError: # exceptions is not iterable exc.append(exceptions) exc = tuple(exc) if not msg: msg = "Could not recover from Exception(s): {}".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 calculate_rate(country_code, postal_code, city): """ Calculates the VAT rate that should be collected based on address information provided :param country_co...
if not country_code or not isinstance(country_code, str_cls): raise ValueError('Invalidly formatted country code') country_code = country_code.strip() if len(country_code) != 2: raise ValueError('Invalidly formatted country code') country_code = country_code.upper() if country_c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_get_device(self, uid, fields='*'): """Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid), fields=fields))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_get_measurements(self, uid, fields='*'): """Get measurements of a device."""
return (yield from self._get('/pods/{}/measurements'.format(uid), fields=fields))[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_get_ac_states(self, uid, limit=1, offset=0, fields='*'): """Get log entries of a device."""
return (yield from self._get('/pods/{}/acStates'.format(uid), limit=limit, fields=fields, offset=offset))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_get_ac_state_log(self, uid, log_id, fields='*'): """Get a specific log entry."""
return ( yield from self._get('/pods/{}/acStates/{}'.format(uid, log_id), fields=fields))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def async_set_ac_state_property( self, uid, name, value, ac_state=None, assumed_state=False): """Set a specific device property."""
if ac_state is None: ac_state = yield from self.async_get_ac_states(uid) ac_state = ac_state[0]['acState'] data = { 'currentAcState': ac_state, 'newValue': value } if assumed_state: data['reason'] = "StateCorrectionByUser" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bind_with_timeout(bind_function, args, n_tries=3, retry_interval_s=0.5): """Attempt to bind a socket a number of times with a short interval in between Espe...
n_tries_left = n_tries while n_tries_left > 0: try: return bind_function(*args) except zmq.error.ZMQError as exc: _logger.warn("%s; %d tries remaining", exc, n_tries_left) n_tries_left -= 1 except OSError as exc: if exc.errno == errno.EADD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_beacon(port=None): """Start a beacon thread within this process if no beacon is currently running on this machine. In general this is called automatic...
global _beacon if _beacon is None: _logger.debug("About to start beacon with port %s", port) try: _beacon = _Beacon(port) except (OSError, socket.error) as exc: if exc.errno == errno.EADDRINUSE: _logger.warn("Beacon already active on this machine"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_command_request(self): """If the command RPC socket has an incoming request, separate it into its action and its params and put it on the command reques...
try: message = self.rpc.recv(zmq.NOBLOCK) except zmq.ZMQError as exc: if exc.errno == zmq.EAGAIN: return else: raise _logger.debug("Received command %s", message) segments = _unpack(message) action, params = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_command_reponse(self): """If the latest request has a response, issue it as a reply to the RPC socket. """
if self._command.response is not Empty: _logger.debug("Sending response %s", self._command.response) self.rpc.send(_pack(self._command.response)) self._command = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_rate(country_code, subdivision, city, address_country_code=None, address_exception=None): """ Calculates the VAT rate from the data returned by a G...
if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') if not isinstance(subdivision, str_cls): raise ValueError('Subdivision is not a string') if not isinstance(city, str_cls): raise ValueError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_xrates(base, rates): """ If using the Python money package, this will set up the xrates exchange rate data. :param base: The string currency code to us...
xrates.install('money.exchange.SimpleBackend') xrates.base = base for code, value in rates.items(): xrates.setrate(code, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(amount, currency=None): """ Formats a decimal or Money object into an unambiguous string representation for the purpose of invoices in English. :param...
if currency is None and hasattr(amount, 'currency'): currency = amount.currency # Allow Money objects if not isinstance(amount, Decimal) and hasattr(amount, 'amount'): amount = amount.amount if not isinstance(currency, str_cls): raise ValueError('The currency specified is not...
<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_momentum_by_name(self, name): """Gets a momentum by the given name. :param name: the momentum name. :returns: a momentum found. :raises TypeError: `name`...
if name is None: raise TypeError('\'name\' should not be None') for momentum in self.momenta: if momentum.name == name: return momentum raise KeyError('No such momentum named {0}'.format(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 pop_momentum_by_name(self, name): """Removes and returns a momentum by the given name. :param name: the momentum name. :returns: a momentum removed. :raises ...
momentum = self.get_momentum_by_name(name) self.remove_momentum(momentum) return momentum
<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_momentum_by_name(self, name, **kwargs): """Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new...
momentum = self.pop_momentum_by_name(name) velocity, since, until = momentum[:3] velocity = kwargs.get('velocity', velocity) since = kwargs.get('since', since) until = kwargs.get('until', until) return self.add_momentum(velocity, since, until, 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 snap_momentum_by_name(self, name, velocity, at=None): """Changes the velocity of a momentum named `name`. :param name: the momentum name. :param velocity: a ...
at = now_or(at) self.forget_past(at=at) return self.update_momentum_by_name(name, velocity=velocity, since=at)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uricompose(scheme=None, authority=None, path='', query=None, fragment=None, userinfo=None, host=None, port=None, querysep='&', encoding='utf-8'): """Compose ...
# RFC 3986 3.1: Scheme names consist of a sequence of characters # beginning with a letter and followed by any combination of # letters, digits, plus ("+"), period ("."), or hyphen ("-"). # Although schemes are case-insensitive, the canonical form is # lowercase and documents that specify schemes ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until(self, func, message='', *args, **kwargs): """ Continues to execute the function until successful or time runs out. :param func: function to execute :pa...
value = None end_time = time.time() + self._timeout while True: value = func(*args, **kwargs) if self._debug: print("Value from func within ActionWait: {}".format(value)) if value: break time.sleep(self._poll) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_connection(self): """Return string representation of the device, including the connection state"""
if self.device==None: return "%s [disconnected]" % (self.name) else: return "%s connected to %s %s version: %s [serial: %s]" % (self.name, self.vendor_name, self.product_name, self.version_number, self.serial_number)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_event( name, runbook, status, output, team, page=False, tip=None, notification_email=None, check_every='30s', realert_every=-1, alert_after='0s', depende...
if not (name and team): raise ValueError("Name and team must be present") if not re.match(r'^[\w\.-]+$', name): raise ValueError("Name cannot contain special characters") if not runbook: runbook = 'Please set a runbook!' result_dict = { 'name': name, 'status': st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uriencode(uristring, safe='', encoding='utf-8', errors='strict'): """Encode a URI string or string component."""
if not isinstance(uristring, bytes): uristring = uristring.encode(encoding, errors) if not isinstance(safe, bytes): safe = safe.encode('ascii') try: encoded = _encoded[safe] except KeyError: encoded = _encoded[b''][:] for i in _tointseq(safe): encoded...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uridecode(uristring, encoding='utf-8', errors='strict'): """Decode a URI string or string component."""
if not isinstance(uristring, bytes): uristring = uristring.encode(encoding or 'ascii', errors) parts = uristring.split(b'%') result = [parts[0]] append = result.append decode = _decoded.get for s in parts[1:]: append(decode(s[:2], b'%' + s[:2])) append(s[2:]) if enco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_to_array(x, size, name): """Check length of array or convert scalar to array. Check to see is `x` has the given length `size`. If this is true then ...
try: l = len(x) if l != size: raise ValueError( "{0} must be scalar or of length {1}".format( name, size)) except TypeError: # Only one item xa = np.array([x] * size) # Each item is a diff. object. else: xa = np.array(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique_labels(line_labels): """If a label occurs more than once, add num. as suffix."""
from collections import defaultdict d = defaultdict(int) for i in line_labels: d[i] += 1 d = dict((i, k) for i, k in d.items() if k != 1) line_labels_u = [] for lab in reversed(line_labels): c = d.get(lab, 0) if c >= 1: v = lab + "_num_" + str(c) ...
<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_box_loc(fig, ax, line_wave, arrow_tip, box_axes_space=0.06): """Box loc in data coords, given Fig. coords offset from arrow_tip. Parameters fig: matplotl...
# Plot boxes in their original x position, at a height given by the # key word box_axes_spacing above the arrow tip. The default # is set to 0.06. This is in figure fraction so that the spacing # doesn't depend on the data y range. box_loc = [] fig_inv_trans = fig.transFigure.inverted() for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_boxes(line_wave, box_widths, left_edge, right_edge, max_iter=1000, adjust_factor=0.35, factor_decrement=3.0, fd_p=0.75): """Ajdust given boxes so that...
# Adjust positions. niter = 0 changed = True nlines = len(line_wave) wlp = line_wave[:] while changed: changed = False for i in range(nlines): if i > 0: diff1 = wlp[i] - wlp[i - 1] separation1 = (box_widths[i] + box_widths[i - 1]) / 2...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1), ax_dim=(0.85, 0.65)): """Create fig and axes if needed and layout axes in fig."""
# Axes location in figure. if not fig: fig = plt.figure() ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]]) ax.plot(wave, flux) return fig, ax
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initial_annotate_kwargs(): """Return default parameters passed to Axes.annotate to create labels."""
return dict( xycoords="data", textcoords="data", rotation=90, horizontalalignment="center", verticalalignment="center", arrowprops=dict(arrowstyle="-", relpos=(0.5, 0.0)) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interpolate_grid(cin, cout, data, fillval=0): """Return the 2D field averaged radially w.r.t. the center"""
if np.iscomplexobj(data): phase = interpolate_grid( cin, cout, unwrap.unwrap_phase(np.angle(data)), fillval=0) ampli = interpolate_grid(cin, cout, np.abs(data), fillval=1) return ampli * np.exp(1j * phase) ipol = spinterp.interp2d(x=cin[0], y=cin[1], z=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 rytov(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=.5e-6, grid_size=(80, 80), center=(39.5, 39.5), focus=0, radius_sampl...
# sample the sphere radius with approximately 42px # (rounded to next integer pixel size) samp_mult = radius_sampling * pixel_size / radius sizex = grid_size[0] * samp_mult sizey = grid_size[1] * samp_mult grid_size_sim = [np.int(np.round(sizex)), np.int(np.round(sizey))] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_resources_file(path, stack): """ With a bit of import magic, we load the given path as a python module, while providing it access to the given stack und...
import imp, sys, random, string, copy class ContextImporter(object): def find_module(self, fullname, path=None): if fullname == '_context': self.path = path return self return None def load_module(self, name): mod = imp.new_mod...
<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_template_srcmodule(self, stack, path): """ This function actually fills the stack with definitions coming from a template file """
srcmodule = _run_resources_file(path, stack) # Process the loaded module and find the stack elements elements = self.find_stack_elements(srcmodule) elements = sorted(elements, key=lambda x: x[:-1]) # Assign a name to each element and add to our dictionaries for (module_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_to_template_obj(self, stack, t): """ Add resource definitions to the given template object """
if len(self.Parameters) > 0: t['Parameters'] = dict([e.contents(stack) for e in self.Parameters]) if len(self.Mappings) > 0: t['Mappings'] = dict([e.contents(stack) for e in self.Mappings]) if len(self.Resources) > 0: t['Resources'] = dict([e.contents(stack) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_json(self, pretty=True): """ Return a string representation of this CloudFormation template. """
# Build template t = {} t['AWSTemplateFormatVersion'] = '2010-09-09' if self.description is not None: t['Description'] = self.description self.elements.dump_to_template_obj(self, t) return _CustomJSONEncoder(indent=2 if pretty else None, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def embedded_preview(src_path): ''' Returns path to temporary copy of embedded QuickLook preview, if it exists ''' try: assert(exists(src_path) and isdir(src_path)) preview_list = glob(join(src_path, '[Q|q]uicklook', '[P|p]review.*')) assert(preview_list) # Assert there's at least one preview file ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def thumbnail_preview(src_path): ''' Returns the path to small thumbnail preview. ''' try: assert(exists(src_path)) width = '1980' dest_dir = mkdtemp(prefix='pyglass') cmd = [QLMANAGE, '-t', '-s', width, src_path, '-o', dest_dir] assert(check_call(cmd) == 0) src_filename = basename(src_pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke_in_mainloop(func, *args, **kwargs): """ Invoke a function in the mainloop, pass the data back. """
results = queue.Queue() @gcall def run(): try: data = func(*args, **kwargs) results.put(data) results.put(None) except BaseException: # XXX: handle results.put(None) results.put(sys.exc_info()) raise data = resul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gtk_threadsafe(func): ''' Decorator to make wrapped function threadsafe by forcing it to execute within the GTK main thread. .. versionadded:: 0.18 .. versionchanged:: 0.22 Add support for keyword arguments in callbacks by supporting functions wrapped by `functools.partial()`. ...