code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 3) self.transmit_error_counter = data[0] self.receive_error_counte...
:return: None
def toimage(self, width=None, height=None): '''Return the current scene as a PIL Image. **Example** You can build your molecular viewer as usual and dump an image at any resolution supported by the video card (up to the memory limits):: v = QtViewer() ...
Return the current scene as a PIL Image. **Example** You can build your molecular viewer as usual and dump an image at any resolution supported by the video card (up to the memory limits):: v = QtViewer() # Add the renderers v.add_renderer(...) ...
def get_new_document( # noqa: C901 include_wdom_js: bool = True, include_skeleton: bool = False, include_normalizecss: bool = False, autoreload: bool = None, reload_wait: float = None, log_level: Union[int, str] = None, log_prefix: str = None, log_console...
Create new :class:`Document` object with options. :arg bool include_wdom_js: Include wdom.js file. Usually should be True. :arg bool include_skeleton: Include skelton.css. :arg bool include_normalizecss: Include normalize.css. :arg bool autoreload: Enable autoreload flag. This flag overwrites `...
def _group_filter_values(seg, filter_indices, ms_per_input): """ Takes a list of 1s and 0s and returns a list of tuples of the form: ['y/n', timestamp]. """ ret = [] for filter_value, (_segment, timestamp) in zip(filter_indices, seg.generate_frames_as_segments(ms_per_input)): if filter_v...
Takes a list of 1s and 0s and returns a list of tuples of the form: ['y/n', timestamp].
def _remap_key(key): """ Change key into correct casing if we know the parameter """ if key in KNOWN_PARAMS: return key if key.lower() in known_params: return KNOWN_PARAMS[known_params.index(key.lower())] return key
Change key into correct casing if we know the parameter
def _instruction_list(self, filters): """Generates the instructions for a bot and its filters. Note: The guidance for each filter is generated by combining the docstrings of the predicate filter and resulting dispatch function with a single space between. The class's ...
Generates the instructions for a bot and its filters. Note: The guidance for each filter is generated by combining the docstrings of the predicate filter and resulting dispatch function with a single space between. The class's :py:attr:`INSTRUCTIONS` and the default help...
def get_ancestors_through_subont(self, go_term, relations): """ Returns the ancestors from the relation filtered GO subontology of go_term's ancestors. subontology() primarily used here for speed when specifying relations to traverse. Point of this is to first get a smaller graph (all a...
Returns the ancestors from the relation filtered GO subontology of go_term's ancestors. subontology() primarily used here for speed when specifying relations to traverse. Point of this is to first get a smaller graph (all ancestors of go_term regardless of relation) and then filter relations on that in...
def stddev(values, meanval=None): #from AI: A Modern Appproach """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )
The standard deviation of a set of values. Pass in the mean if you already know it.
def extend_service_volume(self, stack, service, volume, args): """扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: ...
扩容存储卷 为指定名称的服务增加存储卷资源,并挂载到部署的容器中。 Args: - stack: 服务所属的服务组名称 - service: 服务名 - volume: 存储卷名 - args: 请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/ Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result ...
async def delete(query): """Perform DELETE query asynchronously. Returns number of rows deleted. """ assert isinstance(query, peewee.Delete),\ ("Error, trying to run delete coroutine" "with wrong query class %s" % str(query)) cursor = await _execute_query_async(query) rowcount = cu...
Perform DELETE query asynchronously. Returns number of rows deleted.
def register(self, name, *slots): """ Registers a given signal :param name: the signal to register """ # setdefault initializes the object even if it exists. This is more efficient if name not in self: self[name] = Signal() for slot in slots: ...
Registers a given signal :param name: the signal to register
def thread_details(io_handler, thread_id, max_depth=0): """ Prints details about the thread with the given ID (not its name) """ # Normalize maximum depth try: max_depth = int(max_depth) if max_depth < 1: max_depth = None except (Va...
Prints details about the thread with the given ID (not its name)
def street(random=random, *args, **kwargs): """ Produce something that sounds like a street name >>> mock_random.seed(0) >>> street(random=mock_random) 'chimp place' >>> street(random=mock_random, capitalize=True) 'Boatbench Block' >>> mock_random.seed(3) >>> street(random=mock_rand...
Produce something that sounds like a street name >>> mock_random.seed(0) >>> street(random=mock_random) 'chimp place' >>> street(random=mock_random, capitalize=True) 'Boatbench Block' >>> mock_random.seed(3) >>> street(random=mock_random, slugify=True) 'central-britches-boulevard'
def check_running(self): ''' Check if a pid file exists and if it is associated with a running process. ''' if self.check_pidfile(): pid = self.get_pidfile() if not salt.utils.platform.is_windows(): if self.check_pidfile() and self.is_daem...
Check if a pid file exists and if it is associated with a running process.
def context(self): """ Convenient access to shared context """ if self._context is not None: return self._context else: logger.warning("Using shared context without a lock") return self._executor._shared_context
Convenient access to shared context
def _init_data_line(self, fnc, lnum, line): """Process Data line.""" fld = re.split(self.sep, line) # Lines may contain different numbers of items. # The line should have all columns requested by the user. if self.usr_max_idx < len(fld): self.convert_ints_floats(fld) ...
Process Data line.
def get_stats_display(self, args=None, max_width=None): """Return a dict with all the information needed to display the stat. key | description ---------------------------- display | Display the stat (True or False) msgdict | Message to display (list of dict [{ 'msg': msg, '...
Return a dict with all the information needed to display the stat. key | description ---------------------------- display | Display the stat (True or False) msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ]) align | Message position
def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. ''' # Dirty hack to fix non included default language_code = 'en-us' if language_co...
Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``.
def maximum_likelihood_estimator(self, data, states): """ Fit using MLE method. Parameters ---------- data: pandas.DataFrame or 2D array Dataframe of values containing samples from the conditional distribution, (Y|X) and corresponding X values. ...
Fit using MLE method. Parameters ---------- data: pandas.DataFrame or 2D array Dataframe of values containing samples from the conditional distribution, (Y|X) and corresponding X values. states: All the input states that are jointly gaussian. Returns ...
def from_series(series): """ Deseralize a PercentRankTransform the given pandas.Series, as returned by `to_series()`. Parameters ---------- series : pandas.Series Returns ------- PercentRankTransform """ result = PercentRankTrans...
Deseralize a PercentRankTransform the given pandas.Series, as returned by `to_series()`. Parameters ---------- series : pandas.Series Returns ------- PercentRankTransform
def _parse_known_pattern(self, pattern: str) -> List[str]: """ Expand pattern if identified as a directory and return found sub packages """ if pattern.endswith(os.path.sep): patterns = [ filename for filename in os.listdir(pattern) ...
Expand pattern if identified as a directory and return found sub packages
def create_container_student(self, parent_container_id, environment, network_grading, mem_limit, student_path, socket_path, systemfiles_path, course_common_student_path): """ Creates a student container :param parent_container_id: id of the "parent" container ...
Creates a student container :param parent_container_id: id of the "parent" container :param environment: env to start (name/id of a docker image) :param network_grading: boolean to indicate if the network should be enabled in the container or not (share the parent stack) :param mem_limit...
def UpdateFlows(self, client_id_flow_id_pairs, pending_termination=db.Database.unchanged): """Updates flow objects in the database.""" for client_id, flow_id in client_id_flow_id_pairs: try: self.UpdateFlow( client_id, flow_id, pending_termination=pe...
Updates flow objects in the database.
def bundle_lambda(zipfile): """Write zipfile contents to file. :param zipfile: :return: exit_code """ # TODO have 'bundle.zip' as default config if not zipfile: return 1 with open('bundle.zip', 'wb') as zfile: zfile.write(zipfile) log.info('Finished - a bundle.zip is wai...
Write zipfile contents to file. :param zipfile: :return: exit_code
def parseLine(line, lineNumber=None): """ Parse line """ match = line_re.match(line) if match is None: raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber) # Underscores are replaced with dash to work around Lotus Notes return (match.group('name').replace('_', '-'...
Parse line
def to_json_data(self, model_name=None): """ Parameters ---------- model_name: str, default None if given, will be used as external file directory base name Returns ------- A dictionary of serialized data. """ return collections.Ordere...
Parameters ---------- model_name: str, default None if given, will be used as external file directory base name Returns ------- A dictionary of serialized data.
def to_record(self): """Create a CertStore record from this TLSFileBundle""" tf_list = [getattr(self, k, None) for k in [_.value for _ in TLSFileType]] # If a cert isn't defined in this bundle, remove it tf_list = filter(lambda x: x, tf_list) files = {tf.file_...
Create a CertStore record from this TLSFileBundle
def _8bit_oper(op1, op2=None, reversed_=False): """ Returns pop sequence for 8 bits operands 1st operand in H, 2nd operand in A (accumulator) For some operations (like comparisons), you can swap operands extraction by setting reversed = True """ output = [] if op2 is not None and reversed_...
Returns pop sequence for 8 bits operands 1st operand in H, 2nd operand in A (accumulator) For some operations (like comparisons), you can swap operands extraction by setting reversed = True
def addSpecfile(self, specfiles, path): """Prepares the container for loading ``mrc`` files by adding specfile entries to ``self.info``. Use :func:`MsrunContainer.load()` afterwards to actually import the files :param specfiles: the name of an ms-run file or a list of names :typ...
Prepares the container for loading ``mrc`` files by adding specfile entries to ``self.info``. Use :func:`MsrunContainer.load()` afterwards to actually import the files :param specfiles: the name of an ms-run file or a list of names :type specfiles: str or [str, str, ...] :param ...
def set_window_title(self): """Set window title.""" if DEV is not None: title = u"Spyder %s (Python %s.%s)" % (__version__, sys.version_info[0], sys.version_info[1]) else: ...
Set window title.
def detect_number_of_threads(): """ DEPRECATED: use `_init_num_threads` instead. If this is modified, please update the note in: https://github.com/pydata/numexpr/wiki/Numexpr-Users-Guide """ log.warning('Deprecated, use `init_num_threads` instead.') try: nthreads = int(os.environ.get('N...
DEPRECATED: use `_init_num_threads` instead. If this is modified, please update the note in: https://github.com/pydata/numexpr/wiki/Numexpr-Users-Guide
def validate_token(self, token): '''retrieve a subject based on a token. Valid means we return a participant invalid means we return None ''' from expfactory.database.models import Participant p = Participant.query.filter(Participant.token == token).first() if p is not None: if p.toke...
retrieve a subject based on a token. Valid means we return a participant invalid means we return None
def import_list( self, listName, pathToTaskpaperDoc ): """ *import tasks from a reminder.app list into a given taskpaper document* **Key Arguments:** - ``listName`` -- the name of the reminders list - ``pathToTaskpaperDoc`` -- the path to the ...
*import tasks from a reminder.app list into a given taskpaper document* **Key Arguments:** - ``listName`` -- the name of the reminders list - ``pathToTaskpaperDoc`` -- the path to the taskpaper document to import the tasks into **Usage:** The following will import ...
def percentile(self, percentile, axis, inclusive=True): """Returns d-1 dimensional histogram containing percentile of values along axis if inclusive=True, will report bin center of first bin for which percentile% of data lies in or below the bin =False, ... data lies strictly below t...
Returns d-1 dimensional histogram containing percentile of values along axis if inclusive=True, will report bin center of first bin for which percentile% of data lies in or below the bin =False, ... data lies strictly below the bin 10% percentile is calculated as: value at least 10% ...
def handle_keywords(self, func, node, offset=0): ''' Gather keywords to positional argument information Assumes the named parameter exist, raises a KeyError otherwise ''' func_argument_names = {} for i, arg in enumerate(func.args.args[offset:]): assert isinst...
Gather keywords to positional argument information Assumes the named parameter exist, raises a KeyError otherwise
def _load_entries(self, func, count, page=1, entries=None, **kwargs): """ Load entries :param function func: function (:meth:`.API._req_files` or :meth:`.API._req_search`) that returns entries :param int count: number of entries to load. This value should never b...
Load entries :param function func: function (:meth:`.API._req_files` or :meth:`.API._req_search`) that returns entries :param int count: number of entries to load. This value should never be greater than self.count :param int page: page number (starting from 1)
def valuemap(f): """ Decorator to help PEG functions handle value conversions. """ @wraps(f) def wrapper(*args, **kwargs): if 'value' in kwargs: val = kwargs['value'] del kwargs['value'] _f = f(*args, **kwargs) def valued_f(*args, **kwargs): ...
Decorator to help PEG functions handle value conversions.
def gone_assignments(self): ''' Returns the list of past assignments the user did not submit for before the hard deadline. ''' # Include only assignments with past hard deadline qs = Assignment.objects.filter(hard_deadline__lt=timezone.now()) # Include onl...
Returns the list of past assignments the user did not submit for before the hard deadline.
def handle(self, *args, **options): """Run the management command.""" self.stdout.write('Apply settings to index:') for model in get_registered_model(): if options.get('model', None) and not (model.__name__ in options['model']): ...
Run the management command.
def init_config(app): """Initialize configuration.""" for k in dir(config): if k.startswith('CLASSIFIER_'): app.config.setdefault(k, getattr(config, k))
Initialize configuration.
def WriteSessionCompletion(self, aborted=False): """Writes session completion information. Args: aborted (Optional[bool]): True if the session was aborted. Raises: IOError: if the storage type is not supported or when the storage writer is closed. OSError: if the storage type i...
Writes session completion information. Args: aborted (Optional[bool]): True if the session was aborted. Raises: IOError: if the storage type is not supported or when the storage writer is closed. OSError: if the storage type is not supported or when the storage writer is ...
def break_on_error(self, pid, errorCode): """ Sets or clears the system breakpoint for a given Win32 error code. Use L{Process.is_system_defined_breakpoint} to tell if a breakpoint exception was caused by a system breakpoint or by the application itself (for example because of a...
Sets or clears the system breakpoint for a given Win32 error code. Use L{Process.is_system_defined_breakpoint} to tell if a breakpoint exception was caused by a system breakpoint or by the application itself (for example because of a failed assertion in the code). @note: This functiona...
def _friends_leaveoneout_radius(points, ftype): """Internal method used to compute the radius (half-side-length) for each ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using leave-one-out (LOO) cross-validation.""" # Construct KDTree to enable quick nearest-neighbor lookup for # our...
Internal method used to compute the radius (half-side-length) for each ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using leave-one-out (LOO) cross-validation.
def insert_many(conn, tablename, column_names, records, chunksize=2500): """Insert many records by chunking data into insert statements. Notes ----- records should be Iterable collection of namedtuples or tuples. """ groups = chunks(records, chunksize) column_str = ','.join(column_names) ...
Insert many records by chunking data into insert statements. Notes ----- records should be Iterable collection of namedtuples or tuples.
def fetch_and_filter_tags(self): """ Fetch and filter tags, fetch dates and sort them in time order. """ self.all_tags = self.fetcher.get_all_tags() self.filtered_tags = self.get_filtered_tags(self.all_tags) self.fetch_tags_dates()
Fetch and filter tags, fetch dates and sort them in time order.
def compute_within_collection_vowel_duration(self, prefix, no_singletons=False): """ Computes the mean duration of vowels from Units within clusters. :param str prefix: Prefix for the key entry in self.measures :param bool no_singletons: If False, excludes collections of length 1 from calculati...
Computes the mean duration of vowels from Units within clusters. :param str prefix: Prefix for the key entry in self.measures :param bool no_singletons: If False, excludes collections of length 1 from calculations and adds "no_singletons" to the prefix Adds the following measures t...
def get_default_config(self): """ Returns the default collector settings """ config = super(DarnerCollector, self).get_default_config() config.update({ 'path': 'darner', # Which rows of 'status' you would like to publish. # 'telnet host po...
Returns the default collector settings
def scatter(slope, zero, x1, x2, x1err=[], x2err=[]): """ Used mainly to measure scatter for the BCES best-fit """ n = len(x1) x2pred = zero + slope * x1 s = sum((x2 - x2pred) ** 2) / (n - 1) if len(x2err) == n: s_obs = sum((x2err / x2) ** 2) / n s0 = s - s_obs print num...
Used mainly to measure scatter for the BCES best-fit
def findAllSubstrings(string, substring): """ Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of subst...
Returns a list of all substring starting positions in string or an empty list if substring is not present in string. :param string: a template string :param substring: a string, which is looked for in the ``string`` parameter. :returns: a list of substring starting positions in the template string
def is_link(self, path, use_sudo=False): """ Check if a path exists, and is a symbolic link. """ func = use_sudo and _sudo or _run with self.settings(hide('running', 'warnings'), warn_only=True): return func('[ -L "%(path)s" ]' % locals()).succeeded
Check if a path exists, and is a symbolic link.
def convolve(input, weights, mask=None, slow=False): """2 dimensional convolution. This is a Python implementation of what will be written in Fortran. Borders are handled with reflection. Masking is supported in the following way: * Masked points are skipped. * Parts of the input whic...
2 dimensional convolution. This is a Python implementation of what will be written in Fortran. Borders are handled with reflection. Masking is supported in the following way: * Masked points are skipped. * Parts of the input which are masked have weight 0 in the kernel. * Since th...
def collect(cls, result_key, func): """ Sets the `result_key` to an iterable of objects for which `func(obj)` returns True """ def scanner(self, obj): if not getattr(self, result_key, None): setattr(self, result_key, []) rv = func(obj) ...
Sets the `result_key` to an iterable of objects for which `func(obj)` returns True
def gallery_images(self): """Instance depends on the API version: * 2018-06-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImagesOperations>` * 2019-03-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleryImagesOperatio...
Instance depends on the API version: * 2018-06-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2018_06_01.operations.GalleryImagesOperations>` * 2019-03-01: :class:`GalleryImagesOperations<azure.mgmt.compute.v2019_03_01.operations.GalleryImagesOperations>`
def load_service(config): """ Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the APIs defined by the co...
Load a restful service specified by some YAML file at config_path. :param config_path: A pathlib Path object that points to the yaml config :returns: A python module containing a Client class, call factory, and the definition of each of the APIs defined by the config.
def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' if _service_is_upstart(name): cmd = 'stop {0}'.format(name) else: cmd = '/sbin/service {0} stop'.format(name) return not __salt__['cmd.retc...
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
def delete_object(self, id): """Deletes the object with the given ID from the graph.""" # x=self.request(id, post_args={"method": "delete"}) params = urllib.parse.urlencode({"method": "delete", 'access_token': str(id)}) u = requests.get("https://graph.facebook.com/" + str(id) + "?" + par...
Deletes the object with the given ID from the graph.
def register(**criteria): """ class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( ...
class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( type='motor', cur...
def create_resource(self, path, transaction): """ Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response """ t = self._parent.root.with_prefix(path) max_len = 0 imax = None for...
Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response
def system_exit(object): """ Handles proper system exit in case of critical exception. :param object: Object to decorate. :type object: object :return: Object. :rtype: object """ @functools.wraps(object) def system_exit_wrapper(*args, **kwargs): """ Handles proper s...
Handles proper system exit in case of critical exception. :param object: Object to decorate. :type object: object :return: Object. :rtype: object
def guess_encoding(blob): """ uses file magic to determine the encoding of the given data blob. :param blob: file content as read by file.read() :type blob: data :returns: encoding :rtype: str """ # this is a bit of a hack to support different versions of python magic. # Hopefully a...
uses file magic to determine the encoding of the given data blob. :param blob: file content as read by file.read() :type blob: data :returns: encoding :rtype: str
def add(self, agent_id, media_type, media_file): """ 新增其它类型永久素材 详情请参考 https://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90 :param agent_id: 企业应用的id :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)普通文件(file) ...
新增其它类型永久素材 详情请参考 https://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90 :param agent_id: 企业应用的id :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)普通文件(file) :param media_file: 要上传的文件,一个 File-object :return: 返回的 JS...
def parse_declaration(self, i): """Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.""" j = None if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) ...
Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.
def _run(self): """Run method that can be profiled""" self.set_state(self.STATE_INITIALIZING) self.ioloop = ioloop.IOLoop.current() self.consumer_lock = locks.Lock() self.sentry_client = self.setup_sentry( self._kwargs['config'], self.consumer_name) try: ...
Run method that can be profiled
def print_options(self): """ Print all options as parsed by the script """ options = [] print("The script is running with the following options:") options.append(("dry_run", self.options.dry_run)) options.append(("worker_config", self.__class__)) datab...
Print all options as parsed by the script
def scalar_inc_dec(word, valence, is_cap_diff): """ Check if the preceding words increase, decrease, or negate/nullify the valence """ scalar = 0.0 word_lower = word.lower() if word_lower in BOOSTER_DICT: scalar = BOOSTER_DICT[word_lower] if valence < 0: scalar *=...
Check if the preceding words increase, decrease, or negate/nullify the valence
def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3): """Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload...
Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue which will be filled in. destination: The CN of the remote system...
def getRegexpsByName(regexpNames = ['all']): ''' Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes. ''' allRegexpList = getAllRegexp() if 'al...
Method that recovers the names of the <RegexpObject> in a given list. :param regexpNames: list of strings containing the possible regexp. :return: Array of <RegexpObject> classes.
def import_class(import_path, setting_name=None): """ Import a class by name. """ mod_name, class_name = import_path.rsplit('.', 1) # import module mod = import_module_or_none(mod_name) if mod is not None: # Loaded module, get attribute try: return getattr(mod, c...
Import a class by name.
def get_mining_equipment(): """Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ....
Get all the mining equipment information available. Returns: This function returns two major dictionaries. The first one contains information about the coins for which mining equipment data is available. coin_data: {symbol1: {'BlockNumber': ..., 'BlockReward': ..., 'BlockRewardRe...
def paths_for_download(self): """List of URLs available for downloading.""" if self._paths_for_download is None: queries = list() try: for sra in self.gsm.relations['SRA']: query = sra.split("=")[-1] if 'SRX' not in query: ...
List of URLs available for downloading.
def checksum(file_path, hash_type='md5', block_size=65536): """Returns either the md5 or sha256 hash of a file at `file_path`. md5 is the default hash_type as it is faster than sha256 The default block size is 64 kb, which appears to be one of a few command choices according to https://stackoverfl...
Returns either the md5 or sha256 hash of a file at `file_path`. md5 is the default hash_type as it is faster than sha256 The default block size is 64 kb, which appears to be one of a few command choices according to https://stackoverflow.com/a/44873382/2680. The code below is an extension of the e...
def is_quoted(value): ''' Return a single or double quote, if a string is wrapped in extra quotes. Otherwise return an empty string. ''' ret = '' if isinstance(value, six.string_types) \ and value[0] == value[-1] \ and value.startswith(('\'', '"')): ret = value[0]...
Return a single or double quote, if a string is wrapped in extra quotes. Otherwise return an empty string.
def get_status_job(self, id_job, hub=None, group=None, project=None, access_token=None, user_id=None): """ Get the status about a job, by its id """ if access_token: self.req.credential.set_token(access_token) if user_id: self.req.cr...
Get the status about a job, by its id
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
Serializes mac_type and resource into a HAWK string.
def verify_verify(self, id, token): """Verify the token of a specific verification.""" return Verify().load(self.request('verify/' + str(id), params={'token': token}))
Verify the token of a specific verification.
def qtt_fft1(self,tol,inverse=False, bitReverse=True): """ Compute 1D (inverse) discrete Fourier Transform in the QTT format. :param tol: error tolerance. :type tol: float :param inverse: whether do an inverse FFT or not. :type inverse: Boolean :param...
Compute 1D (inverse) discrete Fourier Transform in the QTT format. :param tol: error tolerance. :type tol: float :param inverse: whether do an inverse FFT or not. :type inverse: Boolean :param bitReverse: whether do the bit reversion or not. If this function i...
def digest(self,data=None): """ Method digest is redefined to return keyed MAC value instead of just digest. """ if data is not None: self.update(data) b=create_string_buffer(256) size=c_size_t(256) if libcrypto.EVP_DigestSignFinal(self.ctx,b,p...
Method digest is redefined to return keyed MAC value instead of just digest.
def equivalent_to(self, token): """ Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset` """ return self.filter(character_id=token.character_id).require_scopes_exact(...
Gets all tokens which match the character and scopes of a reference token :param token: :class:`esi.models.Token` :return: :class:`esi.managers.TokenQueryset`
def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. """ if n > 0 and other_day < reference_day: n = n - 1 elif n <= 0 and other_day > reference_day: n = n + 1 ...
Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided.
def parse(self, stream, full_statusline=None): """ parse stream for status line and headers return a StatusAndHeaders object support continuation headers starting with space or tab """ # status line w newlines intact if full_statusline is None: full_...
parse stream for status line and headers return a StatusAndHeaders object support continuation headers starting with space or tab
def indent_list(inlist, level): """Join a list of strings, one per line with 'level' spaces before each one""" indent = ' '*level joinstr = '\n' + indent retval = joinstr.join(inlist) return indent + retval
Join a list of strings, one per line with 'level' spaces before each one
def _get_time_at_horizon(self, utc_time, obslon, obslat, **kwargs): """Get the time closest in time to *utc_time* when the satellite is at the horizon relative to the position of an observer on ground (altitude = 0) Note: This is considered deprecated and it's functionality is currently...
Get the time closest in time to *utc_time* when the satellite is at the horizon relative to the position of an observer on ground (altitude = 0) Note: This is considered deprecated and it's functionality is currently replaced by 'get_next_passes'.
def cleanDir(self): ''' Remove existing json datafiles in the target directory. ''' if os.path.isdir(self.outdir): baddies = ['tout.json','nout.json','hout.json'] for file in baddies: filepath = os.path.join(self.outdir,file) if os.path.isfile(file...
Remove existing json datafiles in the target directory.
def get_image_hashes(image_path, version=None, levels=None): '''get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level. ''' if levels is None: levels = get_levels(version=version) hashes = dict...
get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level.
def get_line_relative_to_node(self, target_node: ast.AST, offset: int) -> str: """ Raises: IndexError: when ``offset`` takes the request out of bounds of this Function's lines. """ return self.lines[target_node.lineno - self.node.lineno + offset]
Raises: IndexError: when ``offset`` takes the request out of bounds of this Function's lines.
def save(self, file_path): """ Method to save the dataset to disk. Parameters ---------- file_path : str File path to save the current dataset to Raises ------ IOError If saving to disk is not successful. """ # T...
Method to save the dataset to disk. Parameters ---------- file_path : str File path to save the current dataset to Raises ------ IOError If saving to disk is not successful.
def is_timed_out(self): """ determines whether a Session has been inactive/idle for too long a time OR exceeds the absolute time that a Session may exist """ if (self.is_expired): return True try: if (not self.last_access_time): ms...
determines whether a Session has been inactive/idle for too long a time OR exceeds the absolute time that a Session may exist
def cas(self, key, value, cas, time=0, compress_level=-1): """ Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param cas: The CAS v...
Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: six.string_types :param value: A value to be stored on server. :type value: object :param cas: The CAS value previously obtained from a call to get*. :type cas: int :p...
def get_tile_image(self, x, y, l): """ Get a tile image, respecting current animations :param x: x coordinate :param y: y coordinate :param l: layer :type x: int :type y: int :type l: int :rtype: pygame.Surface """ # disabled for now, re...
Get a tile image, respecting current animations :param x: x coordinate :param y: y coordinate :param l: layer :type x: int :type y: int :type l: int :rtype: pygame.Surface
def on_click(self, button, **kwargs): """ Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself """ if button in (4, 5): return super().on_click(button, **kwargs) else: activemodule = self.get_active_module() ...
Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself
def _HuntFlowCondition(self, condition): """Builds an SQL condition matching db.HuntFlowsCondition.""" if condition == db.HuntFlowsCondition.UNSET: return "", [] elif condition == db.HuntFlowsCondition.FAILED_FLOWS_ONLY: return ("AND flow_state = %s ", [int(rdf_flow_objects.Flow.Fl...
Builds an SQL condition matching db.HuntFlowsCondition.
def get_pending_servermanager(): ''' Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash ...
Determine whether there are pending Server Manager tasks that require a reboot. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if there are pending Server Manager tasks, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_servermanager
def start_instance(self, build): """ I start a new instance of a VM. If a base_image is specified, I will make a clone of that otherwise i will use image directly. If i'm not given libvirt domain definition XML, I will look for my name in the list of defined virtual mac...
I start a new instance of a VM. If a base_image is specified, I will make a clone of that otherwise i will use image directly. If i'm not given libvirt domain definition XML, I will look for my name in the list of defined virtual machines and start that.
def required_permission(f, level): """Assert that subject has access at given level or higher for object.""" @functools.wraps(f) def wrapper(request, pid, *args, **kwargs): d1_gmn.app.auth.assert_allowed(request, level, pid) return f(request, pid, *args, **kwargs) return wrapper
Assert that subject has access at given level or higher for object.
def asm_binary(exprs, dst_reg, sym_to_reg, triple_or_target=None): ''' Compile and assemble an expression for a given architecture. Arguments: * *exprs*: list of expressions to convert. This can represent a graph of expressions. * *dst_reg*: final register on which to store the result o...
Compile and assemble an expression for a given architecture. Arguments: * *exprs*: list of expressions to convert. This can represent a graph of expressions. * *dst_reg*: final register on which to store the result of the last expression. This is represented by a tuple ("reg_name", reg_...
async def _get_subscriptions(self) -> Tuple[Set[Text], Text]: """ List the subscriptions currently active """ url, params = self._get_subscriptions_endpoint() get = self.session.get(url, params=params) async with get as r: await self._handle_fb_response(r) ...
List the subscriptions currently active
def get_source_value(self, obj, source, **kwargs): """ Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object to which term coercions and the query type lookup are delegated. """ result = [] for sub_source in self.expand_source(source): ...
Treat ``field`` as a nested sub-Column instance, which explicitly stands in as the object to which term coercions and the query type lookup are delegated.
def has_snap(self): """ This method won't count the snaps in "destroying" state! :return: false if no snaps or all snaps are destroying. """ return len(list(filter(lambda s: s.state != SnapStateEnum.DESTROYING, self.snapshots))) > 0
This method won't count the snaps in "destroying" state! :return: false if no snaps or all snaps are destroying.
def get_sequence_rules_by_ids(self, sequence_rule_ids): """Gets a ``SequenceRuleList`` corresponding to the given ``IdList``. arg: sequence_rule_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.assessment.authoring.SequenceRuleList) - the re...
Gets a ``SequenceRuleList`` corresponding to the given ``IdList``. arg: sequence_rule_ids (osid.id.IdList): the list of ``Ids`` to retrieve return: (osid.assessment.authoring.SequenceRuleList) - the returned ``SequenceRule`` list raise: NotFound - a ``Id was`...
def inject(self, require: Optional[List[Text]] = None, fail: Text = 'missing_context', var_name: Text = 'context'): """ This is a decorator intended to be used on states (and actually only work on state handlers). The `require` argument is a ...
This is a decorator intended to be used on states (and actually only work on state handlers). The `require` argument is a list of keys to be checked in the context. If at least one of them is missing, then instead of calling the handler another method will be called. By default the meth...