_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q52600
get_msw
train
def get_msw(requestURL): """Get MSW API response.""" msw_response = requests.get(requestURL) msw_response.raise_for_status() json_d = msw_response.json() headers = msw_response.headers if ERROR_RESPONSE in json_d: code = json_d.get(ERROR_RESPONE).get('code') msg = json_d.get(ER...
python
{ "resource": "" }
q52601
MSW_Forecast.get_current
train
def get_current(self): """Get current forecast.""" now = dt.now().timestamp() url = build_url(self.api_key, self.spot_id, self.fields, self.unit, now, now) return get_msw(url)
python
{ "resource": "" }
q52602
MSW_Forecast.get_future
train
def get_future(self): """Get current and future forecasts.""" now = dt.now() four_days = now + timedelta(hours=96) now = now.timestamp() four_days = four_days.timestamp() url = build_url(self.api_key, self.spot_id, self.fields, self.unit, now, four...
python
{ "resource": "" }
q52603
MSW_Forecast.get_all
train
def get_all(self): """Get default forecasts, some in past.""" url = build_url(self.api_key, self.spot_id, self.fields, self.unit, None, None) return get_msw(url)
python
{ "resource": "" }
q52604
MSW_Forecast.get_manual
train
def get_manual(self, start, end): """Get forecasts for a manually selected time period.""" url = build_url(self.api_key, self.spot_id, self.fields, self.unit, start, end) return get_msw(url)
python
{ "resource": "" }
q52605
ForecastDataPoint.get_swell_url
train
def get_swell_url(self, swell_type): """Get swell arrow url.""" if swell_type not in SWELL_TYPES: raise ValueError('Invalid swell type: {}'.format(swell_type)) key = "swell_components_{}_direction".format(swell_type) swell_direction = self.f_d.get(key) if swell_direct...
python
{ "resource": "" }
q52606
ForecastDataPoint.get_wind_url
train
def get_wind_url(self): """Get wind arrow url.""" wind_direction = self.f_d.get('wind_direction', None) if wind_direction is not None: rounded = int(5 * round(float(wind_direction)/5)) return WIND_ARROW_URL.format(rounded)
python
{ "resource": "" }
q52607
RequestInfo._get_all_set_properties
train
def _get_all_set_properties(self): """ Collect names of set properties. Returns: set: Set containing names of all properties, which are set to \ non-None value. """ return set( property_name for property_name in worker_mapping...
python
{ "resource": "" }
q52608
RequestInfo.progress
train
def progress(self): """ Get progress. Returns: namedtuple: :class:`Progress`. """ return Progress( done=len(self._get_all_set_properties()), base=len(worker_mapping()), )
python
{ "resource": "" }
q52609
RequestInfo.is_old
train
def is_old(self): """ Is the object cached for too long, so it should be redownloaded? See :attr:`.DB_MAX_WAIT_TIME` and :attr:`.DB_CACHE_TIME` for details. Returns: bool: True if it is. """ if not self.processing_started_ts: return True ...
python
{ "resource": "" }
q52610
RequestInfo.to_dict
train
def to_dict(self): """ This method is used in with connection to REST API. It basically converts all important properties to dictionary, which may be used by frontend. Returns: dict: ``{"all_set": bool, "progress": [int(done), int(how_many)], \ "val...
python
{ "resource": "" }
q52611
securitycli
train
def securitycli(): """ Entry point for the runner defined in setup.py. """ parser = argparse.ArgumentParser(description="Runner for security test suite") parser.add_argument("-l", "--list-test-groups", action="store_true", help="List all logical test groups") parser.add_...
python
{ "resource": "" }
q52612
Location.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a location into this object. ''' self.x = int(node.getAttributeNS(RTS_EXT_NS, 'x')) self.y = int(node.getAttributeNS(RTS_EXT_NS, 'y')) self.height = int(node.getAttributeNS(RTS_EXT_NS, 'height')...
python
{ "resource": "" }
q52613
Location.parse_yaml
train
def parse_yaml(self, y): '''Parse a YAML specification of a location into this object.''' self.x = int(y['x']) self.y = int(y['y']) self.height = int(y['height']) self.width = int(y['width']) self.direction = dir.from_string(y['direction']) return self
python
{ "resource": "" }
q52614
Location.save_xml
train
def save_xml(self, doc, element): '''Save this location into an xml.dom.Element object.''' element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'x', str(self.x)) element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'y', str(self.y)) element.setAttributeNS(RTS_EXT_NS, RTS_EXT_NS_S + 'height', ...
python
{ "resource": "" }
q52615
Location.to_dict
train
def to_dict(self): '''Save this location into a dictionary.''' return {'x': self.x, 'y': self.y, 'height': self.height, 'width': self.width, 'direction': dir.to_string(self.direction)}
python
{ "resource": "" }
q52616
Component.get_configuration_set_by_id
train
def get_configuration_set_by_id(self, id): '''Finds a configuration set in the component by its ID. @param id The ID of the configuration set to search for. @return The ConfigurationSet object for the set, or None if it was not found. ''' for cs in self.configuration_se...
python
{ "resource": "" }
q52617
Component.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a component into this object. >>> c = Component() ''' self._reset() # Get the attributes self.id = node.getAttributeNS(RTS_NS, 'id') self.path_uri = node.getAttributeNS(RTS_NS, '...
python
{ "resource": "" }
q52618
Component.save_xml
train
def save_xml(self, doc, element): '''Save this component into an xml.dom.Element object.''' element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:component_ext') element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id) element.setAttributeNS(RTS_NS, RTS_NS_S + 'pathUri', self.path_ur...
python
{ "resource": "" }
q52619
Component.parse_yaml
train
def parse_yaml(self, y): '''Parse a YAML specification of a component into this object.''' self._reset() self.id = y['id'] self.path_uri = y['pathUri'] if 'activeConfigurationSet' in y: self.active_configuration_set = y['activeConfigurationSet'] else: ...
python
{ "resource": "" }
q52620
GABA._calc_auc
train
def _calc_auc(self, model, params, idx): """ Helper function to calculate the area under the curve of a model Parameters ---------- model : callable Probably either ut.lorentzian or ut.gaussian, but any function will do, as long as its first parameter is ...
python
{ "resource": "" }
q52621
GABA._outlier_rejection
train
def _outlier_rejection(self, params, model, signal, ii): """ Helper function to reject outliers DRY! """ # Z score across repetitions: z_score = (params - np.mean(params, 0))/np.std(params, 0) # Silence warnings: with warnings.catch_warnings(): ...
python
{ "resource": "" }
q52622
GABA.fit_creatine
train
def fit_creatine(self, reject_outliers=3.0, fit_lb=2.7, fit_ub=3.5): """ Fit a model to the portion of the summed spectra containing the creatine and choline signals. Parameters ---------- reject_outliers : float or bool If set to a float, this is the z score ...
python
{ "resource": "" }
q52623
GABA._xval_choose_funcs
train
def _xval_choose_funcs(self, fit_spectra, reject_outliers, fit_lb, fit_ub, fitters=[ana.fit_gaussian,ana.fit_two_gaussian], funcs = [ut.gaussian, ut.two_gaussian]): """ Helper function used to do split-half xvalidation to select among alternative...
python
{ "resource": "" }
q52624
GABA._xval_model_error
train
def _xval_model_error(self, fit_spectra, reject_outliers, fit_lb, fit_ub, fitter, func): """ Helper function for calculation of split-half cross-validation model error and signal reliability. """ set1 = fit_spectra[::2] set2 = fit_spectra[1::2]...
python
{ "resource": "" }
q52625
GABA.fit_gaba
train
def fit_gaba(self, reject_outliers=3.0, fit_lb=2.8, fit_ub=3.4, phase_correct=True, fit_func=None): """ Fit either a single Gaussian, or a two-Gaussian to the GABA 3 PPM peak. Parameters ---------- reject_outliers : float Z-score criterion fo...
python
{ "resource": "" }
q52626
GABA._rm_outlier_by_amp
train
def _rm_outlier_by_amp(self, params, model, signal, ii): """ Helper function to reject outliers based on mean amplitude """ maxamps = np.nanmax(np.abs(model),0) z_score = (maxamps - np.nanmean(maxamps,0))/np.nanstd(maxamps,0) with warnings.catch_warnings(): wa...
python
{ "resource": "" }
q52627
GABA.est_gaba_conc
train
def est_gaba_conc(self): """ Estimate gaba concentration based on equation adapted from Sanacora 1999, p1045 Ref: Sanacora, G., Mason, G. F., Rothman, D. L., Behar, K. L., Hyder, F., Petroff, O. A., ... & Krystal, J. H. (1999). Reduced cortical $\gamma$-aminobutyric acid...
python
{ "resource": "" }
q52628
AbstractStartPartner._init
train
def _init(self, state, initiate_arg): ''' Set initial state of the task. Called from initiate. @param initiate_arg: either the PartnerClass object (StartTask) or an agent_id (RestartTask) ''' state.descriptor = None state.hosts = state.agent.q...
python
{ "resource": "" }
q52629
ifdef
train
def ifdef(parser, token): """ Check if variable is defined in the context. Similar to django.template.defaulttags.do_if. """ block_tokens = ('elifdef', 'else', 'endifdef') # {% ifdef ... %} bits = token.split_contents()[1:] if len(bits) > 1: raise TemplateSyntaxError('%r is not ...
python
{ "resource": "" }
q52630
down
train
def down(queue, user=None, group=None, mode=None, host=None) : '''Down a queue, by creating a down file''' # default our owners and mode user, group, mode = _dflts(user, group, mode) down_path = fsq_path.down(queue, host=host) fd = None created = False try: # try to guarentee creatio...
python
{ "resource": "" }
q52631
is_down
train
def is_down(queue, host=None): '''Returns True if queue is down, False if queue is up''' down_path = fsq_path.down(queue, host=host) _queue_ok(os.path.dirname(down_path)) # use stat instead of os.path.exists because non-ENOENT errors are a # configuration issue, and should raise exeptions (e.g. if y...
python
{ "resource": "" }
q52632
trigger
train
def trigger(queue, user=None, group=None, mode=None, trigger=_c.FSQ_TRIGGER): '''Installs a trigger for the specified queue.''' # default our owners and mode user, group, mode = _dflts(user, group, mode) trigger_path = fsq_path.trigger(queue, trigger=trigger) created = False try: # mkfif...
python
{ "resource": "" }
q52633
trigger_pull
train
def trigger_pull(queue, ignore_listener=False, trigger=_c.FSQ_TRIGGER): '''Write a non-blocking byte to a trigger fifo, to cause a triggered scan''' fd = None trigger_path = fsq_path.trigger(queue, trigger=trigger) _queue_ok(os.path.dirname(trigger_path)) try: fd = os.open(trigger_pat...
python
{ "resource": "" }
q52634
down_host
train
def down_host(trg_queue, host, user=None, group=None, mode=None): ''' Down a host queue by creating a down file in the host queue directory ''' down(trg_queue, user=user, group=group, mode=mode, host=host)
python
{ "resource": "" }
q52635
host_trigger
train
def host_trigger(trg_queue, user=None, group=None, mode=None): '''Installs a host trigger for the specified queue.''' trigger(trg_queue, user=user, group=group, mode=mode, trigger=_c.FSQ_HOSTS_TRIGGER)
python
{ "resource": "" }
q52636
host_trigger_pull
train
def host_trigger_pull(trg_queue, ignore_listener=False): '''Write a non-blocking byte to a host trigger fifo, to cause a triggered scan''' trigger_pull(trg_queue, ignore_listener=ignore_listener, trigger=_c.FSQ_HOSTS_TRIGGER)
python
{ "resource": "" }
q52637
ComponentGroup.parse_xml_node
train
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a component group into this object. ''' self.group_id = node.getAttributeNS(RTS_NS, 'groupId') self._members = [] for c in node.getElementsByTagNameNS(RTS_NS, 'Members'): self._membe...
python
{ "resource": "" }
q52638
ComponentGroup.parse_yaml
train
def parse_yaml(self, node): '''Parse a YAML specification of a component group into this object. ''' self.group_id = y['groupId'] self._members = [] if 'members' in y: for m in y.get('members'): self._members.append(TargetComponent().parse_yam...
python
{ "resource": "" }
q52639
ComponentGroup.save_xml
train
def save_xml(self, doc, element): '''Save this component group into an xml.dom.Element object.''' element.setAttributeNS(RTS_NS, RTS_NS_S + 'groupID', self.group_id) for m in self.members: new_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Members') m.save_xml(doc, new...
python
{ "resource": "" }
q52640
ComponentGroup.to_dict
train
def to_dict(self): '''Save this component group to a dictionary.''' d = {'groupId': self.group_id} members = [] for m in self.members: members.append(m.to_dict()) if members: d['members'] = members return d
python
{ "resource": "" }
q52641
invalidate_paths
train
def invalidate_paths(paths): ''' Invalidate all pages for a certain path. ''' for path in paths: for key in all_cache_keys_from_path(path): InvalidationLogger.invalidate(path, key) dumper.utils.cache.delete(key)
python
{ "resource": "" }
q52642
all_cache_keys_from_path
train
def all_cache_keys_from_path(path): ''' Each path can actually have multiple cached entries, varying based on different HTTP methods. So a GET request will have a different cached response from a HEAD request. In order to invalidate a path, we must first know all the different cache keys that the ...
python
{ "resource": "" }
q52643
render_registered
train
def render_registered(url_id, remote_info): """ Render template file for the registered user, which has some of the values prefilled. Args: url_id (str): Seeder URL id. remote_info (dict): Informations read from Seeder. Returns: str: Template filled with data. """ r...
python
{ "resource": "" }
q52644
render_unregistered
train
def render_unregistered(error=None): """ Render template file for the unregistered user. Args: error (str, default None): Optional error message. Returns: str: Template filled with data. """ return template( read_index_template(), registered=False, error...
python
{ "resource": "" }
q52645
static_data
train
def static_data(fn): """ Static file handler. This functions accesses all static files in ``static`` directory. """ file_path = os.path.normpath(fn) full_path = os.path.join(STATIC_PATH, file_path) if not os.path.exists(full_path): abort(404, "Soubor '%s' neexistuje!" % fn) ret...
python
{ "resource": "" }
q52646
render_form_template
train
def render_form_template(): """ Rennder template for user. Decide whether the user is registered or not, pull remote info and so on. """ error = "" remote_info = {} registered_user_id = request.query.get("url_id", False) # try to read remote info, the the url_id parameter was specified...
python
{ "resource": "" }
q52647
IncludeGraph.unfold_file
train
def unfold_file(self, path): """ Parse given file and add it to graph """ yaml_config = self.file_index.unfold_yaml(path) self.unfold_config(path, yaml_config)
python
{ "resource": "" }
q52648
Feature.getValue
train
def getValue(self, unit=None): """ Return the value of the feature. If the unit is specified and the feature has a unit, the value is converted Args: - unit(str,optional): A unit to convert the current feature value ('B','K','M','G') """ if unit or self.unit: ...
python
{ "resource": "" }
q52649
Feature._check
train
def _check(self, check, radl): """ Check type, operator and unit in a feature. Args: - check(tuple): - v[0]: expected type of the feature value. - v[1]: can be a list of possible values or a function to test the value or None. - v[2] (optional): can be a...
python
{ "resource": "" }
q52650
Features.features
train
def features(self): """List of features.""" r = [] for _, inter in self.props.items(): if isinstance(inter, tuple): if (inter[0] and inter[1] and inter[0].getValue() == inter[1].getValue() and inter[0].operator == "=" and inter[1].operator == ...
python
{ "resource": "" }
q52651
Features.addFeature
train
def addFeature(self, f, conflict="error", missing="other"): """ Add a feature. Args: - f(Feature): feature to add. - conflict(str): if a property hasn't compatible values/constrains, do: - ``"error"``: raise exception. - ``"ignore"``: go on. - `...
python
{ "resource": "" }
q52652
Features.hasFeature
train
def hasFeature(self, prop, check_softs=False): """Return if there is a property with that name.""" return prop in self.props or (check_softs and any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])]))
python
{ "resource": "" }
q52653
Features.getValue
train
def getValue(self, prop, default=None): """Return the value of feature with that name or ``default``.""" f = self.props.get(prop, None) if not f: return default if isinstance(f, Feature): return f.getValue() if isinstance(f, tuple): # if f[0]....
python
{ "resource": "" }
q52654
Features.getFeature
train
def getFeature(self, prop): """Return the feature with that name.""" f = self.props.get(prop, None) if not f: return None if isinstance(f, Feature): return f if isinstance(f, tuple): if f[0]: return f[0] elif f[1]: ...
python
{ "resource": "" }
q52655
Features.setValue
train
def setValue(self, prop, value, unit=None): """Set the value of feature with that name.""" if isinstance(value, int) or isinstance(value, float): if prop in self.props: for i, j in [(0, 1), (1, 0)]: if self.props[prop][i] is None: ...
python
{ "resource": "" }
q52656
Features._applyInter
train
def _applyInter(finter0, finter1, conflict="ignore"): """ Return the restriction of first interval by the second. Args: - inter0, inter1 (tuple of Feature): intervals Return(tuple of Feature): the resulting interval - conflict(str): if a property hasn't compatible valu...
python
{ "resource": "" }
q52657
Features.applyFeatures
train
def applyFeatures(self, new_features, conflict="error", missing="error"): """ Apply the constrain of the features passed to this instance. .. warning:: Feature instances are only considered, that is, SoftFeatures will be not considered. Args: - new_featur...
python
{ "resource": "" }
q52658
Features.check_simple
train
def check_simple(self, checks, radl): """Check types, operators and units in simple features.""" for f in self.features: if not isinstance(f, Feature) or f.prop not in checks: continue f._check(checks[f.prop], radl)
python
{ "resource": "" }
q52659
Features.check_num
train
def check_num(self, checks, radl): """ Check types, operators and units in features with numbers. Args: - checks(dict of dict of str:tuples): keys are property name prefixes, and the values are dict with keys are property name suffixes and values are iterable as in ...
python
{ "resource": "" }
q52660
contextualize_item.check
train
def check(self, radl): """Check a line under a contextualize.""" if not radl.get_system_by_name(self.system): raise RADLParseException("Invalid system id '%s'" % self.system, line=self.line) if not radl.get_configure_by_name(self.configure): raise RADLParseException("Inv...
python
{ "resource": "" }
q52661
contextualize.update
train
def update(self, cont): """Update this instance with the contextualize passed.""" self.max_time = max(self.max_time, cont.max_time) if cont.items is not None: if self.items is None: self.items = cont.items else: self.items.update(cont.item...
python
{ "resource": "" }
q52662
contextualize.check
train
def check(self, radl): """Check a contextualize.""" if not isinstance(self.max_time, int) or self.max_time < 0: raise RADLParseException("Invalid 'max time' in 'contextualize'", line=self.line) if self.items is not None: for i in self...
python
{ "resource": "" }
q52663
contextualize.get_contextualize_items_by_step
train
def get_contextualize_items_by_step(self, default=None): """Get a dictionary of the contextualize_items grouped by the step or the default value""" if self.items: res = {} for elem in self.items.values(): if elem.num in res: res[elem.num].appen...
python
{ "resource": "" }
q52664
configure.check
train
def check(self, _): """Check this configure.""" try: import yaml except: return True try: yaml.safe_load(self.recipes) except Exception as e: raise RADLParseException("Invalid YAML code: %s." % e, line=self.line) return Tru...
python
{ "resource": "" }
q52665
deploy.check
train
def check(self, radl): """Check this deploy.""" if not radl.get_system_by_name(self.id): raise RADLParseException("Invalid system id in the deploy.", line=self.line) if self.vm_number < 0: raise RADLParseException("Invalid number of virtual machines to deploy.", ...
python
{ "resource": "" }
q52666
FeaturesApp.isNewerThan
train
def isNewerThan(self, other): """ Compare if the version of this app is newer that the other """ if self.getValue("name") == other.getValue("name"): if other.getValue("version"): if not other.getValue("version"): return False else: ...
python
{ "resource": "" }
q52667
FeaturesApp.check
train
def check(self, radl): """Check the features in this application.""" SIMPLE_FEATURES = { "name": (str, lambda x, _: bool(x.value)), "path": (str, lambda x, _: bool(x.value)), "version": (str, is_version), "preinstalled": (str, ["YES", "NO"]) } ...
python
{ "resource": "" }
q52668
system.hasIP
train
def hasIP(self, ip): """Return True if some system has this IP.""" for f in self.features: if (f.prop.startswith("net_interface.") and f.prop.endswith(".ip") and f.value == ip): return True return False
python
{ "resource": "" }
q52669
system.getNumNetworkWithConnection
train
def getNumNetworkWithConnection(self, connection): """Return the number of network interfaces with id ``connection``.""" i = 0 while True: value = self.getValue("net_interface.%d.connection" % i, None) if not value: return None if value == con...
python
{ "resource": "" }
q52670
system.getRequestedNameIface
train
def getRequestedNameIface(self, iface_num=0, num=None, default_hostname=None, default_domain=None): """Return the dns name associated to the net interface.""" full_name = self.getValue("net_interface.%d.dns_name" % iface_num) if full_name: replaced_full_name = system.replaceTemplat...
python
{ "resource": "" }
q52671
system.getNetworkIDs
train
def getNetworkIDs(self): """Return a list of network id of this system.""" res = [] i = 0 while True: netid = self.getValue("net_interface.%d.connection" % i) if not netid: return res res.append(netid) i += 1
python
{ "resource": "" }
q52672
system.updateNewCredentialValues
train
def updateNewCredentialValues(self): """ Set the new credential values to the credentials to use, and delete the new ones """ credentials_base = "disk.0.os.credentials." new_credentials_base = "disk.0.os.credentials.new." for elem in ['password', 'public_key', 'private_...
python
{ "resource": "" }
q52673
system.getCredentials
train
def getCredentials(self): """Return UserKeyCredential or UserPassCredential.""" (username, password, public_key, private_key) = self.getCredentialValues() if public_key or private_key: return UserKeyCredential(username, public_key, private_key) if username or password: ...
python
{ "resource": "" }
q52674
system.setCredentials
train
def setCredentials(self, creds): """Set values in UserKeyCredential or UserPassCredential.""" if isinstance(creds, UserKeyCredential): self.setUserKeyCredentials(creds.username, creds.public_key, creds.private_key) elif isinstance(creds, UserPassCredential): self.setUser...
python
{ "resource": "" }
q52675
system.setUserPasswdCredentials
train
def setUserPasswdCredentials(self, username, password): """Set username and password in ``disk.0.os.credentials``.""" self.setCredentialValues(username=username, password=password)
python
{ "resource": "" }
q52676
system.setUserKeyCredentials
train
def setUserKeyCredentials(self, username, public_key=None, private_key=None): """Set these properties in ``disk.0.os.credentials``.""" self.setCredentialValues(username=username, public_key=public_key, private_key=private_key)
python
{ "resource": "" }
q52677
system.getApplications
train
def getApplications(self): """Return a list of Application with the specified apps in this system.""" res = [] for f in self.features: if isinstance(f, Feature) and f.prop == "disk.0.applications": res.append(FeaturesApp(f.value.features)) return res
python
{ "resource": "" }
q52678
system.addApplication
train
def addApplication(self, name, version=None, path=None, disk_num=0, soft=-1): """Add a new application in some disk.""" fapp = Features() fapp.features.append(Feature("name", "=", name)) if version: fapp.features.append(Feature("version", "=", version)) if path: ...
python
{ "resource": "" }
q52679
system.check
train
def check(self, radl): """Check the features in this system.""" def positive(f, _): return f.value >= 0 def check_ansible_host(f, radl0): if radl0.get_ansible_by_id(f.value) is None: return False return True mem_units = ["", "B", "K"...
python
{ "resource": "" }
q52680
system.concrete
train
def concrete(self, other=None): """ Return copy and score after being applied other system and soft features. Args: - other(system, optional): system to apply just before soft features. Return(tuple): tuple of the resulting system and its score. """ new_system...
python
{ "resource": "" }
q52681
RADL.add
train
def add(self, aspect, ifpresent="error"): """ Add a network, ansible_host, system, deploy, configure or contextualize. Args: - aspect(network, system, deploy, configure or contextualize): thing to add. - ifpresent(str): if it has been defined, do: - ``"ignore"``: not...
python
{ "resource": "" }
q52682
RADL.get
train
def get(self, aspect): """Get a network, system or configure or contextualize with the same id as aspect passed.""" classification = [(network, self.networks), (system, self.systems), (configure, self.configures)] aspect_list = [l for t, l in classification if isinstan...
python
{ "resource": "" }
q52683
RADL.hasPublicNet
train
def hasPublicNet(self, system_name): """ Return true if some system has a public network.""" nets_id = [net.id for net in self.networks if net.isPublic()] system = self.get_system_by_name(system_name) if system: i = 0 while True: f = system.getFea...
python
{ "resource": "" }
q52684
RADL.check
train
def check(self): """Check if it is a valid RADL document.""" for i in [f for fs in [self.networks, self.ansible_hosts, self.systems, self.deploys, self.configures, [self.contextualize]] for f in fs]: i.check(self) snames = [s.name for s in self.system...
python
{ "resource": "" }
q52685
RADL.get_system_by_name
train
def get_system_by_name(self, name): """Return a system with that name or None.""" for elem in self.systems: if elem.name == name: return elem return None
python
{ "resource": "" }
q52686
RADL.get_deploy_by_id
train
def get_deploy_by_id(self, dep_id): """Return a deploy with that system id or None.""" for elem in self.deploys: if elem.id == dep_id: return elem return None
python
{ "resource": "" }
q52687
RADL.get_configure_by_name
train
def get_configure_by_name(self, name): """Return a configure with that id or None.""" for elem in self.configures: if elem.name == name: return elem return None
python
{ "resource": "" }
q52688
RADL.get_network_by_id
train
def get_network_by_id(self, net_id): """Return a network with that id or None.""" for elem in self.networks: if elem.id == net_id: return elem return None
python
{ "resource": "" }
q52689
RADL.get_ansible_by_id
train
def get_ansible_by_id(self, ansible_id): """Return a ansible with that id or None.""" for elem in self.ansible_hosts: if elem.id == ansible_id: return elem return None
python
{ "resource": "" }
q52690
create_date_formats
train
def create_date_formats(): """Generate time and date formats with different delimeters.""" # European style: base_formats = ['%d %m %Y', '%d %m %y', '%Y %m %d'] # US style: base_formats += ['%m %d %Y', '%m %d %y', '%Y %m %d'] # Things with words in base_formats += ['%d %b %Y', '%d %B %Y'] ...
python
{ "resource": "" }
q52691
injectClassCallback
train
def injectClassCallback(annotationName, depth, methodName, *args, **kwargs): """ Inject an annotation for a class method to be called after class initialization without dealing with metaclass. depth parameter specify the stack depth from the class definition. """ locals = reflect.class_locals(d...
python
{ "resource": "" }
q52692
slack_message
train
def slack_message(): """When we receive a message from Slack, generate a Trello card and reply""" # Incoming request format: # token=TOKEN # team_id=T0001 # team_domain=example # channel_id=C12345 # channel_name=test # user_id=U12345 # user_name=Steve # command=/weather # tex...
python
{ "resource": "" }
q52693
merge_users
train
def merge_users(merge_to, merge_from): """Merge a non-umail account with a umail account.""" # Determine most active user based on most recently created group assert(merge_to.username.endswith('umail.ucsb.edu')) # Merge groups for u2g in merge_from.groups_assocs[:]: merge_to.group_with(merg...
python
{ "resource": "" }
q52694
Glances.get_metrics
train
async def get_metrics(self, element): """Get all the metrics for a monitored element.""" await self.get_data() await self.get_plugins() if element in self.plugins: self.values = self.data[element] else: raise exceptions.GlancesApiError("Element data not a...
python
{ "resource": "" }
q52695
run
train
def run(cmd, cwd=None, silent=None, return_output=False, raises=True, **subprocess_args): """ Runs a CLI command. :param list/str cmd: Command with args to run. :param str cwd: Change directory to cwd before running :param bool/int silent: Suppress stdout/stderr. If True...
python
{ "resource": "" }
q52696
UserData.parse
train
def parse(self, raw): """Convert raw incoming to class attributes.""" self._raw = raw self.hub_name = self._parse("userData", "hubName", converter=base64_to_unicode) self.ip = self._parse("userData", "ip") self.ssid = self._parse("userData", "ssid")
python
{ "resource": "" }
q52697
Hub.query_firmware
train
async def query_firmware(self): """Query the firmware versions.""" _version = await self.request.get(join_path(self._base_path, "/fwversion")) _fw = _version.get("firmware") if _fw: _main = _fw.get("mainProcessor") if _main: self._main_processor_v...
python
{ "resource": "" }
q52698
load_from_package
train
def load_from_package(): ''' Try to load category ranges from module. :returns: category ranges dict or None :rtype: None or dict of RangeGroup ''' try: import pkg_resources f = pkg_resources.resource_stream( meta.__app__, 'cache/unicategories.cache' ...
python
{ "resource": "" }
q52699
load_from_cache
train
def load_from_cache(path=user_path): ''' Try to load category ranges from userlevel cache file. :param path: path to userlevel cache file :type path: str :returns: category ranges dict or None :rtype: None or dict of RangeGroup ''' if not path: return try: with open(...
python
{ "resource": "" }