INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Download a capture as a PCAP file.
def download(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) ...
Get a capture s summary.
def summary(self, id, seq, intf, filter=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional...
Get a capture s decode.
def decode(self, id, seq, intf, filter=None, frame=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter:...
Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences.
def send_to_cloudshark(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID ...
Check for errors in the response and return the resulting JSON.
def get_dict_from_response(response): """Check for errors in the response and return the resulting JSON.""" if getattr(response, '_resp') and response._resp.code > 400: raise OAuthResponseError( 'Application mis-configuration in Globus', None, response ) return response....
Get user information from Globus.
def get_user_info(remote): """Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/ """ response = remote.get(GLOBUS_USER_INFO_URL) user_info = get_dict_from_response(response) response.data['username'] = response.data['prefer...
Get the Globus identity for a users given email.
def get_user_id(remote, email): """Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/ """ try: url = '{}?usernames={}'.format(GLOBUS_USER_ID_...
Retrieve remote account information used to find local user.
def account_info(remote, resp): """Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'email': '...', 'profile': { 'username': '...', ...
Perform additional setup after user have been logged in.
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response. """ info = get_user_info(remote) user_id = get_user_id(remote, info['preferred_username']) ...
Handle unlinking of remote account.
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account. :param remote: The remote application. :returns: The HTML response. """ if not current_user.is_authenticated: return current_app.login_manager.unauthorized() remote_account = RemoteAccount.get(user_...
Return the signature string of the specified function.
def get_function_signature(func): """ Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: Th...
Acquire a read lock several threads can hold this type of lock.
def acquire_reader(self): """ Acquire a read lock, several threads can hold this type of lock. """ with self.mutex: while self.rwlock < 0 or self.rwlock == self.max_reader_concurrency or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1
Acquire a write lock only one thread can hold this lock and only when no read locks are also held.
def acquire_writer(self): """ Acquire a write lock, only one thread can hold this lock and only when no read locks are also held. """ with self.mutex: while self.rwlock != 0: self._writer_wait() self.rwlock = -1
Promote an already acquired read lock to a write lock notice: this function can easily cause a deadlock!!!!!!!!!
def promote(self): """ Promote an already acquired read lock to a write lock notice: this function can easily cause a deadlock!!!!!!!!! """ with self.mutex: self.rwlock -= 1 while self.rwlock != 0: self._writer_wait() self.rwloc...
Get a list of packages.
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields...
Get a package.
def get(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema() resp = self.service.get_id(se...
Create a new package.
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated',...
Get a list of tests that will be skipped for a package.
def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis """ schema = Analy...
Bulk copy a set of packages.
def bulk_copy(self, ids): """Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list """ schema = PackageSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Bulk edit a set of packages.
def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) St...
Generate strings that are not comments or lines with only whitespace.
def clean_lines(commands): """ Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It ...
Filter xml based on an xpath expression.
def xpath(source_xml, xpath_expr, req_format='string'): """ Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return ...
Делает из obj строку true или false
def lowcase_str_boolean(obj): "Делает из obj строку `true` или `false`" if isinstance(obj, str): if obj not in ["true", "false"]: raise RuntimeError( 'Expecting "true" or "false", got {}'.format(obj)) return obj return str(bool(obj)).lower()
Проверяет и формирует аргументы для запроса
def validate_args(api_key, *, rate="informers", **kwargs): "Проверяет и формирует аргументы для запроса" rate = Rate.validate(rate) headers = {"X-Yandex-API-Key": api_key} url = "https://api.weather.yandex.ru/v1/{}".format(rate) if rate == "informers": params = ARGS_SCHEMA(kwargs) else: ...
Выполняет доступ к API.
def get(session, api_key, **kwargs): """ Выполняет доступ к API. session - модуль requests или сессия из него api_key - строка ключа доступа к API rate - тариф, может быть `informers` или `forecast` lat, lon - широта и долгота ``` import yandex_weather_api import requests as req ...
Get etcd status.
def status(self, timeout=None): """ Get etcd status. :param timeout: Request timeout in seconds. :type timeout: int :returns: The current etcd cluster status. :rtype: instance of :class:`txaioetcd.Status` """ assembler = commons.StatusRequestAssembler(se...
Set the value for the key in the key - value store.
def set(self, key, value, lease=None, return_previous=None, timeout=None): """ Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the ...
Range gets the keys in the range from the key - value store.
def get(self, key, range_end=None, count_only=None, keys_only=None, limit=None, max_create_revision=None, min_create_revision=None, min_mod_revision=None, revision=None, serializable=None, ...
Delete value ( s ) from etcd.
def delete(self, key, return_previous=None, timeout=None): """ Delete value(s) from etcd. :param key: key is the first key to delete in the range. :type key: bytes or instance of :class:`txaioetcd.KeySet` :param return_previous: If enabled, return the deleted key-value pairs ...
Watch one or more keys or key sets and invoke a callback.
def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None): """ Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction rev...
Submit a transaction.
def submit(self, txn, timeout=None): """ Submit a transaction. Processes multiple requests in a single transaction. A transaction increments the revision of the key-value store and generates events with the same revision for every completed request. It is not al...
Creates a lease which expires if the server does not receive a keep alive within a given time to live period.
def lease(self, time_to_live, lease_id=None, timeout=None): """ Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired ke...
Get a list of staged ( in - progress ) imports.
def list(self): """Get a list of staged (in-progress) imports. :return: :class:`imports.Import <imports.Import>` list """ schema = ImportSchema() resp = self.service.list(self.base) return self.service.decode(schema, resp, many=True)
Stage an import from a file upload.
def stage_import_from_file(self, fd, filename='upload.gz'): """Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object """ schema...
Stage an import from a filesystem path.
def stage_import_from_filesystem(self, filepath): """Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, ...
Stage an import from a URL to another CDRouter system.
def stage_import_from_url(self, url, token=None, username=None, password=None, insecure=False): """Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ sy...
Get a commit request for a staged import.
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestS...
Commit a staged import.
def commit(self, id, impreq): # pylint: disable=invalid-name,redefined-builtin """Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: im...
Takes a model instance and converts it into a dict.
def model_to_dict(instance, **options): "Takes a model instance and converts it into a dict." options = _defaults(options) attrs = {} if options['prehook']: if isinstance(options['prehook'], collections.Callable): instance = options['prehook'](instance) if instance is N...
Recursively attempts to find Model and QuerySet instances to convert them into their representative datastructure per their Resource ( if one exists ).
def serialize(self, obj, fields=None, exclude=None, **options): """Recursively attempts to find ``Model`` and ``QuerySet`` instances to convert them into their representative datastructure per their ``Resource`` (if one exists). """ options = _merge({}, self.options, options) ...
Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size.
def set_save_directory(base, source): """Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size. """ root = os.path.join(base, source) if not os.path.isdir(root): os.makedirs(root) world.screensho...
Change a user s password.
def change_password(self, id, new, old=None, change_token=True): # pylint: disable=invalid-name,redefined-builtin """Change a user's password. :param id: User ID as an int. :param new: New password as string. :param old: (optional) Old password as string (required if performing action a...
Change a user s token.
def change_token(self, id): # pylint: disable=invalid-name,redefined-builtin """Change a user's token. :param id: User ID as an int. :return: :class:`users.User <users.User>` object :rtype: users.User """ schema = UserSchema(exclude=('password', 'password_confirm')) ...
Bulk copy a set of users.
def bulk_copy(self, ids): """Bulk copy a set of users. :param ids: Int list of user IDs. :return: :class:`users.User <users.User>` list """ schema = UserSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Use FIFO ( First In First Out ) strategy for evicting it will find an item by earliest birthday date then remove it.
def fifo_for_evict(cache_dict, evict_number=1): """ Use FIFO(First In First Out) strategy for evicting, it will find an item by earliest birthday date then remove it. Test: >>> from common_cache import CacheItem >>> dict = {} >>> dict['a'] = CacheItem(key='a', value=0, expire=5) >>> dict['b...
Use LRU ( Least Recently Used ) strategy for evicting the item that last used of time is the earliest will be removed. The parameter cache_dict must is an OrderedDict because its implementation based on the OrderedDict and reinsert key and value when every time to get the cache this operation will make the cache of the...
def lru_for_evict(cache_dict, evict_number=1): """ Use LRU(Least Recently Used) strategy for evicting, the item that last used of time is the earliest will be removed. The parameter cache_dict must is an OrderedDict because its implementation based on the OrderedDict and reinsert key and value when ever...
Get a list of a device s attachments.
def list(self, id, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=invalid-name,redefined-builtin """Get a list of a device's attachments. :param id: Device ID as an int. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `u...
Get a list of attachments. Whereas list fetches a single page of attachments according to its limit and page arguments iter_list returns all attachments by internally making successive calls to list.
def iter_list(self, id, *args, **kwargs): """Get a list of attachments. Whereas ``list`` fetches a single page of attachments according to its ``limit`` and ``page`` arguments, ``iter_list`` returns all attachments by internally making successive calls to ``list``. :param id: D...
Get a device s attachment.
def get(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Get a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment...
Add an attachment to a device.
def create(self, id, fd, filename='attachment-name'): # pylint: disable=invalid-name,redefined-builtin """Add an attachment to a device. :param id: Device ID as an int. :param fd: File-like object to upload. :param filename: (optional) Name to use for new attachment as a string. ...
Download a device s attachment.
def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Download a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get_id(self._base(id...
Edit a device s attachment.
def edit(self, resource): # pylint: disable=invalid-name,redefined-builtin """Edit a device's attachment. :param resource: :class:`attachments.Attachment <attachments.Attachment>` object :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachm...
Delete a device s attachment.
def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. """ return self.service.edit(self._base(id), attid)
Get a device by name.
def get_by_name(self, name): # pylint: disable=invalid-name,redefined-builtin """Get a device by name. :param name: Device name as string. :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device """ rs, _ = self.list(filter=field('name').eq(name),...
Edit a device.
def edit(self, resource): """Edit a device. :param resource: :class:`devices.Device <devices.Device>` object :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device """ schema = DeviceSchema(exclude=('id', 'created', 'updated', 'result_id', 'attac...
Get information on proxy connection to a device s management interface.
def get_connection(self, id): # pylint: disable=invalid-name,redefined-builtin """Get information on proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection "...
Open proxy connection to a device s management interface.
def connect(self, id): # pylint: disable=invalid-name,redefined-builtin """Open proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection """ schema = C...
Close proxy connection to a device s management interface.
def disconnect(self, id): # pylint: disable=invalid-name,redefined-builtin """Close proxy connection to a device's management interface. :param id: Device ID as an int. """ return self.service.post(self.base+str(id)+'/disconnect/')
Power on a device using it s power on command.
def power_on(self, id): # pylint: disable=invalid-name,redefined-builtin """Power on a device using it's power on command. :param id: Device ID as an int. :return: :class:`devices.PowerCmd <devices.PowerCmd>` object :rtype: devices.PowerCmd """ schema = PowerCmdSchema() ...
Bulk copy a set of devices.
def bulk_copy(self, ids): """Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list """ schema = DeviceSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Wrap value in list if it is not one.
def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]: """Wrap value in list if it is not one.""" if value is None: return [] return value if isinstance(value, list) else [value]
Проверяет что переданный объект - один из возможных VALUES
def validate(cls, cnd): "Проверяет, что переданный объект - один из возможных `VALUES`" if cnd not in cls.VALUES: raise ValueError("Value {} cannot be used in {}".format( cnd, cls )) return cls(cnd)
Highlight string for terminal color coding.
def color(out_string, color='grn'): """ Highlight string for terminal color coding. Purpose: We use this utility function to insert a ANSI/win32 color code | and Bright style marker before a string, and reset the color and | style after the string. We then return the string with these ...
Add color ANSI codes for diff lines.
def color_diffs(string): """ Add color ANSI codes for diff lines. Purpose: Adds the ANSI/win32 color coding for terminal output to output | produced from difflib. @param string: The string to be replacing @type string: str @returns: The new string with ANSI codes injected. @rtype: ...
List linked accounts.
def index(): """List linked accounts.""" oauth = current_app.extensions['oauthlib.client'] services = [] service_map = {} i = 0 for appid, conf in six.iteritems( current_app.config['OAUTHCLIENT_REMOTE_APPS']): if not conf.get('hide', False): services.append(dict...
Ensure that JavaScript at a given URL is available to the browser.
def load_script(browser, url): """Ensure that JavaScript at a given URL is available to the browser.""" if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascr...
Find HTML elements using jQuery - style selectors.
def find_elements_by_jquery(browser, selector): """Find HTML elements using jQuery-style selectors. Ensures that jQuery is available to the browser; if it gets a WebDriverException that looks like jQuery is not available, it attempts to include it and reexecute the script.""" try: return br...
Find a single HTML element using jQuery - style selectors.
def find_element_by_jquery(step, browser, selector): """Find a single HTML element using jQuery-style selectors.""" elements = find_elements_by_jquery(browser, selector) assert_true(step, len(elements) > 0) return elements[0]
: return: True when we can access the REST API
def can_access_api(self): """ :return: True when we can access the REST API """ try: version_dict = self.get_version() except Exception, e: msg = 'An exception was raised when connecting to REST API: "%s"' raise APIException(msg % e) el...
: return: A list with all the Scan instances available in the remote API
def get_scans(self): """ :return: A list with all the Scan instances available in the remote API """ code, data = self.send_request('/scans/', method='GET') if code != 200: msg = 'Failed to retrieve scans. Unexpected code %s' raise APIException(msg % code...
Return the id of a label s for attribute
def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
Locate an input field of a given value
def find_field(browser, field, value): """Locate an input field of a given value This first looks for the value as the id of the element, then the name of the element, then a label for the element. """ return find_field_by_id(browser, field, value) + \ find_field_by_name(browser, field, va...
Find a field of any of the specified types.
def find_any_field(browser, field_types, field_name): """ Find a field of any of the specified types. """ return reduce( operator.add, (find_field(browser, field_type, field_name) for field_type in field_types) )
Locate the control input that has a label pointing to it
def find_field_by_label(browser, field, label): """Locate the control input that has a label pointing to it This will first locate the label element that has a label of the given name. It then pulls the id out of the 'for' attribute, and uses it to locate the element by its id. """ return XPa...
Returns the Element specified by @option or None
def option_in_select(browser, select_name, option): """ Returns the Element specified by @option or None Looks at the real <select> not the select2 widget, since that doesn't create the DOM until we click on it. """ select = find_field(browser, 'select', select_name) assert select try...
A decorator to invoke a function periodically until it returns a truthy value.
def wait_for(func): """ A decorator to invoke a function periodically until it returns a truthy value. """ def wrapped(*args, **kwargs): timeout = kwargs.pop('timeout', 15) start = time() result = None while time() - start < timeout: result = func(*args...
The cached list of elements.
def _elements(self): """ The cached list of elements. """ if not hasattr(self, '_elements_cached'): setattr(self, '_elements_cached', list(self._select())) return self._elements_cached
Returns a dictionary of variables and their possibly os - dependent defaults.
def get_defaults(): """ Returns a dictionary of variables and their possibly os-dependent defaults. """ DEFAULTS = {} # Determine the run-time pipe read/write buffer. if 'PC_PIPE_BUF' in os.pathconf_names: # unix x, y = os.pipe() DEFAULTS['PIPE_BUF'] = os.fpathconf(x...
Configures and starts a logger to monitor the execution of a ** PaPy ** pipeline.
def start_logger(log_to_file=False, \ log_to_stream=False, \ log_to_file_level=logging.INFO, \ log_to_stream_level=logging.INFO, \ log_filename=None, \ log_stream=None, \ log_rotate=True, \ log_size=52...
Determine the server URL.
def site_url(url): """ Determine the server URL. """ base_url = 'http://%s' % socket.gethostname() if server.port is not 80: base_url += ':%d' % server.port return urlparse.urljoin(base_url, url)
Get external id from account info.
def _get_external_id(account_info): """Get external id from account info.""" if all(k in account_info for k in ('external_id', 'external_method')): return dict(id=account_info['external_id'], method=account_info['external_method']) return None
Retrieve user object for the given request.
def oauth_get_user(client_id, account_info=None, access_token=None): """Retrieve user object for the given request. Uses either the access token or extracted account information to retrieve the user object. :param client_id: The client id. :param account_info: The dictionary with the account info....
Authenticate an oauth authorized callback.
def oauth_authenticate(client_id, user, require_existing_link=False): """Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True...
Register user if possible.
def oauth_register(form): """Register user if possible. :param form: A form instance. :returns: A :class:`invenio_accounts.models.User` instance. """ if form.validate(): data = form.to_dict() if not data.get('password'): data['password'] = '' user = register_user...
Link a user to an external id.
def oauth_link_external_id(user, external_id=None): """Link a user to an external id. :param user: A :class:`invenio_accounts.models.User` instance. :param external_id: The external id associated with the user. (Default: ``None``) :raises invenio_oauthclient.errors.AlreadyLinkedError: Raised if...
Unlink a user from an external id.
def oauth_unlink_external_id(external_id): """Unlink a user from an external id. :param external_id: The external id associated with the user. """ with db.session.begin_nested(): UserIdentity.query.filter_by(id=external_id['id'], method=external_id['method']...
Get URL to redirect to and ensure that it is local.
def get_safe_redirect_target(arg='next'): """Get URL to redirect to and ensure that it is local. :param arg: URL argument. :returns: The redirect target or ``None``. """ for target in request.args.get(arg), request.referrer: if target: redirect_uri = urisplit(target) ...
Make a registration form.
def create_registrationform(*args, **kwargs): """Make a registration form.""" class RegistrationForm(_security.confirm_register_form): password = None recaptcha = None return RegistrationForm(*args, **kwargs)
Prefill form with data.
def fill_form(form, data): """Prefill form with data. :param form: The form to fill. :param data: The data to insert in the form. :returns: A pre-filled form. """ for (key, value) in data.items(): if hasattr(form, key): if isinstance(value, dict): fill_form(g...
Return the right param to disable CSRF depending on WTF - Form version.
def _get_csrf_disabled_param(): """Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`. """ import flask_wtf from pkg_resources import parse_version supports_meta = parse_...
Find and load step definitions and them find and load features under base_path specified on constructor
def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e ...
A recursive method to return a list of * all * ** node objects ** connected from this ** toplogical node **.
def deep_nodes(self, allnodes=None): """ A recursive method to return a ``list`` of *all* **node objects** connected from this **toplogical node**. """ allnodes = (allnodes or []) for (node, node_) in ((node, node_) for (node, node_) in\ self.iterite...
comparison of ** node objects ** based on the branch attribute of their ** topological nodes **.
def cmp_branch(self, node1, node2): """ comparison of **node objects** based on the ``"branch"`` attribute of their **topological nodes**. """ # note reverse return cmp(getattr(self[node2], "branch", None), \ getattr(self[node1], "branch", Non...
Recursive depth first search. By default ( order = append ) this returns the ** node objects ** in the reverse postorder. To change this into the preorder use a collections. deque as bucket and appendleft as order. Arguments:
def dfs(self, node, bucket=None, order="append"): """ Recursive depth first search. By default ("order" = ``"append"``) this returns the **node objects** in the reverse postorder. To change this into the preorder use a ``collections.deque`` as "bucket" and ``"appendleft"`` as ...
Returns a valid postorder of the ** node objects ** of the DictGraph * if * the topology is a directed acyclic graph. This postorder is semi - random because the order of elements in a dictionary is semi - random and so are the starting nodes of the depth - first search traversal which determines the postorder conseque...
def postorder(self): """ Returns a valid postorder of the **node objects** of the ``DictGraph`` *if* the topology is a directed acyclic graph. This postorder is semi-random, because the order of elements in a dictionary is semi-random and so are the starting nodes of the depth...
Returns the maximum rank for each ** topological node ** in the DictGraph. The rank of a node is defined as the number of edges between the node and a node which has rank 0. A ** topological node ** has rank 0 if it has no incoming edges.
def node_rank(self): """ Returns the maximum rank for each **topological node** in the ``DictGraph``. The rank of a node is defined as the number of edges between the node and a node which has rank 0. A **topological node** has rank 0 if it has no incoming edges. ...
Returns the width of each node in the graph. #TODO
def node_width(self): """ Returns the width of each node in the graph. #TODO """ nodes = self.postorder() node_width = {} for node in nodes: sum_width = 0 for child in self[node].nodes(): sum_width += node_width[child] ...
Returns the width of each rank in the graph. #TODO
def rank_width(self): """ Returns the width of each rank in the graph. #TODO """ rank_width = defaultdict(int) node_rank = self.node_rank() for rank in node_rank.values(): rank_width[rank] += 1 return dict(rank_width)
Adds a ** node object ** to the DictGraph. Returns True if a new ** node object ** has been added. If the ** node object ** is already in the DictGraph returns False. Arguments: - node ( object ) Node to be added. Any hashable Python object. - xtra ( dict ) [ default: None ] The newly created topological Node. xtra dic...
def add_node(self, node, xtra=None, branch=None): """ Adds a **node object** to the ``DictGraph``. Returns ``True`` if a new **node object** has been added. If the **node object** is already in the ``DictGraph`` returns ``False``. Arguments: - node(``...
Removes a ** node object ** from the DictGraph. Returns True if a ** node object ** has been removed. If the ** node object ** is not in the DictGraph raises a KeyError. Arguments: - node ( object ) ** node object ** to be removed. Any hashable Python object.
def del_node(self, node): """ Removes a **node object** from the ``DictGraph``. Returns ``True`` if a **node object** has been removed. If the **node object** is not in the ``DictGraph`` raises a ``KeyError``. Arguments: - node(``object``) **node ...