sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def publish_metric(self, metric_name, metric_value, epoch_seconds=None): '''Record a single hit on a given metric. Args: metric_name: The name of the metric to record with Carbon. metric_value: The value to record with Carbon. epoch_seconds: Optionally specify the ti...
Record a single hit on a given metric. Args: metric_name: The name of the metric to record with Carbon. metric_value: The value to record with Carbon. epoch_seconds: Optionally specify the time for the metric hit. Returns: None
entailment
def register_repeating_metric(self, metric_name, frequency, getter): '''Record hits to a metric at a specified interval. Args: metric_name: The name of the metric to record with Carbon. frequency: The frequency with which to poll the getter and record the value with Carbon. ...
Record hits to a metric at a specified interval. Args: metric_name: The name of the metric to record with Carbon. frequency: The frequency with which to poll the getter and record the value with Carbon. getter: A function which takes no arguments and returns the value to rec...
entailment
def setup(console=False, port=None, menu=True): """Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Arguments: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to conn...
Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Arguments: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to connect with Pyblish QML, default provided by P...
entailment
def show(): """Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the user. """ parent = None current = QtWidgets.QApplication.activeWindow() while current: parent = current cur...
Try showing the most desirable GUI This function cycles through the currently registered graphical user interfaces, if any, and presents it to the user.
entailment
def _nuke_set_zero_margins(widget_object): """Remove Nuke margins when docked UI .. _More info: https://gist.github.com/maty974/4739917 """ parentApp = QtWidgets.QApplication.allWidgets() parentWidgetList = [] for parent in parentApp: for child in parent.children(): i...
Remove Nuke margins when docked UI .. _More info: https://gist.github.com/maty974/4739917
entailment
def dock(window): """ Expecting a window to parent into a Nuke panel, that is dockable. """ # Deleting existing dock # There is a bug where existing docks are kept in-memory when closed via UI if self._dock: print("Deleting existing dock...") parent = self._dock dialog = None ...
Expecting a window to parent into a Nuke panel, that is dockable.
entailment
def remove_index_from_handle(handle_with_index): ''' Returns index and handle separately, in a tuple. :handle_with_index: The handle string with an index (e.g. 500:prefix/suffix) :return: index and handle as a tuple. ''' split = handle_with_index.split(':') if len(split) == 2: ...
Returns index and handle separately, in a tuple. :handle_with_index: The handle string with an index (e.g. 500:prefix/suffix) :return: index and handle as a tuple.
entailment
def check_handle_syntax(string): ''' Checks the syntax of a handle without an index (are prefix and suffix there, are there too many slashes?). :string: The handle without index, as string prefix/suffix. :raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError` :return: True....
Checks the syntax of a handle without an index (are prefix and suffix there, are there too many slashes?). :string: The handle without index, as string prefix/suffix. :raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError` :return: True. If it's not ok, exceptions are raised.
entailment
def create_authentication_string(username, password): ''' Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string. ''' username_utf8 = username.encode('utf-8') userpw_utf8 = password.encode('utf-8') user...
Creates an authentication string from the username and password. :username: Username. :password: Password. :return: The encoded string.
entailment
def make_request_log_message(**args): ''' Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the requ...
Creates a string containing all relevant information about a request made to the Handle System, for logging purposes. :handle: The handle that the request is about. :url: The url the request is sent to. :headers: The headers sent along with the request. :verify: Boolean parameter passed to the ...
entailment
def request_xml(url, auth=None): ''' Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML ''' try: r = requests.get(url, auth=auth, verify=False) return r.text.encode('utf-8') except BaseException: logger.error("Skippi...
Returns an etree.XMLRoot object loaded from the url :param str url: URL for the resource to load as an XML
entailment
def _get_catalog_url(self, url): ''' Returns the appropriate catalog URL by replacing html with xml in some cases :param str url: URL to the catalog ''' u = urlparse.urlsplit(url) name, ext = os.path.splitext(u.path) if ext == ".html": u = urlp...
Returns the appropriate catalog URL by replacing html with xml in some cases :param str url: URL to the catalog
entailment
def _yield_leaves(self, url, tree): ''' Yields a URL corresponding to a leaf dataset for each dataset described by the catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' for leaf in tree.findall('.//{%s}dataset[@urlPat...
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree
entailment
def _compile_references(self, url, tree): ''' Returns a list of catalog reference URLs for the current catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' references = [] for ref in tree.findall('.//{%s}catalogR...
Returns a list of catalog reference URLs for the current catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree
entailment
def _run(self, url, auth): ''' Performs a multiprocess depth-first-search of the catalog references and yields a URL for each leaf dataset found :param str url: URL for the current catalog :param requests.auth.AuthBase auth: requets auth object to use ''' if url i...
Performs a multiprocess depth-first-search of the catalog references and yields a URL for each leaf dataset found :param str url: URL for the current catalog :param requests.auth.AuthBase auth: requets auth object to use
entailment
def _build_catalog(self, url, xml_content): ''' Recursive function to perform the DFS and yield the leaf datasets :param str url: URL for the current catalog :param str xml_content: XML Body returned from HTTP Request ''' try: tree = etree.XML(xml_content) ...
Recursive function to perform the DFS and yield the leaf datasets :param str url: URL for the current catalog :param str xml_content: XML Body returned from HTTP Request
entailment
def find_module(fdr, fqname, path = None): '''Find a loader for module or package `fqname`. This method will be called with the fully qualified name of the module. If the finder is installed on `sys.meta_path`, it will receive a second argument, which is `None` for a top-level module, ...
Find a loader for module or package `fqname`. This method will be called with the fully qualified name of the module. If the finder is installed on `sys.meta_path`, it will receive a second argument, which is `None` for a top-level module, or `package.__path__` for submodules or sub...
entailment
def load_module(ldr, fqname): '''Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added t...
Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added to `sys.modules`. However, the `find_...
entailment
def zthread_fork(ctx, func, *args, **kwargs): """ Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe, and exit if the pipe becomes unreadable. Returns pipe, or NULL if there was an error. """ a = ctx.socket(zmq.PAIR) a.setsoc...
Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe, and exit if the pipe becomes unreadable. Returns pipe, or NULL if there was an error.
entailment
def _remap(object, name, value, safe=True): """Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that ...
Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that the new attribute was not overwritten. ...
entailment
def init(): """Try loading each binding in turn Please note: the entire Qt module is replaced with this code: sys.modules["Qt"] = binding() This means no functions or variables can be called after this has executed. For debugging and testing, this module may be accessed through `Qt.__...
Try loading each binding in turn Please note: the entire Qt module is replaced with this code: sys.modules["Qt"] = binding() This means no functions or variables can be called after this has executed. For debugging and testing, this module may be accessed through `Qt.__shim__`.
entailment
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False): ''' Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments pa...
Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments passed to the instantiation, which will be logged on debug level. :forbidden: ...
entailment
def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.it...
convert dict value if value is bool type, False -> "false" True -> "true"
entailment
def _handler_response(self, response, data=None): """ error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: """ if response.s...
error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return:
entailment
def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base + suffix params = filter_params(params) response = self.session.get(url=url, params=params) ...
request weibo api :param suffix: str, :param params: dict, url query parameters :return:
entailment
def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, data=data)
:return:
entailment
def search_handle(self, **args): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b...
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. ...
entailment
def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are ...
Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param f...
entailment
def __set_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Pa...
Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password.
entailment
def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json ...
Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_s...
entailment
def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=F...
Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPytho...
entailment
def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
Get all non-zero bits
entailment
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
Returns a hexadecimal string
entailment
def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
Construct BitMap from hex string
entailment
def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("I...
Construct BitMap from string
entailment
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
Get version information or return default if unable to do so.
entailment
def get_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE cert...
Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string.
entailment
def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bund...
Setup filter (only called when filter is actually used).
entailment
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
Initialize filter just before it will be used.
entailment
def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.ind...
Determine which option name to use.
entailment
def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
Input filtering.
entailment
def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) ...
Wrap translation in Angular module.
entailment
def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gett...
Process individual translation file.
entailment
def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, models.USERS.c.email == username ) user = self.identity_fro...
Check the combination username/password that is valid on the database.
entailment
def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sani...
Query the Github API to retrieve the needed infos.
entailment
def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): ...
Cache the return value in the correct cache directory. Set 'method' to false for static methods.
entailment
def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename)
Download a file into the correct cache directory.
entailment
def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_di...
Path that should be used for caching. Different for all subclasses.
entailment
def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci """ db_conn = db_conn or flask.g.db_conn __TA...
Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci
entailment
def get_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.""" db_conn = db_conn or flask.g.db_conn last_rconfiguration_id = get_las...
Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.
entailment
def send(self, request: Request) -> None: """ Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command """ handle...
Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command
entailment
def publish(self, request: Request) -> None: """ Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None. """ handler_factories = self._registry.lookup(request) for factory in handler_factories: ...
Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None.
entailment
def post(self, request: Request) -> None: """ Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None ...
Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None
entailment
def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML doc...
Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML document.
entailment
def get_ns_info_from_node_name(self, name, impl_node): """ Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace informatio...
Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace information, None is return for those tuple members.
entailment
def up(self, count=1, to_name=None): """ :return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the...
:return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the number of number of ancestors return the doc...
entailment
def element(self, *args, **kwargs): """ Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. """ child_element = ...
Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`.
entailment
def attributes(self, *args, **kwargs): """ Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`. """ self._element.set_attributes(*a...
Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`.
entailment
def processing_instruction(self, target, data): """ Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`. """ self._element....
Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`.
entailment
def ns_prefix(self, prefix, ns_uri): """ Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. """ self._element.set_ns_prefix(prefix, ...
Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`.
entailment
def createCertRequest(pkey, digest="sha256"): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible ...
Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible arguments are: C - Cou...
entailment
def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the r...
Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the row to look for :param get_id: if True, return only the ID :return...
entailment
def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( ...
Retrieve the list of topics IDs a user has access to.
entailment
def verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics. """ if user.is_super_admin() or user.is_read_only_user(): return if str(topic_id) not in user_topic_ids(user): ...
Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics.
entailment
def _format_level_1(rows, root_table_name): """ Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name':...
Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, ...
entailment
def _format_level_2(rows, list_embeds, embed_many): """ From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id'...
From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', ...
entailment
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = ...
Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place.
entailment
def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: """ query = self.get_query(use_labels=use_labels) ...
:param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return:
entailment
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name...
Returns some information about the currently authenticated identity
entailment
def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has be...
Get all issues for a specific job.
entailment
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, ...
Unattach an issue from a specific job.
entailment
def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. if table.name == 'jobs': ...
Attach an issue to a specific job.
entailment
def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)]
Remove collect's static root folder from list.
entailment
def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.teams_ids and ...
Get all jobstates.
entailment
def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_headers(access_token)) if r.status_code in (...
Create the dci client in the master realm.
entailment
def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'enabled': True, 'emailVerified': True, 'credentials':...
Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io
entailment
def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) """ The dbname of the site. : s...
The name of the site. : str | `None`
entailment
def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value ...
Convert all booleans to lowercase strings
entailment
def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self...
Requests wrapper function
entailment
def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer ...
Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer Default: None *...
entailment
def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offs...
Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) ...
entailment
def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check
Returns a detailed description of a specified check.
entailment
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). ...
Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer De...
entailment
def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid'...
Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid' : <Integer> Probe identifier ...
entailment
def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listi...
Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listing (requires limit.) Typ...
entailment
def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Ce...
Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In...
entailment
def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, ...
Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message
entailment
def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports
Returns a list of PingdomEmailReport instances.
entailment
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -...
Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String [...
entailment
def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
Returns a list of PingdomSharedReport instances
entailment
def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Typ...
Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type ...
entailment
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :para...
When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is ...
entailment
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None: """ Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispat...
Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispatch to :return:
entailment
def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: """ key = request.__class__.__...
Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return:
entailment
def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type """ ...
Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type
entailment
def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessage]: """ Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_c...
Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_class: :return:
entailment
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provi...
This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), t...
entailment
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provid...
This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * providing a single argument (ref_type), th...
entailment
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.p...
Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.pickle'.
entailment
def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = ...
Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath.
entailment