Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def execute(self, query): c = self.conn.cursor() result = c.execute(query) for i in result: yield i
[ "\n Execute a query directly on the database.\n " ]
Please provide a description of the function:def _replace(self, feature, cursor): try: cursor.execute( constants._UPDATE, list(feature.astuple()) + [feature.id]) except sqlite3.ProgrammingError: cursor.execute( constants._I...
[ "\n Insert a feature into the database.\n " ]
Please provide a description of the function:def wait_for_js(function): @functools.wraps(function) def wrapper(*args, **kwargs): # pylint: disable=missing-docstring # If not a method, then just call the function if len(args) < 1: return function(*args, **kwargs) # Ot...
[ "\n Method decorator that waits for JavaScript dependencies before executing `function`.\n If the function is not a method, the decorator has no effect.\n\n Args:\n function (callable): Method to decorate.\n\n Returns:\n Decorated method\n " ]
Please provide a description of the function:def _decorator(store_name, store_values): def decorator(clz): # pylint: disable=missing-docstring # Add a `wait_for_js` method to the class if not hasattr(clz, 'wait_for_js'): setattr(clz, 'wait_for_js', _wait_for_js) # pylint: disable...
[ "\n Return a class decorator that:\n\n 1) Defines a new class method, `wait_for_js`\n 2) Defines a new class list variable, `store_name` and adds\n `store_values` to the list.\n " ]
Please provide a description of the function:def _wait_for_js(self): # No Selenium browser available, so return without doing anything if not hasattr(self, 'browser'): return # pylint: disable=protected-access # Wait for JavaScript variables to be defined if hasattr(self, '_js_vars') ...
[ "\n Class method added by the decorators to allow\n decorated classes to manually re-check JavaScript\n dependencies.\n\n Expect that `self` is a class that:\n 1) Has been decorated with either `js_defined` or `requirejs`\n 2) Has a `browser` property\n\n If either (1) or (2) is not satisfied, ...
Please provide a description of the function:def _are_js_vars_defined(browser, js_vars): # This script will evaluate to True iff all of # the required vars are defined. script = u" && ".join([ u"!(typeof {0} === 'undefined')".format(var) for var in js_vars ]) try: retur...
[ "\n Return a boolean indicating whether all the JavaScript\n variables `js_vars` are defined on the current page.\n\n `browser` is a Selenium webdriver instance.\n " ]
Please provide a description of the function:def _are_requirejs_deps_loaded(browser, deps): # This is a little complicated # # We're going to use `execute_async_script` to give control to # the browser. The browser indicates that it wants to return # control to us by calling `callback`, which...
[ "\n Return a boolean indicating whether all the RequireJS\n dependencies `deps` have loaded on the current page.\n\n `browser` is a WebDriver instance.\n ", "\n // Retrieve the callback function used to return control to the test suite\n var callback = arguments[arguments.length - 1];\n\...
Please provide a description of the function:def no_selenium_errors(func): def _inner(*args, **kwargs): # pylint: disable=missing-docstring try: return_val = func(*args, **kwargs) except WebDriverException: LOGGER.warning(u'Exception ignored during retry loop:', exc_inf...
[ "\n Decorator to create an `EmptyPromise` check function that is satisfied\n only when `func` executes without a Selenium error.\n\n This protects against many common test failures due to timing issues.\n For example, accessing an element after it has been modified by JavaScript\n ordinarily results ...
Please provide a description of the function:def pre_verify(method): @wraps(method) def wrapper(self, *args, **kwargs): # pylint: disable=missing-docstring self._verify_page() # pylint: disable=protected-access return method(self, *args, **kwargs) return wrapper
[ "\n Decorator that calls self._verify_page() before executing the decorated method\n\n Args:\n method (callable): The method to decorate.\n\n Returns:\n Decorated method\n " ]
Please provide a description of the function:def set_rules(self, rules): self.rules_to_ignore = rules.get("ignore", []) self.rules_to_run = rules.get("apply", [])
[ "\n Sets the rules to be run or ignored for the audit.\n\n Args:\n\n rules: a dictionary of the format `{\"ignore\": [], \"apply\": []}`.\n\n See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits\n\n Passing `{\"apply\": []}` or `{}` means to...
Please provide a description of the function:def set_scope(self, include=None, exclude=None): if include: self.scope = u"document.querySelector(\"{}\")".format( u', '.join(include) ) else: self.scope = "null" if exclude is not None: ...
[ "\n Sets `scope`, the \"start point\" for the audit.\n\n Args:\n\n include: A list of css selectors specifying the elements that\n contain the portion of the page that should be audited.\n Defaults to auditing the entire document.\n exclude: This arg...
Please provide a description of the function:def _check_rules(browser, rules_js, config): if config.rules_to_run is None: msg = 'No accessibility rules were specified to check.' log.warning(msg) return None # This line will only be included in the script if ...
[ "\n Check the page for violations of the configured rules. By default,\n all rules in the ruleset will be checked.\n\n Args:\n browser: a browser instance.\n rules_js: the ruleset JavaScript as a string.\n config: an AxsAuditConfig instance.\n\n Returns:\...
Please provide a description of the function:def get_errors(audit_results): errors = [] if audit_results: if audit_results.errors: errors.extend(audit_results.errors) return errors
[ "\n Args:\n\n audit_results: results of `AxsAudit.do_audit()`.\n\n Returns: a list of errors.\n " ]
Please provide a description of the function:def report_errors(audit, url): errors = AxsAudit.get_errors(audit) if errors: msg = u"URL '{}' has {} errors:\n{}".format( url, len(errors), ', '.join(errors) ) raise...
[ "\n Args:\n\n audit: results of `AxsAudit.do_audit()`.\n url: the url of the page being audited.\n\n Raises: `AccessibilityError`\n " ]
Please provide a description of the function:def fulfill(self): is_fulfilled, result = self._check_fulfilled() if is_fulfilled: return result else: raise BrokenPromise(self)
[ "\n Evaluate the promise and return the result.\n\n Returns:\n The result of the `Promise` (second return value from the `check_func`)\n\n Raises:\n BrokenPromise: the `Promise` was not satisfied within the time or attempt limits.\n " ]
Please provide a description of the function:def _check_fulfilled(self): is_fulfilled = False result = None start_time = time.time() # Check whether the promise has been fulfilled until we run out of time or attempts while self._has_time_left(start_time) and self._has_m...
[ "\n Return tuple `(is_fulfilled, result)` where\n `is_fulfilled` is a boolean indicating whether the promise has been fulfilled\n and `result` is the value to pass to the `with` block.\n " ]
Please provide a description of the function:def search(self): self.q(css='button.btn').click() GitHubSearchResultsPage(self.browser).wait_for_page()
[ "\n Click on the Search button and wait for the\n results page to be displayed\n " ]
Please provide a description of the function:def set_rules(self, rules): options = {} if rules: if rules.get("ignore"): options["rules"] = {} for rule in rules.get("ignore"): options["rules"][rule] = {"enabled": False} ...
[ "\n Set rules to ignore XOR limit to when checking for accessibility\n errors on the page.\n\n Args:\n\n rules: a dictionary one of the following formats.\n If you want to run all of the rules except for some::\n\n {\"ignore\": []}\n\n ...
Please provide a description of the function:def set_scope(self, include=None, exclude=None): context = {} if exclude: context["exclude"] = [[selector] for selector in exclude] if include: context["include"] = [[selector] for selector in include] self....
[ "\n Sets `scope` (refered to as `context` in ruleset documentation), which\n defines the elements on a page to include or exclude in the audit. If\n neither `include` nor `exclude` are passed, the entire document will\n be included.\n\n Args:\n\n include (optional): a l...
Please provide a description of the function:def customize_ruleset(self, custom_ruleset_file=None): custom_file = custom_ruleset_file or os.environ.get( "BOKCHOY_A11Y_CUSTOM_RULES_FILE" ) if not custom_file: return with open(custom_file, "r") as additio...
[ "\n Updates the ruleset to include a set of custom rules. These rules will\n be _added_ to the existing ruleset or replace the existing rule with\n the same ID.\n\n Args:\n\n custom_ruleset_file (optional): The filepath to the custom rules.\n Defaults to `None`....
Please provide a description of the function:def _check_rules(browser, rules_js, config): audit_run_script = dedent(u).format( rules_js=rules_js, custom_rules=config.custom_rules, context=config.context, options=config.rules ) audit_resul...
[ "\n Run an accessibility audit on the page using the axe-core ruleset.\n\n Args:\n browser: a browser instance.\n rules_js: the ruleset JavaScript as a string.\n config: an AxsAuditConfig instance.\n\n Returns:\n A list of violations.\n\n Relat...
Please provide a description of the function:def get_errors(audit_results): errors = {"errors": [], "total": 0} if audit_results: errors["errors"].extend(audit_results) for i in audit_results: for _node in i["nodes"]: errors["total"] +...
[ "\n Args:\n\n audit_results: results of `AxeCoreAudit.do_audit()`.\n\n Returns:\n\n A dictionary with keys \"errors\" and \"total\".\n " ]
Please provide a description of the function:def format_errors(errors): def _get_message(node): messages = set() try: messages.update([node['message']]) except KeyError: pass for check_group in ['any', 'all'...
[ "\n Args:\n\n errors: results of `AxeCoreAudit.get_errors()`.\n\n Returns: The errors as a formatted string.\n ", "\n Get the message to display in the error output.\n " ]
Please provide a description of the function:def report_errors(audit, url): errors = AxeCoreAudit.get_errors(audit) if errors["total"] > 0: msg = u"URL '{}' has {} errors:\n\n{}".format( url, errors["total"], AxeCoreAudit.format_errors...
[ "\n Args:\n\n audit: results of `AxeCoreAudit.do_audit()`.\n url: the url of the page being audited.\n\n Raises: `AccessibilityError`\n " ]
Please provide a description of the function:def save_source(driver, name): source = driver.page_source file_name = os.path.join(os.environ.get('SAVED_SOURCE_DIR'), '{name}.html'.format(name=name)) try: with open(file_name, 'wb') as output_file: output_...
[ "\n Save the rendered HTML of the browser.\n\n The location of the source can be configured\n by the environment variable `SAVED_SOURCE_DIR`. If not set,\n this defaults to the current working directory.\n\n Args:\n driver (selenium.webdriver): The Selenium-controlled browser.\n name (...
Please provide a description of the function:def save_screenshot(driver, name): if hasattr(driver, 'save_screenshot'): screenshot_dir = os.environ.get('SCREENSHOT_DIR') if not screenshot_dir: LOGGER.warning('The SCREENSHOT_DIR environment variable was not set; not saving a screensho...
[ "\n Save a screenshot of the browser.\n\n The location of the screenshot can be configured\n by the environment variable `SCREENSHOT_DIR`. If not set,\n this defaults to the current working directory.\n\n Args:\n driver (selenium.webdriver): The Selenium-controlled browser.\n name (str...
Please provide a description of the function:def save_driver_logs(driver, prefix): browser_name = os.environ.get('SELENIUM_BROWSER', 'firefox') log_dir = os.environ.get('SELENIUM_DRIVER_LOG_DIR') if not log_dir: LOGGER.warning('The SELENIUM_DRIVER_LOG_DIR environment variable was not set; not s...
[ "\n Save the selenium driver logs.\n\n The location of the driver log files can be configured\n by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set,\n this defaults to the current working directory.\n\n Args:\n driver (selenium.webdriver): The Selenium-controlled browser.\n ...
Please provide a description of the function:def browser(tags=None, proxy=None, other_caps=None): browser_name = os.environ.get('SELENIUM_BROWSER', 'firefox') def browser_check_func(): # See https://openedx.atlassian.net/browse/TE-701 try: # Get the class and kwargs r...
[ "\n Interpret environment variables to configure Selenium.\n Performs validation, logging, and sensible defaults.\n\n There are three cases:\n\n 1. Local browsers: If the proper environment variables are not all set for the second case,\n then we use a local browser.\n\n * The environment ...
Please provide a description of the function:def _firefox_profile(): profile_dir = os.environ.get(FIREFOX_PROFILE_ENV_VAR) if profile_dir: LOGGER.info(u"Using firefox profile: %s", profile_dir) try: firefox_profile = webdriver.FirefoxProfile(profile_dir) except OSError ...
[ "Configure the Firefox profile, respecting FIREFOX_PROFILE_PATH if set" ]
Please provide a description of the function:def _local_browser_class(browser_name): # Log name of local browser LOGGER.info(u"Using local browser: %s [Default is firefox]", browser_name) # Get class of local browser based on name browser_class = BROWSERS.get(browser_name) headless = os.envir...
[ "\n Returns class, kwargs, and args needed to instantiate the local browser.\n " ]
Please provide a description of the function:def _remote_browser_class(env_vars, tags=None): if tags is None: tags = [] # Interpret the environment variables, raising an exception if they're # invalid envs = _required_envs(env_vars) envs.update(_optional_envs()) # Turn the environ...
[ "\n Returns class, kwargs, and args needed to instantiate the remote browser.\n " ]
Please provide a description of the function:def _proxy_kwargs(browser_name, proxy, browser_kwargs={}): # pylint: disable=dangerous-default-value proxy_dict = { "httpProxy": proxy.proxy, "proxyType": 'manual', } if browser_name == 'firefox' and 'desired_capabilities' not in browser_k...
[ "\n Determines the kwargs needed to set up a proxy based on the\n browser type.\n\n Returns: a dictionary of arguments needed to pass when\n instantiating the WebDriver instance.\n " ]
Please provide a description of the function:def _required_envs(env_vars): envs = { key: os.environ.get(key) for key in env_vars } # Check for missing keys missing = [key for key, val in list(envs.items()) if val is None] if missing: msg = ( u"These environm...
[ "\n Parse environment variables for required values,\n raising a `BrowserConfig` error if they are not found.\n\n Returns a `dict` of environment variables.\n " ]
Please provide a description of the function:def _optional_envs(): envs = { key: os.environ.get(key) for key in OPTIONAL_ENV_VARS if key in os.environ } # If we're using Jenkins, check that we have all the required info if 'JOB_NAME' in envs and 'BUILD_NUMBER' not in envs: ...
[ "\n Parse environment variables for optional values,\n raising a `BrowserConfig` error if they are insufficiently specified.\n\n Returns a `dict` of environment variables.\n " ]
Please provide a description of the function:def _capabilities_dict(envs, tags): capabilities = { 'browserName': envs['SELENIUM_BROWSER'], 'acceptInsecureCerts': bool(envs.get('SELENIUM_INSECURE_CERTS', False)), 'video-upload-on-pass': False, 'sauce-advisor': False, 'cap...
[ "\n Convert the dictionary of environment variables to\n a dictionary of desired capabilities to send to the\n Remote WebDriver.\n\n `tags` is a list of string tags to apply to the SauceLabs job.\n " ]
Please provide a description of the function:def replace(self, **kwargs): clone = copy(self) clone.transforms = list(clone.transforms) for key, value in kwargs.items(): if not hasattr(clone, key): raise TypeError(u'replace() got an unexpected keyword argumen...
[ "\n Return a copy of this `Query`, but with attributes specified\n as keyword arguments replaced by the keyword values.\n\n Keyword Args:\n Attributes/values to replace in the copy.\n\n Returns:\n A copy of the query that has its attributes updated with the specifi...
Please provide a description of the function:def transform(self, transform, desc=None): if desc is None: desc = u'transform({})'.format(getattr(transform, '__name__', '')) return self.replace( transforms=self.transforms + [transform], desc_stack=self.desc_st...
[ "\n Create a copy of this query, transformed by `transform`.\n\n Args:\n transform (callable): Callable that takes an iterable of values and\n returns an iterable of transformed values.\n\n Keyword Args:\n desc (str): A description of the transform, to use i...
Please provide a description of the function:def map(self, map_fn, desc=None): if desc is None: desc = getattr(map_fn, '__name__', '') desc = u'map({})'.format(desc) return self.transform(lambda xs: (map_fn(x) for x in xs), desc=desc)
[ "\n Return a copy of this query, with the values mapped through `map_fn`.\n\n Args:\n map_fn (callable): A callable that takes a single argument and returns a new value.\n\n Keyword Args:\n desc (str): A description of the mapping transform, for use in log message.\n ...
Please provide a description of the function:def filter(self, filter_fn=None, desc=None, **kwargs): if filter_fn is not None and kwargs: raise TypeError('Must supply either a filter_fn or attribute filter parameters to filter(), but not both.') if filter_fn is None and not kwargs: ...
[ "\n Return a copy of this query, with some values removed.\n\n Example usages:\n\n .. code:: python\n\n # Returns a query that matches even numbers\n q.filter(filter_fn=lambda x: x % 2)\n\n # Returns a query that matches elements with el.description == \"foo\"\n...
Please provide a description of the function:def _execute(self): data = self.seed_fn() for transform in self.transforms: data = transform(data) return list(data)
[ "\n Run the query, generating data from the `seed_fn` and performing transforms on the results.\n " ]
Please provide a description of the function:def execute(self, try_limit=5, try_interval=0.5, timeout=30): return Promise( no_error(self._execute), u"Executing {!r}".format(self), try_limit=try_limit, try_interval=try_interval, timeout=timeout...
[ "\n Execute this query, retrying based on the supplied parameters.\n\n Keyword Args:\n try_limit (int): The number of times to retry the query.\n try_interval (float): The number of seconds to wait between each try (float).\n timeout (float): The maximum number of seco...
Please provide a description of the function:def first(self): def _transform(xs): # pylint: disable=missing-docstring, invalid-name try: return [six.next(iter(xs))] except StopIteration: return [] return self.transform(_transform, 'first...
[ "\n Return a Query that selects only the first element of this Query.\n If no elements are available, returns a query with no results.\n\n Example usage:\n\n .. code:: python\n\n >> q = Query(lambda: list(range(5)))\n >> q.first.results\n [0]\n\n R...
Please provide a description of the function:def nth(self, index): def _transform(xs): # pylint: disable=missing-docstring, invalid-name try: return [next(islice(iter(xs), index, None))] # Gracefully handle (a) running out of elements, and (b) negative indices ...
[ "\n Return a query that selects the element at `index` (starts from 0).\n If no elements are available, returns a query with no results.\n\n Example usage:\n\n .. code:: python\n\n >> q = Query(lambda: list(range(5)))\n >> q.nth(2).results\n [2]\n\n ...
Please provide a description of the function:def attrs(self, attribute_name): desc = u'attrs({!r})'.format(attribute_name) return self.map(lambda el: el.get_attribute(attribute_name), desc).results
[ "\n Retrieve HTML attribute values from the elements matched by the query.\n\n Example usage:\n\n .. code:: python\n\n # Assume that the query matches html elements:\n # <div class=\"foo\"> and <div class=\"bar\">\n >> q.attrs('class')\n ['foo', 'bar'...
Please provide a description of the function:def selected(self): query_results = self.map(lambda el: el.is_selected(), 'selected').results if query_results: return all(query_results) return False
[ "\n Check whether all the matched elements are selected.\n\n Returns:\n bool\n " ]
Please provide a description of the function:def visible(self): query_results = self.map(lambda el: el.is_displayed(), 'visible').results if query_results: return all(query_results) return False
[ "\n Check whether all matched elements are visible.\n\n Returns:\n bool\n " ]
Please provide a description of the function:def is_focused(self): active_el = self.browser.execute_script("return document.activeElement") query_results = self.map(lambda el: el == active_el, 'focused').results if query_results: return any(query_results) return Fal...
[ "\n Checks that *at least one* matched element is focused. More\n specifically, it checks whether the element is document.activeElement.\n If no matching element is focused, this returns `False`.\n\n Returns:\n bool\n " ]
Please provide a description of the function:def fill(self, text): def _fill(elem): # pylint: disable=missing-docstring elem.clear() elem.send_keys(text) self.map(_fill, u'fill({!r})'.format(text)).execute()
[ "\n Set the text value of each matched element to `text`.\n\n Example usage:\n\n .. code:: python\n\n # Set the text of the first element matched by the query to \"Foo\"\n q.first.fill('Foo')\n\n Args:\n text (str): The text used to fill the element (usua...
Please provide a description of the function:def url_converter(self, *args, **kwargs): upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs) def converter(matchobj): try: upstream_converter(matchobj) except Va...
[ "\n Return the custom URL converter for the given file name.\n " ]
Please provide a description of the function:def prepare_headers(table, bound_columns): if table.request is None: return for column in bound_columns: if column.sortable: params = table.request.GET.copy() param_path = _with_path_prefix(table, 'order') ord...
[ "\n :type bound_columns: list of BoundColumn\n " ]
Please provide a description of the function:def order_by_on_list(objects, order_field, is_desc=False): if callable(order_field): objects.sort(key=order_field, reverse=is_desc) return def order_key(x): v = getattr_path(x, order_field) if v is None: return MIN ...
[ "\n Utility function to sort objects django-style even for non-query set collections\n\n :param objects: list of objects to sort\n :param order_field: field name, follows django conventions, so \"foo__bar\" means `foo.bar`, can be a callable.\n :param is_desc: reverse the sorting\n :return:\n " ]
Please provide a description of the function:def default_cell_formatter(table, column, row, value, **_): formatter = _cell_formatters.get(type(value)) if formatter: value = formatter(table=table, column=column, row=row, value=value) if value is None: return '' return conditional_e...
[ "\n :type column: tri.table.Column\n " ]
Please provide a description of the function:def django_pre_2_0_table_context( request, table, links=None, paginate_by=None, page=None, extra_context=None, paginator=None, show_hits=False, hit_label='Items'): if extra_context is None: # p...
[ "\n :type table: Table\n " ]
Please provide a description of the function:def table_context(request, table, links=None, paginate_by=None, page=None, extra_context=None, paginator=None, show_hits=False, hit...
[ "\n :type table: Table\n " ]
Please provide a description of the function:def render_table(request, table, links=None, context=None, template='tri_table/list.html', blank_on_empty=False, paginate_by=40, # pragma: no mutate page=N...
[ "\n Render a table. This automatically handles pagination, sorting, filtering and bulk operations.\n\n :param request: the request object. This is set on the table object so that it is available for lambda expressions.\n :param table: an instance of Table\n :param links: a list of instances of Link\n ...
Please provide a description of the function:def render_table_to_response(*args, **kwargs): response = render_table(*args, **kwargs) if isinstance(response, HttpResponse): # pragma: no cover return response return HttpResponse(response)
[ "\n Shortcut for `HttpResponse(render_table(*args, **kwargs))`\n " ]
Please provide a description of the function:def generate_duid(mac): valid = mac and isinstance(mac, six.string_types) if not valid: raise ValueError("Invalid argument was passed") return "00:" + mac[9:] + ":" + mac
[ "DUID is consisted of 10 hex numbers.\n\n 0x00 + mac with last 3 hex + mac with 6 hex\n " ]
Please provide a description of the function:def try_value_to_bool(value, strict_mode=True): if strict_mode: true_list = ('True',) false_list = ('False',) val = value else: true_list = ('true', 'on', 'yes') false_list = ('false', 'off', 'no') val = str(value)...
[ "Tries to convert value into boolean.\n\n strict_mode is True:\n - Only string representation of str(True) and str(False)\n are converted into booleans;\n - Otherwise unchanged incoming value is returned;\n\n strict_mode is False:\n - Anything that looks like True or False is converted into bool...
Please provide a description of the function:def create_network(self, net_view_name, cidr, nameservers=None, members=None, gateway_ip=None, dhcp_trel_ip=None, network_extattrs=None): ipv4 = ib_utils.determine_ip_version(cidr) == 4 options = [] ...
[ "Create NIOS Network and prepare DHCP options.\n\n Some DHCP options are valid for IPv4 only, so just skip processing\n them for IPv6 case.\n\n :param net_view_name: network view name\n :param cidr: network to allocate, example '172.23.23.0/24'\n :param nameservers: list of name s...
Please provide a description of the function:def create_ip_range(self, network_view, start_ip, end_ip, network, disable, range_extattrs): return obj.IPRange.create(self.connector, network_view=network_view, star...
[ "Creates IPRange or fails if already exists." ]
Please provide a description of the function:def network_exists(self, network_view, cidr): LOG.warning( "DEPRECATION WARNING! Using network_exists() is deprecated " "and to be removed in next releases. " "Use get_network() or objects.Network.search instead") ...
[ "Deprecated, use get_network() instead." ]
Please provide a description of the function:def delete_objects_associated_with_a_record(self, name, view, delete_list): search_objects = {} if 'record:cname' in delete_list: search_objects['record:cname'] = 'canonical' if 'record:txt' in delete_list: search_obje...
[ "Deletes records associated with record:a or record:aaaa." ]
Please provide a description of the function:def _parse_options(self, options): attributes = ('host', 'wapi_version', 'username', 'password', 'ssl_verify', 'http_request_timeout', 'max_retries', 'http_pool_connections', 'http_pool_maxsize', ...
[ "Copy needed options to self" ]
Please provide a description of the function:def _parse_reply(request): try: return jsonutils.loads(request.content) except ValueError: raise ib_ex.InfobloxConnectionError(reason=request.content)
[ "Tries to parse reply from NIOS.\n\n Raises exception with content if reply is not in json format\n " ]
Please provide a description of the function:def get_object(self, obj_type, payload=None, return_fields=None, extattrs=None, force_proxy=False, max_results=None, paging=False): self._validate_obj_type_or_die(obj_type, obj_type_expected=False) # max_results...
[ "Retrieve a list of Infoblox objects of type 'obj_type'\n\n Some get requests like 'ipv4address' should be always\n proxied to GM on Hellfire\n If request is cloud and proxy is not forced yet,\n then plan to do 2 request:\n - the first one is not proxied to GM\n - the secon...
Please provide a description of the function:def create_object(self, obj_type, payload, return_fields=None): self._validate_obj_type_or_die(obj_type) query_params = self._build_query_params(return_fields=return_fields) url = self._construct_url(obj_type, query_params) opts = s...
[ "Create an Infoblox object of type 'obj_type'\n\n Args:\n obj_type (str): Infoblox object type,\n e.g. 'network', 'range', etc.\n payload (dict): Payload with data to send\n return_fields (list): List of fields to be returned\n ...
Please provide a description of the function:def update_object(self, ref, payload, return_fields=None): query_params = self._build_query_params(return_fields=return_fields) opts = self._get_request_options(data=payload) url = self._construct_url(ref, query_params) self._log_req...
[ "Update an Infoblox object\n\n Args:\n ref (str): Infoblox object reference\n payload (dict): Payload with data to send\n Returns:\n The object reference of the updated object\n Raises:\n InfobloxException\n " ]
Please provide a description of the function:def delete_object(self, ref, delete_arguments=None): opts = self._get_request_options() if not isinstance(delete_arguments, dict): delete_arguments = {} url = self._construct_url(ref, query_params=delete_arguments) self._l...
[ "Remove an Infoblox object\n\n Args:\n ref (str): Object reference\n delete_arguments (dict): Extra delete arguments\n Returns:\n The object reference of the removed object\n Raises:\n InfobloxException\n " ]
Please provide a description of the function:def _remap_fields(cls, kwargs): mapped = {} for key in kwargs: if key in cls._remap: mapped[cls._remap[key]] = kwargs[key] else: mapped[key] = kwargs[key] return mapped
[ "Map fields from kwargs into dict acceptable by NIOS" ]
Please provide a description of the function:def from_dict(cls, eas_from_nios): if not eas_from_nios: return return cls({name: cls._process_value(ib_utils.try_value_to_bool, eas_from_nios[name]['value']) for name in ea...
[ "Converts extensible attributes from the NIOS reply." ]
Please provide a description of the function:def to_dict(self): return {name: {'value': self._process_value(str, value)} for name, value in self._ea_dict.items() if not (value is None or value == "" or value == [])}
[ "Converts extensible attributes into the format suitable for NIOS." ]
Please provide a description of the function:def _process_value(func, value): if isinstance(value, (list, tuple)): return [func(item) for item in value] return func(value)
[ "Applies processing method for value or each element in it.\n\n :param func: method to be called with value\n :param value: value to process\n :return: if 'value' is list/tupe, returns iterable with func results,\n else func result is returned\n " ]
Please provide a description of the function:def from_dict(cls, connector, ip_dict): mapping = cls._global_field_processing.copy() mapping.update(cls._custom_field_processing) # Process fields that require building themselves as objects for field in mapping: if field...
[ "Build dict fields as SubObjects if needed.\n\n Checks if lambda for building object from dict exists.\n _global_field_processing and _custom_field_processing rules\n are checked.\n " ]
Please provide a description of the function:def field_to_dict(self, field): value = getattr(self, field) if isinstance(value, (list, tuple)): return [self.value_to_dict(val) for val in value] return self.value_to_dict(value)
[ "Read field value and converts to dict if possible" ]
Please provide a description of the function:def to_dict(self, search_fields=None): fields = self._fields if search_fields == 'update': fields = self._search_for_update_fields elif search_fields == 'all': fields = self._all_searchable_fields elif search_f...
[ "Builds dict without None object fields" ]
Please provide a description of the function:def _ip_setter(self, ipaddr_name, ipaddrs_name, ips): if isinstance(ips, six.string_types): setattr(self, ipaddr_name, ips) elif isinstance(ips, (list, tuple)) and isinstance(ips[0], IP): setattr(self, ipaddr_name, ips[0].ip) ...
[ "Setter for ip fields\n\n Accept as input string or list of IP instances.\n String case:\n only ipvXaddr is going to be filled, that is enough to perform\n host record search using ip\n List of IP instances case:\n ipvXaddrs is going to be filled with ips conten...
Please provide a description of the function:def mac(self, mac): self._mac = mac if mac: self.duid = ib_utils.generate_duid(mac) elif not hasattr(self, 'duid'): self.duid = None
[ "Set mac and duid fields\n\n To have common interface with FixedAddress accept mac address\n and set duid as a side effect.\n 'mac' was added to _shadow_fields to prevent sending it out over wapi.\n " ]
Please provide a description of the function:def render_property(property): # This ain't the prettiest thing, but it should get the job done. # I don't think we have anything more elegant available at bosh-manifest-generation time. # See https://docs.pivotal.io/partners/product-template-reference.html for list. i...
[ "Render a property for bosh manifest, according to its type." ]
Please provide a description of the function:def match(obj, matchers=TYPES): buf = get_bytes(obj) for matcher in matchers: if matcher.match(buf): return matcher return None
[ "\n Matches the given input againts the available\n file type matchers.\n\n Args:\n obj: path to file, bytes or bytearray.\n\n Returns:\n Type instance if type matches. Otherwise None.\n\n Raises:\n TypeError: if obj is not a supported type.\n " ]
Please provide a description of the function:def signature(array): length = len(array) index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length return array[:index]
[ "\n Returns the first 262 bytes of the given bytearray\n as part of the file header signature.\n\n Args:\n array: bytearray to extract the header signature.\n\n Returns:\n First 262 bytes of the file content as bytearray type.\n " ]
Please provide a description of the function:def get_bytes(obj): try: obj = obj.read(_NUM_SIGNATURE_BYTES) except AttributeError: # duck-typing as readable failed - we'll try the other options pass kind = type(obj) if kind is bytearray: return signature(obj) i...
[ "\n Infers the input type and reads the first 262 bytes,\n returning a sliced bytearray.\n\n Args:\n obj: path to readable, file, bytes or bytearray.\n\n Returns:\n First 262 bytes of the file content as bytearray type.\n\n Raises:\n TypeError: if obj is not a supported type.\n ...
Please provide a description of the function:def get_type(mime=None, ext=None): for kind in types: if kind.extension is ext or kind.mime is mime: return kind return None
[ "\n Returns the file type instance searching by\n MIME type or file extension.\n\n Args:\n ext: file extension string. E.g: jpg, png, mp4, mp3\n mime: MIME string. E.g: image/jpeg, video/mpeg\n\n Returns:\n The matched file type instance. Otherwise None.\n " ]
Please provide a description of the function:def open(self, encoding=None): try: if IS_GZIPPED_FILE.search(self._filename): _file = gzip.open(self._filename, 'rb') else: if encoding: _file = io.open(self._filename, 'r', encodin...
[ "Opens the file with the appropriate call" ]
Please provide a description of the function:def close(self): if not self.active: return self.active = False if self._file: self._file.close() self._sincedb_update_position(force_update=True) if self._current_event: event = '\n'....
[ "Closes all currently open file pointers" ]
Please provide a description of the function:def _buffer_extract(self, data): # Extract token-delimited entities from the input string with the split command. # There's a bit of craftiness here with the -1 parameter. Normally split would # behave no differently regardless of if the tok...
[ "\n Extract takes an arbitrary string of input data and returns an array of\n tokenized entities, provided there were any available to extract. This\n makes for easy processing of datagrams using a pattern like:\n\n tokenizer.extract(data).map { |entity| Decode(entity) }.each do ..." ...
Please provide a description of the function:def _ensure_file_is_good(self, current_time): if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval: return self._last_file_mapping_update = time.time() try: st = ...
[ "Every N seconds, ensures that the file we are tailing is the file we expect to be tailing" ]
Please provide a description of the function:def _run_pass(self): while True: try: data = self._file.read(4096) except IOError, e: if e.errno == errno.ESTALE: self.active = False return False li...
[ "Read lines from a file and performs a callback against them" ]
Please provide a description of the function:def _sincedb_init(self): if not self._sincedb_path: return if not os.path.exists(self._sincedb_path): self._log_debug('initializing sincedb sqlite schema') conn = sqlite3.connect(self._sincedb_path, isolation_leve...
[ "Initializes the sincedb schema in an sqlite db", "\n create table sincedb (\n fid text primary key,\n filename text,\n position integer default 1\n );\n " ]
Please provide a description of the function:def _sincedb_update_position(self, lines=0, force_update=False): if not self._sincedb_path: return False self._line_count = self._line_count + lines old_count = self._line_count_sincedb lines = self._line_count c...
[ "Retrieves the starting position from the sincedb sql db for a given file\n Returns a boolean representing whether or not it updated the record\n " ]
Please provide a description of the function:def _sincedb_start_position(self): if not self._sincedb_path: return None self._sincedb_init() self._log_debug('retrieving start_position from sincedb') conn = sqlite3.connect(self._sincedb_path, isolation_level=None) ...
[ "Retrieves the starting position from the sincedb sql db\n for a given file\n " ]
Please provide a description of the function:def _update_file(self, seek_to_end=True): try: self.close() self._file = self.open() except IOError: pass else: if not self._file: return self.active = True ...
[ "Open the file for tailing" ]
Please provide a description of the function:def tail(self, fname, encoding, window, position=None): if window <= 0: raise ValueError('invalid window %r' % window) encodings = ENCODINGS if encoding: encodings = [encoding] + ENCODINGS for enc in encoding...
[ "Read last N lines from file fname." ]
Please provide a description of the function:def create_transport(beaver_config, logger): transport_str = beaver_config.get('transport') if '.' not in transport_str: # allow simple names like 'redis' to load a beaver built-in transport module_path = 'beaver.transports.%s_transport' % transp...
[ "Creates and returns a transport object" ]
Please provide a description of the function:def listdir(self): ls = os.listdir(self._folder) return [x for x in ls if os.path.splitext(x)[1][1:] == "log"]
[ "HACK around not having a beaver_config stanza\n TODO: Convert this to a glob" ]
Please provide a description of the function:def update_files(self): if self._update_time and int(time.time()) - self._update_time < self._discover_interval: return self._update_time = int(time.time()) possible_files = [] files = [] if len(self._beaver_conf...
[ "Ensures all files are properly loaded.\n Detects new files, file removals, file rotation, and truncation.\n On non-linux platforms, it will also manually reload the file for tailing.\n Note that this hack is necessary because EOF is cached on BSD systems.\n " ]
Please provide a description of the function:def close(self, signalnum=None, frame=None): self._running = False self._log_debug("Closing all tail objects") self._active = False for fid in self._tails: self._tails[fid].close() for n in range(0,self._number_of_...
[ "Closes all currently open Tail objects" ]
Please provide a description of the function:def eglob(path, exclude=None): fi = itertools.chain.from_iterable paths = list(fi(glob2.iglob(d) for d in expand_paths(path))) if exclude: cached_regex = cached_regices.get(exclude, None) if not cached_regex: cached_regex = cached...
[ "Like glob.glob, but supports \"/path/**/{a,b,c}.txt\" lookup" ]
Please provide a description of the function:def expand_paths(path): pr = itertools.product parts = MAGIC_BRACKETS.findall(path) if not path: return if not parts: return [path] permutations = [[(p[0], i, 1) for i in p[1].split(',')] for p in parts] return [_replace_all(pa...
[ "When given a path with brackets, expands it to return all permutations\n of the path with expanded brackets, similar to ant.\n\n >>> expand_paths('../{a,b}/{c,d}')\n ['../a/c', '../a/d', '../b/c', '../b/d']\n >>> expand_paths('../{a,b}/{a,b}.py')\n ['../a/a.py', '../a/b.py', '../b/a.p...
Please provide a description of the function:def multiline_merge(lines, current_event, re_after, re_before): events = [] for line in lines: if re_before and re_before.match(line): current_event.append(line) elif re_after and current_event and re_after.match(current_event[-1]): ...
[ " Merge multi-line events based.\n\n Some event (like Python trackback or Java stracktrace) spawn\n on multiple line. This method will merge them using two\n regular expression: regex_after and regex_before.\n\n If a line match re_after, it will be merged with next line.\n\n If a ...
Please provide a description of the function:def create_ssh_tunnel(beaver_config, logger=None): if not beaver_config.use_ssh_tunnel(): return None logger.info("Proxying transport using through local ssh tunnel") return BeaverSshTunnel(beaver_config, logger=logger)
[ "Returns a BeaverSshTunnel object if the current config requires us to" ]