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 handler, succeed silently If the handler raises an exception, fail with the exception message """
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: function(*params) return "OK" except KeyboardInterrupt: raise except Exception as exc: log.exception("Problem executing action %s", action) return "ERROR: %s" % exc
<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, keep returning intervals forever. """
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_interval
<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 expires without anything on the socket. This is implemented in loops of self.try_length_ms milliseconds to allow Ctrl-C handling to take place. """
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): sockets = dict(poller.poll(interval_ms)) ms_so_far += interval_ms if socket in sockets: if use_multipart: return socket.recv_multipart() else: return socket.recv() else: raise core.SocketTimedOutError(timeout_s) except KeyboardInterrupt: raise core.SocketInterruptedError(ms_so_far / 1000.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 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: # this box is either one not added by lineidplot or has no label. continue lineid_boxes.append(box) for line in lines: l = line.get_label() try: loc = labels_u_line.index(l) except ValueError: # this line is either one not added by lineidplot or has no label. continue lineid_lines.append(line) return lineid_boxes, lineid_lines
<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_line_ids function. """
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: continue # No changes for this box box.set_color(colors[loc]) if color_arrow: box.arrow_patch.set_color(colors[loc]) ax.figure.canvas.draw()
<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) except ValueError: continue # No changes for this line line.set_color(colors[loc]) ax.figure.canvas.draw()
<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['tool_specific'][self.tool] except KeyError: return 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 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 options which define tools supported for target # TODO: we might create a list of what tool requires if self.tool: # tool_specific requested look for it try: for k,v in mcu_record['tool_specific'].items(): if k == self.tool: return True except (TypeError, KeyError) as err: pass return False else: # supports generic part (mcu part) return 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 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 the real key it points to, plus any other aliases of that real key. (The given alias itself is not included in the return value.) """
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. names.append(key) # 'key' is now a realkey, whose aliases are all keys whose value is # itself. Filter out the original name given. names.extend([ k for k, v in six.iteritems(self.aliases) if v == key and k != name ]) return names
<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 contain a fragment component. """
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) locator parameters :param timeout: (optional) time to wait for element :return: None """
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) locator parameters :param timeout: (optional) time to wait for element :return: None """
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: (optional) locator parameters :param timeout: (optional) time to wait for element :return: None """
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 command key. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param timeout: (optional) time to wait for element :return: None """
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 :param last_element: WebElement instance :return: None """
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 WebElement instance :param value: string :param params: (optional) locator parameters :return: None """
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 drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance :param option_locator: locator tuple (if any, params needs to be in place) :param option_text: text to base option selection on :param params: Dictionary containing dictionary of params :return: None """
# 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(option) break
<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_down_locator: locator tuple or WebElement instance :param option_locator: locator tuple or WebElement instance :param params: Dictionary containing dictionary of params :return: None """
# 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. Calls get_element() with expected condition: visibility of element located :param locator: locator tuple or WebElement instance :param attribute: attribute to return :param params: (optional) locator parameters :param timeout: (optional) time to wait for text (default: None) :param visible: should element be visible before getting text (default: False) :return: element attribute """
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!".format(attribute) raise NoSuchElementException(msg)
<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 locator: element identifier :param params: (optional) locator parameters :param timeout: (optional) time to wait for text (default: None) :param visible: should element be visible before getting text (default: True) :return: element text, value or empty string """
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') except AttributeError: return ""
<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 tuple or WebElement instance :param text: text to input :param with_click: clicks the input field :param with_clear: clears the input field :param with_enter: hits enter-key after text input :param params: (optional) locator params :return: None """
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): actions = BasePage.handle_at_sign_for_ie(text, actions) else: actions.send_keys_to_element(element, text) if with_clear: element.clear() # Click to regain focus as clear does clear w/ blur by design - # https://w3c.github.io/webdriver/webdriver-spec.html#element-clear self.click(element) if with_enter: actions.send_keys(Keys.ENTER) actions.perform()
<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 or WebElement instance :param click: clicks the input field :param clear: clears the input field :param backspace: how many times to hit backspace :param params: (optional) locator params :return: None """
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) for _ in range(backspace): actions.send_keys(Keys.BACKSPACE) actions.perform()
<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 or a list with x- and y-coordinates (integers) :param source_element: WebElement instance :param target_element: WebElement instance or list of x- and y-coordinates :param params: Dictionary containing dictionary of params :return: None """
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_element, params['target'] if params else None) action = ActionChains(self.driver) if isinstance(target_element, WebElement): action.drag_and_drop(source_element, target_element) else: action.click_and_hold(source_element).move_by_offset(*target_element).release() action.perform()
<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 WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: element identifier :param params: (optional) locator parameters :param timeout: (optional) time to wait for element (default: self._explicit_wait) :param visible: (optional) if the element should also be visible (default: False) :param parent: internal (see #get_present_child) :return: WebElement instance """
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 instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :return: WebElement instance """
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) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: element identifier :param params: (optional) locator parameters :param timeout: (optional) time to wait for element (default: self._explicit_wait) :param visible: (optional) if the element should also be visible (default: False) :param parent: internal (see #get_present_children) :return: WebElement instance """
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 WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :return: WebElement instance """
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 WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :param visible: (optional) if the element should also be visible (default: False) :return: WebElement instance """
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 WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :return: WebElement instance """
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 WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :param visible: (optional) if the element should also be visible (default: False) :return: WebElement instance """
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) return WebElement instance or None, else we wait and retry for timeout and raise TimeoutException should the element not be found. :param parent: parent-element :param locator: locator tuple :param params: (optional) locator params :param timeout: (optional) time to wait for element (default: self._explicit_wait) :return: WebElement instance """
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 parameters. Uses selenium.webdriver.support.expected_conditions to determine the state of the element(s). :param locator: element identifier :param expected_condition: expected condition of element (ie. visible, clickable, etc) :param params: (optional) locator parameters :param timeout: (optional) time to wait for element (default: self._explicit_wait) :param error_msg: (optional) customized error message :param driver: (optional) alternate Webdriver instance (example: parent-element) :param kwargs: optional arguments to expected conditions :return: WebElement instance, list of WebElements, or None """
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(*locator, params=params) _driver = driver or self.driver exp_cond = expected_condition(locator, **kwargs) if timeout == 0: try: return exp_cond(_driver) except NoSuchElementException: return None if timeout is None: timeout = self._explicit_wait error_msg += "\nExpected condition: {}" \ "\nTimeout: {}".format(expected_condition, timeout) return WebDriverWait(_driver, timeout).until(exp_cond, error_msg)
<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: None """
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: (optional) locator parameters :param use_js: use javascript to open hover :return: element hovered """
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).perform() actions.reset_actions() return 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 triggered the hover to open :param use_js: use javascript to close hover :return: None """
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, MoveTargetOutOfBoundsException): return 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 perform_hover_action(self, locator, func, error_msg='', exceptions=None, params=None, alt_loc=None, alt_params=None, **kwargs): """ Hovers an element and performs whatever action is specified in the supplied function. NOTE: Specified function MUST return a non-false value upon success! :param locator: locator tuple or WebElement instance :param func: action to perform while hovering :param error_msg: error message to display if hovering failed :param exceptions: list of exceptions (default: StaleElementReferenceException) :param params: (optional) locator parameters :param alt_loc: alternate locator tuple or WebElement instance to move to with offset :param alt_params: (optional) alternate locator parameters :param kwargs: keyword arguments to the function func :return: result of performed action """
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: exc.extend(iter(exceptions)) except TypeError: # exceptions is not iterable exc.append(exceptions) exc = tuple(exc) msg = error_msg or "Performing hover actions failed!" return ActionWait().until(_do_hover, msg)
<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 self.hover(locator, params): // do something with the hover :param locator: locator tuple or WebElement instance :param params: (optional) locator params :param use_js: use javascript to hover :param alt_loc: alternate locator tuple or WebElement instance for close hover :param alt_params: (optional) alternate locator params :return: None """
# 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_element(alt_loc, alt_params) self.close_hover(element, use_js)
<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 :param params: (optional) locator params :param timeout: (optional) maximum waiting time (in seconds) (default: 5) :return: list of WebElements """
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 never populated!")
<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 re-get's the element in a loop to avoid caching or stale element issues. :Example: Wait for the class attribute to get 'board-hidden' value :param locator: locator tuple :param attribute: element attribute :param value: attribute value to wait for :param params: (optional) locator params :param timeout: (optional) maximum waiting time (in seconds) (default: 5) :return: None """
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 had. :param timeout: time to wait for silence (default: 5 seconds) :return: None """
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: if "broadcast" in info: yield info['broadcast']
<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.gateways()['default'] if proto in default_gateway: _, default_gateway_interface = default_gateway[proto] else: default_gateway_interface = None for interface in netifaces.interfaces(): for info in netifaces.ifaddresses(interface).get(netifaces.AF_INET, []): if info['addr']: if interface == default_gateway_interface: _ip4_addresses.insert(0, info['addr']) else: _ip4_addresses.append(info['addr']) return _ip4_addresses
<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: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :param address_exception: The user's exception name, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :raises: ValueError - error with phone number provided UndefinitiveError - when no address_country_code and address_exception are provided and the phone number area code matching isn't specific enough :return: A tuple of (Decimal percentage rate, country code, exception name [or None]) """
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[0] != '+': raise ValueError('Phone number is not in international format with a leading +') phone_number = phone_number[1:] if not phone_number: raise ValueError('Phone number does not appear to contain any digits') country_code = _lookup_country_code(phone_number) if not country_code: raise ValueError('Phone number does not appear to be a valid international phone number') if country_code in CALLING_CODE_EXCEPTIONS: for info in CALLING_CODE_EXCEPTIONS[country_code]: if not re.match(info['regex'], phone_number): continue mapped_country = info['country_code'] mapped_name = info['name'] if not info['definitive']: if address_country_code is None: raise UndefinitiveError('It is not possible to determine the users VAT rates based on the information provided') if address_country_code != mapped_country: continue if address_exception != info['name']: continue rate = rates.BY_COUNTRY[mapped_country]['exceptions'][mapped_name] return (rate, mapped_country, mapped_name) if country_code not in rates.BY_COUNTRY: return (Decimal('0.0'), country_code, None) return (rates.BY_COUNTRY[country_code]['rate'], country_code, 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 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.append(path) if query is not None: result.extend([self.QUEST, query]) if fragment is not None: result.extend([self.HASH, fragment]) return self.EMPTY.join(result)
<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 three-item tuple. """
# 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 default length') # TODO: this could be much more efficient by using a dedicated regex return ( self.getuserinfo(default[0], encoding, errors), self.gethost(default[1], errors), self.getport(default[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 getuserinfo(self, default=None, encoding='utf-8', errors='strict'): """Return the decoded userinfo subcomponent of the URI authority, or `default` if the original URI reference did not contain a userinfo field. """
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 contain a query component. """
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 a dictionary of query variables. The dictionary keys are the unique query variable names and the values are lists of values for each name. """
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 information. :param country_code: The two-character country code where the user resides :param exception_name: The name of an exception for the country, as returned from vat_moss.declared_residence.options() :raises: ValueError - if country_code is not two characers, or exception_name is not None or a valid exception from options() :return: A tuple of (Decimal VAT rate, country_code, exception name [or None]) """
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_code.upper() if country_code not in rates.BY_COUNTRY: return (Decimal('0.0'), country_code, None) country_info = rates.BY_COUNTRY[country_code] if not exception_name: return (country_info['rate'], country_code, None) if exception_name not in country_info['exceptions']: raise ValueError('"%s" is not a valid exception for %s' % (exception_name, country_code)) rate_info = country_info['exceptions'][exception_name] if isinstance(rate_info, Decimal): rate = rate_info else: # This allows handling the complex case of the UK RAF bases in Cyprus # that map to the standard country rate. The country code and exception # name need to be changed in addition to gettting a special rate. rate, country_code, exception_name = rate_info return (rate, country_code, exception_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 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 user :raises: ValueError - if country_code is not two characers :return: A list of strings that are VAT exceptions for the country specified """
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 ID to check. Allows "GR" prefix for Greece, even though it should be "EL". :raises: ValueError - If the is not a string or is not in the format of two characters plus an identifier :return: None if the VAT ID is blank or not for an EU country or Norway Otherwise a normalized string containing the VAT ID """
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) vat_id = vat_id.replace('-', '') vat_id = vat_id.replace('.', '') vat_id = vat_id.upper() country_prefix = vat_id[0:2] # Fix people using GR prefix for Greece if country_prefix == 'GR': vat_id = 'EL' + vat_id[2:] country_prefix = 'EL' if country_prefix not in ID_PATTERNS: return None return vat_id
<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 exceptions to handle :return: the result of the decorated function """
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(', '.join([e.__name__ for e in exc])) def wrapper(func): def exc_handler(*args, **kwargs): import time timeout = 10 poll_freq = 0.5 end_time = time.time() + timeout while time.time() <= end_time: try: return func(*args, **kwargs) except exc: time.sleep(poll_freq) poll_freq *= 1.25 continue raise RuntimeError(msg) return exc_handler return wrapper
<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 message :param exceptions: Extra exceptions to handle :param timeout: time to keep trying (default: 10 seconds) :return: the result of the decorated function """
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(', '.join([e.__name__ for e in exc])) def wrapper(func): def wait_handler(*args, **kwargs): import time poll_freq = 0.5 end_time = time.time() + timeout while time.time() <= end_time: try: value = func(*args, **kwargs) if value: return value except exc as e: LOGGER.debug(e) pass # continue time.sleep(poll_freq) poll_freq *= 1.25 raise RuntimeError(msg) return wait_handler return wrapper
<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_code: The two-character country code :param postal_code: The postal code for the user :param city: The city name for the user :raises: ValueError - If country code is not two characers, or postal_code or city are not strings. postal_code may be None or blank string for countries without postal codes. :return: A tuple of (Decimal percentage rate, country code, exception name [or None]) """
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_code not in COUNTRIES_WITHOUT_POSTAL_CODES: if not postal_code or not isinstance(postal_code, str_cls): raise ValueError('Postal code is not a string') if not city or not isinstance(city, str_cls): raise ValueError('City is not a string') if isinstance(postal_code, str_cls): postal_code = re.sub('\\s+', '', postal_code) postal_code = postal_code.upper() # Remove the common european practice of adding the country code # to the beginning of a postal code, followed by a dash if len(postal_code) > 3 and postal_code[0:3] == country_code + '-': postal_code = postal_code[3:] postal_code = postal_code.replace('-', '') city = city.lower().strip() if country_code not in rates.BY_COUNTRY and country_code not in POSTAL_CODE_EXCEPTIONS: return (Decimal('0.0'), country_code, None) country_default = rates.BY_COUNTRY.get(country_code, {'rate': Decimal('0.0')})['rate'] if country_code not in POSTAL_CODE_EXCEPTIONS: return (country_default, country_code, None) exceptions = POSTAL_CODE_EXCEPTIONS[country_code] for matcher in exceptions: # Postal code-only match if isinstance(matcher, str_cls): postal_regex = matcher city_regex = None else: postal_regex, city_regex = matcher if not re.match(postal_regex, postal_code): continue if city_regex and not re.search(city_regex, city): continue mapped_country = exceptions[matcher]['country_code'] # There is at least one entry where we map to a different country, # but are not mapping to an exception if 'name' not in exceptions[matcher]: country_code = mapped_country country_default = rates.BY_COUNTRY[country_code]['rate'] break mapped_name = exceptions[matcher]['name'] rate = rates.BY_COUNTRY[mapped_country]['exceptions'][mapped_name] return (rate, mapped_country, mapped_name) return (country_default, country_code, 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 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" resp = yield from self._session.patch( _SERVER + '/pods/{}/acStates/{}'.format(uid, name), data=json.dumps(data), params=self._params, timeout=self._timeout) try: return (yield from resp.json())['result'] except aiohttp.client_exceptions.ContentTypeError: pass raise SensiboError((yield from resp.text()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 Especially on Linux, crashing out of a networkzero process can leave the sockets lingering and unable to re-bind on startup. We give it a few goes here to see if we can bind within a couple of seconds. """
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.EADDRINUSE: _logger.warn("%s; %d tries remaining", exc, n_tries_left) n_tries_left -= 1 else: raise else: raise core.SocketAlreadyExistsError("Failed to bind after %s tries" % n_tries)
<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 automatically when an attempt is made to advertise or discover. It might be convenient, though, to call this function directly if you want to have a process whose only job is to host this beacon so that it doesn't shut down when other processes shut down. """
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") # # _remote_beacon is simply a not-None sentinel value # to distinguish between the case where we have not # yet started a beacon and where we have found one # in another process. # _beacon = _remote_beacon else: raise else: _beacon.start()
<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 request queue. """
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 = segments[0], segments[1:] _logger.debug("Adding %s, %s to the request queue", action, params) self._command = _Command(action, 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 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 GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param city: The city name :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :param address_exception: The user's exception name, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :raises: ValueError - if country code is not two characers, or subdivision or city are not strings UndefinitiveError - when no address_country_code and address_exception are provided and the geoip2 information is not specific enough :return: A tuple of (Decimal percentage rate, country code, exception name [or None]) """
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('City is not a string') country_code = country_code.upper() subdivision = subdivision.lower() city = city.lower() if country_code not in rates.BY_COUNTRY: return (Decimal('0.0'), country_code, None) country_default = rates.BY_COUNTRY[country_code]['rate'] if country_code not in GEOIP2_EXCEPTIONS: return (country_default, country_code, None) exceptions = GEOIP2_EXCEPTIONS[country_code] for matcher in exceptions: # Subdivision-only match if isinstance(matcher, str_cls): sub_match = matcher city_match = None else: sub_match, city_match = matcher if sub_match != subdivision: continue if city_match and city_match != city: continue info = exceptions[matcher] exception_name = info['name'] if not info['definitive']: if address_country_code is None: raise UndefinitiveError('It is not possible to determine the users VAT rates based on the information provided') if address_country_code != country_code: continue if address_exception != exception_name: continue rate = rates.BY_COUNTRY[country_code]['exceptions'][exception_name] return (rate, country_code, exception_name) return (country_default, country_code, 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 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 use as the base :param rates: A dict with keys that are string currency codes and values that are a Decimal of the exchange rate for that currency. """
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 amount: A Decimal or Money object :param currency: If the amount is a Decimal, the currency of the amount :return: A string representation of the amount in the currency """
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 a string') if currency not in FORMATTING_RULES: valid_currencies = sorted(FORMATTING_RULES.keys()) formatted_currencies = ', '.join(valid_currencies) raise ValueError('The currency specified, "%s", is not a supported currency: %s' % (currency, formatted_currencies)) if not isinstance(amount, Decimal): raise ValueError('The amount specified is not a Decimal') rules = FORMATTING_RULES[currency] format_string = ',.%sf' % rules['decimal_places'] result = builtin_format(amount, format_string) result = result.replace(',', '_') result = result.replace('.', '|') result = result.replace('_', rules['thousands_separator']) result = result.replace('|', rules['decimal_mark']) if rules['symbol_first']: result = rules['symbol'] + result else: result = result + rules['symbol'] return result
<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` is ``None``. :raises KeyError: failed to find a momentum named `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 TypeError: `name` is ``None``. :raises KeyError: failed to find a momentum named `name`. """
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 value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value for `until`. :returns: a momentum updated. :raises TypeError: `name` is ``None``. :raises KeyError: failed to find a momentum named `name`. """
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 new velocity. :param at: the time to snap. (default: now) :returns: a momentum updated. :raises TypeError: `name` is ``None``. :raises KeyError: failed to find a momentum named `name`. """
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 a URI reference string from its individual components."""
# 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 must do so with # lowercase letters. An implementation should accept uppercase # letters as equivalent to lowercase in scheme names (e.g., allow # "HTTP" as well as "http") for the sake of robustness but should # only produce lowercase scheme names for consistency. if isinstance(scheme, bytes): scheme = _scheme(scheme) elif scheme is not None: scheme = _scheme(scheme.encode()) # authority must be string type or three-item iterable if authority is None: authority = (None, None, None) elif isinstance(authority, bytes): authority = _AUTHORITY_RE_BYTES.match(authority).groups() elif isinstance(authority, _unicode): authority = _AUTHORITY_RE_UNICODE.match(authority).groups() elif not isinstance(authority, collections.Iterable): raise TypeError('Invalid authority type') elif len(authority) != 3: raise ValueError('Invalid authority length') authority = _authority( userinfo if userinfo is not None else authority[0], host if host is not None else authority[1], port if port is not None else authority[2], encoding ) # RFC 3986 3.3: If a URI contains an authority component, then the # path component must either be empty or begin with a slash ("/") # character. If a URI does not contain an authority component, # then the path cannot begin with two slash characters ("//"). path = uriencode(path, _SAFE_PATH, encoding) if authority is not None and path and not path.startswith(b'/'): raise ValueError('Invalid path with authority component') if authority is None and path.startswith(b'//'): raise ValueError('Invalid path without authority component') # RFC 3986 4.2: A path segment that contains a colon character # (e.g., "this:that") cannot be used as the first segment of a # relative-path reference, as it would be mistaken for a scheme # name. Such a segment must be preceded by a dot-segment (e.g., # "./this:that") to make a relative-path reference. if scheme is None and authority is None and not path.startswith(b'/'): if b':' in path.partition(b'/')[0]: path = b'./' + path # RFC 3986 3.4: The characters slash ("/") and question mark ("?") # may represent data within the query component. Beware that some # older, erroneous implementations may not handle such data # correctly when it is used as the base URI for relative # references (Section 5.1), apparently because they fail to # distinguish query data from path data when looking for # hierarchical separators. However, as query components are often # used to carry identifying information in the form of "key=value" # pairs and one frequently used value is a reference to another # URI, it is sometimes better for usability to avoid percent- # encoding those characters. if isinstance(query, _strtypes): query = uriencode(query, _SAFE_QUERY, encoding) elif isinstance(query, collections.Mapping): query = _querydict(query, querysep, encoding) elif isinstance(query, collections.Iterable): query = _querylist(query, querysep, encoding) elif query is not None: raise TypeError('Invalid query type') # RFC 3986 3.5: The characters slash ("/") and question mark ("?") # are allowed to represent data within the fragment identifier. # Beware that some older, erroneous implementations may not handle # this data correctly when it is used as the base URI for relative # references. if fragment is not None: fragment = uriencode(fragment, _SAFE_FRAGMENT, encoding) result = uriunsplit((scheme, authority, path, query, fragment)) # always return platform `str` type return result if isinstance(result, str) else result.decode()
<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 :param message: message to print if time ran out :param args: arguments :param kwargs: key word arguments :return: result of function or None """
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) self._poll *= 1.25 if time.time() > end_time: raise RuntimeError(message) return 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 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', dependencies=[], irc_channels=None, slack_channels=None, ticket=False, project=None, priority=None, source=None, tags=[], ttl=None, sensu_host='169.254.255.254', sensu_port=3030, component=None, description=None, ): """Send a new event with the given information. Requires a name, runbook, status code, event output, and team but the other keys are kwargs and have defaults. :type name: str :param name: Name of the check :type runbook: str :param runbook: The runbook associated with the check :type status: int :param status: Exit status code, 0,1,2,3. Must comply with the Nagios conventions. See `the Sensu docs <https://sensuapp.org/docs/latest/checks#sensu-check-specification>`_ for the exact specification. :type output: str :param output: The output of the check itself. May include CRIT/WARN/OK to make it easy to evaluate how things went. Should be newline separated, but try to put the most relevant data in the first line. Example: OK: Everything is fine or CRIT: Accounts are locked. Users can't buy widgets. :type team: str :param team: Team responsible for this check. This team must already be defined server-side in the Sensu handler configuration. :type page: bool :param page: Boolean on whether this alert is page-worthy. Activates handlers that send pages. :type tip: str :param tip: A short 1-line version of the runbook. Example: "Set clip-jawed monodish to 6" :type notification_email: str :param notification_email: A comma-separated string of email destinations. Unset will default to the "team" default. :type check_every: str :param check_every: Human readable time unit to let Sensu know how of then this event is fired. Defaults to "30s". If this parameter is not set correctly, the math for `alert_after` will be incorrect. :type realert_every: int :param realert_every: Integer value for filtering repeat occurrences. A value of 2 would send every other alert. Defaults to -1, which is a special value representing exponential backoff. (alerts on event number 1,2,4,8, etc) :type alert_after: str :param alert_after: A human readable time unit to suspend handler action until enough occurrences have taken place. Only valid when check_every is accurate. :type dependencies: list :param dependencies: An list of strings representing checks that *this* check is dependent on. :type irc_channels: list :param irc_channels: An list of IRC channels to send the event notification to. Defaults to the team setting. Set an empty list to specify no IRC notifications. :type slack_channels: list :param slack_channels: An list of Slack channels to send the event notification to. Defaults to the team setting. Set an empty list to specify no Slack notifications. :type ticket: bool :param ticket: A Boolean value to enable ticket creation. Defaults to false. :type project: str :param project: A string representing the JIRA project that the ticket should go under. Defaults to the team value. :type priority: str :param priority: A JIRA priority to use when creating a ticket. This only makes sense to use when in combination with the ticket parameter set to true. :type source: str :param source: Allows "masquerading" the source value of the event, otherwise comes from the fqdn of the host it runs on. This is especially important to set on events that could potentially be created from multiple hosts. For example if ``send_event`` is called from three different hosts in a cluster, you wouldn't want three different events, you would only want one event that looked like it came from ``the_cluster``, so you would set ``source='the_cluster'``. :type tags: list :param tags: An list of arbitrary tags that can be used in handlers for different metadata needs such as labels in JIRA handlers. :type ttl: str :param ttl: A human readable time unit to set the check TTL. If Sensu does not hear from the check after this time unit, Sensu will spawn a new failing event! (aka check staleness) Defaults to None, meaning Sensu will only spawn events when send_event is called. :type sensu_host: str :param sensu_host: The IP or Name to connect to for sending the event. Defaults to the yocalhost IP. :type component: list :param component: Component(s) affected by the event. Good example here would would be to include the service that is being affected or a module of that service such as healthcheck. :type description: str :param description: Human readable text giving more context on the event. This could include information on what the check means or why was it created. Note on TTL events and alert_after: ``alert_after`` and ``check_every`` only really make sense on events that are created periodically. Setting ``alert_after`` on checks that are not periodic is not advised because the math will be incorrect. For example, if check was written that called ``send_event`` on minute values that were prime, what should the ``check_every`` setting be? No matter what it was, it would be wrong, and therefore ``alert_after`` would be incorrectly calculated (as it is a function of the number of failing events seen multiplied by the ``check_every`` setting). If in doubt, set ``alert_after`` to ``0`` to ensure you never miss an alert due to incorrect ``alert_after`` math on non-periodic events. (See also this `Pull request <https://github.com/sensu/sensu/pull/1200>`_) """
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': status, 'output': output, 'handler': 'default', 'team': team, 'runbook': runbook, 'tip': tip, 'notification_email': notification_email, 'interval': human_to_seconds(check_every), 'page': page, 'realert_every': int(realert_every), 'dependencies': dependencies, 'alert_after': human_to_seconds(alert_after), 'ticket': ticket, 'project': project, 'priority': priority, 'source': source, 'tags': tags, 'ttl': human_to_seconds(ttl), } if irc_channels is not None: result_dict['irc_channels'] = irc_channels if slack_channels is not None: result_dict['slack_channels'] = slack_channels if component is not None: result_dict['component'] = component if description is not None: result_dict['description'] = description json_hash = json.dumps(result_dict) sock = socket.socket() try: sock.connect((sensu_host, sensu_port)) sock.sendall(six.b(json_hash) + b'\n') finally: sock.close()
<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[i] = _fromint(i) _encoded[safe] = encoded return b''.join(map(encoded.__getitem__, _tointseq(uristring)))
<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 encoding is not None: return b''.join(result).decode(encoding, errors) else: return b''.join(result)
<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 return Numpy array equivalent of `x`. If not then raise ValueError, using `name` as an idnetification. If len(x) returns TypeError, then assume it is a scalar and create a Numpy array of length `size`. Each item of this array will have the value as `x`. """
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(x) return xa
<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) d[lab] -= 1 else: v = lab line_labels_u.insert(0, v) return line_labels_u
<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: matplotlib Figure artist Figure on which the boxes will be placed. ax: matplotlib Axes artist Axes on which the boxes will be placed. arrow_tip: list or array of floats Location of tip of arrow, in data coordinates. box_axes_space: float Vertical space between arrow tip and text box in figure coordinates. Default is 0.06. Returns ------- box_loc: list of floats Box locations in data coordinates. Notes ----- Note that this function is not needed if user provides both arrow tip positions and box locations. The use case is when the program has to automatically find positions of boxes. In the automated plotting case, the arrow tip is set to be the top of the Axes (outside this function) and the box locations are determined by `box_axes_space`. In Matplotlib annotate function, both the arrow tip and the box location can be specified. While calculating automatic box locations, it is not ideal to use data coordinates to calculate box location, since plots will not have a uniform appearance. Given locations of arrow tips, and a spacing in figure fraction, this function will calculate the box locations in data coordinates. Using this boxes can be placed in a uniform manner. """
# 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 w, a in zip(line_wave, arrow_tip): # Convert position of tip of arrow to figure coordinates, add # the vertical space between top edge and text box in figure # fraction. Convert this text box position back to data # coordinates. display_coords = ax.transData.transform((w, a)) figure_coords = fig_inv_trans.transform(display_coords) figure_coords[1] += box_axes_space display_coords = fig.transFigure.transform(figure_coords) ax_coords = ax.transData.inverted().transform(display_coords) box_loc.append(ax_coords) return box_loc
<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 they don't overlap. Parameters line_wave: list or array of floats Line wave lengths. These are assumed to be the initial y (wave length) location of the boxes. box_widths: list or array of floats Width of box containing labels for each line identification. left_edge: float Left edge of valid data i.e., wave length minimum. right_edge: float Right edge of valid data i.e., wave lengths maximum. max_iter: int Maximum number of iterations to attempt. adjust_factor: float Gap between boxes are reduced or increased by this factor after each iteration. factor_decrement: float The `adjust_factor` itself if reduced by this factor, after certain number of iterations. This is useful for crowded regions. fd_p: float Percentage, given as a fraction between 0 and 1, after which adjust_factor must be reduced by a factor of `factor_decrement`. Default is set to 0.75. Returns ------- wlp, niter, changed: (float, float, float) The new y (wave length) location of the text boxes, the number of iterations used and a flag to indicated whether any changes to the input locations were made or not. Notes ----- This is a direct translation of the code in lineid_plot.pro file in NASA IDLAstro library. Positions are returned either when the boxes no longer overlap or when `max_iter` number of iterations are completed. So if there are many boxes, there is a possibility that the final box locations overlap. References + http://idlastro.gsfc.nasa.gov/ftp/pro/plot/lineid_plot.pro + http://idlastro.gsfc.nasa.gov/ """
# 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.0 else: diff1 = wlp[i] - left_edge + box_widths[i] * 1.01 separation1 = box_widths[i] if i < nlines - 2: diff2 = wlp[i + 1] - wlp[i] separation2 = (box_widths[i] + box_widths[i + 1]) / 2.0 else: diff2 = right_edge + box_widths[i] * 1.01 - wlp[i] separation2 = box_widths[i] if diff1 < separation1 or diff2 < separation2: if wlp[i] == left_edge: diff1 = 0 if wlp[i] == right_edge: diff2 = 0 if diff2 > diff1: wlp[i] = wlp[i] + separation2 * adjust_factor wlp[i] = wlp[i] if wlp[i] < right_edge else \ right_edge else: wlp[i] = wlp[i] - separation1 * adjust_factor wlp[i] = wlp[i] if wlp[i] > left_edge else \ left_edge changed = True niter += 1 if niter == max_iter * fd_p: adjust_factor /= factor_decrement if niter >= max_iter: break return wlp, changed, niter
<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, kind="linear", copy=False, bounds_error=False, fill_value=fillval) return ipol(cout[0], cout[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 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_sampling=42): """Field behind a dielectric sphere in the Rytov approximation Parameters radius: float Radius of the sphere [m] sphere_index: float Refractive index of the sphere medium_index: float Refractive index of the surrounding medium wavelength: float Vacuum wavelength of the imaging light [m] pixel_size: float Pixel size [m] grid_size: tuple of floats Resulting image size in x and y [px] center: tuple of floats Center position in image coordinates [px] focus: float .. versionadded:: 0.5.0 Axial focus position [m] measured from the center of the sphere in the direction of light propagation. radius_sampling: int Number of pixels used to sample the sphere radius when computing the Rytov field. The default value of 42 pixels is a reasonable number for single-cell analysis. Returns ------- qpi: qpimage.QPImage Quantitative phase data set """
# 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))] size_factor = grid_size_sim[0] / grid_size[0] pixel_size_sim = pixel_size / size_factor field = sphere_prop_fslice_bessel(radius=radius, sphere_index=sphere_index, medium_index=medium_index, wavelength=wavelength, pixel_size=pixel_size_sim, grid_size=grid_size_sim, lD=focus, approx="rytov", zeropad=5, oversample=1 ) # interpolate field back to original image coordinates # simulation coordinates x_sim = (np.arange(grid_size_sim[0]) + .5) * pixel_size_sim y_sim = (np.arange(grid_size_sim[1]) + .5) * pixel_size_sim # output coordinates x = (np.arange(grid_size[0]) + grid_size[0] / 2 - center[0]) * pixel_size y = (np.arange(grid_size[1]) + grid_size[1] / 2 - center[1]) * pixel_size # Interpolate resulting field with original extent field = interpolate_grid(cin=(y_sim, x_sim), cout=(y, x), data=field) meta_data = {"pixel size": pixel_size, "wavelength": wavelength, "medium index": medium_index, "sim center": center, "sim radius": radius, "sim index": sphere_index, "sim model": "rytov", } qpi = qpimage.QPImage(data=field, which_data="field", meta_data=meta_data) return qpi
<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 under the import name '_context'. This function returns the module's global dictionary. """
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_module("_context") mod.stack = stack return mod # Temporarily add the context importer into the meta path old_meta_path = copy.copy(sys.meta_path) old_path = copy.copy(sys.path) # Save the modules list, in order to remove modules loaded after this point old_sys_modules = sys.modules.keys() # Run the module # Prepare import environment abspath = os.path.abspath(path) sys.meta_path.append(ContextImporter()) sys.path.append(os.path.dirname(abspath)) # Enable importing files within module's folder # Perform the importing srcf = open(abspath, "r") module_name = ''.join(random.choice(string.digits + string.lowercase) for i in range(16)) srcmodule = imp.load_source("cloudcast._template_" + module_name, abspath, srcf) srcf.close() # Restore meta path, modules list and return module sys.meta_path = old_meta_path sys.path = old_path for modname in sys.modules.keys(): if not modname in old_sys_modules: del sys.modules[modname] return srcmodule
<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_name, el_name, element) in elements: full_name = self.generate_cfn_name(module_name, el_name) self.name_stack_element(element, full_name) self.add_stack_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 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) for e in self.Resources]) if len(self.Outputs) > 0: t['Outputs'] = dict([e.contents(stack) for e in self.Outputs])
<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, sort_keys=False).encode(t)
<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 preview_path = preview_list[0] # Simplistically, assume there's only one with NamedTemporaryFile(prefix='pyglass', suffix=extension(preview_path), delete=False) as tempfileobj: dest_path = tempfileobj.name shutil.copy(preview_path, dest_path) assert(exists(dest_path)) return dest_path except: return 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 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_path) dest_list = glob(join(dest_dir, '%s.png' % (src_filename))) assert(dest_list) dest_path = dest_list[0] assert(exists(dest_path)) return dest_path except: return 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 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 = results.get() exception = results.get() if exception is None: return data else: tp, val, tb = results.get() raise tp, val, tb
<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()`. Also, ignore callback return value to prevent callback from being called repeatedly indefinitely. See the `gobject.idle_add() documentation`_ for further information. .. _`gobject.idle_add() documentation`: http://library.isr.ist.utl.pt/docs/pygtk2reference/gobject-functions.html#function-gobject--idle-add Parameters ---------- func : function or functools.partial ''' # Set up GDK threading. # XXX This must be done to support running multiple threads in GTK # applications. gtk.gdk.threads_init() # Support wraps_func = func.func if isinstance(func, functools.partial) else func @functools.wraps(wraps_func) def _gtk_threadsafe(*args): def _no_return_func(*args): func(*args) gobject.idle_add(_no_return_func, *args) return _gtk_threadsafe