code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def touch(path): """ Creates a file located at the given path. """ with open(path, 'a') as f: os.utime(path, None) f.close()
Creates a file located at the given path.
def extend(self, items): """ extend items and print them to stdout using the new line separator """ print('\n'.join(items)) super(MyList, self).extend(items)
extend items and print them to stdout using the new line separator
def _with_error_handling(resp, error, mode, response_format): """ Static method for error handling. :param resp - API response :param error - Error thrown :param mode - Error mode :param response_format - XML or json """ def safe_parse(r): try...
Static method for error handling. :param resp - API response :param error - Error thrown :param mode - Error mode :param response_format - XML or json
def named_module(name): """Returns a module given its name.""" module = __import__(name) packages = name.split(".")[1:] m = module for p in packages: m = getattr(m, p) return m
Returns a module given its name.
def value2json(obj, pretty=False, sort_keys=False, keep_whitespace=True): """ :param obj: THE VALUE TO TURN INTO JSON :param pretty: True TO MAKE A MULTI-LINE PRETTY VERSION :param sort_keys: True TO SORT KEYS :param keep_whitespace: False TO strip() THE WHITESPACE IN THE VALUES :return: ""...
:param obj: THE VALUE TO TURN INTO JSON :param pretty: True TO MAKE A MULTI-LINE PRETTY VERSION :param sort_keys: True TO SORT KEYS :param keep_whitespace: False TO strip() THE WHITESPACE IN THE VALUES :return:
def receive_messages_from_queue(self, wait_time=15, num_messages=1): """ Returns the first (according to FIFO) element in the queue; if none, then returns None.""" return self.queue.receive_messages(MaxNumberOfMessages=num_messages, WaitTimeSeconds=wait_time)
Returns the first (according to FIFO) element in the queue; if none, then returns None.
def logp_gradient_of_set(variable_set, calculation_set=None): """ Calculates the gradient of the joint log posterior with respect to all the variables in variable_set. Calculation of the log posterior is restricted to the variables in calculation_set. Returns a dictionary of the gradients. """ ...
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set. Calculation of the log posterior is restricted to the variables in calculation_set. Returns a dictionary of the gradients.
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. """ string_linking_scores: Dict[str, List[i...
Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to.
def _compute_finite_fault_correction(self, mag): """ Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in ...
Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in hazgridXnga2.f
def send_pending_requests(self): """Can block on network if request is larger than send_buffer_bytes""" try: with self._lock: if not self._can_send_recv(): return Errors.NodeNotReadyError(str(self)) # In the future we might manage an intern...
Can block on network if request is larger than send_buffer_bytes
def find_tags_from_xml( self, xml_name, tag_name, **attribute_filter ): """ Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name """ xml = s...
Return a list of all the matched tags in a specific xml w :param str xml_name: specify from which xml to pick the tag from :param str tag_name: specify the tag name
def preprocess_plain_text_string(self, text, pmid, extra_annotations): """Preprocess plain text string for use by ISI reader. Preprocessing is done by tokenizing into sentences and writing each sentence on its own line in a plain text file. All other preprocessing functions ultimately c...
Preprocess plain text string for use by ISI reader. Preprocessing is done by tokenizing into sentences and writing each sentence on its own line in a plain text file. All other preprocessing functions ultimately call this one. Parameters ---------- text : str ...
def deserialize(stream_or_string, **options): ''' Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types...
Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module.
def _uri_to_etext(cls, uri_ref): """Converts the representation used to identify a text in the meta-data RDF graph to a human-friendly integer text identifier. """ try: return validate_etextno(int(os.path.basename(uri_ref.toPython()))) except InvalidEtextIdException:...
Converts the representation used to identify a text in the meta-data RDF graph to a human-friendly integer text identifier.
def compose(self, *args, **kwargs): """ Generate a file from the current template and given arguments. Warning: Make certain to check the formatted editor for correctness! Args: args: Positional arguments to update the template kwargs: Keywo...
Generate a file from the current template and given arguments. Warning: Make certain to check the formatted editor for correctness! Args: args: Positional arguments to update the template kwargs: Keyword arguments to update the template Returns: ...
def add_timestamp(logger_class, log_method, event_dict): ''' Attach the event time, as unix epoch ''' event_dict['timestamp'] = calendar.timegm(time.gmtime()) return event_dict
Attach the event time, as unix epoch
def _syscall(self, command, input=None, env=None, *params): ''' Call an external system command. ''' return Popen([command] + list(params), stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=env or os.environ).communicate(input=input)
Call an external system command.
def get_banks_by_item(self, item_id): """Gets the list of ``Banks`` mapped to an ``Item``. arg: item_id (osid.id.Id): ``Id`` of an ``Item`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ``item_id`` is not found raise: NullArgument - ``item_id`` is ``n...
Gets the list of ``Banks`` mapped to an ``Item``. arg: item_id (osid.id.Id): ``Id`` of an ``Item`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ``item_id`` is not found raise: NullArgument - ``item_id`` is ``null`` raise: OperationFailed - unable to...
def _writable_dir(path): """Whether `path` is a directory, to which the user has write access.""" return os.path.isdir(path) and os.access(path, os.W_OK)
Whether `path` is a directory, to which the user has write access.
def engines(opts, functions, runners, utils, proxy=None): ''' Return the master services plugins ''' pack = {'__salt__': functions, '__runners__': runners, '__proxy__': proxy, '__utils__': utils} return LazyLoader( _module_dirs(opts, 'engines'), op...
Return the master services plugins
def setDefaultIREncoding(encoding): ''' setDefaultIREncoding - Sets the default encoding used by IndexedRedis. This will be the default encoding used for field data. You can override this on a per-field basis by using an IRField (such as IRUnicodeField or IRRawField) @param encoding - An encoding (like ut...
setDefaultIREncoding - Sets the default encoding used by IndexedRedis. This will be the default encoding used for field data. You can override this on a per-field basis by using an IRField (such as IRUnicodeField or IRRawField) @param encoding - An encoding (like utf-8)
def process_messages_loop_internal(self): """ Busy loop that processes incoming WorkRequest messages via functions specified by add_command. Disconnects while servicing a message, reconnects once finished processing a message Terminates if a command runs shutdown method """ ...
Busy loop that processes incoming WorkRequest messages via functions specified by add_command. Disconnects while servicing a message, reconnects once finished processing a message Terminates if a command runs shutdown method
def to_image(self, digest, blob, mime_type, index, size=500): """Convert a file to a list of images. Returns image at the given index. """ # Special case, for now (XXX). if mime_type.startswith("image/"): return "" cache_key = f"img:{index}:{size}:{digest}" ...
Convert a file to a list of images. Returns image at the given index.
def remove(name=None, pkgs=None, jail=None, chroot=None, root=None, all_installed=False, force=False, glob=False, dryrun=False, recurse=False, regex=False, pcre=False, **kwargs): ''' ...
Remove a package from the database and system .. note:: This function can accessed using ``pkg.delete`` in addition to ``pkg.remove``, to more closely match the CLI usage of ``pkg(8)``. name The package to remove CLI Example: .. code-block:: bash salt '*...
def add_pythonpath(path): """ Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value. """ # Get PYTHONPATH value. Default is empty string. pythonpath = os.environ.setdefault('PYTHONPATH', '') # If given path is not ...
Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value.
def timedelta_range(start=None, end=None, periods=None, freq=None, name=None, closed=None): """ Return a fixed frequency TimedeltaIndex, with day as the default frequency Parameters ---------- start : string or timedelta-like, default None Left bound for generating t...
Return a fixed frequency TimedeltaIndex, with day as the default frequency Parameters ---------- start : string or timedelta-like, default None Left bound for generating timedeltas end : string or timedelta-like, default None Right bound for generating timedeltas periods : integ...
def deploy_branch_exists(deploy_branch): """ Check if there is a remote branch with name specified in ``deploy_branch``. Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and ``master`` for ``github.io`` repos. This isn't completely robust. If there are multiple remotes and you...
Check if there is a remote branch with name specified in ``deploy_branch``. Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and ``master`` for ``github.io`` repos. This isn't completely robust. If there are multiple remotes and you have a ``deploy_branch`` branch on the non-defau...
def amplitude_by_fft(self, data_frame): """ This methods extract the fft components and sum the ones from lower to upper freq as per \ :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl ...
This methods extract the fft components and sum the ones from lower to upper freq as per \ :cite:`Kassavetis2015` :param data_frame: the data frame :type data_frame: pandas.DataFrame :return ampl: the ampl :rtype ampl: float :return freq: the freq...
def _get_center(self): '''Returns the center point of the path, disregarding transforms. ''' w, h = self.layout.get_pixel_size() x = (self.x + w / 2) y = (self.y + h / 2) return x, y
Returns the center point of the path, disregarding transforms.
def _mb_model(self, beta, mini_batch): """ Creates the structure of the model (model matrices etc) for mini batch model Parameters ---------- beta : np.ndarray Contains untransformed starting values for the latent variables mini_batch : int Mini batch si...
Creates the structure of the model (model matrices etc) for mini batch model Parameters ---------- beta : np.ndarray Contains untransformed starting values for the latent variables mini_batch : int Mini batch size for the data sampling Returns -...
def play(self, uri=None): """Start playing :param uri: (optional) play a specific uri """ if uri: self.av_transport.SetAVTransportURI( InstanceID=1, CurrentURI=uri, CurrentURIMetaData="") else: self.av_transport.Play(InstanceID=1, Speed=2)
Start playing :param uri: (optional) play a specific uri
def addFeatureSA(self, callback, default=None, name=None): """ Add a feature to the suffix array. The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self.SA[i]. It is called with one argument: the instance of S...
Add a feature to the suffix array. The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self.SA[i]. It is called with one argument: the instance of SuffixArray self. The callback may traverse self.SA in any fashion. ...
def detect_control_flow(self, offset, op, extended_arg): """ Detect type of block structures and their boundaries to fix optimized jumps in python2.3+ """ code = self.code # Detect parent structure parent = self.structs[0] start = parent['start'] ...
Detect type of block structures and their boundaries to fix optimized jumps in python2.3+
def create_subject_access_review(self, body, **kwargs): """ create a SubjectAccessReview This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_subject_access_review(body, async_req=True) ...
create a SubjectAccessReview This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_subject_access_review(body, async_req=True) >>> result = thread.get() :param async_req bool :par...
def make_replacement_visitor(find_expression, replace_expression): """Return a visitor function that replaces every instance of one expression with another one.""" def visitor_fn(expression): """Return the replacement if this expression matches the expression we're looking for.""" if expression ...
Return a visitor function that replaces every instance of one expression with another one.
def walknset_vars(self, task_class=None, *args, **kwargs): """ Set the values of the ABINIT variables in the input files of the nodes Args: task_class: If not None, only the input files of the tasks belonging to class `task_class` are modified. Example: ...
Set the values of the ABINIT variables in the input files of the nodes Args: task_class: If not None, only the input files of the tasks belonging to class `task_class` are modified. Example: flow.walknset_vars(ecut=10, kptopt=4)
def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1
Execute one action.
def cli(*args, **kwargs): """ CSVtoTable commandline utility. """ # Convert CSV file content = convert.convert(kwargs["input_file"], **kwargs) # Serve the temporary file in browser. if kwargs["serve"]: convert.serve(content) # Write to output file elif kwargs["output_file"]:...
CSVtoTable commandline utility.
def get_milestones(session, project_ids=[], milestone_ids=[], user_details=None, limit=10, offset=0): """ Get the list of milestones """ get_milestones_data = {} if milestone_ids: get_milestones_data['milestones[]'] = milestone_ids if project_ids: get_milestones_data['projects[]'...
Get the list of milestones
def change_encryption(self, current_password, cipher, new_password, new_password_id): """Starts encryption of this medium. This means that the stored data in the medium is encrypted. This medium will be placed to :py:attr:`MediumState.locked_write` state. Pleas...
Starts encryption of this medium. This means that the stored data in the medium is encrypted. This medium will be placed to :py:attr:`MediumState.locked_write` state. Please note that the results can be either returned straight away, or later as the result of t...
def getProcessDatabase(self): """Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of processes. """ info_dict = {} cur = self._conn.cursor() cur.execute("""SHOW FULL PROCESSLIST;""") ...
Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of processes.
def _prefix_from_prefix_string(self, prefixlen_str): """Turn a prefix length string into an integer. Args: prefixlen_str: A decimal string containing the prefix length. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the inpu...
Turn a prefix length string into an integer. Args: prefixlen_str: A decimal string containing the prefix length. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the input is malformed or out of range.
def get_market_tops(symbols=None, **kwargs): """ MOVED to iexfinance.iexdata.get_tops """ import warnings warnings.warn(WNG_MSG % ("get_market_tops", "iexdata.get_tops")) return TOPS(symbols, **kwargs).fetch()
MOVED to iexfinance.iexdata.get_tops
def wrap_get_user(cls, response): """Wrap the response from getting a user into an instance and return it :param response: The response from getting a user :type response: :class:`requests.Response` :returns: the new user instance :rtype: :class:`list` of :class:`User` ...
Wrap the response from getting a user into an instance and return it :param response: The response from getting a user :type response: :class:`requests.Response` :returns: the new user instance :rtype: :class:`list` of :class:`User` :raises: None
def hmget(self, key, field, *fields, encoding=_NOTSET): """Get the values of all the given fields.""" return self.execute(b'HMGET', key, field, *fields, encoding=encoding)
Get the values of all the given fields.
def dynamic_part_name(raml_resource, route_name, pk_field): """ Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' ...
Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' is used as the 2nd part. E.g. if your dynamic part on route ...
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
Pop a request timeout not support in this queue class
def _get_sk(**kwargs): ''' Return sk ''' config = _get_config(**kwargs) key = salt.utils.stringutils.to_str(config['sk']) sk_file = config['sk_file'] if not key and sk_file: with salt.utils.files.fopen(sk_file, 'rb') as keyf: key = salt.utils.stringutils.to_unicode(keyf.r...
Return sk
def jrepr(value): '''customized `repr()`.''' if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return 'object ' + t.__name__
customized `repr()`.
def __post_save_receiver(self, instance, **kwargs): """Signal handler for when a registered model has been saved.""" logger.debug('RECEIVE post_save FOR %s', instance.__class__) self.save_record(instance, **kwargs)
Signal handler for when a registered model has been saved.
def guard(ctx, opts=""): """ Execute all tests and then watch for changes, re-running. """ # TODO if coverage was run via pytest-cov, we could add coverage here too return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
Execute all tests and then watch for changes, re-running.
def add_it(workbench, file_list, labels): """Add the given file_list to workbench as samples, also add them as nodes. Args: workbench: Instance of Workbench Client. file_list: list of files. labels: labels for the nodes. Returns: A list of md5s. """ md5s = [] f...
Add the given file_list to workbench as samples, also add them as nodes. Args: workbench: Instance of Workbench Client. file_list: list of files. labels: labels for the nodes. Returns: A list of md5s.
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options :param device_options...
def searchTag(self,HTAG="#python"): """Set Twitter search or stream criteria for the selection of tweets""" self.t = Twython(app_key =self.app_key , app_secret =self.app_secret , oauth_token =self.oauth_token ...
Set Twitter search or stream criteria for the selection of tweets
def set_labels(self, subj_labels): """ Parameters ---------- subj_labels: list of int or str This list will be checked to have the same size as files list (self.items) """ if len(subj_labels) != self.n_subjs: raise ValueError('The numbe...
Parameters ---------- subj_labels: list of int or str This list will be checked to have the same size as files list (self.items)
def prepare_headers(self, headers, cache_info=None): """ Prepare headers object for request (add cache information :param headers: Headers object :type headers: dict :param cache_info: Cache information to add :type cache_info: floscraper.models.CacheInfo :return...
Prepare headers object for request (add cache information :param headers: Headers object :type headers: dict :param cache_info: Cache information to add :type cache_info: floscraper.models.CacheInfo :return: Prepared headers :rtype: dict
def get_definition(self, project, definition_id, revision=None, min_metrics_time=None, property_filters=None, include_latest_builds=None): """GetDefinition. Gets a definition, optionally at a specific revision. :param str project: Project ID or project name :param int definition_id: The ...
GetDefinition. Gets a definition, optionally at a specific revision. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :param int revision: The revision number to retrieve. If this is not specified, the latest version will be returned. ...
def dump(self, data, stream=None): """Encrypt data and print stdout or write to stream.""" yaml_text = yaml.dump( data, default_flow_style=False, allow_unicode=True) return self.dump_raw(yaml_text, stream=stream)
Encrypt data and print stdout or write to stream.
def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None): # type: (str, bool, Optional[ExceptionUpperBound]) -> Tuple[[Optional[str], bool]] """Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second showing if the match is exact or ...
Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second showing if the match is exact or not. Args: country (str): Country for which to get ISO3 code use_live (bool): Try to get use latest data from web rather than file in package. Defa...
def multinomial_like(x, n, p): R""" Multinomial log-likelihood. Generalization of the binomial distribution, but instead of each trial resulting in "success" or "failure", each one results in exactly one of some fixed finite number k of possible outcomes over n independent trials. 'x[i]' indica...
R""" Multinomial log-likelihood. Generalization of the binomial distribution, but instead of each trial resulting in "success" or "failure", each one results in exactly one of some fixed finite number k of possible outcomes over n independent trials. 'x[i]' indicates the number of times outcome...
def prepend_to_list(self, key, *value, pipeline=False): """Add new element to the start of the list stored at key. Args: key (str): Key where the list is stored value: Value to add to the list pipeline (bool): True, start a transaction block. Default false. ...
Add new element to the start of the list stored at key. Args: key (str): Key where the list is stored value: Value to add to the list pipeline (bool): True, start a transaction block. Default false.
def refresh_state(self, id_or_uri, configuration, timeout=-1): """ Refreshes a drive enclosure. Args: id_or_uri: Can be either the resource ID or the resource URI. configuration: Configuration timeout: Timeout in seconds. Wait for task completion by default. ...
Refreshes a drive enclosure. Args: id_or_uri: Can be either the resource ID or the resource URI. configuration: Configuration timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops ...
def settings_module_update(self, mode_audiopin_enable=None, mode_audiopass_enable=None, mode_default=None): """ Set Module settings. Uses PUT to /settings/modules interface. :Args: * *mode_audiopin_en...
Set Module settings. Uses PUT to /settings/modules interface. :Args: * *mode_audiopin_enable*: (bool) Turn on and off the AudioPIN feature * *mode_audiopass_enable*: (bool) Turn on and off the AudioPass feature * *mode_default*: (str) Set the default verification mode. Either '...
def phase3(self): """ Find out differences between common files. Ensure we are using content comparison with shallow=False. """ fcomp = filecmp.cmpfiles(self.left, self.right, self.common_files, shallow=False) self.same_files, self.diff_fi...
Find out differences between common files. Ensure we are using content comparison with shallow=False.
def _get_layout_as_etree(layout_dict): """ Convert something that looks like this: { 'color' : ['red'], 'shapefile' : ['blah.shp'] } Into something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> ...
Convert something that looks like this: { 'color' : ['red'], 'shapefile' : ['blah.shp'] } Into something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> ...
def last_first(self): """Return a name in the format of: Lastname, Firstname [(Nickname)] """ return "{}, {} ".format(self.last_name, self.first_name) + ("({})".format(self.nickname) if self.nickname else "")
Return a name in the format of: Lastname, Firstname [(Nickname)]
def _remove_uri_scheme_from_textbuffer(self, scheme): """Remove the URI scheme of a new external link from the textbuffer.""" length = len(scheme) while length: if length < len(self._textbuffer[-1]): self._textbuffer[-1] = self._textbuffer[-1][:-length] ...
Remove the URI scheme of a new external link from the textbuffer.
def zPushLens(self, update=None): """Push lens in ZOS COM server to UI""" self.SaveAs(self._sync_ui_file) OpticalSystem._dde_link.zLoadFile(self._sync_ui_file) OpticalSystem._dde_link.zPushLens(update)
Push lens in ZOS COM server to UI
def translate_to_stackdriver(self, trace): """Translate the spans json to Stackdriver format. See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/ projects.traces/batchWrite :type trace: dict :param trace: Trace dictionary :rtype: dict :returns: ...
Translate the spans json to Stackdriver format. See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/ projects.traces/batchWrite :type trace: dict :param trace: Trace dictionary :rtype: dict :returns: Spans in Google Cloud StackDriver Trace format.
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 128 return hparams
separate rgb embeddings.
def install_webpi(name, install_args=None, override_args=False): ''' Instructs Chocolatey to install a package via the Microsoft Web PI service. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to th...
Instructs Chocolatey to install a package via the Microsoft Web PI service. name The name of the package to be installed. Only accepts a single argument. install_args A list of install arguments you want to pass to the installation process i.e product key or feature list override_...
def mouseMoveEvent( self, event ): """ Sets the value for the slider at the event position. :param event | <QMouseEvent> """ self.setValue(self.valueAt(event.pos().x()))
Sets the value for the slider at the event position. :param event | <QMouseEvent>
def describe_spot_price_history(DryRun=None, StartTime=None, EndTime=None, InstanceTypes=None, ProductDescriptions=None, Filters=None, AvailabilityZone=None, MaxResults=None, NextToken=None): """ Describes the Spot price history. For more information, see Spot Instance Pricing History in the Amazon Elastic Comp...
Describes the Spot price history. For more information, see Spot Instance Pricing History in the Amazon Elastic Compute Cloud User Guide . When you specify a start and end time, this operation returns the prices of the instance types within the time range that you specified and the time when the price changed. The ...
def strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet m...
Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str`
def _init_offsets(self, batchsize): """ Compute new initial and target offsets and do other maintenance tasks """ upper_offsets = previous_lower_offsets = self._lower_offsets if not upper_offsets: upper_offsets = self.latest_offsets self._upper_offsets = {p: o...
Compute new initial and target offsets and do other maintenance tasks
def _setup_metrics(self): """ Start metric exposition """ path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) e...
Start metric exposition
def delete(self, uri): """Method deletes a Fedora Object in the repository Args: uri(str): URI of Fedora Object """ try: self.connect(uri, method='DELETE') return True except urllib.error.HTTPError: return False
Method deletes a Fedora Object in the repository Args: uri(str): URI of Fedora Object
def pydoc_cli_monkey_patched(port): """In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process. """ # Monkey-patch input so that input does not raise EOFError when # called by pydoc.cli def input(_): # pylint: disable=W0622 """Monkey-patched ...
In Python 3, run pydoc.cli with builtins.input monkey-patched so that pydoc can be run as a process.
def types(self): ''' Returns an iterator over the types of the neurites in the object. If the object is a tree, then one value is returned. ''' neurites = self._obj.neurites if hasattr(self._obj, 'neurites') else (self._obj,) return (neu.type for neu in neurites)
Returns an iterator over the types of the neurites in the object. If the object is a tree, then one value is returned.
def all(self, data={}, **kwargs): """" Fetch all Order entities Returns: Dictionary of Order data """ return super(Order, self).all(data, **kwargs)
Fetch all Order entities Returns: Dictionary of Order data
def extract_ids(text, extractors): """ Uses `extractors` to extract citation identifiers from a text. :Parameters: text : str The text to process extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` -- a generat...
Uses `extractors` to extract citation identifiers from a text. :Parameters: text : str The text to process extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` -- a generator of extracted identifiers
def total_charges(self): """ Represents the 'goods' acquired in the invoice. """ selected_charges = Charge.objects \ .filter(invoice=self) \ .charges() \ .exclude(product_code=CARRIED_FORWARD) return total_amount(selected_charges)
Represents the 'goods' acquired in the invoice.
def get_occupation(self, atom_index, orbital): """ Returns the occupation for a particular orbital of a particular atom. Args: atom_num (int): Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is conve...
Returns the occupation for a particular orbital of a particular atom. Args: atom_num (int): Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is converted to 0-based indexing in this parser to be consi...
def create_configwidget(self, parent): """Create configuration dialog box page widget""" if self.CONFIGWIDGET_CLASS is not None: configwidget = self.CONFIGWIDGET_CLASS(self, parent) configwidget.initialize() return configwidget
Create configuration dialog box page widget
def check_unique_named_object_has_class(root, name, class_name): """ checks the type (type name) of an unique named object (no fully qualified name) Args: root: start of search name: name of object class_name: the name of the type to be checked Returns: nothing (if ...
checks the type (type name) of an unique named object (no fully qualified name) Args: root: start of search name: name of object class_name: the name of the type to be checked Returns: nothing (if not unique, raises an error)
def solve(self): """ Run the solver and assign the solution's :class:`CoordSystem` instances as the corresponding part's world coordinates. """ if self.world_coords is None: log.warning("solving for Assembly without world coordinates set: %r", self) for (comp...
Run the solver and assign the solution's :class:`CoordSystem` instances as the corresponding part's world coordinates.
def get_item_position(self, analysis_uid): """Returns a list with the position for the analysis_uid passed in within the current worksheet in accordance with the current layout, where the first item from the list returned is the slot and the second is the position of the analysis within ...
Returns a list with the position for the analysis_uid passed in within the current worksheet in accordance with the current layout, where the first item from the list returned is the slot and the second is the position of the analysis within the slot. :param analysis_uid: uid of the ana...
def add_space(self, line): """Add a Space object to the section Used during initial parsing mainly Args: line (str): one line that defines the space, maybe whitespaces """ if not isinstance(self.last_item, Space): space = Space(self._structure) ...
Add a Space object to the section Used during initial parsing mainly Args: line (str): one line that defines the space, maybe whitespaces
def unwrap(self): """Remove the security layer. Use this method only if you want to send plaintext data on the connection after the security layer has been removed. In all other cases, use :meth:`close`. If the unwrap is initiated by us, then any data sent after it will be ...
Remove the security layer. Use this method only if you want to send plaintext data on the connection after the security layer has been removed. In all other cases, use :meth:`close`. If the unwrap is initiated by us, then any data sent after it will be buffered until the corres...
def iodp_dscr_lore(dscr_file,dscr_ex_file="", dir_path=".", input_dir_path="",volume=7,noave=False,\ meas_file="measurements.txt", offline_meas_file="",spec_file="specimens.txt"): """ Convert IODP discrete measurement files in MagIC file(s). This program assumes that you have created the speci...
Convert IODP discrete measurement files in MagIC file(s). This program assumes that you have created the specimens, samples, sites and location files using convert_2_magic.iodp_samples_csv from files downloaded from the LIMS online repository and that all samples are in that file. If there are offline ...
def admin_footer(parser, token): """ Template tag that renders the footer information based on the authenticated user's permissions. """ # split_contents() doesn't know how to split quoted strings. tag_name = token.split_contents() if len(tag_name) > 1: raise base.TemplateSyntaxErro...
Template tag that renders the footer information based on the authenticated user's permissions.
def get_CV_prediction(self): """ Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`). """ # TODO: get it from the test_prediction ... # test_id, prediction # sort by test_id predict_vec = np.zeros((self._n_...
Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`).
def _add_entity_id(self, config, co_name): """ Use the CO name to construct the entity ID for the virtual IdP for the CO. The entity ID has the form {base_entity_id}/{co_name} :type config: satosa.satosa_config.SATOSAConfig :type co_name: str :rtype: sa...
Use the CO name to construct the entity ID for the virtual IdP for the CO. The entity ID has the form {base_entity_id}/{co_name} :type config: satosa.satosa_config.SATOSAConfig :type co_name: str :rtype: satosa.satosa_config.SATOSAConfig :param config: satosa ...
def write_hdf5_dict(flags, output, path=None, append=False, overwrite=False, **kwargs): """Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to an HDF5-format file. Parameters ---------- output : `str`, :class:`h5py.Group` path to new output file, or o...
Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to an HDF5-format file. Parameters ---------- output : `str`, :class:`h5py.Group` path to new output file, or open h5py `Group` to write to. path : `str` the HDF5 group path in which to write a new group for this ...
def allocate_clusters(self, eps = 0.01, indexes = None, iteration = None): """! @brief Returns list of clusters in line with state of ocillators (phases). @param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one cluster. @...
! @brief Returns list of clusters in line with state of ocillators (phases). @param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one cluster. @param[in] indexes (list): List of real object indexes and it should be equal to amount ...
def getPlannedFor(self, plannedfor_name, projectarea_id=None, projectarea_name=None, archived=False, returned_properties=None): """Get :class:`rtcclient.models.PlannedFor` object by its name :param plannedfor_name: the plannedfor name :param projectar...
Get :class:`rtcclient.models.PlannedFor` object by its name :param plannedfor_name: the plannedfor name :param projectarea_id: the :class:`rtcclient.project_area.ProjectArea` id :param projectarea_name: the project area name :param archived: (default is False) whether the pl...
def smart_truncate(string, max_length=0, word_boundary=False, separator=' ', save_order=False): """ Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of outp...
Truncate a string. :param string (str): string for modification :param max_length (int): output string length :param word_boundary (bool): :param save_order (bool): if True then word order of output string is like input string :param separator (str): separator between words :return:
def do_list(self): """! @brief Handle 'list' subcommand.""" # Default to listing probes. if (self._args.probes, self._args.targets, self._args.boards) == (False, False, False): self._args.probes = True # Create a session with no device so we load any config. ...
! @brief Handle 'list' subcommand.
def enter_password_change(self, username=None, old_password=None): """ Responds to a forced password change via `passwd` prompts due to password expiration. """ from fabric.state import connections from fabric.network import disconnect_all r = self.local_renderer # ...
Responds to a forced password change via `passwd` prompts due to password expiration.
def user_activity_stats(self, username, format=None): """ Retrieve the activity stats about a specific user over the last year. Params: username (string): filters the username of the user whose activity you are interested in. format (string): Allows changing the of the d...
Retrieve the activity stats about a specific user over the last year. Params: username (string): filters the username of the user whose activity you are interested in. format (string): Allows changing the of the date/time returned from iso format to unix tim...