code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def cells_rt_meta(workbook, sheet, row, col): """ Traverse all cells in a row. If you find new data in a cell, add it to the list. :param obj workbook: :param str sheet: :param int row: :param int col: :return list: Cell data for a specific row """ logger_excel.info("enter cells_rt_m...
Traverse all cells in a row. If you find new data in a cell, add it to the list. :param obj workbook: :param str sheet: :param int row: :param int col: :return list: Cell data for a specific row
def render_html(self, obj, context=None): """ Generate the 'html' attribute of an oembed resource using a template. Sort of a corollary to the parser's render_oembed method. By default, the current mapping will be passed in as the context. OEmbed templates are stored in...
Generate the 'html' attribute of an oembed resource using a template. Sort of a corollary to the parser's render_oembed method. By default, the current mapping will be passed in as the context. OEmbed templates are stored in: oembed/provider/[app_label]_[model].html ...
def lreshape(data, groups, dropna=True, label=None): """ Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data ...
Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... ...
def face_function(script, function='(fi == 0)'): """Boolean function using muparser lib to perform face selection over current mesh. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, ...
Boolean function using muparser lib to perform face selection over current mesh. See help(mlx.muparser_ref) for muparser reference documentation. It's possible to use parenthesis, per-vertex variables and boolean operator: (, ), and, or, <, >, = It's possible to use per-face variables like...
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs): r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate ...
r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate an inverse for y (float): desired output of fun x0 (float): initial guess at input to ...
def create_ar (archive, compression, cmd, verbosity, interactive, filenames): """Create a AR archive.""" opts = 'rc' if verbosity > 1: opts += 'v' cmdlist = [cmd, opts, archive] cmdlist.extend(filenames) return cmdlist
Create a AR archive.
def available_composite_ids(self, available_datasets=None): """Get names of compositors that can be generated from the available datasets. Returns: generator of available compositor's names """ if available_datasets is None: available_datasets = self.available_dataset_ids(co...
Get names of compositors that can be generated from the available datasets. Returns: generator of available compositor's names
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt ...
Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop ...
def _detect_sse41(self): "Does this compiler support SSE4.1 intrinsics?" self._print_support_start('SSE4.1') result = self.hasfunction( '__m128 v; _mm_round_ps(v,0x00)', include='<smmintrin.h>', extra_postargs=['-msse4']) self._print_...
Does this compiler support SSE4.1 intrinsics?
def newton(self): """ Newton power flow routine Returns ------- (bool, int) success flag, number of iterations """ dae = self.system.dae while True: inc = self.calc_inc() dae.x += inc[:dae.n] dae.y += inc[d...
Newton power flow routine Returns ------- (bool, int) success flag, number of iterations
def type_converter(text): """ I convert strings into integers, floats, and strings! """ if text.isdigit(): return int(text), int try: return float(text), float except ValueError: return text, STRING_TYPE
I convert strings into integers, floats, and strings!
def jsonresolver_loader(url_map): """Jsonresolver hook for funders resolving.""" def endpoint(doi_code): pid_value = "10.13039/{0}".format(doi_code) _, record = Resolver(pid_type='frdoi', object_type='rec', getter=Record.get_record).resolve(pid_value) return ...
Jsonresolver hook for funders resolving.
def b_pathInTree(self, astr_path): """ Converts a string <astr_path> specifier to a list-based *absolute* lookup, i.e. "/node1/node2/node3" is converted to ['/' 'node1' 'node2' 'node3']. The method also understands a paths that start with: '..' or ...
Converts a string <astr_path> specifier to a list-based *absolute* lookup, i.e. "/node1/node2/node3" is converted to ['/' 'node1' 'node2' 'node3']. The method also understands a paths that start with: '..' or combination of '../../..' and is also aware that the root ...
def get_model_indexes(model, add_reserver_flag=True): """ Creating indexes suit for model_config. """ import uliweb.orm as orm from sqlalchemy.engine.reflection import Inspector indexes = [] engine = model.get_engine().engine insp = Inspector.from_engine(engine) for index in insp.ge...
Creating indexes suit for model_config.
def parse_mini(memory_decriptor, buff): """ memory_descriptor: MINIDUMP_MEMORY_DESCRIPTOR buff: file_handle """ mms = MinidumpMemorySegment() mms.start_virtual_address = memory_decriptor.StartOfMemoryRange mms.size = memory_decriptor.Memory.DataSize mms.start_file_address = memory_decriptor.Memory.Rva ...
memory_descriptor: MINIDUMP_MEMORY_DESCRIPTOR buff: file_handle
def obfn_dfd(self): r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m \mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2` """ Ef = self.eval_Rf(self.Xf) E = sl.irfftn(Ef, self.cri.Nv, self.cri.axisN) return (np.linalg.norm(self.W * E)**2) / 2.0
r"""Compute data fidelity term :math:`(1/2) \sum_k \| W (\sum_m \mathbf{d}_m * \mathbf{x}_{k,m} - \mathbf{s}_k) \|_2^2`
def create_argparser(): """Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values. """ parser = argparse.ArgumentParser() arg_defaults = { "daemon": False, "loop": False, "listpresets": False, "config": None, "debug": Fa...
Instantiate an `argparse.ArgumentParser`. Adds all basic cli options including default values.
def get_block_info(self): """ Get the retrieved block information. Return [(height, [txs])] on success, ordered on height Raise if not finished downloading """ if not self.finished: raise Exception("Not finished downloading") ret = [] for (blo...
Get the retrieved block information. Return [(height, [txs])] on success, ordered on height Raise if not finished downloading
def request_forward_agent(self, handler): """ Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param function handler: a required handler to use for incoming SSH Agent connections :return: True if we are ok, else...
Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from OpenSSH !!! :param function handler: a required handler to use for incoming SSH Agent connections :return: True if we are ok, else False (at that time we always return ok) :raises: SS...
def guest_delete_disks(self, userid, disk_vdev_list): """Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102'] """ action = "de...
Delete disks from an existing guest vm. :param userid: (str) the userid of the vm to be deleted :param disk_vdev_list: (list) the vdev list of disks to be deleted, for example: ['0101', '0102']
def _extensions(self, line): """ Extract the extension from the given line. :param line: The line from the official public suffix repository. :type line: str """ # We strip the parsed line. line = line.strip() if not line.startswith("//") and "." in lin...
Extract the extension from the given line. :param line: The line from the official public suffix repository. :type line: str
def _set_request_referer_metric(self, request): """ Add metric 'request_referer' for http referer. """ if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']: monitoring.set_custom_metric('request_referer', request.META['HTTP_REFERER'])
Add metric 'request_referer' for http referer.
def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']: """ Get an effect class by the class name Args: effect_name (str): Name of the effect class Keyword Args: package_name (str): The package the effect belongs to. This is opt...
Get an effect class by the class name Args: effect_name (str): Name of the effect class Keyword Args: package_name (str): The package the effect belongs to. This is optional and only needed when effect class names are not unique. Returns...
def open_required(func): """ Use this decorator to raise an error if the project is not opened """ def wrapper(self, *args, **kwargs): if self._status == "closed": raise aiohttp.web.HTTPForbidden(text="The project is not opened") return func(self, *args, **kwargs) return...
Use this decorator to raise an error if the project is not opened
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names): """ Convert upsample_bilinear2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs ...
Convert upsample_bilinear2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short n...
def hoverEnterEvent(self, event): """ Processes when this hotspot is entered. :param event | <QHoverEvent> :return <bool> | processed """ self._hovered = True if self.toolTip(): QToolTip.showText(QCursor.pos(), self...
Processes when this hotspot is entered. :param event | <QHoverEvent> :return <bool> | processed
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs): """ Given some coefficients, return a the derivative of a B-spline. """ return cls._basis_spline_factory(coef, degree, knots, 1, ext)
Given some coefficients, return a the derivative of a B-spline.
def voltage_delta_vde(v_nom, s_max, r, x, cos_phi): """ Estimate voltrage drop/increase The VDE [#]_ proposes a simplified method to estimate voltage drop or increase in radial grids. Parameters ---------- v_nom : int Nominal voltage s_max : float Apparent power r :...
Estimate voltrage drop/increase The VDE [#]_ proposes a simplified method to estimate voltage drop or increase in radial grids. Parameters ---------- v_nom : int Nominal voltage s_max : float Apparent power r : float Short-circuit resistance from node to HV/MV subst...
def open(filename, mode="r", iline = 189, xline = 193, strict = True, ignore_geometry = False, endian = 'big'): """Open a segy file. Opens a segy file and tries to figure out its sorting, inline ...
Open a segy file. Opens a segy file and tries to figure out its sorting, inline numbers, crossline numbers, and offsets, and enables reading and writing to this file in a simple manner. For reading, the access mode `r` is preferred. All write operations will raise an exception. For writing, the mo...
def _unmount_devicemapper(self, cid): """ Devicemapper unmount backend. """ mountpoint = self.mountpoint Mount.unmount_path(mountpoint) cinfo = self.client.inspect_container(cid) dev_name = cinfo['GraphDriver']['Data']['DeviceName'] Mount.remove_thin_dev...
Devicemapper unmount backend.
def text_ui(self): """ Start Text UI main loop """ self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
Start Text UI main loop
def _get_name(self, name): """ Find a team's name and abbreviation. Given the team's HTML name tag, determine their name, abbreviation, and whether or not they compete in Division-I. Parameters ---------- name : PyQuery object A PyQuery object of a t...
Find a team's name and abbreviation. Given the team's HTML name tag, determine their name, abbreviation, and whether or not they compete in Division-I. Parameters ---------- name : PyQuery object A PyQuery object of a team's HTML name tag in the boxscore. R...
def save_code(self, title, addr, _bytes): """ Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes """ self.standard_bytes_header(title, addr, len(_bytes)) _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates...
Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes
def nvmlDeviceGetCurrPcieLinkWidth(handle): r""" /** * Retrieves the current PCIe link width * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param currLinkWidth Refere...
r""" /** * Retrieves the current PCIe link width * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param currLinkWidth Reference in which to return the current PCIe link gen...
def image(self, well_row, well_column, field_row, field_column): """Get path of specified image. Parameters ---------- well_row : int Starts at 0. Same as --U in files. well_column : int Starts at 0. Same as --V in files. field_row : int ...
Get path of specified image. Parameters ---------- well_row : int Starts at 0. Same as --U in files. well_column : int Starts at 0. Same as --V in files. field_row : int Starts at 0. Same as --Y in files. field_column : int ...
def modified_Wilson_Vc(zs, Vcs, Aijs): r'''Calculates critical volume of a mixture according to mixing rules in [1]_ with parameters. Equation .. math:: V_{cm} = \sum_i x_i V_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)V_{ref} For a binary mxiture, this simplifies to: .. ma...
r'''Calculates critical volume of a mixture according to mixing rules in [1]_ with parameters. Equation .. math:: V_{cm} = \sum_i x_i V_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)V_{ref} For a binary mxiture, this simplifies to: .. math:: V_{cm} = x_1 V_{c1} + x_2 V_{c...
def __startOpenThread(self): """start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack """ print 'call startOpenThread' try: if self.hasActiveDatasetToCommit: ...
start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack
def _close_stdout_stderr_streams(self): """Close output-capturing stuff. This also flushes anything left in the buffers. """ # we don't have tee_file's in headless mode if self._stdout_tee.tee_file is not None: self._stdout_tee.tee_file.close() if self._stder...
Close output-capturing stuff. This also flushes anything left in the buffers.
def expected_log_joint_probability(self): """ Compute E_{q(z) q(x)} [log p(z) + log p(x | z) + log p(y | x, z)] """ # E_{q(z)}[log p(z)] from pyslds.util import expected_hmm_logprob elp = expected_hmm_logprob( self.pi_0, self.trans_matrix, (self.ex...
Compute E_{q(z) q(x)} [log p(z) + log p(x | z) + log p(y | x, z)]
def _run_configure_script(self, script): """Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails """ ...
Run the script to install the Juju agent on the target machine. :param str script: The script returned by the ProvisioningScript API :raises: :class:`paramiko.ssh_exception.AuthenticationException` if the upload fails
def run(suite, stream, args, testing=False): """ Run the given test case or test suite with the specified arguments. Any args.stream passed in will be wrapped in a GreenStream """ if not issubclass(GreenStream, type(stream)): stream = GreenStream(stream, disable_windows=args.disable_windows...
Run the given test case or test suite with the specified arguments. Any args.stream passed in will be wrapped in a GreenStream
def data(self, data, part=False, dataset=''): """ Parameters ---------- data : `PIL.Image` Image to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: ''). ...
Parameters ---------- data : `PIL.Image` Image to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: '').
def get_object(self, subject=None, predicate=None): """Eliminates some of the glue code for searching RDF. Pass in a URIRef object (generated by the `uri` function above or a BNode object (returned by this function) for either of the parameters.""" # Get the result of the search...
Eliminates some of the glue code for searching RDF. Pass in a URIRef object (generated by the `uri` function above or a BNode object (returned by this function) for either of the parameters.
def gcs_get_url(url, altexts=None, client=None, service_account_json=None, raiseonfail=False): """This gets a single file from a Google Cloud Storage bucket. This uses the gs:// URL instead of a bucket name and key. Parameters ---------- ...
This gets a single file from a Google Cloud Storage bucket. This uses the gs:// URL instead of a bucket name and key. Parameters ---------- url : str GCS URL to download. This should begin with 'gs://'. altexts : None or list of str If not None, this is a list of alternate extens...
def prime(self): """ Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties} """ for d in self.definitions.values(): self.defined[d.name] = d.default return self
Prime the stored values based on default values found in property definitions. @return: self @rtype: L{Properties}
def _verify_inputs(inputs, channel_index, data_format): """Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If th...
Verifies `inputs` is semantically correct. Args: inputs: An input tensor provided by the user. channel_index: The index of the channel dimension. data_format: The format of the data in `inputs`. Raises: base.IncompatibleShapeError: If the shape of `inputs` doesn't match `data_format`. ba...
async def get_protocol_version(self): """ This method retrieves the Firmata protocol version. JSON command: {"method": "get_protocol_version", "params": ["null"]} :returns: {"method": "protocol_version_reply", "params": [PROTOCOL_VERSION]} """ value = await self.core.ge...
This method retrieves the Firmata protocol version. JSON command: {"method": "get_protocol_version", "params": ["null"]} :returns: {"method": "protocol_version_reply", "params": [PROTOCOL_VERSION]}
def fixed_inputs(model, non_fixed_inputs, fix_routine='median', as_list=True, X_all=False): """ Convenience function for returning back fixed_inputs where the other inputs are fixed using fix_routine :param model: model :type model: Model :param non_fixed_inputs: dimensions of non fixed inputs ...
Convenience function for returning back fixed_inputs where the other inputs are fixed using fix_routine :param model: model :type model: Model :param non_fixed_inputs: dimensions of non fixed inputs :type non_fixed_inputs: list :param fix_routine: fixing routine to use, 'mean', 'median', 'zero' ...
def refreshButtons(self): """ Refreshes the buttons for building this sql query. """ last = self._last first = self._first joiner = self._containerWidget.currentJoiner() # the first button set can contain the toggle options if f...
Refreshes the buttons for building this sql query.
def display(self): """ Get screen width and height """ w, h = self.session.window_size() return Display(w*self.scale, h*self.scale)
Get screen width and height
def expQt(self, t): ''' Parameters ---------- t : float Time to propagate Returns -------- expQt : numpy.array Matrix exponential of exo(Qt) ''' eLambdaT = np.diag(self._exp_lt(t)) # vector length = a Qs = self....
Parameters ---------- t : float Time to propagate Returns -------- expQt : numpy.array Matrix exponential of exo(Qt)
def codigo_ibge_uf(sigla): """Retorna o código do IBGE para a UF informada.""" idx = [s for s, i, n, r in UNIDADES_FEDERACAO].index(sigla) return UNIDADES_FEDERACAO[idx][_UF_CODIGO_IBGE]
Retorna o código do IBGE para a UF informada.
def ColorLuminance(color): """Compute the brightness of an sRGB color using the formula from http://www.w3.org/TR/2000/WD-AERT-20000426#color-contrast. Args: color: a string of 6 hex digits in the format verified by IsValidHexColor(). Returns: A floating-point number between 0.0 (black) and 255.0 (whi...
Compute the brightness of an sRGB color using the formula from http://www.w3.org/TR/2000/WD-AERT-20000426#color-contrast. Args: color: a string of 6 hex digits in the format verified by IsValidHexColor(). Returns: A floating-point number between 0.0 (black) and 255.0 (white).
def entity_to_protobuf(entity): """Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity. """ entity_pb = ent...
Converts an entity into a protobuf. :type entity: :class:`google.cloud.datastore.entity.Entity` :param entity: The entity to be turned into a protobuf. :rtype: :class:`.entity_pb2.Entity` :returns: The protobuf representing the entity.
def connect(self, factory): """Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will ...
Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will then store the protocol under a...
def error_redirect(self, errormsg='', errorlog=''): ''' Shortcut for redirecting Django view to LTI Consumer with errors ''' from django.shortcuts import redirect self.lti_errormsg = errormsg self.lti_errorlog = errorlog return redirect(self.build_return_url())
Shortcut for redirecting Django view to LTI Consumer with errors
def add_eval(self, agent, e, fr=None): """Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluat...
Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation.
def XYZ_to_galcenrect(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True): """ NAME: XYZ_to_galcenrect PURPOSE: transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates INPUT: X - X Y - Y Z - Z Xsun - cylindrical distance to the GC ...
NAME: XYZ_to_galcenrect PURPOSE: transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates INPUT: X - X Y - Y Z - Z Xsun - cylindrical distance to the GC Zsun - Sun's height above the midplane _extra_rot= (True) if True...
def value_splitter(self, reference, prop, value, mode): """ Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property n...
Split a string into a list items. Default behavior is to split on white spaces. Arguments: reference (string): Reference name used when raising possible error. prop (string): Property name used when raising possible error. value (string): Property v...
def t_string_NGRAPH(t): r"\\[ '.:][ '.:]" global __STRING P = {' ': 0, "'": 2, '.': 8, ':': 10} N = {' ': 0, "'": 1, '.': 4, ':': 5} __STRING += chr(128 + P[t.value[1]] + N[t.value[2]])
r"\\[ '.:][ '.:]
def writeImageToFile(self, filename, _format="PNG"): ''' Write the View image to the specified filename in the specified format. @type filename: str @param filename: Absolute path and optional filename receiving the image. If this points to a directory, then the...
Write the View image to the specified filename in the specified format. @type filename: str @param filename: Absolute path and optional filename receiving the image. If this points to a directory, then the filename is determined by this View unique ID and ...
def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': self._player_num += 1 elif playe...
Compute number of players, both human and computer.
def _iter_path_collection(paths, path_transforms, offsets, styles): """Build an iterator over the elements of the path collection""" N = max(len(paths), len(offsets)) if not path_transforms: path_transforms = [np.eye(3)] edgecolor = styles['edgecolor'] if np.size(ed...
Build an iterator over the elements of the path collection
def ecn(ns=None, cn=None, di=None): # pylint: disable=redefined-outer-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.EnumerateClassNames`. Enumerate the names of subclasses of a class, or of the top-level classes in a namespace. Parameters: ns (:term:`string`)...
This function is a wrapper for :meth:`~pywbem.WBEMConnection.EnumerateClassNames`. Enumerate the names of subclasses of a class, or of the top-level classes in a namespace. Parameters: ns (:term:`string`): Name of the CIM namespace to be used (case independent). If `None`, ...
def index(self, index, doc_type, body, id=None, **query_params): """ Adds or updates a typed JSON document in a specific index, making it searchable. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :param index: The name of the index :param d...
Adds or updates a typed JSON document in a specific index, making it searchable. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`_ :param index: The name of the index :param doc_type: The type of the document :param body: The document :param id...
def encrypted_gradient(self, sum_to=None): """Compute and encrypt gradient. When `sum_to` is given, sum the encrypted gradient to it, assumed to be another vector of the same size """ gradient = self.compute_gradient() encrypted_gradient = encrypt_vector(self.pubkey, gra...
Compute and encrypt gradient. When `sum_to` is given, sum the encrypted gradient to it, assumed to be another vector of the same size
def validate(self, ip, **kwargs): """Check to see if this is a valid ip address.""" if ip is None: return False ip = stringify(ip) if self.IPV4_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET, ip) return True ...
Check to see if this is a valid ip address.
def decorate_with_checker(func: CallableT) -> CallableT: """Decorate the function with a checker that verifies the preconditions and postconditions.""" assert not hasattr(func, "__preconditions__"), \ "Expected func to have no list of preconditions (there should be only a single contract checker per fun...
Decorate the function with a checker that verifies the preconditions and postconditions.
def changeSubMenu(self,submenu): """ Changes the submenu that is displayed. :raises ValueError: if the name was not previously registered """ if submenu not in self.submenus: raise ValueError("Submenu %s does not exist!"%submenu) elif submenu == self....
Changes the submenu that is displayed. :raises ValueError: if the name was not previously registered
def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the ...
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoi...
def add(path=None, force=False, quiet=False): """Add that path to git's staging area (default current dir) so that it will be included in next commit """ option = '-f' if force else '' return run('add %s %s' % (option, path) or '.', quiet=quiet)
Add that path to git's staging area (default current dir) so that it will be included in next commit
def algorithm(G, method_name, **kwargs): """ Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the :class:`.GraphCollection` ``G``. For options, see the `list of algorithms <http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_...
Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the :class:`.GraphCollection` ``G``. For options, see the `list of algorithms <http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_ in the NetworkX documentation. Not all of these ...
def expect(self, searcher, timeout=3): """Wait for input matching *searcher* Waits for input matching *searcher* for up to *timeout* seconds. If a match is found, the match result is returned (the specific type of returned result depends on the :class:`Searcher` type). If no match is ...
Wait for input matching *searcher* Waits for input matching *searcher* for up to *timeout* seconds. If a match is found, the match result is returned (the specific type of returned result depends on the :class:`Searcher` type). If no match is found within *timeout* seconds, raise an :cl...
def build_structure(self, check_name, groups, source_name, limit=1): ''' Compiles the checks, results and scores into an aggregate structure which looks like: { "scored_points": 396, "low_count": 0, "possible_points": 400, "testname": ...
Compiles the checks, results and scores into an aggregate structure which looks like: { "scored_points": 396, "low_count": 0, "possible_points": 400, "testname": "gliderdac", "medium_count": 2, "source_name": ".//rutgers/ru...
def delete_collection_namespaced_replica_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, p...
delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_replica_set(namesp...
def make_bcbiornaseq_object(data): """ load the initial bcb.rda object using bcbioRNASeq """ if "bcbiornaseq" not in dd.get_tools_on(data): return data upload_dir = tz.get_in(("upload", "dir"), data) report_dir = os.path.join(upload_dir, "bcbioRNASeq") safe_makedir(report_dir) or...
load the initial bcb.rda object using bcbioRNASeq
def rollback(self, label=None, plane='sdr'): """Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or Non...
Rollback the configuration. This method rolls back the configuration on the device. Args: label (text): The configuration label ID plane: (text): sdr or admin Returns: A string with commit label or None
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
Redirect to the latest version of a resource given its identifier.
def submission_storage_path(instance, filename): """ Function DocString """ string = '/'.join(['submissions', instance.submission_user.user_nick, str(instance.submission_question.question_level), str(instance.submission_question.question_level_id)]) string += '/'+datetime.datetime.now().strftime...
Function DocString
def items(self): """ Generator that iterates through the items of the value mapping. The items are the array entries of the `Values` and `ValueMap` qualifiers, and they are iterated in the order specified in the arrays. If the `ValueMap` qualifier is not specified, the default of...
Generator that iterates through the items of the value mapping. The items are the array entries of the `Values` and `ValueMap` qualifiers, and they are iterated in the order specified in the arrays. If the `ValueMap` qualifier is not specified, the default of consecutive integers startin...
def save(self, logmessage=None): """Save datastream content and any changed datastream profile information to Fedora. :rtype: boolean for success """ if self.as_of_date is not None: raise RuntimeError('Saving is not implemented for datastream versions') save...
Save datastream content and any changed datastream profile information to Fedora. :rtype: boolean for success
def member_add(self, cluster_id, params): """add new member into configuration""" cluster = self._storage[cluster_id] result = cluster.member_add(params.get('id', None), params.get('shardParams', {})) self._storage[cluster_id] = cluster return result
add new member into configuration
def find_field(self, field=None, alias=None): """ Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: ...
Finds a field by name or alias. :param field: string of the field name or alias, dict of {'alias': field}, or a Field instance :type field: str or dict or Field :returns: The field if it is found, otherwise None :rtype: :class:`Field <querybuilder.fields.Field>` or None
def _array_slice(array, index): """Slice or index `array` at `index`. Parameters ---------- index : int or ibis.expr.types.IntegerValue or slice Returns ------- sliced_array : ibis.expr.types.ValueExpr If `index` is an ``int`` or :class:`~ibis.expr.types.IntegerValue` then ...
Slice or index `array` at `index`. Parameters ---------- index : int or ibis.expr.types.IntegerValue or slice Returns ------- sliced_array : ibis.expr.types.ValueExpr If `index` is an ``int`` or :class:`~ibis.expr.types.IntegerValue` then the return type is the element type of ...
def cxxRecordDecl(*args): """Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... ...
Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X
def get(package_name, pypi_server="https://pypi.python.org/pypi/"): """ Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> ...
Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> package = yarg.get('yarg') <Package yarg>
def handle_sap(q): question_votes = votes = Answer.objects.filter(question=q) users = q.get_users_voted() num_users_votes = {u.id: votes.filter(user=u).count() for u in users} user_scale = {u.id: (1 / num_users_votes[u.id]) for u in users} choices = [] for c in q.choice_set.all().order_by("num")...
Clear vote
def get_available_ip6(self, id_network6): """ Get a available IP in Network ipv6 :param id_network6: Network ipv6 identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip6': {'ip6': < available_ip6 >}} :ra...
Get a available IP in Network ipv6 :param id_network6: Network ipv6 identifier. Integer value and greater than zero. :return: Dictionary with the following structure: :: {'ip6': {'ip6': < available_ip6 >}} :raise IpNotAvailableError: Network dont have available IP. ...
def hasx(self, name, *args): """ Returns true if named parameter(s) was specified on command line """ return lib.zargs_hasx(self._as_parameter_, name, *args)
Returns true if named parameter(s) was specified on command line
def Put(self, key, obj): """Add the object to the cache.""" # Remove the old entry if it is there. node = self._hash.pop(key, None) if node: self._age.Unlink(node) # Make a new node and insert it. node = Node(key=key, data=obj) self._hash[key] = node self._age.AppendNode(node) ...
Add the object to the cache.
def create_socketpair(size=None): """ Create a :func:`socket.socketpair` to use for use as a child process's UNIX stdio channels. As socket pairs are bidirectional, they are economical on file descriptor usage as the same descriptor can be used for ``stdin`` and ``stdout``. As they are sockets their...
Create a :func:`socket.socketpair` to use for use as a child process's UNIX stdio channels. As socket pairs are bidirectional, they are economical on file descriptor usage as the same descriptor can be used for ``stdin`` and ``stdout``. As they are sockets their buffers are tunable, allowing large buffe...
def by_name(cls, session, name, **kwargs): """ Get a classifier from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the classifier :type name: `unicode :return: classifier instance :rtype...
Get a classifier from a given name. :param session: SQLAlchemy session :type session: :class:`sqlalchemy.Session` :param name: name of the classifier :type name: `unicode :return: classifier instance :rtype: :class:`pyshop.models.Classifier`
def get_point( self, x: float = 0, y: float = 0, z: float = 0, w: float = 0 ) -> float: """Return the noise value at the (x, y, z, w) point. Args: x (float): The position on the 1st axis. y (float): The position on the 2nd axis. z (float): The position on...
Return the noise value at the (x, y, z, w) point. Args: x (float): The position on the 1st axis. y (float): The position on the 2nd axis. z (float): The position on the 3rd axis. w (float): The position on the 4th axis.
def _ReadIntegerDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an integer data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str...
Reads an integer data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the data ty...
def transformer_tall_pretrain_lm(): """Hparams for transformer on LM pretraining (with 64k vocab).""" hparams = transformer_tall() hparams.learning_rate_constant = 2e-4 hparams.learning_rate_schedule = ("linear_warmup*constant*cosdecay") hparams.optimizer = "adam_w" hparams.optimizer_adam_beta1 = 0.9 hpar...
Hparams for transformer on LM pretraining (with 64k vocab).
def set_topic_attributes(TopicArn, AttributeName, AttributeValue, region=None, key=None, keyid=None, profile=None): ''' Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue ''' ...
Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue
def get_title(self): """ Return the string literal that is used in the template. The title is used in the admin screens. """ try: return extract_literal(self.meta_kwargs['title']) except KeyError: slot = self.get_slot() if slot is not N...
Return the string literal that is used in the template. The title is used in the admin screens.
def counter(self, ch, part=None): """Return a counter on the channel ch. ch: string or integer. The channel index number or channel name. part: int or None The 0-based enumeration of a True part to return. This has an effect whether or not the mask or filter...
Return a counter on the channel ch. ch: string or integer. The channel index number or channel name. part: int or None The 0-based enumeration of a True part to return. This has an effect whether or not the mask or filter is turned on. Raise IndexError i...
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb): u''' Enable or disable SSL logging :param True | False enable: Enable or disable SSL logging :param func: Callback function for logging ''' if enable: SSL_CTX_set_info_callback(self._ctx, func) el...
u''' Enable or disable SSL logging :param True | False enable: Enable or disable SSL logging :param func: Callback function for logging
def create_sslcert(self, name, common_name, pri, ca): """ 修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11 Args: name: 证书名称 common_name: 相关域名 pri: 证书私钥 ca: 证书内容 Returns: 返回一个tuple对象,其格式...
修改证书,文档 https://developer.qiniu.com/fusion/api/4246/the-domain-name#11 Args: name: 证书名称 common_name: 相关域名 pri: 证书私钥 ca: 证书内容 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回dict{certID:...