code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def is_cached(self): """Returns true if this rule is already cached.""" # TODO: cache by target+hash, not per file. try: for item in self.rule.output_files: log.info(item) self.cachemgr.in_cache(item, self._metahash()) except cache.CacheMiss: ...
Returns true if this rule is already cached.
def write_header(self): """Write `header` to `file`. See Also -------- write_data """ for properties in self.header.values(): value = properties['value'] offset_bytes = int(properties['offset']) self.file.seek(offset_bytes) ...
Write `header` to `file`. See Also -------- write_data
def cancelAllPendingResults( self ): """Cancel all pending results.""" # grab all the pending job ids jobs = self.pendingResults() if len(jobs) > 0: # abort in the cluster self._abortJobs(jobs) # cancel in the notebook ...
Cancel all pending results.
def from_meta(cls, meta, meta_all=None): """Copy DocstringMeta from another instance.""" if len(meta.args) == 2: name = meta.args[1] meta_type = None for x in meta_all: if x.args[1] == name and x.args[0] == 'type': meta_type = x.des...
Copy DocstringMeta from another instance.
def issue_comments(self, issue_id_or_key, extra_query_params={}): """ client = BacklogClient("your_space_name", "your_api_key") client.issue_comments("YOUR_PROJECT-999") """ return self.do("GET", "issues/{issue_id_or_key}/comments", url_params={"issue_id_o...
client = BacklogClient("your_space_name", "your_api_key") client.issue_comments("YOUR_PROJECT-999")
def to_sigproc_keyword(keyword, value=None): """ Generate a serialized string for a sigproc keyword:value pair If value=None, just the keyword will be written with no payload. Data type is inferred by keyword name (via a lookup table) Args: keyword (str): Keyword to write value (None, ...
Generate a serialized string for a sigproc keyword:value pair If value=None, just the keyword will be written with no payload. Data type is inferred by keyword name (via a lookup table) Args: keyword (str): Keyword to write value (None, float, str, double or angle): value to write to file ...
def print_report(label, user, system, real): """ Prints the report of one step of a benchmark. """ print("{:<12s} {:12f} {:12f} ( {:12f} )".format(label, user, system, ...
Prints the report of one step of a benchmark.
def encode(self, b64=False, always_bytes=True): """Encode the packet for transmission.""" if self.binary and not b64: encoded_packet = six.int2byte(self.packet_type) else: encoded_packet = six.text_type(self.packet_type) if self.binary and b64: ...
Encode the packet for transmission.
def start(self, daemon=True): """ Start driving the chain asynchronously, return immediately :param daemon: ungracefully kill the driver when the program terminates :type daemon: bool """ if self._run_lock.acquire(False): try: # there is a sho...
Start driving the chain asynchronously, return immediately :param daemon: ungracefully kill the driver when the program terminates :type daemon: bool
def softmax_to_unary(sm, GT_PROB=1): """Deprecated, use `unary_from_softmax` instead.""" warning("pydensecrf.softmax_to_unary is deprecated, use unary_from_softmax instead.") scale = None if GT_PROB == 1 else GT_PROB return unary_from_softmax(sm, scale, clip=None)
Deprecated, use `unary_from_softmax` instead.
def teardown(self): ''' Clean up the target once all tests are completed ''' if self.controller: self.controller.teardown() for monitor in self.monitors: monitor.teardown()
Clean up the target once all tests are completed
def notify_slaves(self): """Checks to see if slaves should be notified, and notifies them if needed""" if self.disable_slave_notify is not None: LOGGER.debug('Slave notifications disabled') return False if self.zone_data()['kind'] == 'Master': response_code =...
Checks to see if slaves should be notified, and notifies them if needed
def to_api_data(self): """ Returns a dict to communicate with the server :rtype: dict """ data = {} # recurrence pattern if self.__interval and isinstance(self.__interval, int): recurrence_pattern = data[self._cc('pattern')] = {} recurrence_patter...
Returns a dict to communicate with the server :rtype: dict
def get_gradebook_hierarchy_session(self, proxy): """Gets the session traversing gradebook hierarchies. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradebookHierarchySession) - a ``GradebookHierarchySession`` raise: NullArgument - ``proxy`` is ``null...
Gets the session traversing gradebook hierarchies. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradebookHierarchySession) - a ``GradebookHierarchySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete reque...
def create(self, num): """ Creates the environment in your subclassed create function include the line below super().build(arg1, arg2, arg2, ...) """ self.log.record_process('enviroment.py', 'Creating ' + str(num) + ' environments - ' + self.name)
Creates the environment in your subclassed create function include the line below super().build(arg1, arg2, arg2, ...)
def get_moments(metricParams, vary_fmax=False, vary_density=None): """ This function will calculate the various integrals (moments) that are needed to compute the metric used in template bank placement and coincidence. Parameters ----------- metricParams : metricParameters instance ...
This function will calculate the various integrals (moments) that are needed to compute the metric used in template bank placement and coincidence. Parameters ----------- metricParams : metricParameters instance Structure holding all the options for construction of the metric. vary_fmax...
def find_first_version(self): """Finds the first version of igraph that exists in the nightly build repo from the version numbers provided in ``self.versions_to_try``.""" for version in self.versions_to_try: remote_url = self.get_download_url(version=version) if http_url_...
Finds the first version of igraph that exists in the nightly build repo from the version numbers provided in ``self.versions_to_try``.
def file_is_present(self, file_path): """ check if file 'file_path' is present, raises IOError if file_path is not a file :param file_path: str, path to the file :return: True if file exists, False if file does not exist """ p = self.p(file_path) if not o...
check if file 'file_path' is present, raises IOError if file_path is not a file :param file_path: str, path to the file :return: True if file exists, False if file does not exist
def update_members(self, list_id, data): """ Batch subscribe or unsubscribe list members. Only the members array is required in the request body parameters. Within the members array, each member requires an email_address and either a status or status_if_new. The update_existing ...
Batch subscribe or unsubscribe list members. Only the members array is required in the request body parameters. Within the members array, each member requires an email_address and either a status or status_if_new. The update_existing parameter will also be considered required to help pr...
def show(self): """ Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects. """ print("APKs in Session: {}".format(len(self.analyzed_apk))) for d, a in self.analyzed_apk.items(): print("\t{}: {}".format(d, ...
Print information to stdout about the current session. Gets all APKs, all DEX files and all Analysis objects.
def predict_fixation_duration( durations, angles, length_diffs, dataset=None, params=None): """ Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations. """ if dataset is None: dataset = np.ones(durations.shape) corrected_d...
Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations.
def diff_tree(candidate_config=None, candidate_path=None, running_config=None, running_path=None, saltenv='base'): ''' Return the diff, as Python dictionary, between the candidate and the running configuration. candidate_config The candida...
Return the diff, as Python dictionary, between the candidate and the running configuration. candidate_config The candidate configuration sent as text. This argument is ignored when ``candidate_path`` is set. candidate_path Absolute or remote path from where to load the candidate co...
def ensure_unique(qs, field_name, value, exclude_id=None): """ Makes sure that `value` is unique on model.fieldname. And nonempty. """ orig = value if not value: value = "None" for x in itertools.count(1): if not qs.exclude(id=exclude_id).filter(**{field_name: value}).exists(): ...
Makes sure that `value` is unique on model.fieldname. And nonempty.
def check(self, obj, condition) -> "WriteTransaction": """ Add a condition which must be met for the transaction to commit. While the condition is checked against the provided object, that object will not be modified. It is only used to provide the hash and range key to apply the condi...
Add a condition which must be met for the transaction to commit. While the condition is checked against the provided object, that object will not be modified. It is only used to provide the hash and range key to apply the condition to. At most 10 items can be checked, saved, or deleted in the...
def access_zipped_assets(cls, static_module_name, static_path, dir_location=None): """ Create a copy of static resource files as we can't serve them from within the pex file. :param static_module_name: Module name containing module to cache in a tempdir :type static_module_name: string, for example 'tw...
Create a copy of static resource files as we can't serve them from within the pex file. :param static_module_name: Module name containing module to cache in a tempdir :type static_module_name: string, for example 'twitter.common.zookeeper' or similar :param static_path: Module name, for example 'serverset'...
def create_object(self, filename, img_properties=None): """Create an image object on local disk from the given file. The file is copied to a new local directory that is created for the image object. The optional list of image properties will be associated with the new object together wit...
Create an image object on local disk from the given file. The file is copied to a new local directory that is created for the image object. The optional list of image properties will be associated with the new object together with the set of default properties for images. Parameters ...
def column(self): """获取文章所在专栏. :return: 文章所在专栏 :rtype: Column """ from .column import Column if 'column' in self.soup: url = Column_Url + '/' + self.soup['column']['slug'] name = self.soup['column']['name'] return Column(url, name, se...
获取文章所在专栏. :return: 文章所在专栏 :rtype: Column
def pretokenized_tfrecord_dataset(filenames, text2self, eos_included, repeat, batch_size, sequence_length): """Reads tensor2tensor-style data files....
Reads tensor2tensor-style data files. The dataset is defined by sets of TFRecord files of TFExample protos. There should be a "targets" feature (a 1d tensor of integers) If not text2self, there should also be an "inputs" feature. Other features get ignored. eos_included specifies whether the inputs and targ...
def flatten(inputs, scope=None): """Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raise...
Flattens the input while maintaining the batch_size. Assumes that the first dimension represents the batch. Args: inputs: a tensor of size [batch_size, ...]. scope: Optional scope for name_scope. Returns: a flattened tensor with shape [batch_size, k]. Raises: ValueError: if inputs.shape is ...
def _set_police_priority_map(self, v, load=False): """ Setter method for police_priority_map, mapped from YANG variable /police_priority_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_police_priority_map is considered as a private method. Backends looking...
Setter method for police_priority_map, mapped from YANG variable /police_priority_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_police_priority_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
def set(self, time_sec, callback_fn, *args, **kwdargs): """Convenience function to create and set a timer. Equivalent to: timer = timer_factory.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec) """ timer = self.t...
Convenience function to create and set a timer. Equivalent to: timer = timer_factory.timer() timer.set_callback('expired', callback_fn, *args, **kwdargs) timer.set(time_sec)
def default_from_address(self): """ Cache the coinbase address so that we don't make two requests for every single transaction. """ if self._coinbase_cache_til is not None: if time.time - self._coinbase_cache_til > 30: self._coinbase_cache_til = None ...
Cache the coinbase address so that we don't make two requests for every single transaction.
def reset( self ): """ Resets the values to the current application information. """ self.setValue('colorSet', XPaletteColorSet()) self.setValue('font', QApplication.font()) self.setValue('fontSize', QApplication.font().pointSize())
Resets the values to the current application information.
def setText(self, sequence): """Qt method extension.""" self.setToolTip(sequence) super(ShortcutLineEdit, self).setText(sequence)
Qt method extension.
def set_starting_ratio(self, ratio): """ Set the starting conversion ratio for the next `read` call. """ from samplerate.lowlevel import src_set_ratio if self._state is None: self._create() src_set_ratio(self._state, ratio) self.ratio = ratio
Set the starting conversion ratio for the next `read` call.
def connect(self): """Overrides HTTPSConnection.connect to specify TLS version""" # Standard implementation from HTTPSConnection, which is not # designed for extension, unfortunately sock = socket.create_connection((self.host, self.port), self.time...
Overrides HTTPSConnection.connect to specify TLS version
def get_by_ip(cls, ip): 'Returns Host instance for the given ip address.' ret = cls.hosts_by_ip.get(ip) if ret is None: ret = cls.hosts_by_ip[ip] = [Host(ip)] return ret
Returns Host instance for the given ip address.
def multiply(self, a, b): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ if a is None or b is None: return None m, n = len(a), len(b[0]) if len(b) != n: raise Exception("A's column number must be equal to B's row number.") l = len(b[0]) ...
:type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]]
def download(self, url, path): """Download url and save data to path.""" # original_url = url # print(url) qurl = QUrl(url) url = to_text_string(qurl.toEncoded(), encoding='utf-8') logger.debug(str((url, path))) if url in self._workers: while not self....
Download url and save data to path.
def is_unit(q): ''' is_unit(q) yields True if q is a pint unit or a string that names a pint unit and False otherwise. ''' if isinstance(q, six.string_types): try: return hasattr(units, q) except: return False else: cls = type(q) return cls.__module__.startswith...
is_unit(q) yields True if q is a pint unit or a string that names a pint unit and False otherwise.
def _expand_host(self, host): """ Used internally to add the default port to hosts not including portnames. """ if isinstance(host, basestring): return (host, self.default_port) return tuple(host)
Used internally to add the default port to hosts not including portnames.
def write(filename, mesh, write_binary=True): """Writes msh files, cf. <http://gmsh.info//doc/texinfo/gmsh.html#MSH-ASCII-file-format>. """ if mesh.points.shape[1] == 2: logging.warning( "msh2 requires 3D points, but 2D points given. " "Appending 0 third component." ...
Writes msh files, cf. <http://gmsh.info//doc/texinfo/gmsh.html#MSH-ASCII-file-format>.
def _set_pw_profile(self, v, load=False): """ Setter method for pw_profile, mapped from YANG variable /pw_profile (list) If this variable is read-only (config: false) in the source YANG file, then _set_pw_profile is considered as a private method. Backends looking to populate this variable should ...
Setter method for pw_profile, mapped from YANG variable /pw_profile (list) If this variable is read-only (config: false) in the source YANG file, then _set_pw_profile is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_pw_profile() directly...
def when_connected(self): """ Retrieve the currently-connected Protocol, or the next one to connect. Returns: defer.Deferred: A Deferred that fires with a connected :class:`FedoraMessagingProtocolV2` instance. This is similar to the whenConnected meth...
Retrieve the currently-connected Protocol, or the next one to connect. Returns: defer.Deferred: A Deferred that fires with a connected :class:`FedoraMessagingProtocolV2` instance. This is similar to the whenConnected method from the Twisted endpoints APIs, which ...
def view(self, buffer_time = 10.0, sample_size = 10000, name=None, description=None, start=False): """ Defines a view on a stream. A view is a continually updated sampled buffer of a streams's tuples. Views allow visibility into a stream from external clients such as Jupyter Not...
Defines a view on a stream. A view is a continually updated sampled buffer of a streams's tuples. Views allow visibility into a stream from external clients such as Jupyter Notebooks, the Streams console, `Microsoft Excel <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.2.0/com.ibm...
def chempot_vs_gamma_plot_one(self, plt, entry, ref_delu, chempot_range, delu_dict={}, delu_default=0, label='', JPERM2=False): """ Helper function to help plot the surface energy of a single SlabEntry as a function of chemical potential. Args: ...
Helper function to help plot the surface energy of a single SlabEntry as a function of chemical potential. Args: plt (Plot): A plot. entry (SlabEntry): Entry of the slab whose surface energy we want to plot ref_delu (sympy Symbol): The range stabilit...
def add_device_notification(self, data_name, attr, callback, user_handle=None): # type: (str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]] """Add a device notification. :param str data_name: PLC storage address :param pyads.structs.NotificationAttrib attr: object...
Add a device notification. :param str data_name: PLC storage address :param pyads.structs.NotificationAttrib attr: object that contains all the attributes for the definition of a notification :param callback: callback function that gets executed on in the event of ...
def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None): """Retrieves a list of all the applications. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope. Args: fields (list of ...
Retrieves a list of all the applications. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope. Args: fields (list of str, optional): A list of fields to include or exclude from the result (depending on includ...
def connect(host=None, port=rethinkdb.DEFAULT_PORT, timeout=20, verify=True, **kwargs): """ RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run...
RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run POST :param timeout: <int> max time (s) to wait for connection :param kwargs: <dict> passthrough rethinkdb arguments :return:
def p_function_declaration(self, p): """ function_declaration \ : FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \ function_body RBRACE """ if len(p) == 8: ...
function_declaration \ : FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \ function_body RBRACE
def filter_cat(self, axis, cat_index, cat_name): ''' Filter the matrix based on their category. cat_index is the index of the category, the first category has index=1. ''' run_filter.filter_cat(self, axis, cat_index, cat_name)
Filter the matrix based on their category. cat_index is the index of the category, the first category has index=1.
def shewhart(self, data: ['SASdata', str] = None, boxchart: str = None, cchart: str = None, irchart: str = None, mchart: str = None, mrchart: str = None, npchart: str = None, pchart: str = None, ...
Python method to call the SHEWHART procedure Documentation link: https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=qcug&docsetTarget=qcug_shewhart_toc.htm&locale=en :param data: SASdata object or string. This parameter is required. :parm boxchart: The boxcha...
def save_config(self, cmd="save config", confirm=False, confirm_response=""): """Save Config""" return super(ExtremeVspSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Save Config
def generate_n_vectors(N_max, dx=1, dy=1, dz=1, half_lattice=True): r""" Generate integer vectors, :math:`\boldsymbol{n}`, with :math:`|\boldsymbol{n}| < N_{\rm max}`. If ``half_lattice=True``, only return half of the three-dimensional lattice. If the set N = {(i,j,k)} defines the lattice, we restr...
r""" Generate integer vectors, :math:`\boldsymbol{n}`, with :math:`|\boldsymbol{n}| < N_{\rm max}`. If ``half_lattice=True``, only return half of the three-dimensional lattice. If the set N = {(i,j,k)} defines the lattice, we restrict to the cases such that ``(k > 0)``, ``(k = 0, j > 0)``, and ...
def set_voltage(self, value, channel=1): """ channel: 1=OP1, 2=OP2, AUX is not supported""" cmd = "V%d %f" % (channel, value) self.write(cmd)
channel: 1=OP1, 2=OP2, AUX is not supported
def ToRequest(self): """Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes. """ param = {} if self.email: param['email'] = self.email if self.user_id: param['localId'] = self.user_id if self.name: param['displayName'] =...
Converts to gitkit api request parameter dict. Returns: Dict, containing non-empty user attributes.
def partial_derivative(self, X, y=0): """Compute partial derivative :math:`C(u|v)` of cumulative density. Args: X: `np.ndarray` y: `float` Returns: """ self.check_fit() U, V = self.split_matrix(X) if self.theta == 1: return...
Compute partial derivative :math:`C(u|v)` of cumulative density. Args: X: `np.ndarray` y: `float` Returns:
def wmean_and_var_str_array(W, x): """Weighted mean and variance of each component of a structured array. Parameters ---------- W: (N,) ndarray normalised weights (must be >=0 and sum to one). x: (N,) structured array data Returns ------- dictionary {'mean':...
Weighted mean and variance of each component of a structured array. Parameters ---------- W: (N,) ndarray normalised weights (must be >=0 and sum to one). x: (N,) structured array data Returns ------- dictionary {'mean':weighted_means, 'var':weighted_variances}
def is_quota_exceeded(self) -> bool: '''Return whether the quota is exceeded.''' if self.quota and self._url_table is not None: return self.size >= self.quota and \ self._url_table.get_root_url_todo_count() == 0
Return whether the quota is exceeded.
def wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir='.', merge=True, info_only=False, **kwargs): """int, int, int->None Download ONE PART of the course.""" html = json_api_content title = _wanmen_get_title_by_json_topic_part(html, ...
int, int, int->None Download ONE PART of the course.
def filler(self): """Returns the pipeline ID that filled this slot's value. Returns: A string that is the pipeline ID. Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled.' ...
Returns the pipeline ID that filled this slot's value. Returns: A string that is the pipeline ID. Raises: SlotNotFilledError if the value hasn't been filled yet.
def _get_span(self, m): """ Gets a tuple that identifies a span for the specific mention class that m belongs to. """ return (m.sentence.id, m.char_start, m.char_end)
Gets a tuple that identifies a span for the specific mention class that m belongs to.
async def stepper_config(self, steps_per_revolution, stepper_pins): """ Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or ...
Configure stepper motor prior to operation. This is a FirmataPlus feature. :param steps_per_revolution: number of steps per motor revolution :param stepper_pins: a list of control pin numbers - either 4 or 2 :returns: No return value.
def _mod_spec(self): """ Modified length specifiers: mapping between length modifiers and conversion specifiers. This generates all the possibilities, i.e. hhd, etc. """ mod_spec={} for mod, sizes in self.int_len_mod.items(): for conv in self.int_sign['signe...
Modified length specifiers: mapping between length modifiers and conversion specifiers. This generates all the possibilities, i.e. hhd, etc.
def _check_max_running(self, func, data, opts, now): ''' Return the schedule data structure ''' # Check to see if there are other jobs with this # signature running. If there are more than maxrunning # jobs present then don't start another. # If jid_include is Fa...
Return the schedule data structure
def make_app(global_conf, full_stack=True, **app_conf): """ Set depotexample up with the settings found in the PasteDeploy configuration file used. :param global_conf: The global settings for depotexample (those defined under the ``[DEFAULT]`` section). :type global_conf: dict :para...
Set depotexample up with the settings found in the PasteDeploy configuration file used. :param global_conf: The global settings for depotexample (those defined under the ``[DEFAULT]`` section). :type global_conf: dict :param full_stack: Should the whole TG2 stack be set up? :type full_s...
def get_trans(self, out_vec=None): """Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a new Vec3. """ if out_vec: return out_vec.set(*self.data[3][:3]) return Vec3(*self.data[3][:3])
Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a new Vec3.
def set_hot_pluggable_for_device(self, name, controller_port, device, hot_pluggable): """Sets a flag in the device information which indicates that the attached device is hot pluggable or not. This may or may not be supported by a particular controller and/or drive, and is silently ignored in th...
Sets a flag in the device information which indicates that the attached device is hot pluggable or not. This may or may not be supported by a particular controller and/or drive, and is silently ignored in the latter case. Changing the setting while the VM is running is forbidden. The dev...
def format_args(self, args): '''Format a D-Bus argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a...
Format a D-Bus argument tuple into an appropriate logging string.
def create_empty_dataset(self, dataset_id="", project_id="", dataset_reference=None): """ Create a new empty dataset: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/insert :param project_id: The name of the project where we want to create ...
Create a new empty dataset: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/insert :param project_id: The name of the project where we want to create an empty a dataset. Don't need to provide, if projectId in dataset_reference. :type project_id: str :param ...
def add_time_step(self, **create_time_step_kwargs): """Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step. """ ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs) assert isinstance(ts, time_...
Creates a time-step and appends it to the list. Args: **create_time_step_kwargs: Forwarded to time_step.TimeStep.create_time_step.
def absent(name, **kwargs): ''' Ensure the job is absent from the Jenkins configured jobs name The name of the Jenkins job to remove ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': []} if __salt__['jenkins.job_exists'](name...
Ensure the job is absent from the Jenkins configured jobs name The name of the Jenkins job to remove
def status(name, init_system, verbose): """WIP! Try at your own expense """ try: status = Serv(init_system, verbose=verbose).status(name) except ServError as ex: sys.exit(ex) click.echo(json.dumps(status, indent=4, sort_keys=True))
WIP! Try at your own expense
def from_schema(cls, schema, handlers={}, **kwargs): """ Construct a resolver from a JSON schema object. """ return cls( schema.get('$id', schema.get('id', '')) if isinstance(schema, dict) else '', schema, handlers=handlers, **kwarg...
Construct a resolver from a JSON schema object.
def get_argument_parser(): """Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ file_mv = cli.file_mv desc = 'Extracts gene-level ex...
Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx.
def _compress(self, data, operation): """ This private method compresses some data in a given mode. This is used because almost all of the code uses the exact same setup. It wouldn't have to, but it doesn't hurt at all. """ # The 'algorithm' for working out how big to mak...
This private method compresses some data in a given mode. This is used because almost all of the code uses the exact same setup. It wouldn't have to, but it doesn't hurt at all.
def plot_surface(x, y, z, color=default_color, wrapx=False, wrapy=False): """Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param color: {color2d} :param bool wrapx: when True, the x direction is assumed to wrap, and polygons a...
Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param color: {color2d} :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points :param bool wrapy: simular for the ...
def from_url(cls, reactor, url, key, alg=RS256, jws_client=None): """ Construct a client from an ACME directory at a given URL. :param url: The ``twisted.python.url.URL`` to fetch the directory from. See `txacme.urls` for constants for various well-known public directori...
Construct a client from an ACME directory at a given URL. :param url: The ``twisted.python.url.URL`` to fetch the directory from. See `txacme.urls` for constants for various well-known public directories. :param reactor: The Twisted reactor to use. :param ~josepy.jwk.JWK...
def open(self, inf, psw): """Return stream object for file data.""" if inf.file_redir: # cannot leave to unrar as it expects copied file to exist if inf.file_redir[0] in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK): inf = self.getinfo(inf.file_redir[2]) ...
Return stream object for file data.
def get_node_attribute(self, node, attribute_name): """Given a node and the name of an attribute, get a copy of that node's attribute. :param node: reference to the node to retrieve the attribute of. :param attribute_name: name of the attribute to retrieve. :returns: attribute v...
Given a node and the name of an attribute, get a copy of that node's attribute. :param node: reference to the node to retrieve the attribute of. :param attribute_name: name of the attribute to retrieve. :returns: attribute value of the attribute_name key for the specifie...
def list_projects(self): """ Returns the list of projects owned by user. """ data = self._run( url_path="projects/list" ) projects = data['result'].get('projects', []) return [self._project_formatter(item) for item in projects]
Returns the list of projects owned by user.
def reportResourceUsage(imageObjectList, outwcs, num_cores, interactive=False): """ Provide some information to the user on the estimated resource usage (primarily memory) for this run. """ from . import imageObject if outwcs is None: output_mem = 0 else: ...
Provide some information to the user on the estimated resource usage (primarily memory) for this run.
def _gen_vol_xml(vmname, diskname, disktype, size, pool): ''' Generate the XML string to define a libvirt storage volume ''' size = int(size) * 1024 # MB context = { 'name': vmname, 'filename': '{0}.{1}'.format(disk...
Generate the XML string to define a libvirt storage volume
def deleteByteArray(self, context, page, returnError): """please override""" returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.")
please override
def unwrap(s, node_indent): """Group lines of a docstring to blocks. For now, only groups markdown list sections. A block designates a list of consequtive lines that all start at the same indentation level. The lines of the docstring are iterated top to bottom. Each line is added to `block_li...
Group lines of a docstring to blocks. For now, only groups markdown list sections. A block designates a list of consequtive lines that all start at the same indentation level. The lines of the docstring are iterated top to bottom. Each line is added to `block_list` until a line is encountered tha...
def writeto(fpath, to_write, aslines=False, verbose=None): r""" Writes (utf8) text to a file. Args: fpath (PathLike): file path to_write (str): text to write (must be unicode text) aslines (bool): if True to_write is assumed to be a list of lines verbose (bool): verbosity fl...
r""" Writes (utf8) text to a file. Args: fpath (PathLike): file path to_write (str): text to write (must be unicode text) aslines (bool): if True to_write is assumed to be a list of lines verbose (bool): verbosity flag CommandLine: python -m ubelt.util_io writeto --...
def compute_hkdf(ikm, salt): """ Standard hkdf algorithm :param {Buffer} ikm Input key material. :param {Buffer} salt Salt value. :return {Buffer} Strong key material. @private """ prk = hmac.new(salt, ikm, hashlib.sha256).digest() info_bits_update = info_bits + bytearray(chr(1), 'ut...
Standard hkdf algorithm :param {Buffer} ikm Input key material. :param {Buffer} salt Salt value. :return {Buffer} Strong key material. @private
def fromJavascript(cls, javascript_datetime): ''' a method to construct labDT from a javascript datetime string :param javascript_datetime: string with datetime info in javascript formatting :return: labDT object ''' # validate inputs title = 'Javascript d...
a method to construct labDT from a javascript datetime string :param javascript_datetime: string with datetime info in javascript formatting :return: labDT object
def find_win32_generator(): """ Find a suitable cmake "generator" under Windows. """ # XXX this assumes we will find a generator that's the same, or # compatible with, the one which was used to compile LLVM... cmake # seems a bit lacking here. cmake_dir = os.path.join(here_dir, 'dummy') ...
Find a suitable cmake "generator" under Windows.
def walker(self, path=None, base_folder=None): """ This method walk a directory structure and create the Folders and Files as they appear. """ path = path or self.path or '' base_folder = base_folder or self.base_folder # prevent trailing slashes and other inconsi...
This method walk a directory structure and create the Folders and Files as they appear.
def list_sinks(self, project, page_size=0, page_token=None): """List sinks for the project associated with this client. :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, I...
List sinks for the project associated with this client. :type project: str :param project: ID of the project whose sinks are to be listed. :type page_size: int :param page_size: maximum number of sinks to return, If not passed, defaults to a value set by the A...
def plot(self, data): """ Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe. """ import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictiona...
Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.
def branches(self): # type: () -> List[str] """ List of all branches this commit is a part of. """ if self._branches is None: cmd = 'git branch --contains {}'.format(self.sha1) out = shell.run( cmd, capture=True, never_prete...
List of all branches this commit is a part of.
def _spawn_background_rendering(self, rate=5.0): """ Spawns a thread that updates the render window. Sometimes directly modifiying object data doesn't trigger Modified() and upstream objects won't be updated. This ensures the render window stays updated without consuming too ...
Spawns a thread that updates the render window. Sometimes directly modifiying object data doesn't trigger Modified() and upstream objects won't be updated. This ensures the render window stays updated without consuming too many resources.
def delete(self, user, commit=True): """ Delete a user """ events.user_delete_event.send(user) return super().delete(user, commit)
Delete a user
def sde(self): """ Return the state space representation of the covariance. """ variance = float(self.variance.values) lengthscale = float(self.lengthscale.values) foo = np.sqrt(3.)/lengthscale F = np.array([[0, 1], [-foo**2, -2*foo]]) L = np.array(...
Return the state space representation of the covariance.
def train(cls, rdd, k, maxIterations=100, initMode="random"): r""" :param rdd: An RDD of (i, j, s\ :sub:`ij`\) tuples representing the affinity matrix, which is the matrix A in the PIC paper. The similarity s\ :sub:`ij`\ must be nonnegative. This is a symmetric ...
r""" :param rdd: An RDD of (i, j, s\ :sub:`ij`\) tuples representing the affinity matrix, which is the matrix A in the PIC paper. The similarity s\ :sub:`ij`\ must be nonnegative. This is a symmetric matrix and hence s\ :sub:`ij`\ = s\ :sub:`ji`\ For any (i, j) with ...
def set_pool_quota(service, pool_name, max_bytes=None, max_objects=None): """ :param service: The Ceph user name to run the command under :type service: str :param pool_name: Name of pool :type pool_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_...
:param service: The Ceph user name to run the command under :type service: str :param pool_name: Name of pool :type pool_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int :raises: subpro...
def idle_task(self): '''called on idle''' if self.threat_timeout_timer.trigger(): self.check_threat_timeout() if self.threat_detection_timer.trigger(): self.perform_threat_detection()
called on idle
def props_to_image(regionprops, shape, prop): r""" Creates an image with each region colored according the specified ``prop``, as obtained by ``regionprops_3d``. Parameters ---------- regionprops : list This is a list of properties for each region that is computed by PoreSpy's `...
r""" Creates an image with each region colored according the specified ``prop``, as obtained by ``regionprops_3d``. Parameters ---------- regionprops : list This is a list of properties for each region that is computed by PoreSpy's ``regionprops_3D`` or Skimage's ``regionsprops``. ...