positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _register_elements(self, elements): """ Takes elements from the metadata class and creates a base model for all backend models . """ self.elements = elements for key, obj in elements.items(): obj.contribute_to_class(self.metadata, key) # Create the common Django...
Takes elements from the metadata class and creates a base model for all backend models .
def generate_user_controller_access_token(username, controller_endpoints, secret_key, controller_name): """" Implement in python what is currently done in GO https://github.com/juju/juju/blob/a5ab92ec9b7f5da3678d9ac603fe52d45af24412/cmd/juju/user/utils.go#L16 :param username: name of the user to register ...
Implement in python what is currently done in GO https://github.com/juju/juju/blob/a5ab92ec9b7f5da3678d9ac603fe52d45af24412/cmd/juju/user/utils.go#L16 :param username: name of the user to register :param controller_endpoints: juju controller endpoints list in the format <ip>:<port> :param secret_key: b...
def resolve_filenames(all_expr): """resolve expression for a filename :param all_expr: A comma separated list of expressions. The expressions can contain the wildcard characters ``*`` and ``?``. It also resolves Spark datasets to the paths of the individual partition...
resolve expression for a filename :param all_expr: A comma separated list of expressions. The expressions can contain the wildcard characters ``*`` and ``?``. It also resolves Spark datasets to the paths of the individual partitions (i.e. ``my_data`` gets resolve...
def _toSparkGLM(self, model): """ Private method for converting a GLM to a Spark model TODO: Add model parameters as well. """ skl_cls = type(model) py_cls = self._skl2spark_classes[skl_cls].py jvm_cls_name = self._skl2spark_classes[skl_cls].jvm intercept = model....
Private method for converting a GLM to a Spark model TODO: Add model parameters as well.
def parse_args(args=None): """Parse arguments from sys.argv""" parser = argparse.ArgumentParser() parser.add_argument( '-w', '--window', default="pyqt5", choices=find_window_classes(), help='Name for the window type to use', ) parser.add_argument( ...
Parse arguments from sys.argv
def scan(self, scanner, node_list): """Scan a list of this Executor's files (targets or sources) for implicit dependencies and update all of the targets with them. This essentially short-circuits an N*M scan of the sources for each individual target, which is a hell of a lot more efficie...
Scan a list of this Executor's files (targets or sources) for implicit dependencies and update all of the targets with them. This essentially short-circuits an N*M scan of the sources for each individual target, which is a hell of a lot more efficient.
def _fill_gaps(tr): """ Interpolate through gaps and work-out where gaps are. :param tr: Gappy trace (e.g. tr.data is np.ma.MaskedArray) :type tr: `obspy.core.stream.Trace` :return: gaps, trace, where gaps is a list of dict """ tr = tr.split() gaps = tr.get_gaps() tr = tr.detrend()...
Interpolate through gaps and work-out where gaps are. :param tr: Gappy trace (e.g. tr.data is np.ma.MaskedArray) :type tr: `obspy.core.stream.Trace` :return: gaps, trace, where gaps is a list of dict
def parse(self, fo): """ Convert HMS output to motifs Parameters ---------- fo : file-like File object containing HMS output. Returns ------- motifs : list List of Motif instances. """ motifs = [] m...
Convert HMS output to motifs Parameters ---------- fo : file-like File object containing HMS output. Returns ------- motifs : list List of Motif instances.
def _is_qstring(message): """Check if its a QString without adding any dep to PyQt5.""" my_class = str(message.__class__) my_class_name = my_class.replace('<class \'', '').replace('\'>', '') if my_class_name == 'PyQt5.QtCore.QString': return True return False
Check if its a QString without adding any dep to PyQt5.
def replicate_filter(sources, model, cache=None): '''Replicates the list of objects to other class and returns their reflections''' targets = [replicate_no_merge(source, model, cache=cache) for source in sources] # Some objects may not be available in target DB (not published), so we ...
Replicates the list of objects to other class and returns their reflections
def get_sequence_time(cycles, unit_converter=None, eres=None): """ Calculates the time the move sequence will take to complete. Calculates the amount of time it will take to complete the given move sequence. Types of motion supported are moves from one position to another (the motion will always come t...
Calculates the time the move sequence will take to complete. Calculates the amount of time it will take to complete the given move sequence. Types of motion supported are moves from one position to another (the motion will always come to a stop before doing the next motion), waiting a given interval of...
def _variogram_residuals(params, x, y, variogram_function, weight): """Function used in variogram model estimation. Returns residuals between calculated variogram and actual data (lags/semivariance). Called by _calculate_variogram_model. Parameters ---------- params: list or 1D array pa...
Function used in variogram model estimation. Returns residuals between calculated variogram and actual data (lags/semivariance). Called by _calculate_variogram_model. Parameters ---------- params: list or 1D array parameters for calculating the model variogram x: ndarray lags (d...
def make_table(self): """Make numpy array from timeseries data.""" num_records = int(np.sum([1 for frame in self.timeseries])) dtype = [ ("frame",float),("time",float),("proteinring",list), ("ligand_ring_ids",list),("distance",float),("angle",float), ...
Make numpy array from timeseries data.
def ep_style_location_string(self): """Return EnergyPlus's location string.""" return "Site:Location,\n " + \ self.city + ',\n ' + \ str(self.latitude) + ', !Latitude\n ' + \ str(self.longitude) + ', !Longitude\n ' + \ str(self.time_zone) + ',...
Return EnergyPlus's location string.
def in_8(library, session, space, offset, extended=False): """Reads in an 8-bit value from the specified memory space and offset. Corresponds to viIn8* function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param s...
Reads in an 8-bit value from the specified memory space and offset. Corresponds to viIn8* function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param space: Specifies the address space. (Constants.*SPACE*) :param ...
def service(name, action): """ Open/close access to a service :param name: could be a service name defined in `/etc/services` or a port number. :param action: `open` or `close` """ if action == 'open': subprocess.check_output(['ufw', 'allow', str(name)], ...
Open/close access to a service :param name: could be a service name defined in `/etc/services` or a port number. :param action: `open` or `close`
def get_rate(self, code): """ Helper function to access the rates structure Returns a dict containing name, price, symbol (the code), timestamp, type, utctime & volume """ rateslist = self.rates['list']['resources'] for rate in rateslist: rateobj = rate['resou...
Helper function to access the rates structure Returns a dict containing name, price, symbol (the code), timestamp, type, utctime & volume
def unsubscribe(self, channel): """ Remove the channel from this socket's channels, and from the list of subscribed session IDs for the channel. Return False if not subscribed, otherwise True. """ try: CHANNELS[channel].remove(self.socket.session.session_id) ...
Remove the channel from this socket's channels, and from the list of subscribed session IDs for the channel. Return False if not subscribed, otherwise True.
def _move_begin_to_cxn(self, shape, cxn_pt_idx): """ Move the begin point of this connector to coordinates of the connection point of *shape* specified by *cxn_pt_idx*. """ x, y, cx, cy = shape.left, shape.top, shape.width, shape.height self.begin_x, self.begin_y = { ...
Move the begin point of this connector to coordinates of the connection point of *shape* specified by *cxn_pt_idx*.
def _table_arg_to_table_ref(value, default_project=None): """Helper to convert a string or Table to TableReference. This function keeps TableReference and other kinds of objects unchanged. """ if isinstance(value, six.string_types): value = TableReference.from_string(value, default_project=defa...
Helper to convert a string or Table to TableReference. This function keeps TableReference and other kinds of objects unchanged.
def in_words_float(amount, _gender=FEMALE): """ Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative """ check_positive(amount) pts = []...
Float in words @param amount: float numeral @type amount: C{float} or C{Decimal} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise ValueError: when ammount is negative
def index(self, element: Element) -> int: """ Return the index in the array of the first item whose value is element. It is an error if there is no such item. >>> element = String('hello') >>> array = Array(content=[element]) >>> array.index(element) 0 ""...
Return the index in the array of the first item whose value is element. It is an error if there is no such item. >>> element = String('hello') >>> array = Array(content=[element]) >>> array.index(element) 0
def _flattenComponent(glyphSet, component): """Returns a list of tuples (baseGlyph, transform) of nested component.""" glyph = glyphSet[component.baseGlyph] if not glyph.components: transformation = Transform(*component.transformation) return [(component.baseGlyph, transformation)] all...
Returns a list of tuples (baseGlyph, transform) of nested component.
def get_bar(self, code, time): """ 获取一个bar的数据 返回一个series 如果不存在,raise ValueError """ try: return self.data.loc[(pd.Timestamp(time), code)] except: raise ValueError( 'DATASTRUCT CURRENTLY CANNOT FIND THIS BAR WITH {} {}'.forma...
获取一个bar的数据 返回一个series 如果不存在,raise ValueError
def _expand_files(self, file_name, original_path, indent=""): """This recursive function accepts a file name, opens the file and then spools the contents of the file into a list, examining each line as it does so. If it detects a line beginning with "+include", it assumes the string imm...
This recursive function accepts a file name, opens the file and then spools the contents of the file into a list, examining each line as it does so. If it detects a line beginning with "+include", it assumes the string immediately following is a file name. Recursing, the file new file ...
def distribution_to_markdown(distribution): """Genera texto en markdown a partir de los metadatos de una `distribution`. Args: distribution (dict): Diccionario con metadatos de una `distribution`. Returns: str: Texto que describe una `distribution`. """ text_template = ...
Genera texto en markdown a partir de los metadatos de una `distribution`. Args: distribution (dict): Diccionario con metadatos de una `distribution`. Returns: str: Texto que describe una `distribution`.
def export_saved_model(self, sess, export_dir, tag_set, signatures): """Convenience function to access ``TFNode.export_saved_model`` directly from this object instance.""" TFNode.export_saved_model(sess, export_dir, tag_set, signatures)
Convenience function to access ``TFNode.export_saved_model`` directly from this object instance.
def get_sds_by_name(self,name): """ Get ScaleIO SDS object by its name :param name: Name of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified name found :rtype: SDS object """ for sds in self.sds: if sds.name == name: ...
Get ScaleIO SDS object by its name :param name: Name of SDS :return: ScaleIO SDS object :raise KeyError: No SDS with specified name found :rtype: SDS object
def show_firmware_version_output_show_firmware_version_control_processor_chipset(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_firmware_version = ET.Element("show_firmware_version") config = show_firmware_version output = ET.SubElement(sho...
Auto Generated Code
def fix_aspect(fig, nrows, ncols, title=None, extra_artists=[], vspace=0.2, hspace=0.2): """ Calculate heights and widths of axes and adjust the size of the figure to match the aspect. """ fig.canvas.draw() w, h = fig.get_size_inches() # Compute maximum height and width of ea...
Calculate heights and widths of axes and adjust the size of the figure to match the aspect.
def lookup_casstype(casstype): """ Given a Cassandra type as a string (possibly including parameters), hand back the CassandraType class responsible for it. If a name is not recognized, a custom _UnrecognizedType subclass will be created for it. Example: >>> lookup_casstype('org.apache.cas...
Given a Cassandra type as a string (possibly including parameters), hand back the CassandraType class responsible for it. If a name is not recognized, a custom _UnrecognizedType subclass will be created for it. Example: >>> lookup_casstype('org.apache.cassandra.db.marshal.MapType(org.apache.cassan...
def get_validated_type(object_type: Type[Any], name: str, enforce_not_joker: bool = True) -> Type[Any]: """ Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or ac...
Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or accepted 'as is' :param object_type: the type to validate :param name: a name used in exceptions if any :...
def collision_rate(Temperature, element, isotope): r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and ta...
r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and taking the cross section of the collision to be ...
def extract_tree(self, labels, without, suppress_unifurcations=True): '''Helper function for ``extract_tree_*`` functions''' if not isinstance(suppress_unifurcations, bool): raise TypeError("suppress_unifurcations must be a bool") if labels is not None and not isinstance(labels, set)...
Helper function for ``extract_tree_*`` functions
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: _dict['subject'] = self.s...
Return a json dictionary representing this model.
def require_bool(self, key: str) -> bool: """ Returns a configuration value, as a bool, by its given key. If it doesn't exist, or the configuration value is not a legal bool, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's v...
Returns a configuration value, as a bool, by its given key. If it doesn't exist, or the configuration value is not a legal bool, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: bool :raises ConfigMissingError:...
def _summarize_action(self, root_action): """Return a dictionary with various information about this root_action. Note: Scoring assumes that each actor makes the "best" choices in their turn based on the simulation available. """ def is_target_node(node): ret...
Return a dictionary with various information about this root_action. Note: Scoring assumes that each actor makes the "best" choices in their turn based on the simulation available.
def link(self, next_stage): """Link to the given downstream stage *next_stage* by adding its input tube to the list of this stage's output tubes. Return this stage.""" if next_stage is self: raise ValueError('cannot link stage to itself') self._output_tubes.append(next_stage._inp...
Link to the given downstream stage *next_stage* by adding its input tube to the list of this stage's output tubes. Return this stage.
def inserir( self, nome, protegida, descricao, id_ligacao_front, id_ligacao_back, id_equipamento, tipo=None, vlan=None): """Insert new interface for an equipment. :param nome: Interface name. ...
Insert new interface for an equipment. :param nome: Interface name. :param protegida: Indication of protected ('0' or '1'). :param descricao: Interface description. :param id_ligacao_front: Front end link interface identifier. :param id_ligacao_back: Back end link interface iden...
def _utc_to_local(self, data, local_zone="America/Los_Angeles"): """ Adjust index of dataframe according to timezone that is requested by user. Parameters ---------- data : pd.DataFrame() Pandas dataframe of json timeseries response from server. local_zone :...
Adjust index of dataframe according to timezone that is requested by user. Parameters ---------- data : pd.DataFrame() Pandas dataframe of json timeseries response from server. local_zone : str pytz.timezone string of specified local timezone to change i...
def translate_word(word, dictionary=['simplified']): ''' Return the set of translations for a single character or word, if available. ''' if not dictionaries: init() for d in dictionary: if word in dictionaries[d]: return dictionaries[d][word] return None
Return the set of translations for a single character or word, if available.
def list_settings(self): """ Get list of all appropriate settings and their default values. """ result = super().list_settings() result.append((self.SETTING_TREE_FORMATING, {})) result.append((self.SETTING_TREE_STYLE, 'utf8.a')) return result
Get list of all appropriate settings and their default values.
def eps(self): """Print the canvas to a postscript file""" import tkFileDialog,tkMessageBox filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps']) if filename is None: return self.postscript(file=filename)
Print the canvas to a postscript file
def _adjust_datetime(self, sampfrom): """ Adjust date and time fields to reflect user input if possible. Helper function for the `_arrange_fields` of both Record and MultiRecord objects. """ if sampfrom: dt_seconds = sampfrom / self.fs if self.bas...
Adjust date and time fields to reflect user input if possible. Helper function for the `_arrange_fields` of both Record and MultiRecord objects.
def _GenerateAssertion(self): """Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion. """ now = int(time.time()) payload = { 'aud': RpcHelper.TOKEN_ENDPOINT, 'scope': 'https://www.googleapis.com/auth/identityt...
Generates the signed assertion that will be used in the request. Returns: string, signed Json Web Token (JWT) assertion.
def get_url(self, filename, locations, command='curl', shutit_pexpect_child=None, timeout=shutit_global.shutit_global_object.default_timeout, fail_on_empty_before=True, record_command=True, exit_values=None, ...
Handles the getting of a url for you. Example: get_url('somejar.jar', ['ftp://loc.org','http://anotherloc.com/jars']) @param filename: name of the file to download @param locations: list of URLs whence the file can be downloaded @param command: program to use to download ...
def serialize_to_txt(self): """ Serialize this subdomain record to a TXT record. The trailing newline will be omitted """ txtrec = { 'name': self.fqn if self.independent else self.subdomain, 'txt': self.pack_subdomain()[1:] } return blockstack_zon...
Serialize this subdomain record to a TXT record. The trailing newline will be omitted
def write(self, char): """ Display a single character on the display :type char: str or int :param char: Character to display """ char = str(char).lower() self.segments.write(self.font[char])
Display a single character on the display :type char: str or int :param char: Character to display
def MSE(x1, x2=-1): """ Mean squared error - this function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then this shou...
Mean squared error - this function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then this should be the second series **R...
def bin1d(x, bins): """ Place values of a 1-d array into bins and determine counts of values in each bin Parameters ---------- x : array (n, 1), values to bin bins : array (k,1), upper bounds of each bin (monotonic) Returns ------- binIds : array ...
Place values of a 1-d array into bins and determine counts of values in each bin Parameters ---------- x : array (n, 1), values to bin bins : array (k,1), upper bounds of each bin (monotonic) Returns ------- binIds : array 1-d array of integer bin Ids ...
def from_xxx(cls, xxx): """ Create a new Language instance from a LanguageID string :param xxx: LanguageID as string :return: Language instance with instance.xxx() == xxx if xxx is valid else instance of UnknownLanguage """ xxx = str(xxx).lower() if xxx is 'unknow...
Create a new Language instance from a LanguageID string :param xxx: LanguageID as string :return: Language instance with instance.xxx() == xxx if xxx is valid else instance of UnknownLanguage
def draw_pathfinder_trajectory( self, trajectory, color="#ff0000", offset=None, scale=(1, 1), show_dt=False, dt_offset=0.0, **kwargs ): """ Special helper function for drawing trajectories generated by robotpy-pathfinder...
Special helper function for drawing trajectories generated by robotpy-pathfinder :param trajectory: A list of pathfinder segment objects :param offset: If specified, should be x/y tuple to add to the path relative to the robot coordinates ...
def Fierz_to_Bern_chrom(C, dd, parameters): """From Fierz to chromomagnetic Bern basis for Class V. dd should be of the form 'sb', 'ds' etc.""" e = sqrt(4 * pi * parameters['alpha_e']) gs = sqrt(4 * pi * parameters['alpha_s']) if dd == 'sb' or dd == 'db': mq = parameters['m_b'] elif dd =...
From Fierz to chromomagnetic Bern basis for Class V. dd should be of the form 'sb', 'ds' etc.
def _pecl(command, defaults=False): ''' Execute the command passed with pecl ''' cmdline = 'pecl {0}'.format(command) if salt.utils.data.is_true(defaults): cmdline = 'yes ' "''" + ' | ' + cmdline ret = __salt__['cmd.run_all'](cmdline, python_shell=True) if ret['retcode'] == 0: ...
Execute the command passed with pecl
def put(self): """Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ContainerTaskType`: A task type model instance representing the task type just updated. """ return self.manager.put( ...
Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ContainerTaskType`: A task type model instance representing the task type just updated.
def get_dashboard(self, id, **kwargs): """"Retrieve a (v2) dashboard by id. """ resp = self._get_object_by_name(self._DASHBOARD_ENDPOINT_SUFFIX, id, **kwargs) return resp
Retrieve a (v2) dashboard by id.
def status(name, sig=None): ''' Return the status for a service via rest_sample. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionadded:: 2015.8.0 .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) ...
Return the status for a service via rest_sample. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionadded:: 2015.8.0 .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of t...
def dict_merge(o, v): ''' Recursively climbs through dictionaries and merges them together. :param o: The first dictionary :param v: The second dictionary :returns: A dictionary (who would have guessed?) .. note:: Make sure `o` & `v` are indeed dictionaries, ...
Recursively climbs through dictionaries and merges them together. :param o: The first dictionary :param v: The second dictionary :returns: A dictionary (who would have guessed?) .. note:: Make sure `o` & `v` are indeed dictionaries, bad things will happen otherw...
def get_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbrevia...
Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbreviation. Returns ------- t...
def RegisterHelper(cls, resolver_helper): """Registers a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is already set for the corresponding type indicator. """ if resolver_helper.type_i...
Registers a path specification resolver helper. Args: resolver_helper (ResolverHelper): resolver helper. Raises: KeyError: if resolver helper object is already set for the corresponding type indicator.
def sentinel_get_master_ip(master, host=None, port=None, password=None): ''' Get ip for sentinel master .. versionadded: 2016.3.0 CLI Example: .. code-block:: bash salt '*' redis.sentinel_get_master_ip 'mymaster' ''' server = _sconnect(host, port, password) ret = server.senti...
Get ip for sentinel master .. versionadded: 2016.3.0 CLI Example: .. code-block:: bash salt '*' redis.sentinel_get_master_ip 'mymaster'
def set_antialias(self, antialias): """Changes the :ref:`ANTIALIAS` for the font options object. This specifies the type of antialiasing to do when rendering text. """ cairo.cairo_font_options_set_antialias(self._pointer, antialias) self._check_status()
Changes the :ref:`ANTIALIAS` for the font options object. This specifies the type of antialiasing to do when rendering text.
def _reloader_observer(server, app, interval): ''' Start a child process with identical commandline arguments and restart it as long as it exists with status code 3. Also create a lockfile and touch it (update mtime) every interval seconds. ''' fd, lockfile = tempfile.mkstemp(prefix='bottle-...
Start a child process with identical commandline arguments and restart it as long as it exists with status code 3. Also create a lockfile and touch it (update mtime) every interval seconds.
def check_token(token: str) -> bool: """ Validate BOT token :param token: :return: """ if any(x.isspace() for x in token): raise exceptions.ValidationError('Token is invalid!') left, sep, right = token.partition(':') if (not sep) or (not left.isdigit()) or (len(left) < 3): ...
Validate BOT token :param token: :return:
def get_string_plus_property(name, props, default=None): # type: (str, Dict[str, Any], Optional[Any]) -> Any """ Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doe...
Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one
def _sections_to_variance_sections(self, sections_over_time): '''Computes the variance of corresponding sections over time. Returns: a list of np arrays. ''' variance_sections = [] for i in range(len(sections_over_time[0])): time_sections = [sections[i] for sections in sections_over_ti...
Computes the variance of corresponding sections over time. Returns: a list of np arrays.
def data_loader(self, sentences, shuffle=False): """Load, tokenize and prepare the input sentences.""" dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
Load, tokenize and prepare the input sentences.
def get_providers(self, security_filter, name_filter='%', only_providers_flag='Y', internal_external='I', ordering_authority='', real_provider='N'): """ invokes TouchWorksMagicConstants.ACTION_G...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param security_filter - This is the EntryCode of the Security_Code_DE dictionary for the providers being sought. A list of valid security codes can be obtained from GetDictionary on the Security_Code_DE dictio...
def pullPath_copy(self, d_msg, **kwargs): """ Handle the "copy" pull operation """ # Parse "header" information d_meta = d_msg['meta'] d_local = d_meta['local'] str_localPath = d_local['path'] d_remote = d_meta['r...
Handle the "copy" pull operation
def mail_sent_count(self, count): """ Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails """ expected = int(count) actual = len(mail.outbox) assert expected == actual, \ "E...
Test that `count` mails have been sent. Syntax: I have sent `count` emails Example: .. code-block:: gherkin Then I have sent 2 emails
def sort_items(items): """sorts the items into a dictionary of categories, with a list of items""" sorted_items = {} for item in items: category = lookup(item, 'itemCategory', 'categoryCode') if sorted_items.get(category) is None: sorted_items[category] = [] sorted_items...
sorts the items into a dictionary of categories, with a list of items
def iterparse(source, encoding='utf-8'): """ Parse the TDL file *source* and iteratively yield parse events. If *source* is a filename, the file is opened and closed when the generator has finished, otherwise *source* is an open file object and will not be closed when the generator has finished. ...
Parse the TDL file *source* and iteratively yield parse events. If *source* is a filename, the file is opened and closed when the generator has finished, otherwise *source* is an open file object and will not be closed when the generator has finished. Parse events are `(event, object, lineno)` tuples,...
def _compile_vts(self, vts, ctx, upstream_analysis, dependency_classpath, progress_message, settings, compiler_option_sets, zinc_file_manager, counter): """Compiles sources for the given vts into the given output dir. :param vts: VersionedTargetSet with one entry for the target. :param c...
Compiles sources for the given vts into the given output dir. :param vts: VersionedTargetSet with one entry for the target. :param ctx: - A CompileContext instance for the target. :param dependency_classpath: A list of classpath entries of type ClasspathEntry for dependencies May be invoked concurrent...
def _get_lines_from_node_text(cls, node): """ Given an ``lxml`` node, get lines from ``node.text``, where the line separator is ``<br xmlns=... />``. """ # TODO more robust parsing from lxml import etree parts = ([node.text] + list(chain(*([etree.tostring(c, with_...
Given an ``lxml`` node, get lines from ``node.text``, where the line separator is ``<br xmlns=... />``.
def _make_ssh_forward_server(self, remote_address, local_bind_address): """ Make SSH forward proxy Server class """ _Handler = self._make_ssh_forward_handler_class(remote_address) try: if isinstance(local_bind_address, string_types): forward_maker_clas...
Make SSH forward proxy Server class
def load(self, orbit=None): """Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed Note ---- A day of data must be loaded before this routine functions properly. If the last orbit o...
Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed Note ---- A day of data must be loaded before this routine functions properly. If the last orbit of the day is requested, it will automat...
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
Returns a set with each value per config file in it.
def _setup_environ(self): """ Apply changes from /etc/environment files before creating a TemporaryEnvironment to snapshot environment state prior to module run. """ _pam_env_watcher.check() _etc_env_watcher.check() env = dict(self.extra_env or {}) if self...
Apply changes from /etc/environment files before creating a TemporaryEnvironment to snapshot environment state prior to module run.
def delete(name, dry_run, verbose): """Delete a collection.""" collection = Collection.query.filter_by(name=name).one() if verbose: tr = LeftAligned(traverse=AttributeTraversal()) click.secho(tr(collection), fg='red') db.session.delete(collection)
Delete a collection.
def transactions(self) -> TransactionsAggregate: """ Transactions aggregate """ if not self.__transactions_aggregate: self.__transactions_aggregate = TransactionsAggregate(self.book) return self.__transactions_aggregate
Transactions aggregate
def is_std_string(type_): """ Returns True, if type represents C++ `std::string`, False otherwise. """ if utils.is_str(type_): return type_ in string_equivalences type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) return type_.decl_string in s...
Returns True, if type represents C++ `std::string`, False otherwise.
def extract_attr_for_match(items, **kwargs): """Helper method to get attribute value for an item matching some criterion. Specify target criteria value as dict, with target attribute having value -1 Example: to extract state of vpc matching given vpc id response = [{'State': 'available', 'VpcId': 'vpc-2bb...
Helper method to get attribute value for an item matching some criterion. Specify target criteria value as dict, with target attribute having value -1 Example: to extract state of vpc matching given vpc id response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}] extract_attr_for_match(response, State=...
def convert_user_to_ldap(self, ID, DN): """Convert a normal user to a LDAP user.""" # http://teampasswordmanager.com/docs/api-users/#convert_to_ldap data = {'login_dn': DN} log.info('Convert User %s to LDAP DN %s' % (ID, DN)) self.put('users/%s/convert_to_ldap.json' % ID, data)
Convert a normal user to a LDAP user.
def getStore(self) : """get the inner store as dictionary""" res = {} res.update(self.store) for k, v in self.subStores.items() : res[k] = v.getStore() return res
get the inner store as dictionary
def write(self, s): """ Write wrapper. Parameters ---------- s : bytes Bytes to write """ try: return self.handle.write(s) except (OSError, serial.SerialException, serial.writeTimeoutError) as e: if e == s...
Write wrapper. Parameters ---------- s : bytes Bytes to write
async def dump_tuple(self, elem, elem_type, params=None, obj=None): """ Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :param obj: :return: """ if len(elem) != len(elem_type.f_specs()): raise Value...
Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :param obj: :return:
def dockerPredicate(e): """ Used to ensure Docker exceptions are retried if appropriate :param e: Exception :return: True if e retriable, else False """ if not isinstance(e, subprocess.CalledProcessError): return False if e.returncode == 125: return True
Used to ensure Docker exceptions are retried if appropriate :param e: Exception :return: True if e retriable, else False
def set_attributes(self, el, pyobj): '''Instance data attributes contains a dictionary of keys (namespaceURI,localName) and attribute values. These values can be self-describing (typecode), or use attribute_typecode_dict to determine serialization. Paramters: el -- M...
Instance data attributes contains a dictionary of keys (namespaceURI,localName) and attribute values. These values can be self-describing (typecode), or use attribute_typecode_dict to determine serialization. Paramters: el -- MessageInterface representing the element ...
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None): """Leases all available cron jobs.""" leased_jobs = [] now = rdfvalue.RDFDatetime.Now() expiration_time = now + lease_time for job in itervalues(self.cronjobs): if cronjob_ids and job.cron_job_id not in cronjob_ids: continue...
Leases all available cron jobs.
def start_trajectory(self, trajectory_id, time_scale=1.0, relative=False, reversed=False, group_mask=ALL_GROUPS): """ starts executing a specified trajectory :param trajectory_id: id of the trajectory (previously defined by define_trajectory) :par...
starts executing a specified trajectory :param trajectory_id: id of the trajectory (previously defined by define_trajectory) :param time_scale: time factor; 1.0 = original speed; >1.0: slower; <1.0: faster ...
def _display_stream(normalized_data, stream): """ print stream message from docker-py stream. """ try: stream.write(normalized_data['stream']) except UnicodeEncodeError: stream.write(normalized_data['stream'].encode("utf-8"))
print stream message from docker-py stream.
def authenticate(self, request): """ Authenticate the request and return a tuple of (user, token) or None if there was no authentication attempt. """ access_token = self.get_access_token(request) if not access_token: return None try: user...
Authenticate the request and return a tuple of (user, token) or None if there was no authentication attempt.
def _handle_exclude(self, state, sls, saltenv, errors): ''' Take the exclude dec out of the state and apply it to the highstate global dec ''' if 'exclude' in state: exc = state.pop('exclude') if not isinstance(exc, list): err = ('Exclude D...
Take the exclude dec out of the state and apply it to the highstate global dec
def format_step(step, zero_prefix=False): """Return the step value in format suitable for display.""" if isinstance(step, int): return "{:06}".format(step) if zero_prefix else "{}".format(step) elif isinstance(step, tuple): return "{:04}:{:06}".format(*step) if zero_prefix else "{}:{}".forma...
Return the step value in format suitable for display.
def found_check(): """ Temporarily enables spiceypy default behavior which raises exceptions for false found flags for certain spice functions. All spice functions executed within the context manager will check the found flag return parameter and the found flag will be removed from the return for ...
Temporarily enables spiceypy default behavior which raises exceptions for false found flags for certain spice functions. All spice functions executed within the context manager will check the found flag return parameter and the found flag will be removed from the return for the given function. For E...
def _sub32(ins): """ Pops last 2 dwords from the stack and subtract them. Then push the result onto the stack. NOTE: The operation is TOP[0] = TOP[-1] - TOP[0] If TOP[0] is 0, nothing is done """ op1, op2 = tuple(ins.quad[2:]) if is_int(op2): if int(op2) == 0: # A - 0 = A => Do No...
Pops last 2 dwords from the stack and subtract them. Then push the result onto the stack. NOTE: The operation is TOP[0] = TOP[-1] - TOP[0] If TOP[0] is 0, nothing is done
def show_search_results( log_rec, code_view=True, json_view=False, show_message_details=False): """show_search_results Show search results like rsyslog or as pretty-printed JSON dictionaries per log for debugging drill-down fields :param log_rec: log record from splunk ...
show_search_results Show search results like rsyslog or as pretty-printed JSON dictionaries per log for debugging drill-down fields :param log_rec: log record from splunk :param code_view: show as a normal tail -f <log file> view :param json_view: pretty print each log's dictionary :param show...
def need_offset_reset(self, partition, offset_reset_strategy=None): """Mark partition for offset reset using specified or default strategy. Arguments: partition (TopicPartition): partition to mark offset_reset_strategy (OffsetResetStrategy, optional) """ if offse...
Mark partition for offset reset using specified or default strategy. Arguments: partition (TopicPartition): partition to mark offset_reset_strategy (OffsetResetStrategy, optional)
def get_base_info(self, obj): """Returns the base info of an object """ if obj is None: return {} info = { "id": obj.getId(), "uid": obj.UID(), "title": obj.Title(), "description": obj.Description(), "url": obj.abso...
Returns the base info of an object
def count(cls, *criterion, **kwargs): """Returns a count of the instances meeting the specified filter criterion and kwargs. Examples: >>> User.count() 500 >>> User.count(country="India") 300 >>> User.count(User.age > 50, country="I...
Returns a count of the instances meeting the specified filter criterion and kwargs. Examples: >>> User.count() 500 >>> User.count(country="India") 300 >>> User.count(User.age > 50, country="India") 39