sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def write_block_data(self, cmd, block): """ Writes a block of bytes to the bus using I2C format to the specified command register """ self.bus.write_i2c_block_data(self.address, cmd, block) self.log.debug( "write_block_data: Wrote [%s] to command register 0x%0...
Writes a block of bytes to the bus using I2C format to the specified command register
entailment
def read_raw_byte(self): """ Read an 8-bit byte directly from the bus """ result = self.bus.read_byte(self.address) self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result) return result
Read an 8-bit byte directly from the bus
entailment
def read_block_data(self, cmd, length): """ Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length """ results = self.bus.read_i2c_block_data(self.address, cmd, length) self.log.debug( "read_block_da...
Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length
entailment
def read_unsigned_byte(self, cmd): """ Read an unsigned byte from the specified command register """ result = self.bus.read_byte_data(self.address, cmd) self.log.debug( "read_unsigned_byte: Read 0x%02X from command register 0x%02X" % ( result, cmd ...
Read an unsigned byte from the specified command register
entailment
def read_unsigned_word(self, cmd, little_endian=True): """ Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False """ result = self.bus.read_word_data(self.address,...
Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False
entailment
def __connect_to_bus(self, bus): """ Attempt to connect to an I2C bus """ def connect(bus_num): try: self.log.debug("Attempting to connect to bus %s..." % bus_num) self.bus = smbus.SMBus(bus_num) self.log.debug("Success") ...
Attempt to connect to an I2C bus
entailment
def get_formset(self, request, obj=None, **kwargs): """ Default user to the current version owner. """ data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields['user'].initial = request.user.id return data
Default user to the current version owner.
entailment
def reload(self): """ Function reload Reload the full object to ensure sync """ realData = self.load() self.clear() self.update(realData)
Function reload Reload the full object to ensure sync
entailment
def updateAfterDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateAfterDecorator(self, *args, **kwargs): ret = function(self, *args, **kwargs) self.reload() return ret ...
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman
entailment
def updateBeforeDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateBeforeDecorator(self, *args, **kwargs): if self.forceFullSync: self.reload() return function(self, *arg...
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman
entailment
def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ return {x[self.index]: self.itemType(self.api, x['id'], self.objName, self.payloadObj, x...
Function load Get the list of all objects @return RETURN: A ForemanItem list
entailment
def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object """ if key not in self: ...
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object
entailment
def operations(): """ Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class """ def decorator(func): @wraps(func) def wrapped_func(*args, **kwargs): self = args[0] assert self.__can_use, "User oper...
Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class
entailment
def process_actions(action_ids=None): """ Process actions in the publishing schedule. Returns the number of actions processed. """ actions_taken = 0 action_list = PublishAction.objects.prefetch_related( 'content_object', ).filter( scheduled_time__lte=timezone.now(), ) ...
Process actions in the publishing schedule. Returns the number of actions processed.
entailment
def celery_enabled(): """ Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed. """ ...
Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed.
entailment
def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object """ if key not in self: ...
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object
entailment
def __collect_interfaces_return(interfaces): """Collect new style (44.1+) return values to old-style kv-list""" acc = [] for (interfaceName, interfaceData) in interfaces.items(): signalValues = interfaceData.get("signals", {}) for (signalName, signalValue) in signalValues...
Collect new style (44.1+) return values to old-style kv-list
entailment
def return_values(self): """ Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'} """ j = self.json() #TODO: FIXME: get rid of old API when its support will be removed public_api_val...
Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'}
entailment
def get_activitylog(self, after=None, severity=None, start=None, end=None): """ Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or log text """ if after: log_raw = self._router.get_instance_activitylog(org_id=self.organ...
Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or log text
entailment
def json(self): """ return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time. """ if self.fresh(): return self.__cached_json # noinspection PyAttributeOutsideInit self._...
return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time.
entailment
def get_most_recent_update_time(self): """ Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update. """ def parse_time(t): ...
Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update.
entailment
def _is_projection_updated_instance(self): """ This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool """ last = self._last_workflow_started_time if not self._router.public...
This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool
entailment
def find(self, item, description='', event_type=''): """ Find regexp in activitylog find record as if type are in description. """ # TODO: should be refactored, dumb logic if ': ' in item: splited = item.split(': ', 1) if splited[0] in self.TYPES: ...
Find regexp in activitylog find record as if type are in description.
entailment
def do_command_line(infile: typing.IO[str]) -> int: """ Currently a small stub to create an instance of Checker for the passed ``infile`` and run its test functions through linting. Args: infile Returns: int: Number of flake8 errors raised. """ lines = infile.readlines() ...
Currently a small stub to create an instance of Checker for the passed ``infile`` and run its test functions through linting. Args: infile Returns: int: Number of flake8 errors raised.
entailment
def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' if not path: path = [os.getcwd()] if "." in fullname: name = fullname.split(".")[-1] else: name = fullname ...
finds the appropriate properties (spec) of a module, and sets its loader.
entailment
def exec_module(self, module): '''import the source code, transforma it before executing it so that it is known to Python.''' global MAIN_MODULE_NAME if module.__name__ == MAIN_MODULE_NAME: module.__name__ = "__main__" MAIN_MODULE_NAME = None with open...
import the source code, transforma it before executing it so that it is known to Python.
entailment
def _izip(*iterables): """ Iterate through multiple lists or arrays of equal size """ # This izip routine is from itertools # izip('ABCD', 'xy') --> Ax By iterators = map(iter, iterables) while iterators: yield tuple(map(next, iterators))
Iterate through multiple lists or arrays of equal size
entailment
def _checkinput(zi, Mi, z=False, verbose=None): """ Check and convert any input scalar or array to numpy array """ # How many halo redshifts provided? zi = np.array(zi, ndmin=1, dtype=float) # How many halo masses provided? Mi = np.array(Mi, ndmin=1, dtype=float) # Check the input sizes for zi...
Check and convert any input scalar or array to numpy array
entailment
def getcosmo(cosmology): """ Find cosmological parameters for named cosmo in cosmology.py list """ defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(), 'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean(), 'wmap7': cg.WMAP7_ML(), 'wmap9': cg.W...
Find cosmological parameters for named cosmo in cosmology.py list
entailment
def _getcosmoheader(cosmo): """ Output the cosmology to a string for writing to file """ cosmoheader = ("# Cosmology (flat) Om:{0:.3f}, Ol:{1:.3f}, h:{2:.2f}, " "sigma8:{3:.3f}, ns:{4:.2f}".format( cosmo['omega_M_0'], cosmo['omega_lambda_0'], cosmo['h'], ...
Output the cosmology to a string for writing to file
entailment
def cduffy(z, M, vir='200crit', relaxed=True): """ NFW conc from Duffy 08 Table 1 for halo mass and redshift""" if(vir == '200crit'): if relaxed: params = [6.71, -0.091, -0.44] else: params = [5.71, -0.084, -0.47] elif(vir == 'tophat'): if relaxed: ...
NFW conc from Duffy 08 Table 1 for halo mass and redshift
entailment
def _delta_sigma(**cosmo): """ Perturb best-fit constant of proportionality Ascaling for rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c) Parameters ---------- cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, ...
Perturb best-fit constant of proportionality Ascaling for rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c) Parameters ---------- cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0':...
entailment
def getAscaling(cosmology, newcosmo=None): """ Returns the normalisation constant between Rho_-2 and Rho_mean(z_formation) for a given cosmology Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WM...
Returns the normalisation constant between Rho_-2 and Rho_mean(z_formation) for a given cosmology Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15 or dictionar...
entailment
def _int_growth(z, **cosmo): """ Returns integral of the linear growth factor from z=200 to z=z """ zmax = 200 if hasattr(z, "__len__"): for zval in z: assert(zval < zmax) else: assert(z < zmax) y, yerr = scipy.integrate.quad( lambda z: (1 + z)/(cosmo['omega_M_...
Returns integral of the linear growth factor from z=200 to z=z
entailment
def _deriv_growth(z, **cosmo): """ Returns derivative of the linear growth factor at z for a given cosmology **cosmo """ inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5) fz = (1 + z) * inv_h**3 deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\ 1.5 * c...
Returns derivative of the linear growth factor at z for a given cosmology **cosmo
entailment
def growthfactor(z, norm=True, **cosmo): """ Returns linear growth factor at a given redshift, normalised to z=0 by default, for a given cosmology Parameters ---------- z : float or numpy array The redshift at which the growth factor should be calculated norm : boolean, optional ...
Returns linear growth factor at a given redshift, normalised to z=0 by default, for a given cosmology Parameters ---------- z : float or numpy array The redshift at which the growth factor should be calculated norm : boolean, optional If true then normalise the growth factor to...
entailment
def _minimize_c(c, z=0, a_tilde=1, b_tilde=-1, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c) for 1 unknown, i.e. concentration, returned by a minimisation call """ # Fn 1 (LHS of Eqn 18) Y1 = np.log(2) ...
Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c) for 1 unknown, i.e. concentration, returned by a minimisation call
entailment
def formationz(c, z, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Rearrange eqn 18 from Correa et al (2015c) to return formation redshift for a concentration at a given redshift Parameters ---------- c : float / numpy array Concentration of halo z : float / numpy array ...
Rearrange eqn 18 from Correa et al (2015c) to return formation redshift for a concentration at a given redshift Parameters ---------- c : float / numpy array Concentration of halo z : float / numpy array Redshift of halo with concentration c Ascaling : float Cosmolog...
entailment
def calc_ab(zi, Mi, **cosmo): """ Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, ...
Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0....
entailment
def acc_rate(z, zi, Mi, **cosmo): """ Calculate accretion rate and mass history of a halo at any redshift 'z' with mass 'Mi' at a lower redshift 'z' Parameters ---------- z : float Redshift to solve acc_rate / mass history. Note zi<z zi : float Redshift Mi : float ...
Calculate accretion rate and mass history of a halo at any redshift 'z' with mass 'Mi' at a lower redshift 'z' Parameters ---------- z : float Redshift to solve acc_rate / mass history. Note zi<z zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : d...
entailment
def MAH(z, zi, Mi, **cosmo): """ Calculate mass accretion history by looping function acc_rate over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi' Parameters ---------- z : float / numpy array Redshift to output MAH over. Note zi<z always zi : float Redshift M...
Calculate mass accretion history by looping function acc_rate over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi' Parameters ---------- z : float / numpy array Redshift to output MAH over. Note zi<z always zi : float Redshift Mi : float Halo mass at redshi...
entailment
def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictiona...
Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictionary of cosmological parameters, s...
entailment
def run(cosmology, zi=0, Mi=1e12, z=False, com=True, mah=True, filename=None, verbose=None, retcosmo=None): """ Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ----...
Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, W...
entailment
def load(config_path: str): """ Load a configuration and keep it alive for the given context :param config_path: path to a configuration file """ # we bind the config to _ to keep it alive if os.path.splitext(config_path)[1] in ('.yaml', '.yml'): _ = load_yaml_configuration(config_path,...
Load a configuration and keep it alive for the given context :param config_path: path to a configuration file
entailment
def transform_source(text): '''Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample. ''' loop_keyword = 'repeat' nb = text.count(loop_keyword) if nb == 0: return text var_...
Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample.
entailment
def get_unique_variable_names(text, nb): '''returns a list of possible variables names that are not found in the original text.''' base_name = '__VAR_' var_names = [] i = 0 j = 0 while j < nb: tentative_name = base_name + str(i) if text.count(tentative_name) == 0 and tenta...
returns a list of possible variables names that are not found in the original text.
entailment
def tag(self, tag): """Get a release by tag """ url = '%s/tags/%s' % (self, tag) response = self.http.get(url, auth=self.auth) response.raise_for_status() return response.json()
Get a release by tag
entailment
def release_assets(self, release): """Assets for a given release """ release = self.as_id(release) return self.get_list(url='%s/%s/assets' % (self, release))
Assets for a given release
entailment
def upload(self, release, filename, content_type=None): """Upload a file to a release :param filename: filename to upload :param content_type: optional content type :return: json object from github """ release = self.as_id(release) name = os.path.basename(filenam...
Upload a file to a release :param filename: filename to upload :param content_type: optional content type :return: json object from github
entailment
def validate_tag(self, tag_name, prefix=None): """Validate ``tag_name`` with the latest tag from github If ``tag_name`` is a valid candidate, return the latest tag from github """ new_version = semantic_version(tag_name) current = self.latest() if current: ta...
Validate ``tag_name`` with the latest tag from github If ``tag_name`` is a valid candidate, return the latest tag from github
entailment
def full_url(self): """Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object) """ if self.link == '': return None else: return Note._expand_url(self.link, self.sub...
Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object)
entailment
def _compress_url(link): """Convert a reddit URL into the short-hand used by usernotes. Arguments: link: a link to a comment, submission, or message (str) Returns a String of the shorthand URL """ comment_re = re.compile(r'/comments/([A-Za-z\d]{2,})(?:/[^\s]+/([A-Za...
Convert a reddit URL into the short-hand used by usernotes. Arguments: link: a link to a comment, submission, or message (str) Returns a String of the shorthand URL
entailment
def _expand_url(short_link, subreddit=None): """Convert a usernote's URL short-hand into a full reddit URL. Arguments: subreddit: the subreddit the URL is for (PRAW Subreddit object or str) short_link: the compressed link from a usernote (str) Returns a String of the fu...
Convert a usernote's URL short-hand into a full reddit URL. Arguments: subreddit: the subreddit the URL is for (PRAW Subreddit object or str) short_link: the compressed link from a usernote (str) Returns a String of the full URL.
entailment
def get_json(self): """Get the JSON stored on the usernotes wiki page. Returns a dict representation of the usernotes (with the notes BLOB decoded). Raises: RuntimeError if the usernotes version is incompatible with this version of puni. """ ...
Get the JSON stored on the usernotes wiki page. Returns a dict representation of the usernotes (with the notes BLOB decoded). Raises: RuntimeError if the usernotes version is incompatible with this version of puni.
entailment
def _init_notes(self): """Set up the UserNotes page with the initial JSON schema.""" self.cached_json = { 'ver': self.schema, 'users': {}, 'constants': { 'users': [x.name for x in self.subreddit.moderator()], 'warnings': Note.warnings ...
Set up the UserNotes page with the initial JSON schema.
entailment
def set_json(self, reason='', new_page=False): """Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_...
Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_page_size
entailment
def get_notes(self, user): """Return a list of Note objects for the given user. Return an empty list if no notes are found. Arguments: user: the user to search for in the usernotes (str) """ # Try to search for all notes on a user, return an empty list if none ...
Return a list of Note objects for the given user. Return an empty list if no notes are found. Arguments: user: the user to search for in the usernotes (str)
entailment
def _expand_json(self, j): """Decompress the BLOB portion of the usernotes. Arguments: j: the JSON returned from the wiki page (dict) Returns a Dict with the 'blob' key removed and a 'users' key added """ decompressed_json = copy.copy(j) decompressed_json.po...
Decompress the BLOB portion of the usernotes. Arguments: j: the JSON returned from the wiki page (dict) Returns a Dict with the 'blob' key removed and a 'users' key added
entailment
def _compress_json(self, j): """Compress the BLOB data portion of the usernotes. Arguments: j: the JSON in Schema v5 format (dict) Returns a dict with the 'users' key removed and 'blob' key added """ compressed_json = copy.copy(j) compressed_json.pop('users'...
Compress the BLOB data portion of the usernotes. Arguments: j: the JSON in Schema v5 format (dict) Returns a dict with the 'users' key removed and 'blob' key added
entailment
def add_note(self, note): """Add a note to the usernotes wiki page. Arguments: note: the note to be added (Note) Returns the update message for the usernotes wiki Raises: ValueError when the warning type of the note can not be found in the store...
Add a note to the usernotes wiki page. Arguments: note: the note to be added (Note) Returns the update message for the usernotes wiki Raises: ValueError when the warning type of the note can not be found in the stored list of warnings.
entailment
def remove_note(self, username, index): """Remove a single usernote from the usernotes. Arguments: username: the user that for whom you're removing a note (str) index: the index of the note which is to be removed (int) Returns the update message for the usernotes wiki ...
Remove a single usernote from the usernotes. Arguments: username: the user that for whom you're removing a note (str) index: the index of the note which is to be removed (int) Returns the update message for the usernotes wiki
entailment
def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values() cl = [] for i in cl_tmp: cl.extend(i) return {x[self.index]: ItemPuppetC...
Function load Get the list of all objects @return RETURN: A ForemanItem list
entailment
def is_related_to(item, app_id, app_ver=None): """Return True if the item relates to the given app_id (and app_ver, if passed).""" versionRange = item.get('versionRange') if not versionRange: return True for vR in versionRange: if not vR.get('targetApplication'): return True...
Return True if the item relates to the given app_id (and app_ver, if passed).
entailment
def get_related_targetApplication(vR, app_id, app_ver): """Return the first matching target application in this version range. Returns None if there are no target applications or no matching ones.""" targetApplication = vR.get('targetApplication') if not targetApplication: return None for t...
Return the first matching target application in this version range. Returns None if there are no target applications or no matching ones.
entailment
def write_addons_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the addons blocklists. <emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com"> <versionRange minVersion="0" maxVersion="*" severity="3"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> ...
Generate the addons blocklists. <emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com"> <versionRange minVersion="0" maxVersion="*" severity="3"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> <versionRange minVersion="39.0a1" maxVersion="*"/> </targetApplication...
entailment
def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" ...
Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" severity="0" vulnerabilitystatus="1"> <targetApplica...
entailment
def write_gfx_items(xml_tree, records, app_id, api_ver=3): """Generate the gfxBlacklistEntry. <gfxBlacklistEntry blockID="g35"> <os>WINNT 6.1</os> <vendor>0x10de</vendor> <devices> <device>0x0a6c</device> </devices> <feature>DIRECT2D</feature> <featur...
Generate the gfxBlacklistEntry. <gfxBlacklistEntry blockID="g35"> <os>WINNT 6.1</os> <vendor>0x10de</vendor> <devices> <device>0x0a6c</device> </devices> <feature>DIRECT2D</feature> <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus> <driverVers...
entailment
def write_cert_items(xml_tree, records, api_ver=3, app_id=None, app_ver=None): """Generate the certificate blocklists. <certItem issuerName="MIGQMQswCQYD...IENB"> <serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber> </certItem> or <certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQt...
Generate the certificate blocklists. <certItem issuerName="MIGQMQswCQYD...IENB"> <serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber> </certItem> or <certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5' pubKeyHash='VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8='> ...
entailment
def label(self, name, color, update=True): """Create or update a label """ url = '%s/labels' % self data = dict(name=name, color=color) response = self.http.post( url, json=data, auth=self.auth, headers=self.headers ) if response.status_code == 201: ...
Create or update a label
entailment
def translate(source, dictionary): '''A dictionary with a one-to-one translation of keywords is used to provide the transformation. ''' toks = tokenize.generate_tokens(StringIO(source).readline) result = [] for toktype, tokvalue, _, _, _ in toks: if toktype == tokenize.NAME and tokvalue ...
A dictionary with a one-to-one translation of keywords is used to provide the transformation.
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'images': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemImages)})
Function enhance Enhance the object with new item or enhanced items
entailment
async def _run_payloads(self): """Async component of _run""" delay = 0.0 try: while self.running.is_set(): await self._start_payloads() await self._reap_payloads() await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0)...
Async component of _run
entailment
async def _start_payloads(self): """Start all queued payloads""" with self._lock: for coroutine in self._payloads: task = self.event_loop.create_task(coroutine()) self._tasks.add(task) self._payloads.clear() await asyncio.sleep(0)
Start all queued payloads
entailment
async def _reap_payloads(self): """Clean up all finished payloads""" for task in self._tasks.copy(): if task.done(): self._tasks.remove(task) if task.exception() is not None: raise task.exception() await asyncio.sleep(0)
Clean up all finished payloads
entailment
async def _cancel_payloads(self): """Cancel all remaining payloads""" for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel()
Cancel all remaining payloads
entailment
def check_password(password: str, encrypted: str) -> bool: """ Check a plaintext password against a hashed password. """ # some old passwords have {crypt} in lower case, and passlib wants it to be # in upper case. if encrypted.startswith("{crypt}"): encrypted = "{CRYPT}" + encrypted[7:] retu...
Check a plaintext password against a hashed password.
entailment
def validate(ctx, sandbox): """Check if version of repository is semantic """ m = RepoManager(ctx.obj['agile']) if not sandbox or m.can_release('sandbox'): click.echo(m.validate_version())
Check if version of repository is semantic
entailment
def reset(self, force_flush_cache: bool = False) -> None: """ Reset transaction back to original state, discarding all uncompleted transactions. """ super(LDAPwrapper, self).reset() if len(self._transactions) == 0: raise RuntimeError("reset called outside a tr...
Reset transaction back to original state, discarding all uncompleted transactions.
entailment
def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]: """ Object state is cached. When an update is required the update will be simulated on this cache, so that rollback information can be correct. This function retrieves the cached data. """ # no cached item, retrie...
Object state is cached. When an update is required the update will be simulated on this cache, so that rollback information can be correct. This function retrieves the cached data.
entailment
def is_dirty(self) -> bool: """ Are there uncommitted changes? """ if len(self._transactions) == 0: raise RuntimeError("is_dirty called outside a transaction.") if len(self._transactions[-1]) > 0: return True return False
Are there uncommitted changes?
entailment
def leave_transaction_management(self) -> None: """ End a transaction. Must not be dirty when doing so. ie. commit() or rollback() must be called if changes made. If dirty, changes will be discarded. """ if len(self._transactions) == 0: raise RuntimeError("lea...
End a transaction. Must not be dirty when doing so. ie. commit() or rollback() must be called if changes made. If dirty, changes will be discarded.
entailment
def commit(self) -> None: """ Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management. """ if len(self._transactions) == 0: raise RuntimeError("commit called outside transaction") # If we have nes...
Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management.
entailment
def rollback(self) -> None: """ Roll back to previous database state. However stay inside transaction management. """ if len(self._transactions) == 0: raise RuntimeError("rollback called outside transaction") _debug("rollback:", self._transactions[-1]) ...
Roll back to previous database state. However stay inside transaction management.
entailment
def _process(self, on_commit: UpdateCallable, on_rollback: UpdateCallable) -> Any: """ Process action. oncommit is a callback to execute action, onrollback is a callback to execute if the oncommit() has been called and a rollback is required """ _debug("---> commiting", ...
Process action. oncommit is a callback to execute action, onrollback is a callback to execute if the oncommit() has been called and a rollback is required
entailment
def add(self, dn: str, mod_list: dict) -> None: """ Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("add", self, dn, mod_list) # if rollback of add required, delete it def on_commit(obj): ob...
Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
entailment
def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify", self, dn, mod_list) # need to work out how to reverse changes in mod_list; result in revlist ...
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
entailment
def modify_no_rollback(self, dn: str, mod_list: dict): """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify_no_rollback", self, dn, mod_list) result = self._do_with_retry(lambda obj: obj.modify_s(dn, m...
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
entailment
def delete(self, dn: str) -> None: """ delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ _debug("delete", self) # get copy of cache result = self._cache_get_for_dn(dn) # remove special values that ca...
delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
entailment
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ _debug("rename", self, dn, new_rdn, new_base_dn) # split up the parameters ...
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
entailment
def fail(self) -> None: """ for testing purposes only. always fail in commit """ _debug("fail") # on commit carry out action; on rollback reverse rename def on_commit(_obj): raise_testfailure("commit") def on_rollback(_obj): raise_testfailure("rollback"...
for testing purposes only. always fail in commit
entailment
def __experimental_range(start, stop, var, cond, loc={}): '''Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0) ''' locals().update(loc) if start < stop: for __ in ...
Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0)
entailment
def create_for(line, search_result): '''Create a new "for loop" line as a replacement for the original code. ''' try: return line.format(search_result.group("indented_for"), search_result.group("var"), search_result.group("start"), ...
Create a new "for loop" line as a replacement for the original code.
entailment
def setOverrideValue(self, attributes, hostName): """ Function __setitem__ Set a parameter of a foreman object as a dict @param key: The key to modify @param attribute: The data @return RETURN: The API result """ self['override'] = True attrType = type(at...
Function __setitem__ Set a parameter of a foreman object as a dict @param key: The key to modify @param attribute: The data @return RETURN: The API result
entailment
def get_interval_timedelta(self): """ Spits out the timedelta in days. """ now_datetime = timezone.now() current_month_days = monthrange(now_datetime.year, now_datetime.month)[1] # Two weeks if self.interval == reminders_choices.INTERVAL_2_WEEKS: interval_timedelta ...
Spits out the timedelta in days.
entailment
async def awaitable_runner(runner: BaseRunner): """Execute a runner without blocking the event loop""" runner_thread = CapturingThread(target=runner.run) runner_thread.start() delay = 0.0 while not runner_thread.join(timeout=0): await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0...
Execute a runner without blocking the event loop
entailment
def asyncio_main_run(root_runner: BaseRunner): """ Create an ``asyncio`` event loop running in the main thread and watching runners Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread. This function sets up and runs the correct loop in a portable way. In ...
Create an ``asyncio`` event loop running in the main thread and watching runners Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread. This function sets up and runs the correct loop in a portable way. In addition, it runs a single :py:class:`~.BaseRunner` until c...
entailment
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTe...
Function enhance Enhance the object with new item or enhanced items
entailment
def retry(tries=10, delay=1, backoff=2, retry_exception=None): """ Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time. Without exception success means when function returns valid object. With exception success when no exceptions """ assert tries > 0, "tries mus...
Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time. Without exception success means when function returns valid object. With exception success when no exceptions
entailment
def dump(node): """ Dump initialized object structure to yaml """ from qubell.api.private.platform import Auth, QubellPlatform from qubell.api.private.organization import Organization from qubell.api.private.application import Application from qubell.api.private.instance import Instance fro...
Dump initialized object structure to yaml
entailment
def load_env(file): """ Generate environment used for 'org.restore' method :param file: env file :return: env """ env = yaml.load(open(file)) for org in env.get('organizations', []): if not org.get('applications'): org['applications'] = [] if org.get('starter-k...
Generate environment used for 'org.restore' method :param file: env file :return: env
entailment