code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def parse_services(config, services): enabled = 0 for service in services: check_disabled = config.getboolean(service, 'check_disabled') if not check_disabled: enabled += 1 return enabled
Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each service check Returns: A number (i...
def on_batch_begin(self, train, **kwargs:Any)->None: "Record learning rate and momentum at beginning of batch." if train: self.lrs.append(self.opt.lr) self.moms.append(self.opt.mom)
Record learning rate and momentum at beginning of batch.
def get_files(self): files = {} for filename in os.listdir(self.source): path = os.path.join(self.source, filename) files[filename] = frontmatter.load(path, filename=filename, slug=os.path.splitext(filename)[0]) return files
Read and parse files from a directory, return a dictionary of path => post
def install_timers(config, context): timers = [] if config.get('capture_timeout_warnings'): timeout_threshold = config.get('timeout_warning_threshold') time_remaining = context.get_remaining_time_in_millis() / 1000 timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, ...
Create the timers as specified by the plugin configuration.
def execute_sql(self, query): c = self.con.cursor() c.execute(query) result = c.fetchall() return result
Executes a given query string on an open sqlite database.
def get_oncall(self, **kwargs): endpoint = '/'.join((self.endpoint, self.id, 'users')) return self.request('GET', endpoint=endpoint, query_params=kwargs)
Retrieve this schedule's "on call" users.
def get_setup_requires(): if {'--help', '--help-commands'}.intersection(sys.argv): return list() reqlist = [] for cmd, dependencies in SETUP_REQUIRES.items(): if cmd in sys.argv: reqlist.extend(dependencies) return reqlist
Return the list of packages required for this setup.py run
def ext_pillar(minion_id, pillar, command): try: command = command.replace('%s', minion_id) return deserialize(__salt__['cmd.run']('{0}'.format(command))) except Exception: log.critical('YAML data from %s failed to parse', command) return {}
Execute a command and read the output as YAMLEX
def all(cls): api = Client.instance().api endpoint_list = api.endpoint.get() return endpoint_list
Returns a list of all configured endpoints the server is listening on. For each endpoint, the list of allowed databases is returned too if set. The result is a JSON hash which has the endpoints as keys, and the list of mapped database names as values for each endpoint. ...
def jars(self, absolute=True): jars = glob(os.path.join(self._jar_path, '*.jar')) return jars if absolute else map(lambda j: os.path.abspath(j), jars)
List of jars in the jar path
def get_language_details(self, language): for lang in self.user_data.languages: if language == lang['language_string']: return lang return {}
Get user's status about a language.
def stop(name, timeout=None, **kwargs): if timeout is None: try: timeout = inspect_container(name)['Config']['StopTimeout'] except KeyError: timeout = salt.utils.docker.SHUTDOWN_TIMEOUT orig_state = state(name) if orig_state == 'paused': if kwargs.get('unpause...
Stops a running container name Container name or ID unpause : False If ``True`` and the container is paused, it will be unpaused before attempting to stop the container. timeout Timeout in seconds after which the container will be killed (if it has not yet graceful...
def iter_rows(self, start=None, end=None): start = start or 0 end = end or self.nrows for i in range(start, end): yield self.iloc[i, :]
Iterate each of the Region rows in this region
def parse_class_id(self, sel, m, has_selector): selector = m.group(0) if selector.startswith('.'): sel.classes.append(css_unescape(selector[1:])) else: sel.ids.append(css_unescape(selector[1:])) has_selector = True return has_selector
Parse HTML classes and ids.
def _no_spelling_errors(relative_path, contents, linter_options): block_regexps = linter_options.get("block_regexps", None) chunks, shadow = spellcheckable_and_shadow_contents(contents, block_regexps) cache = linter_options.get("spellcheck_cache", None...
No spelling errors in strings, comments or anything of the like.
def calc_area_under_PSD(self, lowerFreq, upperFreq): Freq_startAreaPSD = take_closest(self.freqs, lowerFreq) index_startAreaPSD = int(_np.where(self.freqs == Freq_startAreaPSD)[0][0]) Freq_endAreaPSD = take_closest(self.freqs, upperFreq) index_endAreaPSD = int(_np.where(self.freqs == Fre...
Sums the area under the PSD from lowerFreq to upperFreq. Parameters ---------- lowerFreq : float The lower limit of frequency to sum from upperFreq : float The upper limit of frequency to sum to Returns ------- AreaUnderPSD : float ...
def spectral_norm(w, dim=0, itr=1, eps=1e-12, test=False, u_init=None, fix_parameters=True): assert (0 <= dim and dim < len(w.shape) ), "`dim` must be `0 <= dim and dim < len(w.shape)`." assert 0 < itr, "`itr` must be greater than 0." assert 0 < eps, "`eps` must be greater than 0." if dim ==...
Spectral Normalization. .. math:: W_{sn} = \\frac{W}{\\sigma(W)}. where :math:`W` is the input matrix, and the :math:`\\sigma(W)` is the spectral norm of :math:`W`. The spectral norm is approximately computed by the power iteration. References: Takeru Miyato, Toshiki Kataoka, Masanori K...
def value(self): if self.ready is True: flag, load = self.__queue.get() if flag: return load raise load
Read-only property containing data returned from function.
def exclude(self, scheduled_operation: ScheduledOperation) -> bool: try: self.scheduled_operations.remove(scheduled_operation) return True except ValueError: return False
Omits a scheduled operation from the schedule, if present. Args: scheduled_operation: The operation to try to remove. Returns: True if the operation was present and is now removed, False if it was already not present.
def get_page_template(self, **kwargs): opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, opts.object_name.lower(), self.template_name_suffix, self.page_template_suffix, )
Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*.
def parse_keys(self, sn: "DataNode") -> Dict[InstanceName, ScalarValue]: res = {} for k in self.keys: knod = sn.get_data_child(*k) if knod is None: raise NonexistentSchemaNode(sn.qual_name, *k) kval = knod.type.parse_value(self.keys[k]) if ...
Parse key dictionary in the context of a schema node. Args: sn: Schema node corresponding to a list.
def run_suite(self): if not self.phantomjs_runner: raise JsTestException('phantomjs_runner need to be defined') url = self.get_url() self.phantomjs(self.phantomjs_runner, url, title=self.title) self.cleanup()
Run a phantomjs test suite. - ``phantomjs_runner`` is mandatory. - Either ``url`` or ``url_name`` needs to be defined.
def _configuration(self, *args, **kwargs): data = dict() self.db.open() for pkg in self.db.get(Package): configs = list() for pkg_cfg in self.db.get(PackageCfgFile, eq={'pkgid': pkg.id}): configs.append(pkg_cfg.path) data[pkg.name] = configs ...
Return configuration files.
def values(self): results = {} results['use_calfile'] = self.ui.calfileRadio.isChecked() results['calname'] = str(self.ui.calChoiceCmbbx.currentText()) results['frange'] = (self.ui.frangeLowSpnbx.value(), self.ui.frangeHighSpnbx.value()) return results
Gets the values the user input to this dialog :returns: dict of inputs: | *'use_calfile'*: bool, -- whether to apply calibration at all | *'calname'*: str, -- the name of the calibration dataset to use | *'frange'*: (int, int), -- (min, max) of ...
def _fingerprint_files(self, filepaths): hasher = sha1() for filepath in filepaths: filepath = self._assert_in_buildroot(filepath) hasher.update(os.path.relpath(filepath, get_buildroot()).encode('utf-8')) with open(filepath, 'rb') as f: hasher.update(f.read()) return hasher.hexdige...
Returns a fingerprint of the given filepaths and their contents. This assumes the files are small enough to be read into memory.
def draw_svg(self, svg_str): try: import rsvg except ImportError: self.draw_text(svg_str) return svg = rsvg.Handle(data=svg_str) svg_width, svg_height = svg.get_dimension_data()[:2] transx, transy = self._get_translation(svg_width, svg_height) ...
Draws svg string to cell
def segments (self): for n in xrange(len(self.vertices) - 1): yield Line(self.vertices[n], self.vertices[n + 1]) yield Line(self.vertices[-1], self.vertices[0])
Return the Line segments that comprise this Polygon.
def surface(x, y, z): data = [go.Surface(x=x, y=y, z=z)] return Chart(data=data)
Surface plot. Parameters ---------- x : array-like, optional y : array-like, optional z : array-like, optional Returns ------- Chart
def add_criterion(self, name, priority, and_or, search_type, value): criterion = SearchCriteria(name, priority, and_or, search_type, value) self.criteria.append(criterion)
Add a search criteria object to a smart group. Args: name: String Criteria type name (e.g. "Application Title") priority: Int or Str number priority of criterion. and_or: Str, either "and" or "or". search_type: String Criteria search type. (e.g. "is", "is ...
def class_factory(name, base_class, class_dict): def __init__(self, tcex): base_class.__init__(self, tcex) for k, v in class_dict.items(): setattr(self, k, v) newclass = type(str(name), (base_class,), {'__init__': __init__}) return newclass
Internal method for dynamically building Custom Indicator classes.
def parse_all(self): tokens = self.split_tokens duration = self.duration datetime = self.datetime thread = self.thread operation = self.operation namespace = self.namespace pattern = self.pattern nscanned = self.nscanned nscannedObjects = self.nsca...
Trigger extraction of all information. These values are usually evaluated lazily.
def execution_minutes_for_session(self, session_label): return self.minutes_in_range( start_minute=self.execution_time_from_open( self.schedule.at[session_label, 'market_open'], ), end_minute=self.execution_time_from_close( self.schedule.at[ses...
Given a session label, return the execution minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- pd.DateTimeIndex All the execution minutes...
def clear_events(self, event_name): self.lock.acquire() try: q = self.get_event_q(event_name) q.queue.clear() except queue.Empty: return finally: self.lock.release()
Clear all events of a particular name. Args: event_name: Name of the events to be popped.
def add_text_to_image(fname, txt, opFilename): ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil") print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename) im = Image.open(fname) draw = ImageDraw.Draw(im) draw.text((0, 0), txt, fill=(0, 0, 0), font=ft) d...
convert an image by adding text
def findOne(self, query=None, mode=FindOneMode.FIRST, **kwargs): results = self.find(query, **kwargs) if len(results) is 0: return None elif len(results) is 1 or mode == FindOneMode.FIRST: return results[0] elif mode == FindOneMode.LAST: return results...
Perform a find, with the same options present, but only return a maximum of one result. If find returns an empty array, then None is returned. If there are multiple results from find, the one returned depends on the mode parameter. If mode is FindOneMode.FIRST, then the first result is return...
def get_my_hostname(self, split_hostname_on_first_period=False): hostname = self.init_config.get("os_host") or self.hostname if split_hostname_on_first_period: hostname = hostname.split('.')[0] return hostname
Returns a best guess for the hostname registered with OpenStack for this host
def create_contact(self, attrs, members=None, folder_id=None, tags=None): cn = {} if folder_id: cn['l'] = str(folder_id) if tags: tags = self._return_comma_list(tags) cn['tn'] = tags if members: cn['m'] = members attrs = [{'n': k, '...
Create a contact Does not include VCARD nor group membership yet XML example : <cn l="7> ## ContactSpec <a n="lastName">MARTIN</a> <a n="firstName">Pierre</a> <a n="email">pmartin@example.com</a> </cn> Which would be in zimsoap : attrs = { 'l...
def parse_uinput_mapping(name, mapping): axes, buttons, mouse, mouse_options = {}, {}, {}, {} description = "ds4drv custom mapping ({0})".format(name) for key, attr in mapping.items(): key = key.upper() if key.startswith("BTN_") or key.startswith("KEY_"): buttons[key] = attr ...
Parses a dict of mapping options.
def check( state_engine, nameop, block_id, checked_ops ): sender = nameop['sender'] sending_blockchain_id = None found = False blockchain_namerec = None for blockchain_id in state_engine.get_announce_ids(): blockchain_namerec = state_engine.get_name( blockchain_id ) if blockchain_nam...
Log an announcement from the blockstack developers, but first verify that it is correct. Return True if the announcement came from the announce IDs whitelist Return False otherwise
def asdict(self): result = {} for key in self._fields: value = getattr(self, key) if isinstance(value, list): value = [i.asdict() if isinstance(i, Resource) else i for i in value] if isinstance(value, Resource): value = value.asdict() ...
Convert resource to dictionary
def audit_with_request(**kwargs): def wrap(fn): @audit(**kwargs) def operation(parent_object, *args, **kw): return fn(parent_object.request, *args, **kw) @functools.wraps(fn) def advice_with_request(the_request, *args, **kw): class ParentObject: ...
use this decorator to audit an operation with a request as input variable
def _validate(claims, validate_claims, expiry_seconds): if not validate_claims: return now = time() try: expiration_time = claims[CLAIM_EXPIRATION_TIME] except KeyError: pass else: _check_expiration_time(now, expiration_time) try: issued_at = claims[CLAIM_...
Validate expiry related claims. If validate_claims is False, do nothing. Otherwise, validate the exp and nbf claims if they are present, and validate the iat claim if expiry_seconds is provided.
def build_catalog_info(self, catalog_info): cat = SourceFactory.build_catalog(**catalog_info) catalog_info['catalog'] = cat catalog_info['catalog_table'] = cat.table catalog_info['roi_model'] =\ SourceFactory.make_fermipy_roi_model_from_catalogs([cat]) catalog_info['s...
Build a CatalogInfo object
def update(cls, spec, updates, upsert=False): if 'key' in spec: previous = cls.get(spec['key']) else: previous = None if previous: current = cls(**previous.__dict__) elif upsert: current = cls(**spec) else: current = Non...
The spec is used to search for the data to update, updates contains the values to be updated, and upsert specifies whether to do an insert if the original data is not found.
def should_copy(column): if not isinstance(column.type, Serial): return True if column.nullable: return True if not column.server_default: return True return False
Determine if a column should be copied.
def get_db_row(db, start, size): type_ = snap7.snap7types.wordlen_to_ctypes[snap7.snap7types.S7WLByte] data = client.db_read(db, start, type_, size) return data
Here you see and example of readying out a part of a DB Args: db (int): The db to use start (int): The index of where to start in db data size (int): The size of the db data to read
def spkapo(targ, et, ref, sobs, abcorr): targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) sobs = stypes.toDoubleVector(sobs) ptarg = stypes.emptyDoubleVector(3) lt = ctypes.c_double() libspice.spkapo_c(targ, et, ref,...
Return the position of a target body relative to an observer, optionally corrected for light time and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkapo_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: I...
def on_gtk_prefer_dark_theme_toggled(self, chk): self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active()) select_gtk_theme(self.settings)
Set the `gtk_prefer_dark_theme' property in dconf
def from_keys(cls, keys, loader_func, type_hint=None): return cls({k: LazyLoadedValue( lambda k=k: loader_func(k), type_hint=type_hint) for k in keys})
Factory method for `LazyLoadedDict` Accepts a ``loader_func`` that is to be applied to all ``keys``. :param keys: List of keys to create the dictionary with :type keys: iterable :param loader_func: Function to be applied to all keys :type loader_func: function :param ty...
def _bits_ports_and_isrom_from_memory(mem): is_rom = False bits = 2**mem.addrwidth * mem.bitwidth read_ports = len(mem.readport_nets) try: write_ports = len(mem.writeport_nets) except AttributeError: if not isinstance(mem, RomBlock): raise PyrtlInternalError('Mem with no ...
Helper to extract mem bits and ports for estimation.
def _lane_detail_to_ss(fcid, ldetail): return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"], ldetail["bc_index"], ldetail["description"].encode("ascii", "ignore"), "N", "", "", ldetail["project_name"]]
Convert information about a lane into Illumina samplesheet output.
def _colorize(val, color): if termcolor is not None: val = termcolor.colored(val, color) elif colorama is not None: val = TERMCOLOR2COLORAMA[color] + val + colorama.Style.RESET_ALL return val
Colorize a string using termcolor or colorama. If any of them are available.
def build_from_energy_dict(cls, ebin_name, input_dict): psf_types = input_dict.pop('psf_types') output_list = [] for psf_type, val_dict in sorted(psf_types.items()): fulldict = input_dict.copy() fulldict.update(val_dict) fulldict['evtype_name'] = psf_type ...
Build a list of components from a dictionary for a single energy range
def admin_link(obj): if hasattr(obj, 'get_admin_link'): return mark_safe(obj.get_admin_link()) return mark_safe(admin_link_fn(obj))
Returns a link to the admin URL of an object. No permissions checking is involved, so use with caution to avoid exposing the link to unauthorised users. Example:: {{ foo_obj|admin_link }} renders as:: <a href='/admin/foo/123'>Foo</a> :param obj: A Django model instance. :re...
def gzip_dir(path, compresslevel=6): for f in os.listdir(path): full_f = os.path.join(path, f) if not f.lower().endswith("gz"): with open(full_f, 'rb') as f_in, \ GzipFile('{}.gz'.format(full_f), 'wb', compresslevel=compresslevel) as f_out: ...
Gzips all files in a directory. Note that this is different from shutil.make_archive, which creates a tar archive. The aim of this method is to create gzipped files that can still be read using common Unix-style commands like zless or zcat. Args: path (str): Path to directory. compressl...
def poly_to_pwl(self, n_points=4): assert self.pcost_model == POLYNOMIAL p_min = self.p_min p_max = self.p_max p_cost = [] if p_min > 0.0: step = (p_max - p_min) / (n_points - 2) y0 = self.total_cost(0.0) p_cost.append((0.0, y0)) x ...
Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max.
def create_event_subscription(self, instance, on_data, timeout=60): manager = WebSocketSubscriptionManager(self, resource='events') subscription = WebSocketSubscriptionFuture(manager) wrapped_callback = functools.partial( _wrap_callback_parse_event, on_data) manager.open(wrap...
Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called on each :class:`.Event`. :...
def get_context(self, **kwargs): context = self.get_context_data(form=self.form_obj, **kwargs) context.update(super(FormAdminView, self).get_context()) return context
Use this method to built context data for the template Mix django wizard context data with django-xadmin context
def validate(self) : if not self.mustValidate : return True res = {} for field in self.validators.keys() : try : if isinstance(self.validators[field], dict) and field not in self.store : self.store[field] = DocumentStore(self.collection...
Validate the whole document
def analysis(self): if self._analysis is None: with open(self.path, 'rb') as f: self.read_analysis(f) return self._analysis
Get ANALYSIS segment of the FCS file.
def startLoading(self): if self._loading: return False tree = self.treeWidget() if not tree: return self._loading = True self.setText(0, '') lbl = QtGui.QLabel(self.treeWidget()) lbl.setMovie(XLoaderWidget.getMovie()) lbl....
Updates this item to mark the item as loading. This will create a QLabel with the loading ajax spinner to indicate that progress is occurring.
def get_processing_block_ids(self): _processing_block_ids = [] pattern = '*:processing_block:*' block_ids = self._db.get_ids(pattern) for block_id in block_ids: id_split = block_id.split(':')[-1] _processing_block_ids.append(id_split) return sorted(_proces...
Get list of processing block ids using the processing block id
def _load_version(cls, state, version): from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name']) num_classes = state['num_classes'] num_inputs = state['_fea...
A function to load a previously saved SoundClassifier instance.
def detach_all(self): self.detach_all_classes() self.objects.clear() self.index.clear() self._keepalive[:] = []
Detach from all tracked classes and objects. Restore the original constructors and cleanse the tracking lists.
def _get_action_urls(self): actions = {} model_name = self.model._meta.model_name base_url_name = '%s_%s' % (self.model._meta.app_label, model_name) model_actions_url_name = '%s_actions' % base_url_name self.tools_view_name = 'admin:' + model_actions_url_name for action i...
Get the url patterns that route each action to a view.
def get_config_section(self, name): if self.config.has_section(name): return self.config.items(name) return []
Get a section of a configuration
def find_all_files(self): files = self.find_files() subrepo_files = ( posixpath.join(subrepo.location, filename) for subrepo in self.subrepos() for filename in subrepo.find_files() ) return itertools.chain(files, subrepo_files)
Find files including those in subrepositories.
def one_way_portal(self, other, **stats): return self.character.new_portal( self, other, symmetrical=False, **stats )
Connect a portal from here to another node, and return it.
def _live_receivers(self, sender): receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: ...
Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers.
def smear(idx, factor): s = [idx] for i in range(factor+1): a = i - factor/2 s += [idx + a] return numpy.unique(numpy.concatenate(s))
This function will take as input an array of indexes and return every unique index within the specified factor of the inputs. E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102] Parameters ----------- idx : numpy.array of ints The indexes to be smeared. factor : idx Th...
def nla_put(msg, attrtype, datalen, data): nla = nla_reserve(msg, attrtype, datalen) if not nla: return -NLE_NOMEM if datalen <= 0: return 0 nla_data(nla)[:datalen] = data[:datalen] _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Wrote %d bytes at offset +%d', id(msg), id(nla), nla.nla_type...
Add a unspecific attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L497 Reserves room for an unspecific attribute and copies the provided data into the message as payload of the attribute. Returns an error if there is insufficient space for the attribute. Posi...
def mod_watch(name, **kwargs): ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if kwargs['sfun'] == 'watch': for p in ['sfun', '__reqs__']: del kwargs[p] kwargs['name'] = name ret = present(**kwargs) return ret
The at watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state being triggered. name The name ...
def estimate_frequency(self, start: int, end: int, sample_rate: float): length = 2 ** int(math.log2(end - start)) data = self.data[start:start + length] try: w = np.fft.fft(data) frequencies = np.fft.fftfreq(len(w)) idx = np.argmax(np.abs(w)) freq ...
Estimate the frequency of the baseband signal using FFT :param start: Start of the area that shall be investigated :param end: End of the area that shall be investigated :param sample_rate: Sample rate of the signal :return:
def read(self): with open(self.default_file) as json_file: try: return json.load(json_file) except Exception as e: raise 'empty file'
read default csp settings from json file
def get_development_container_name(self): if self.__prefix: return "{0}:{1}-{2}-dev".format( self.__repository, self.__prefix, self.__branch) else: return "{0}:{1}-dev".format( self.__repository, self...
Returns the development container name
def changeable(self, request): return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none()
Checks the both, check_changeable and apply_changeable, against the owned model and it's instance set
def is_digit(obj): return isinstance(obj, (numbers.Integral, numbers.Complex, numbers.Real))
Check if an object is Number
def get(self, url, params={}, headers={}, auth=(), certificate_path=None): certificate_path = certificate_path if certificate_path else False return self.session.get(url, params=params, headers=headers, verify=certificate_path, auth=auth, timeout=self.timeout)
Returns the response payload from the request to the given URL. Args: url (str): The URL for the WEB API that the request is being made too. params (dict): Dictionary containing the query string parameters. headers (dict): HTTP Headers that may be needed for the request. ...
def softmax(w, t=1.0): w = [Decimal(el) for el in w] e = numpy.exp(numpy.array(w) / Decimal(t)) dist = e / numpy.sum(e) return dist
Calculate the softmax of a list of numbers w. Parameters ---------- w : list of numbers Returns ------- a list of the same length as w of non-negative numbers Examples -------- >>> softmax([0.1, 0.2]) array([ 0.47502081, 0.52497919]) >>> softmax([-0.1, 0.2]) array([ 0...
def create_usuario(self): return Usuario( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of usuario services facade.
def samples(self): if self._samples is None: self._samples = SampleList( self._version, assistant_sid=self._solution['assistant_sid'], task_sid=self._solution['sid'], ) return self._samples
Access the samples :returns: twilio.rest.autopilot.v1.assistant.task.sample.SampleList :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleList
def get_missing_required_annotations(self) -> List[str]: return [ required_annotation for required_annotation in self.required_annotations if required_annotation not in self.annotations ]
Return missing required annotations.
def service(self, name=None, pk=None, scope=None, **kwargs): _services = self.services(name=name, pk=pk, scope=scope, **kwargs) if len(_services) == 0: raise NotFoundError("No service fits criteria") if len(_services) != 1: raise MultipleFoundError("Multiple services fit ...
Retrieve single KE-chain Service. Uses the same interface as the :func:`services` method but returns only a single pykechain :class:`models.Service` instance. :param name: (optional) name to limit the search for :type name: basestring or None :param pk: (optional) primary key o...
def options(self, parser, env=os.environ): "Add options to nosetests." parser.add_option("--%s-record" % self.name, action="store", metavar="FILE", dest="record_filename", help="Record actions to this...
Add options to nosetests.
def get_loss(self, y_pred, y_true, X=None, training=False): y_true = to_tensor(y_true, device=self.device) return self.criterion_(y_pred, y_true)
Return the loss for this batch. Parameters ---------- y_pred : torch tensor Predicted target values y_true : torch tensor True target values. X : input data, compatible with skorch.dataset.Dataset By default, you should be able to pass: ...
def uncomplete(self): args = { 'project_id': self.project.id, 'ids': [self.id] } owner = self.project.owner _perform_command(owner, 'item_uncomplete', args)
Mark the task uncomplete. >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = user.get_project('PyTodoist') >>> task = project.add_task('Install PyTodoist') >>> task.uncomplete()
def assert_succeeds(exception, msg_fmt="{msg}"): class _AssertSucceeds(object): def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if exc_type and issubclass(exc_type, exception): msg = exception.__name__ + " was unexpectedly raised" ...
Fail if a specific exception is raised within the context. This assertion should be used for cases, where successfully running a function signals a successful test, and raising the exception of a certain type signals a test failure. All other raised exceptions are passed on and will usually still resul...
def add_vlan_firewall(self, vlan_id, ha_enabled=False): package = self.get_dedicated_package(ha_enabled) product_order = { 'complexType': 'SoftLayer_Container_Product_Order_Network_' 'Protection_Firewall_Dedicated', 'quantity': 1, 'packageId...
Creates a firewall for the specified vlan. :param int vlan_id: The ID of the vlan to create the firewall for :param bool ha_enabled: If True, an HA firewall will be created :returns: A dictionary containing the VLAN firewall order
def _detect_line_ending(self): candidate_value = '\n' candidate_count = 0 for line_ending in UniversalCsvReader.line_endings: count = self._sample.count(line_ending) if count > candidate_count: candidate_value = line_ending candidate_count ...
Detects the line ending in the sample data.
def ping(): if _worker_name() not in DETAILS: init() try: return DETAILS[_worker_name()].conn.isalive() except TerminalException as e: log.error(e) return False
Ping the device on the other end of the connection .. code-block: bash salt '*' onyx.cmd ping
def handle_cancellation(session: CommandSession): def control(value): if _is_cancellation(value) is True: session.finish(render_expression( session.bot.config.SESSION_CANCEL_EXPRESSION)) return value return control
If the input is a string of cancellation word, finish the command session.
def __get_connection(self) -> redis.Redis: if self.__redis_use_socket: r = redis.from_url( 'unix://{:s}?db={:d}'.format( self.__redis_host, self.__redis_db ) ) else: r = redis.from_url( ...
Get a Redis connection :return: Redis connection instance :rtype: redis.Redis
def load_brain_metadata(proxy, include_fields): ret = {} for index in proxy.indexes(): if index not in proxy: continue if include_fields and index not in include_fields: continue val = getattr(proxy, index) if val != Missing.Value: try: ...
Load values from the catalog metadata into a list of dictionaries
def select_single_column(engine, column): s = select([column]) return column.name, [row[0] for row in engine.execute(s)]
Select data from single column. Example:: >>> select_single_column(engine, table_user.c.id) [1, 2, 3] >>> select_single_column(engine, table_user.c.name) ["Alice", "Bob", "Cathy"]
def gopro_set_response_send(self, cmd_id, status, force_mavlink1=False): return self.send(self.gopro_set_response_encode(cmd_id, status), force_mavlink1=force_mavlink1)
Response from a GOPRO_COMMAND set request cmd_id : Command ID (uint8_t) status : Status (uint8_t)
def truth(f): @wraps(f) def check(v): t = f(v) if not t: raise ValueError return v return check
Convenience decorator to convert truth functions into validators. >>> @truth ... def isdir(v): ... return os.path.isdir(v) >>> validate = Schema(isdir) >>> validate('/') '/' >>> with raises(MultipleInvalid, 'not a valid value'): ... validate('/notaval...
def parenthesize(self, expr, level, *args, strict=False, **kwargs): needs_parenths = ( (precedence(expr) < level) or (strict and precedence(expr) == level)) if needs_parenths: return ( self._parenth_left + self.doprint(expr, *args, **kwargs) + ...
Render `expr` and wrap the result in parentheses if the precedence of `expr` is below the given `level` (or at the given `level` if `strict` is True. Extra `args` and `kwargs` are passed to the internal `doit` renderer
def main(): print() print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print(lorem_gotham_title().center(50)) print("-~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~--~*~-") print() poem = lorem_gotham() for n in range(16): if n in (4, 8, 12): print() print(n...
I provide a command-line interface for this module
def write(self, **kwargs): if 'id' in kwargs and 'data' in kwargs: result = self.write_raw(kwargs['id'], kwargs['data'], bus=kwargs.get('bus', None), frame_format=kwargs.get('frame_format', None)) else: result = self.write_translated(kwargs...
Serialize a raw or translated write request and send it to the VI, following the OpenXC message format.
def autopage(self): while self.items: yield from self.items self.items = self.fetch_next()
Iterate through results from all pages. :return: all results :rtype: generator