code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def init_app(self, app): """ To initiate with Flask :param app: Flask object :return: """ provider = app.config.get("STORAGE_PROVIDER", None) key = app.config.get("STORAGE_KEY", None) secret = app.config.get("STORAGE_SECRET", None) container = app....
To initiate with Flask :param app: Flask object :return:
def add_watch_point(self, string, rating, importance=5): """ For a log session you can add as many watch points which are used in the aggregation and extraction of key things that happen. Each watch point has a rating (up to you and can range from success to total failu...
For a log session you can add as many watch points which are used in the aggregation and extraction of key things that happen. Each watch point has a rating (up to you and can range from success to total failure and an importance for finer control of display
def temporarily_enabled(self): """ Temporarily enable the cache (useful for testing) """ old_setting = self.options.enabled self.enable() try: yield finally: self.options.enabled = old_setting
Temporarily enable the cache (useful for testing)
def credential_delete(self, *ids): """Delete one or more credentials. :param ids: one or more credential ids """ return self.raw_query("credential", "delete", data={ "credentials": [{"id": str(id)} for id in ids] })
Delete one or more credentials. :param ids: one or more credential ids
def add_house(self, complex: str, **kwargs): """ Add a new house to the rumetr db """ self.check_complex(complex) self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=kwargs)
Add a new house to the rumetr db
def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix='', dist=None, plotguinier=True, graph_extension='.png', dmax=None, dmax_from_shanum=False): """Perform Guinier analysis on the samples. Inputs: samplenames: list of sample names qrange...
Perform Guinier analysis on the samples. Inputs: samplenames: list of sample names qranges: dictionary of q ranges for each sample. The keys are sample names. The special '__default__' key corresponds to all samples which do not have a key in the dict. qmax_from_shanum: use the ...
def iter_packages(self, name, range_=None, paths=None): """Same as iter_packages in packages.py, but also applies this filter. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `r...
Same as iter_packages in packages.py, but also applies this filter. Args: name (str): Name of the package, eg 'maya'. range_ (VersionRange or str): If provided, limits the versions returned to those in `range_`. paths (list of str, optional): paths to search ...
def bind(_self, **kwargs): """Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. ...
Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. Returns ------- :c...
def create_record(self, type, name, data, priority=None, port=None, weight=None, **kwargs): # pylint: disable=redefined-builtin """ Add a new DNS record to the domain :param str type: the type of DNS record to add (``"A"``, ``"CNAME"``, etc.) :p...
Add a new DNS record to the domain :param str type: the type of DNS record to add (``"A"``, ``"CNAME"``, etc.) :param str name: the name (hostname, alias, etc.) of the new record :param str data: the value of the new record :param int priority: the priority of the new record...
def _get_dimension_scales(self, dimension, preserve_domain=False): """ Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True. """ if ...
Return the list of scales corresponding to a given dimension. The preserve_domain optional argument specifies whether one should filter out the scales for which preserve_domain is set to True.
def tool_classpath_from_products(products, key, scope): """Get a classpath for the tool previously registered under key in the given scope. :param products: The products of the current pants run. :type products: :class:`pants.goal.products.Products` :param string key: The key the tool configuration was...
Get a classpath for the tool previously registered under key in the given scope. :param products: The products of the current pants run. :type products: :class:`pants.goal.products.Products` :param string key: The key the tool configuration was registered under. :param string scope: The scope the tool ...
def nvmlDeviceGetMultiGpuBoard(handle): r""" /** * Retrieves whether the device is on a Multi-GPU Board * Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value. * * For Fermi &tm; or newer fully supported devices. * * @param device ...
r""" /** * Retrieves whether the device is on a Multi-GPU Board * Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value. * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device ...
def idle_send_acks_and_nacks(self): '''Send packets to UAV in idle loop''' max_blocks_to_send = 10 blocks_sent = 0 i = 0 now = time.time() while (i < len(self.blocks_to_ack_and_nack) and blocks_sent < max_blocks_to_send): # print("ACKLIST: %s" %...
Send packets to UAV in idle loop
def add_dashboard_panel(self, dashboard, name, panel_type, metrics, scope=None, sort_by=None, limit=None, layout=None): """**Description** Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel. **Arguments** - **dashboard...
**Description** Adds a panel to the dashboard. A panel can be a time series, or a top chart (i.e. bar chart), or a number panel. **Arguments** - **dashboard**: dashboard to edit - **name**: name of the new panel - **panel_type**: type of the new panel. Valid valu...
def get_build_output(self, process): """ Parse the output of the ns-3 build process to extract the information that is needed to draw the progress bar. Args: process: the subprocess instance to listen to. """ while True: output = process.stdout.r...
Parse the output of the ns-3 build process to extract the information that is needed to draw the progress bar. Args: process: the subprocess instance to listen to.
def _mkOp(fn): """ Function to create variadic operator function :param fn: function to perform binary operation """ def op(*operands, key=None) -> RtlSignalBase: """ :param operands: variadic parameter of input uperands :param key: optional function applied on every operand...
Function to create variadic operator function :param fn: function to perform binary operation
def main(): """ Set up the server. """ parser = argparse.ArgumentParser(description='AFTV Server') parser.add_argument('-p', '--port', type=int, help='listen port', default=5556) parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?') parser.add_argument('-c', '--config...
Set up the server.
def _set_vni_any(self, v, load=False): """ Setter method for vni_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_vni_any is considered as a private method. Backends looking to...
Setter method for vni_any, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_any (empty) If this variable is read-only (config: false) in the source YANG file, then _set_vni_any is considered as a private method. Backends looking to populate this variable should do so via callin...
def transpose_func(classes, table): """ Transpose table. :param classes: classes :type classes : list :param table: input matrix :type table : dict :return: transposed table as dict """ transposed_table = table for i, item1 in enumerate(classes): for j, item2 in enumerat...
Transpose table. :param classes: classes :type classes : list :param table: input matrix :type table : dict :return: transposed table as dict
def get_next_action(self, request, application, label, roles): """ Django view method. We provide a default detail view for applications. """ # We only provide a view for when no label provided if label is not None: return HttpResponseBadRequest("<h1>Bad Request</h1>") ...
Django view method. We provide a default detail view for applications.
def node_done(self, ssid=None): """ Release the servers for the specified ssid. The API doesn't provide any kind of output, try to be helpful by providing the list of servers to be released. :param ssid: ssid of the server pool :return: [ requested_hosts ] """ ...
Release the servers for the specified ssid. The API doesn't provide any kind of output, try to be helpful by providing the list of servers to be released. :param ssid: ssid of the server pool :return: [ requested_hosts ]
def rowsAboutToBeRemoved(self, parent, start, end): """Marks view for repaint. :qtdoc:`Re-implemented<QAbstractItemView.rowsAboutToBeRemoved>`""" self._viewIsDirty = True super(StimulusView, self).rowsAboutToBeRemoved(parent, start, end)
Marks view for repaint. :qtdoc:`Re-implemented<QAbstractItemView.rowsAboutToBeRemoved>`
def _validate_tileset(self, tileset): """Validate the tileset name and ensure that it includes the username """ if '.' not in tileset: tileset = "{0}.{1}".format(self.username, tileset) pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$' if not re.match(pattern,...
Validate the tileset name and ensure that it includes the username
def take(self, obj): """Get cached value and clean cache.""" cached = self._thread_local.cache[self._get_cache_key(obj)] build_kwargs = {} if 'model' in cached and 'pks' in cached: build_kwargs['queryset'] = cached['model'].objects.filter(pk__in=cached['pks']) elif ...
Get cached value and clean cache.
def send(self, msg, timeout=None): """ Send a message over the serial device. :param can.Message msg: Message to send. .. note:: Flags like ``extended_id``, ``is_remote_frame`` and ``is_error_frame`` will be ignored. .. note:: If the t...
Send a message over the serial device. :param can.Message msg: Message to send. .. note:: Flags like ``extended_id``, ``is_remote_frame`` and ``is_error_frame`` will be ignored. .. note:: If the timestamp is a float value it will be converted ...
def has_mixture_channel(val: Any) -> bool: """Returns whether the value has a mixture channel representation. In contrast to `has_mixture` this method falls back to checking whether the value has a unitary representation via `has_channel`. Returns: If `val` has a `_has_mixture_` method and its...
Returns whether the value has a mixture channel representation. In contrast to `has_mixture` this method falls back to checking whether the value has a unitary representation via `has_channel`. Returns: If `val` has a `_has_mixture_` method and its result is not NotImplemented, that result...
def guess_xml_encoding(self, content): r"""Guess encoding from xml header declaration. :param content: xml content :rtype: str or None """ matchobj = self.__regex['xml_encoding'].match(content) return matchobj and matchobj.group(1).lower()
r"""Guess encoding from xml header declaration. :param content: xml content :rtype: str or None
def clean(self): """Routine to return C/NOFS IVM data cleaned to the specified level Parameters ----------- inst : (pysat.Instrument) Instrument class object, whose attribute clean_level is used to return the desired level of data selectivity. Returns -------- Void : (NoneT...
Routine to return C/NOFS IVM data cleaned to the specified level Parameters ----------- inst : (pysat.Instrument) Instrument class object, whose attribute clean_level is used to return the desired level of data selectivity. Returns -------- Void : (NoneType) data in ins...
def _filehandle(self): """ Return a filehandle to the file being tailed, with the position set to the current offset. """ if not self._fh or self._is_closed(): filename = self._rotated_logfile or self.filename if filename.endswith('.gz'): s...
Return a filehandle to the file being tailed, with the position set to the current offset.
def isCompatible(self, other, cls): """ Evaluate interpolation compatibility with other. """ if not isinstance(other, cls): raise TypeError( """Compatibility between an instance of %r and an \ instance of %r can not be checked.""" ...
Evaluate interpolation compatibility with other.
def saddr(address): """Return a string representation for an address. The *address* paramater can be a pipe name, an IP address tuple, or a socket address. The return value is always a ``str`` instance. """ if isinstance(address, six.string_types): return address elif isinstance(ad...
Return a string representation for an address. The *address* paramater can be a pipe name, an IP address tuple, or a socket address. The return value is always a ``str`` instance.
def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. para...
Turn Authorization: header into parameters.
def solid_angle(center, coords): """ Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle. """ ...
Helper method to calculate the solid angle of a set of coords from the center. Args: center (3x1 array): Center to measure solid angle from. coords (Nx3 array): List of coords to determine solid angle. Returns: The solid angle.
def create(parallel): """Create a queue based on the provided parallel arguments. TODO Startup/tear-down. Currently using default queue for testing """ queue = {k: v for k, v in parallel.items() if k in ["queue", "cores_per_job", "mem"]} yield queue
Create a queue based on the provided parallel arguments. TODO Startup/tear-down. Currently using default queue for testing
def _set_show_firmware_option(self, v, load=False): """ Setter method for show_firmware_option, mapped from YANG variable /show/show_firmware_dummy/show_firmware_option (container) If this variable is read-only (config: false) in the source YANG file, then _set_show_firmware_option is considered as a pr...
Setter method for show_firmware_option, mapped from YANG variable /show/show_firmware_dummy/show_firmware_option (container) If this variable is read-only (config: false) in the source YANG file, then _set_show_firmware_option is considered as a private method. Backends looking to populate this variable sho...
def check_docstring_sections(self, definition, docstring): """D21{4,5}, D4{05,06,07,08,09,10}: Docstring sections checks. Check the general format of a sectioned docstring: '''This is my one-liner. Short Summary ------------- This is my summary. ...
D21{4,5}, D4{05,06,07,08,09,10}: Docstring sections checks. Check the general format of a sectioned docstring: '''This is my one-liner. Short Summary ------------- This is my summary. Returns ------- None. ''' ...
def import_key_pair(name, key, profile, key_type=None, **libcloud_kwargs): ''' Import a new public key from string or a file path :param name: Key pair name. :type name: ``str`` :param key: Public key material, the string or a path to a file :type key: ``str`` or path ``str`` :param prof...
Import a new public key from string or a file path :param name: Key pair name. :type name: ``str`` :param key: Public key material, the string or a path to a file :type key: ``str`` or path ``str`` :param profile: The profile key :type profile: ``str`` :param key_type: The key pair typ...
def _skip_trampoline(handler): """Intercepts events from container handlers, emitting them only if they should not be skipped.""" data_event, self = (yield None) delegate = handler event = None depth = 0 while True: def pass_through(): _trans = delegate.send(Transition(data_e...
Intercepts events from container handlers, emitting them only if they should not be skipped.
def add_node(node, **kwds): """add_node from Sphinx """ nodes._add_node_class_names([node.__name__]) for key, val in kwds.iteritems(): try: visit, depart = val except ValueError: raise ValueError('Value for key %r must be a ' '(vis...
add_node from Sphinx
def is_quote_artifact(orig_text, span): """Distinguish between quotes and units.""" res = False cursor = re.finditer(r'("|\')[^ .,:;?!()*+-].*?("|\')', orig_text) for item in cursor: if item.span()[1] == span[1]: res = True return res
Distinguish between quotes and units.
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) raw_content = properties.get("ipConfiguration", None) if raw_content is not None: resource = Resource.from_raw_data(raw_content) prop...
Create a new model using raw API response.
def maybe_timeout_options(self): """Implements the NailgunProtocol.TimeoutProvider interface.""" if self._exit_timeout_start_time: return NailgunProtocol.TimeoutOptions(self._exit_timeout_start_time, self._exit_timeout) else: return None
Implements the NailgunProtocol.TimeoutProvider interface.
def timestamp_datetime(self, timestamp): """ 将uninx时间戳转换为可读性的时间 """ format = '%Y-%m-%d %H:%M:%S' # timestamp为传入的值为时间戳(10位整数),如:1332888820 timestamp = time.localtime(timestamp) ## 经过localtime转换后变成 ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53...
将uninx时间戳转换为可读性的时间
def get_memory_annotations(cls, exclude=None): """Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude from search. :return: found annotations which inherits from cls. :rtype: set """ result = set() # get g...
Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude from search. :return: found annotations which inherits from cls. :rtype: set
def load_data_split(proc_data_dir): """Loads a split dataset Args: proc_data_dir: Directory with the split and processed data Returns: (Training Data, Validation Data, Test Data) """ ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin')) ds_val = Dataset...
Loads a split dataset Args: proc_data_dir: Directory with the split and processed data Returns: (Training Data, Validation Data, Test Data)
def _build(self, inputs, is_training): """Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data....
Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data. Returns: dict containing the follo...
def compute(self): """Computes the tendencies for all state variables given current state and specified input. The function first computes all diagnostic processes. They don't produce any tendencies directly but they may affect the other processes (such as change in solar distri...
Computes the tendencies for all state variables given current state and specified input. The function first computes all diagnostic processes. They don't produce any tendencies directly but they may affect the other processes (such as change in solar distribution). Subsequently, all ten...
def multiline_merge(lines, current_event, re_after, re_before): """ Merge multi-line events based. Some event (like Python trackback or Java stracktrace) spawn on multiple line. This method will merge them using two regular expression: regex_after and regex_before. If a line match ...
Merge multi-line events based. Some event (like Python trackback or Java stracktrace) spawn on multiple line. This method will merge them using two regular expression: regex_after and regex_before. If a line match re_after, it will be merged with next line. If a line match re_...
def from_dict(input_dict, data=None): """ Instantiate an SparseGPClassification object using the information in input_dict (built by the to_dict method). :param data: It is used to provide X and Y for the case when the model was saved using save_data=False in to_dict method. ...
Instantiate an SparseGPClassification object using the information in input_dict (built by the to_dict method). :param data: It is used to provide X and Y for the case when the model was saved using save_data=False in to_dict method. :type data: tuple(:class:`np.ndarray`, :class:`np....
def apply_new_global_variable_name(self, path, new_gv_name): """Change global variable name/key according handed string Updates the global variable name only if different and already in list store. :param path: The path identifying the edited global variable tree view row, can be str, int or t...
Change global variable name/key according handed string Updates the global variable name only if different and already in list store. :param path: The path identifying the edited global variable tree view row, can be str, int or tuple. :param str new_gv_name: New global variable name
def get_template(self, context, **kwargs): """ Returns the template to be used for the current context and arguments. """ if 'template' in kwargs['params']: self.template = kwargs['params']['template'] return super(GoscaleTemplateInclusionTag, self).get_template(conte...
Returns the template to be used for the current context and arguments.
def capture_message(sock, get_channel=False): """ Captures a message from given socket. :param socket.socket sock: The socket to read a message from. :param bool get_channel: Find out which channel the message comes from. :return: The received message, or None on failure. """ ...
Captures a message from given socket. :param socket.socket sock: The socket to read a message from. :param bool get_channel: Find out which channel the message comes from. :return: The received message, or None on failure.
def on_connected(self, headers, body): """ Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats are not 0, we start up the heartbeat l...
Once the connection is established, and 'heart-beat' is found in the headers, we calculate the real heartbeat numbers (based on what the server sent and what was specified by the client) - if the heartbeats are not 0, we start up the heartbeat loop accordingly. :param dict headers: headers in t...
def merge_segments(filename, scan, cleanup=True, sizelimit=0): """ Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan usin...
Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan using root name fileroot. if cleanup, it will remove segments after mer...
def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one of {}'.format(s)) return one_of_parse...
Parser a char from specified string.
def get_access_token(client_id, client_secret): ''' Name: token Parameters: client_id, client_secret Return: dictionary ''' headers = {'Content-Type': 'application/x-www-form-urlencoded'} payload = { 'client_id': client_id, 'client_secret': client_secret } request = requests.post(token_url, data=payload,...
Name: token Parameters: client_id, client_secret Return: dictionary
def type(self): """return the type of the Line """ properties = {self.is_code: "code", self.is_data: "data", self.is_string: "string", self.is_tail: "tail", self.is_unknown: "unknown"} for k, v in properties....
return the type of the Line
def get_standard_form(self, data): """Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation. data : a text in the given scheme. """ if self.synonym_map is None: return data from indi...
Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation. data : a text in the given scheme.
def currencyFormat(_context, code, symbol, format, currency_digits=True, decimal_quantization=True, name=''): """Handle currencyFormat subdirectives.""" _context.action( discriminator=('currency', name, code), callable=_register_curre...
Handle currencyFormat subdirectives.
def is_locked(self): """Return True, if URI is locked.""" if self.provider.lock_manager is None: return False return self.provider.lock_manager.is_url_locked(self.get_ref_url())
Return True, if URI is locked.
def send_static_file(self, filename): """ Send static files from the static folder in the current selected theme prior to the global static folder. :param filename: static filename :return: response object """ if self.config['MODE'] == 'api-only': # i...
Send static files from the static folder in the current selected theme prior to the global static folder. :param filename: static filename :return: response object
def collect_hunt_results(self, hunt): """Download current set of files in results. Args: hunt: The GRR hunt object to download files from. Returns: list: tuples containing: str: human-readable description of the source of the collection. For example, the name of the sou...
Download current set of files in results. Args: hunt: The GRR hunt object to download files from. Returns: list: tuples containing: str: human-readable description of the source of the collection. For example, the name of the source host. str: path to the collecte...
def _read_vector(ctx: ReaderContext) -> vector.Vector: """Read a vector element from the input stream.""" start = ctx.reader.advance() assert start == "[" return _read_coll(ctx, vector.vector, "]", "vector")
Read a vector element from the input stream.
def make_tmp_name(name): """Generates a tmp name for a file or dir. This is a tempname that sits in the same dir as `name`. If it exists on disk at context exit time, it is deleted. """ path, base = os.path.split(name) tmp_base = ".tmp-%s-%s" % (base, uuid4().hex) tmp_name = os.path.join(pa...
Generates a tmp name for a file or dir. This is a tempname that sits in the same dir as `name`. If it exists on disk at context exit time, it is deleted.
def spendables_for_address(address, netcode, format=None): """ Return a list of Spendable objects for the given bitcoin address. Set format to "text" or "dict" to transform return value from an object to a string or dict. This is intended to be a convenience function. There is no way to know t...
Return a list of Spendable objects for the given bitcoin address. Set format to "text" or "dict" to transform return value from an object to a string or dict. This is intended to be a convenience function. There is no way to know that the list returned is a complete list of spendables for the addr...
def _write_cdx_field(self, record, raw_file_record_size, raw_file_offset): '''Write the CDX field if needed.''' if record.fields[WARCRecord.WARC_TYPE] != WARCRecord.RESPONSE \ or not re.match(r'application/http; *msgtype *= *response', record.fields[WARCRecord.CONTE...
Write the CDX field if needed.
def ptmsiReallocationComplete(): """P-TMSI REALLOCATION COMPLETE Section 9.4.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet
P-TMSI REALLOCATION COMPLETE Section 9.4.8
def sprand(m, n, density, format='csr'): """Return a random sparse matrix. Parameters ---------- m, n : int shape of the result density : float target a matrix with nnz(A) = m*n*density, 0<=density<=1 format : string sparse matrix format to return, e.g. 'csr', 'coo', etc...
Return a random sparse matrix. Parameters ---------- m, n : int shape of the result density : float target a matrix with nnz(A) = m*n*density, 0<=density<=1 format : string sparse matrix format to return, e.g. 'csr', 'coo', etc. Return ------ A : sparse matrix ...
def _verifyHostKey(self, hostKey, fingerprint): """Called when ssh transport requests us to verify a given host key. Return a deferred that callback if we accept the key or errback if we decide to reject it. """ if fingerprint in self.knownHosts: return defer.succeed(...
Called when ssh transport requests us to verify a given host key. Return a deferred that callback if we accept the key or errback if we decide to reject it.
def add_extra_headers(self, sample_names): """ If there are samples, add any additional keys they might use to supplement the default headers. Return the headers headers for adding, with the format: [(header_name, header_display_name), ....] """ if not sample_name...
If there are samples, add any additional keys they might use to supplement the default headers. Return the headers headers for adding, with the format: [(header_name, header_display_name), ....]
def get_elb_names(self, region, config): """ :param region: name of a region :param config: Collector config dict :return: list of elb names to query in the given region """ # This function is ripe to be memoized but when ELBs are added/removed # dynamically over ...
:param region: name of a region :param config: Collector config dict :return: list of elb names to query in the given region
def send_login_code(self, code, context, **kwargs): """ Send a login code via SMS """ from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') sms_content = render_to_string(self.template_name, context) self.twilio_client.messages.create( to...
Send a login code via SMS
def prune(self, root): """Prune stale cache files If the option --cache-target-max-entry is greater than zero, then prune will remove all but n old cache files for each target/task. :param str root: The path under which cacheable artifacts will be cleaned """ max_entries_per_target = self._ma...
Prune stale cache files If the option --cache-target-max-entry is greater than zero, then prune will remove all but n old cache files for each target/task. :param str root: The path under which cacheable artifacts will be cleaned
def _decode_response(response): """Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code. """ cont...
Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code.
def command_drop_tables(self, meta_name=None): ''' Drops all tables without dropping a database:: ./manage.py sqla:drop_tables [meta_name] ''' answer = six.moves.input(u'All data will lost. Are you sure? [y/N] ') if answer.strip().lower()!='y': sys.exit(...
Drops all tables without dropping a database:: ./manage.py sqla:drop_tables [meta_name]
def rewrite_return_as_assignments(func_node, interface): """Modify FunctionDef node to directly assign instead of return.""" func_node = _RewriteReturn(interface).visit(func_node) ast.fix_missing_locations(func_node) return func_node
Modify FunctionDef node to directly assign instead of return.
def _peer_get_bfd(self, tx, rx, multiplier): """Get and merge the `bfd` config from global BGP. You should not use this method. You probably want `BGP.bfd`. Args: tx: XML document with the XML to get the transmit interval. rx: XML document with the XML to get th...
Get and merge the `bfd` config from global BGP. You should not use this method. You probably want `BGP.bfd`. Args: tx: XML document with the XML to get the transmit interval. rx: XML document with the XML to get the receive interval. multiplier: XML document...
def enable_performance_data(self): """Enable performance data processing (globally) Format of the line that triggers function call:: ENABLE_PERFORMANCE_DATA :return: None """ if not self.my_conf.process_performance_data: self.my_conf.modified_attributes |= \...
Enable performance data processing (globally) Format of the line that triggers function call:: ENABLE_PERFORMANCE_DATA :return: None
def wait(self, seconds=None, **kw): 'Wait in a loop and react to events as defined in the namespaces' # Use ping/pong to unblock recv for polling transport self._heartbeat_thread.hurry() # Use timeout to unblock recv for websocket transport self._transport.set_timeout(seconds=1) ...
Wait in a loop and react to events as defined in the namespaces
def _align_orthologous_gene_pairwise(self, g_id, gapopen=10, gapextend=0.5, engine='needle', parse=True, force_rerun=False): """Align orthologous strain sequences to representative Protein sequence, save as new pickle""" protein_seqs_aln_pickle_path = op.join(self.sequences_by_gene_dir, '{}_protein_with...
Align orthologous strain sequences to representative Protein sequence, save as new pickle
def next_requests(self): """Returns a request to be scheduled or none.""" use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 ...
Returns a request to be scheduled or none.
def return_rri(self, begsam, endsam): """Return raw, irregularly-timed RRI.""" interval = endsam - begsam dat = empty(interval) k = 0 with open(self.filename, 'rt') as f: [next(f) for x in range(12)] for j, datum in enumerate(f): ...
Return raw, irregularly-timed RRI.
def dumps(self, msg, use_bin_type=False): ''' Run the correct dumps serialization format :param use_bin_type: Useful for Python 3 support. Tells msgpack to differentiate between 'str' and 'bytes' types by encoding them differently. ...
Run the correct dumps serialization format :param use_bin_type: Useful for Python 3 support. Tells msgpack to differentiate between 'str' and 'bytes' types by encoding them differently. Since this changes the wire protocol, ...
def convert_meas_df_thellier_gui(meas_df_in, output): """ Take a measurement dataframe and convert column names from MagIC 2 --> 3 or vice versa. Use treat_step_num --> measurement_number if available, otherwise measurement --> measurement_number. Parameters ---------- meas_df_in : pand...
Take a measurement dataframe and convert column names from MagIC 2 --> 3 or vice versa. Use treat_step_num --> measurement_number if available, otherwise measurement --> measurement_number. Parameters ---------- meas_df_in : pandas DataFrame input dataframe with measurement data out...
def _ScheduleTasks(self, storage_writer): """Schedules tasks. Args: storage_writer (StorageWriter): storage writer for a session storage. """ logger.debug('Task scheduler started') self._status = definitions.STATUS_INDICATOR_RUNNING # TODO: make tasks persistent. # TODO: protect ta...
Schedules tasks. Args: storage_writer (StorageWriter): storage writer for a session storage.
def set_order(self, order): """ Takes a list of dictionaries. Those correspond to the arguments of `list.sort` and must contain the keys 'key' and 'reverse' (a boolean). You must call `set_labels` before this! """ m = gtk.ListStore(bool, str) for item in order: ...
Takes a list of dictionaries. Those correspond to the arguments of `list.sort` and must contain the keys 'key' and 'reverse' (a boolean). You must call `set_labels` before this!
def index(self, x, x_link=None): """Make an index of record pairs. Use a custom function to make record pairs of one or two dataframes. Each function should return a pandas.MultiIndex with record pairs. Parameters ---------- x: pandas.DataFrame A pandas Data...
Make an index of record pairs. Use a custom function to make record pairs of one or two dataframes. Each function should return a pandas.MultiIndex with record pairs. Parameters ---------- x: pandas.DataFrame A pandas DataFrame. When `x_link` is None, the algorithm ...
def eval_objfn(self): """Compute components of objective function as well as total contribution to objective function. """ dfd = self.obfn_dfd() reg = self.obfn_reg() obj = dfd + reg[0] return (obj, dfd) + reg[1:]
Compute components of objective function as well as total contribution to objective function.
def compare_baselines(old_baseline_filename, new_baseline_filename): """ This function enables developers to more easily configure plugin settings, by comparing two generated baselines and highlighting their differences. For effective use, a few assumptions are made: 1. Baselines are sorted...
This function enables developers to more easily configure plugin settings, by comparing two generated baselines and highlighting their differences. For effective use, a few assumptions are made: 1. Baselines are sorted by (filename, line_number, hash). This allows for a deterministic ord...
def get_tablenames(cur): """ Conveinience: """ cur.execute("SELECT name FROM sqlite_master WHERE type='table'") tablename_list_ = cur.fetchall() tablename_list = [str(tablename[0]) for tablename in tablename_list_ ] return tablename_list
Conveinience:
def changeLocalUserPassword(self, login, user, password): """ Parameters: - login - user - password """ self.send_changeLocalUserPassword(login, user, password) self.recv_changeLocalUserPassword()
Parameters: - login - user - password
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = None allowed_names = [] eof = F...
Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's.
def schedule_host_check(self, host, check_time): """Schedule a check on a host Format of the line that triggers function call:: SCHEDULE_HOST_CHECK;<host_name>;<check_time> :param host: host to check :type host: alignak.object.host.Host :param check_time: time to check ...
Schedule a check on a host Format of the line that triggers function call:: SCHEDULE_HOST_CHECK;<host_name>;<check_time> :param host: host to check :type host: alignak.object.host.Host :param check_time: time to check :type check_time: :return: None
def delete_quick(self, get_count=False): """ Deletes the table without cascading and without user prompt. If this table has populated dependent tables, this will fail. """ query = 'DELETE FROM ' + self.full_table_name + self.where_clause self.connection.query(query) ...
Deletes the table without cascading and without user prompt. If this table has populated dependent tables, this will fail.
def convert_coord(coord_from,matrix_file,base_to_aligned=True): '''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False...
Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``
def query(self, query_dict: Dict[str, Any]) -> None: """ 重写 query """ self.parse_url.query = cast(Any, query_dict)
重写 query
async def list(self, *, filters: Mapping = None) -> List[Mapping]: """ Return a list of services Args: filters: a dict with a list of filters Available filters: id=<service id> label=<service label> mode=["replicated"|"global"] ...
Return a list of services Args: filters: a dict with a list of filters Available filters: id=<service id> label=<service label> mode=["replicated"|"global"] name=<service name>
def create_project(type, schema, server, name, output, verbose): """Create a new project on an entity matching server. See entity matching service documentation for details on mapping type and schema Returns authentication details for the created project. """ if verbose: log("Entity Matchin...
Create a new project on an entity matching server. See entity matching service documentation for details on mapping type and schema Returns authentication details for the created project.
def create_weather(self, **kwargs): """ Creates an instance of the Asset Service. """ weather = predix.admin.weather.WeatherForecast(**kwargs) weather.create() client_id = self.get_client_id() if client_id: weather.grant_client(client_id) wea...
Creates an instance of the Asset Service.
def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE): """Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size....
Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size.