code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def build_knowledge_graph(self, json_ontology: dict) -> List: """ The idea if to be able to build a json knowledge graph from a json like ontology representation, eg: kg_object_ontology = { "uri": doc.doc_id, "country": doc.select_segments("$.Location"), "typ...
The idea if to be able to build a json knowledge graph from a json like ontology representation, eg: kg_object_ontology = { "uri": doc.doc_id, "country": doc.select_segments("$.Location"), "type": [ "Event", doc.extract(self.incomp_decoder, do...
def lessgreater(x, y): """ Return True if x < y or x > y and False otherwise. This function returns False whenever x and/or y is a NaN. """ x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return mpfr.mpfr_lessgreater_p(x, y)
Return True if x < y or x > y and False otherwise. This function returns False whenever x and/or y is a NaN.
def cudnnSetTensor(handle, srcDesc, srcData, value): """" Set all data points of a tensor to a given value : srcDest = alpha. Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. srcDesc : cudnnTensorDescriptor Handle to a previously initializ...
Set all data points of a tensor to a given value : srcDest = alpha. Parameters ---------- handle : cudnnHandle Handle to a previously created cuDNN context. srcDesc : cudnnTensorDescriptor Handle to a previously initialized tensor descriptor. srcData : void_p Pointer to data...
def _index_to_ansi_values(self, index): ''' Converts an palette index to the corresponding ANSI color. Arguments: index - an int (from 0-15) Returns: index as str in a list for compatibility with values. ''' if self.__class__.__name__[0]...
Converts an palette index to the corresponding ANSI color. Arguments: index - an int (from 0-15) Returns: index as str in a list for compatibility with values.
def set_max_waypoint_items(self, max_waypoint_items): """This determines how many waypoint items will be seen for a scaffolded wrong answer""" if self.get_max_waypoint_items_metadata().is_read_only(): raise NoAccess() if not self.my_osid_object_form._is_valid_cardinal(max_waypoint_it...
This determines how many waypoint items will be seen for a scaffolded wrong answer
def _run_qmc(self, boot): """ Runs quartet max-cut QMC on the quartets qdump file. """ ## build command self._tmp = os.path.join(self.dirs, ".tmptre") cmd = [ip.bins.qmc, "qrtt="+self.files.qdump, "otre="+self._tmp] ## run it proc = subprocess.Popen(cmd,...
Runs quartet max-cut QMC on the quartets qdump file.
def _crop(self, bounds, xsize=None, ysize=None, resampling=Resampling.cubic): """Crop raster outside vector (convex hull). :param bounds: bounds on image :param xsize: output raster width, None for full resolution :param ysize: output raster height, None for full resolution :par...
Crop raster outside vector (convex hull). :param bounds: bounds on image :param xsize: output raster width, None for full resolution :param ysize: output raster height, None for full resolution :param resampling: reprojection resampling method, default `cubic` :return: GeoRaste...
def iselect(self, tag, limit=0): """Iterate the specified tags.""" for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit): yield el
Iterate the specified tags.
def set_from_json(self, obj, json, models=None, setter=None): '''Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on json: (JSON-value) : value to set to the attribute to models (dict or None, optional) :...
Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) ...
def check_state(self, state): """ Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool """ if state.addr == ...
Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool
def unary_operator(op): """ Factory function for making unary operator methods for Filters. """ valid_ops = {'~'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) def unary_operator(self): # This can't be hoisted up a scope because the types returned b...
Factory function for making unary operator methods for Filters.
def get_item(self, path): """ Get resource item :param path: string :return: Image """ try: f = tempfile.NamedTemporaryFile() self.blob_service.get_blob_to_path(self.container_name, path, f.name) f.seek(0) image = Image.open...
Get resource item :param path: string :return: Image
def save_to_file(destination_filename, append=False): """ Save the output value to file. """ def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) makedirs(os.path.dirname(destination_filename)) mode = "a" if append...
Save the output value to file.
def _update_docs(self, file_to_update): """ Update the given documentation file or :code:`README.rst` so that it always gives branch related URL and informations. .. note:: This only apply to :code:`dev` and :code:`master` branch. :param file_to_update: The file to ...
Update the given documentation file or :code:`README.rst` so that it always gives branch related URL and informations. .. note:: This only apply to :code:`dev` and :code:`master` branch. :param file_to_update: The file to update. :type file_to_update: str
def groups_invite(self, room_id, user_id, **kwargs): """Adds a user to the private group.""" return self.__call_api_post('groups.invite', roomId=room_id, userId=user_id, kwargs=kwargs)
Adds a user to the private group.
def withdraw(self, account_id, **params): """https://developers.coinbase.com/api/v2#withdraw-funds""" for required in ['payment_method', 'amount', 'currency']: if required not in params: raise ValueError("Missing required parameter: %s" % required) response = self._po...
https://developers.coinbase.com/api/v2#withdraw-funds
def validate_config(self, values, argv=None, strict=False): """Validate all config values through the command-line parser. This takes all supplied options (which could have been retrieved from a number of sources (such as CLI, env vars, etc...) and then validates them by running them th...
Validate all config values through the command-line parser. This takes all supplied options (which could have been retrieved from a number of sources (such as CLI, env vars, etc...) and then validates them by running them through argparser (and raises SystemExit on failure). :r...
def from_dict(cls, eas_from_nios): """Converts extensible attributes from the NIOS reply.""" if not eas_from_nios: return return cls({name: cls._process_value(ib_utils.try_value_to_bool, eas_from_nios[name]['value']) fo...
Converts extensible attributes from the NIOS reply.
def add_service(self, service_name): """ Add the given service to the manifest. """ if service_name not in self.manifest['services']: self.manifest['services'].append(service_name)
Add the given service to the manifest.
def get_pv_args(name, session=None, call=None): ''' Get PV arguments for a VM .. code-block:: bash salt-cloud -a get_pv_args xenvm01 ''' if call == 'function': raise SaltCloudException( 'This function must be called with -a or --action.' ) if session is Non...
Get PV arguments for a VM .. code-block:: bash salt-cloud -a get_pv_args xenvm01
def _compile(self, dirpath, makename, compiler, debug, profile): """Compiles the makefile at the specified location with 'compiler'. :arg dirpath: the full path to the directory where the makefile lives. :arg compiler: one of ['ifort', 'gfortran']. :arg makename: the name of the make fi...
Compiles the makefile at the specified location with 'compiler'. :arg dirpath: the full path to the directory where the makefile lives. :arg compiler: one of ['ifort', 'gfortran']. :arg makename: the name of the make file to compile.
def removeComments( self, comment = None ): """ Inserts comments into the editor based on the current selection.\ If no comment string is supplied, then the comment from the language \ will be used. :param comment | <str> || None :return <bool> ...
Inserts comments into the editor based on the current selection.\ If no comment string is supplied, then the comment from the language \ will be used. :param comment | <str> || None :return <bool> | success
def expect_lit(char, buf, pos): """Expect a literal character at the current buffer position.""" if pos >= len(buf) or buf[pos] != char: return None, len(buf) return char, pos+1
Expect a literal character at the current buffer position.
def deleteAll(self): """ Deletes whole Solr index. Use with care. """ for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{\"delete\": { \"query\" : \"*:*\"}}")
Deletes whole Solr index. Use with care.
def results_path(self) -> str: """The path where the project results will be written""" def possible_paths(): yield self._results_path yield self.settings.fetch('path_results') yield environ.configs.fetch('results_directory') yield environ.paths.results(s...
The path where the project results will be written
def extract_variables(href): """Return a list of variable names used in a URI template.""" patterns = [re.sub(r'\*|:\d+', '', pattern) for pattern in re.findall(r'{[\+#\./;\?&]?([^}]+)*}', href)] variables = [] for pattern in patterns: for part in pattern.split(","): ...
Return a list of variable names used in a URI template.
def writelines(self, lines): """Write a list of strings to file.""" self.make_dir() with open(self.path, "w") as f: return f.writelines(lines)
Write a list of strings to file.
def add_user_to_group(iam_client, user, group, quiet = False): """ Add an IAM user to an IAM group :param iam_client: :param group: :param user: :param user_info: :param dry_run: :return: """ if not quiet: printInfo('Adding user to group %s...' % group) iam_client.ad...
Add an IAM user to an IAM group :param iam_client: :param group: :param user: :param user_info: :param dry_run: :return:
def attribute(self): """ Attribute that serves as a reference getter """ refs = re.findall( "\@([a-zA-Z:]+)=\\\?[\'\"]\$"+str(self.refsDecl.count("$"))+"\\\?[\'\"]", self.refsDecl ) return refs[-1]
Attribute that serves as a reference getter
def find_nested_meta_first_bf(d, prop_name): """Returns the $ value of the first meta element with the @property that matches @prop_name (or None). """ m_list = d.get('meta') if not m_list: return None if not isinstance(m_list, list): m_list = [m_list] for m_el in m_list: ...
Returns the $ value of the first meta element with the @property that matches @prop_name (or None).
def backup(): """ zips into db_backups_dir and uploads to bucket_name/s3_folder fab -f ./fabfile.py backup_dbs """ args = parser.parse_args() s3_backup_dir( args.datadir, args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name, args.zip_back...
zips into db_backups_dir and uploads to bucket_name/s3_folder fab -f ./fabfile.py backup_dbs
def add_user_to_group(self, user_name, group_name): """Adds a user to a group. :param user_name: name of user to be added :param group_name: name of group user is to be added to :returns: True if user added :raises: HTTPResponseError in case an HTTP error status was returned ...
Adds a user to a group. :param user_name: name of user to be added :param group_name: name of group user is to be added to :returns: True if user added :raises: HTTPResponseError in case an HTTP error status was returned
def translate(offset, dtype=None): """Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix descr...
Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the translation.
def _set_renamed_columns(self, table_diff, command, column): """ Set the renamed columns on the table diff. :rtype: orator.dbal.TableDiff """ new_column = Column(command.to, column.get_type(), column.to_dict()) table_diff.renamed_columns = {command.from_: new_column} ...
Set the renamed columns on the table diff. :rtype: orator.dbal.TableDiff
def encrypt(self, pkt, seq_num=None, iv=None): """ Encrypt (and encapsulate) an IP(v6) packet with ESP or AH according to this SecurityAssociation. @param pkt: the packet to encrypt @param seq_num: if specified, use this sequence number instead of the ...
Encrypt (and encapsulate) an IP(v6) packet with ESP or AH according to this SecurityAssociation. @param pkt: the packet to encrypt @param seq_num: if specified, use this sequence number instead of the generated one @param iv: if specified, use this initi...
def migrate1(): "Migrate from version 0 to 1" initial = [ "create table Chill (version integer);", "insert into Chill (version) values (1);", "alter table SelectSQL rename to Query;", "alter table Node add column template integer references Template (id) on delete set null;", "alter table N...
Migrate from version 0 to 1
def show(*args, **kwargs): r"""Show created figures, alias to ``plt.show()``. By default, showing plots does not block the prompt. Calling this function will block execution. """ _, plt, _ = _import_plt() plt.show(*args, **kwargs)
r"""Show created figures, alias to ``plt.show()``. By default, showing plots does not block the prompt. Calling this function will block execution.
def changed_lines(self): """ A list of dicts in the format: { 'file_name': str, 'content': str, 'line_number': int, 'position': int } """ lines = [] file_name = '' line_number = 0 ...
A list of dicts in the format: { 'file_name': str, 'content': str, 'line_number': int, 'position': int }
def plot_gaussian_cdf(mean=0., variance=1., ax=None, xlim=None, ylim=(0., 1.), xlabel=None, ylabel=None, label=None): """ Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-...
Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- mean : scalar, default 0. mean for the normal distribution. variance : scalar, default 0. variance for the normal distribu...
def columnCount(self, parent): """Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None """ if parent.isValid(): ...
Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None
def reference(self, install, upgrade): """Reference list with packages installed and upgraded """ self.template(78) print("| Total {0} {1} installed and {2} {3} upgraded".format( len(install), self.pkg(len(install)), len(upgrade), self.pkg(len(upgrade)))) ...
Reference list with packages installed and upgraded
def getcomponents(self, product, force_refresh=False): """ Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bug...
Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed di...
def winning_abbr(self): """ Returns a ``string`` of the winning team's abbreviation, such as 'HOU' for the Houston Astros. """ if self.winner == HOME: return utils._parse_abbreviation(self._home_name) return utils._parse_abbreviation(self._away_name)
Returns a ``string`` of the winning team's abbreviation, such as 'HOU' for the Houston Astros.
def delete(ids, yes): """ Delete datasets. """ failures = False for id in ids: data_source = get_data_object(id, use_data_config=True) if not data_source: failures = True continue data_name = normalize_data_name(data_source.name) suffix = da...
Delete datasets.
async def add_items(self, *items): '''append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items : ''' items = [item.id for item in await self.process(items)] if not items: re...
append items to the playlist |coro| Parameters ---------- items : array_like list of items to add(or their ids) See Also -------- remove_items :
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth obj...
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class ...
def dumps(obj, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False...
Serialize ``obj`` as Python ``string`` or ``bytes`` object, using the conversion table used by ``dump`` (above). Args: obj (Any): A python object to serialize according to the above table. Any Python object which is neither an instance of nor inherits from one of the types in the above table wi...
def json_obj_to_cursor(self, json): """(Deprecated) Converts a JSON object to a mongo db cursor :param str json: A json string :returns: dictionary with ObjectId type :rtype: dict """ cursor = json_util.loads(json) if "id" in json: cursor["_id"] = Obj...
(Deprecated) Converts a JSON object to a mongo db cursor :param str json: A json string :returns: dictionary with ObjectId type :rtype: dict
def OnPaneClose(self, event): """Pane close toggle event handler (via close button)""" toggle_label = event.GetPane().caption # Get menu item to toggle menubar = self.main_window.menubar toggle_id = menubar.FindMenuItem(_("View"), toggle_label) toggle_item = menubar.Fin...
Pane close toggle event handler (via close button)
def sort(self, **kwargs): """ Adds a sort stage to aggregation query :param kwargs: Specifies the field(s) to sort by and the respective sort order. :return: The current object """ query = {} for field in kwargs: query[field] = kwargs[field] se...
Adds a sort stage to aggregation query :param kwargs: Specifies the field(s) to sort by and the respective sort order. :return: The current object
def decode_format_timestamp(timestamp): """Convert unix timestamp (millis) into date & time we use in logs output. :param timestamp: unix timestamp in millis :return: date, time in UTC """ dt = maya.MayaDT(timestamp / 1000).datetime(naive=True) return dt.strftime('%Y-%m-%d'), dt.strftime('%H:%M...
Convert unix timestamp (millis) into date & time we use in logs output. :param timestamp: unix timestamp in millis :return: date, time in UTC
def _jobs_to_do(self, restrictions): """ :return: the relation containing the keys to be computed (derived from self.key_source) """ if self.restriction: raise DataJointError('Cannot call populate on a restricted table. ' 'Instead, pass condit...
:return: the relation containing the keys to be computed (derived from self.key_source)
def is_artifact_optional(chain, task_id, path): """Tells whether an artifact is flagged as optional or not. Args: chain (ChainOfTrust): the chain of trust object task_id (str): the id of the aforementioned task Returns: bool: True if artifact is optional """ upstream_artif...
Tells whether an artifact is flagged as optional or not. Args: chain (ChainOfTrust): the chain of trust object task_id (str): the id of the aforementioned task Returns: bool: True if artifact is optional
def detect_iter(self, det_iter, show_timer=False): """ detect all images in iterator Parameters: ---------- det_iter : DetIter iterator for all testing images show_timer : Boolean whether to print out detection exec time Returns: ...
detect all images in iterator Parameters: ---------- det_iter : DetIter iterator for all testing images show_timer : Boolean whether to print out detection exec time Returns: ---------- list of detection results
def validate_output_format(self, default_format): """ Prepare output format for later use. """ output_format = self.options.output_format # Use default format if none is given if output_format is None: output_format = default_format # Check if it's a custom ...
Prepare output format for later use.
def token_count_pandas(self): """ See token counts as pandas dataframe""" freq_df = pd.DataFrame.from_dict(self.indexer.word_counts, orient='index') freq_df.columns = ['count'] return freq_df.sort_values('count', ascending=False)
See token counts as pandas dataframe
def save(self, commit=True, **kwargs): '''Register the current user as admin on creation''' org = super(OrganizationForm, self).save(commit=False, **kwargs) if not org.id: user = current_user._get_current_object() member = Member(user=user, role='admin') org....
Register the current user as admin on creation
def showlist(self, window_name, object_name): """ Show combo box list / menu @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full na...
Show combo box list / menu @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type...
def find_one(self, **kwargs): """Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future Example:: manager = EntityManager(Product) product_saved = yield manager.find_one(_id=object_id) ...
Returns future. Executes collection's find_one method based on keyword args maps result ( dict to instance ) and return future Example:: manager = EntityManager(Product) product_saved = yield manager.find_one(_id=object_id)
def copy(self, filename: Optional[PathLike] = None) -> 'AnnData': """Full copy, optionally on disk.""" if not self.isbacked: return AnnData(self._X.copy() if self._X is not None else None, self._obs.copy(), self._var.copy(), ...
Full copy, optionally on disk.
def onAutoIndentTriggered(self): """Indent current line or selected lines """ cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != end...
Indent current line or selected lines
def _mean_prediction(self,theta,Y,scores,h,t_params): """ Creates a h-step ahead mean prediction Parameters ---------- theta : np.array The past predicted values Y : np.array The past data scores : np.array The past scores h...
Creates a h-step ahead mean prediction Parameters ---------- theta : np.array The past predicted values Y : np.array The past data scores : np.array The past scores h : int How many steps ahead for the prediction ...
def setDaemon(self, runnable, isdaemon, noregister = False): ''' If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons. ''' if not noregister and runnable not in self.registerIndex: self.register((), ru...
If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons.
def get_subcols(module_ident, plpy): """Get all the sub-collections that the module is part of.""" plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid FROM trees tr WHERE tr.documentid = $1 and tr...
Get all the sub-collections that the module is part of.
def readCell(self, row, col): ''' read a cell''' try: if self.__sheet is None: self.openSheet(super(ExcelRead, self).DEFAULT_SHEET) return self.__sheet.cell(row, col).value except BaseException as excp: raise UfException(Errors.UNKNOWN...
read a cell
def main(): """Commande line interface""" parser = argparse.ArgumentParser(description='Extract parameters from an ULog file') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') parser.add_argument('-d', '--delimiter', dest='delimiter', action='store', ...
Commande line interface
def basic_auth(f): """ Injects auth, into requests call over route :return: route """ def wrapper(*args, **kwargs): self = args[0] if 'auth' in kwargs: raise AttributeError("don't set auth token explicitly") assert self.is_connected, "not connected, call router.c...
Injects auth, into requests call over route :return: route
def export_compound(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue): """ Export Compound TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" ...
Export Compound TSV/CSV tables
def movementCompute(self, displacement, noiseFactor = 0): """ Shift the current active cells by a vector. @param displacement (pair of floats) A translation vector [di, dj]. """ if noiseFactor != 0: displacement = copy.deepcopy(displacement) xnoise = np.random.normal(0, noiseFactor...
Shift the current active cells by a vector. @param displacement (pair of floats) A translation vector [di, dj].
def load(self, size): """open and read the file is existent""" if self.exists() and self.isfile(): return eval(open(self).read(size))
open and read the file is existent
def _build_credentials_tuple(mech, source, user, passwd, extra, database): """Build and return a mechanism specific credentials tuple. """ if mech != 'MONGODB-X509' and user is None: raise ConfigurationError("%s requires a username." % (mech,)) if mech == 'GSSAPI': if source is not None ...
Build and return a mechanism specific credentials tuple.
def copy_random_state(random_state, force_copy=False): """ Creates a copy of a random state. Parameters ---------- random_state : numpy.random.RandomState The random state to copy. force_copy : bool, optional If True, this function will always create a copy of every random ...
Creates a copy of a random state. Parameters ---------- random_state : numpy.random.RandomState The random state to copy. force_copy : bool, optional If True, this function will always create a copy of every random state. If False, it will not copy numpy's default random state,...
def update_video_image(edx_video_id, course_id, image_data, file_name): """ Update video image for an existing video. NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise a new file name is constructed based on uuid and extension from `file_name` value. `image_data`...
Update video image for an existing video. NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise a new file name is constructed based on uuid and extension from `file_name` value. `image_data` will be None in case of course re-run and export. Arguments: image_dat...
def gnpool(name, start, room, lenout=_default_len_out): """ Return names of kernel variables matching a specified template. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gnpool_c.html :param name: Template that names should match. :type name: str :param start: Index of first matching...
Return names of kernel variables matching a specified template. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gnpool_c.html :param name: Template that names should match. :type name: str :param start: Index of first matching name to retrieve. :type start: int :param room: The largest...
def bounds_window(bounds, affine): """Create a full cover rasterio-style window """ w, s, e, n = bounds row_start, col_start = rowcol(w, n, affine) row_stop, col_stop = rowcol(e, s, affine, op=math.ceil) return (row_start, row_stop), (col_start, col_stop)
Create a full cover rasterio-style window
def network_lpf_contingency(network, snapshots=None, branch_outages=None): """ Computes linear power flow for a selection of branch outages. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, defau...
Computes linear power flow for a selection of branch outages. Parameters ---------- snapshots : list-like|single snapshot A subset or an elements of network.snapshots on which to run the power flow, defaults to network.snapshots NB: currently this only works for a single snapshot ...
def to_dict(self): """ Return a dictionary of the worker stats. Returns: dict: Dictionary of the stats. """ return { 'name': self.name, 'broker': self.broker.to_dict(), 'pid': self.pid, 'process_pids': self.process_pids, ...
Return a dictionary of the worker stats. Returns: dict: Dictionary of the stats.
def process_schema(value): """Load schema from JSONSchema registry based on given value. :param value: Schema path, relative to the directory when it was registered. :returns: The schema absolute path. """ schemas = current_app.extensions['invenio-jsonschemas'].schemas try: retu...
Load schema from JSONSchema registry based on given value. :param value: Schema path, relative to the directory when it was registered. :returns: The schema absolute path.
def merge_from(self, other): """Merge information from another PhoneNumberDesc object into this one.""" if other.national_number_pattern is not None: self.national_number_pattern = other.national_number_pattern if other.example_number is not None: self.example_number = ot...
Merge information from another PhoneNumberDesc object into this one.
def get_repository_nodes(self, repository_id, ancestor_levels, descendant_levels, include_siblings): """Gets a portion of the hierarchy for the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of anc...
Gets a portion of the hierarchy for the given repository. arg: repository_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to include. A value of 0 returns no parents in the node. arg: descendant...
def urlretrieve(self, url, filename=None, method='GET', body=None, dir=None, **kwargs): """ Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided o...
Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided or :meth:`urlretrieve` will safely create a temporary file. If a directory is provided, a file will b...
def preflight(self): """Handles request authentication""" origin = self.request.headers.get('Origin', '*') self.set_header('Access-Control-Allow-Origin', origin) headers = self.request.headers.get('Access-Control-Request-Headers') if headers: self.set_header('Access-...
Handles request authentication
def _setextra(self, extradata): ''' Set the _extra field in the struct, which stands for the additional ("extra") data after the defined fields. ''' current = self while hasattr(current, '_sub'): current = current._sub _set(current, '_extra', extradata...
Set the _extra field in the struct, which stands for the additional ("extra") data after the defined fields.
def _calc_validation_statistics(validation_results): """ Calculate summary statistics for the validation results and return ``ExpectationStatistics``. """ # calc stats successful_expectations = sum(exp["success"] for exp in validation_results) evaluated_expectations = len(validation_results)...
Calculate summary statistics for the validation results and return ``ExpectationStatistics``.
def imshow_z(data, name): """2D color plot of the quasiparticle weight as a function of interaction and doping""" zmes = pick_flat_z(data) plt.figure() plt.imshow(zmes.T, origin='lower', \ extent=[data['doping'].min(), data['doping'].max(), \ 0, data['u_int'].max()], asp...
2D color plot of the quasiparticle weight as a function of interaction and doping
def _backup_dir_item(self, dir_path, process_bar): """ Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() instance """ self.path_helper.set_src_filepath(dir_path) if self.path_helper.abs_src_filepath is None: self.total_errored_items += 1 ...
Backup one dir item :param dir_path: filesystem_walk.DirEntryPath() instance
def _compute_distance(self, dists, C): """ Compute the second term of the equation described on p. 1144: `` c4 * np.log(sqrt(R ** 2. + h ** 2.) """ return C["c4"] * np.log(np.sqrt(dists.rrup ** 2. + C["h"] ** 2.))
Compute the second term of the equation described on p. 1144: `` c4 * np.log(sqrt(R ** 2. + h ** 2.)
def create_language_dataset_from_url(self, file_url, token=None, url=API_CREATE_LANGUAGE_DATASET): """ Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox,...
Creates a dataset from a publicly accessible file stored in the cloud. :param file_url: string, in the form of a URL to a file accessible on the cloud. Popular options include Dropbox, AWS S3, Google Drive. warning: Google Drive by default gives you a link to a web ui that allows yo...
def read_csv(self, file: str, table: str, libref: str ="", nosub: bool =False, opts: dict = None) -> '<SASdata object>': """ This method will import a csv file into a SAS Data Set and return the SASdata object referring to it. file - eithe the OS filesystem path of the file, or HTTP://... for a url...
This method will import a csv file into a SAS Data Set and return the SASdata object referring to it. file - eithe the OS filesystem path of the file, or HTTP://... for a url accessible file table - the name of the SAS Data Set to create libref - the libref for the SAS Data Set being created. De...
def LoadElement(href, only_etag=False): """ Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache """ request = SMCRequest(href=href) request.exception = FetchElementFailed result = request.read() if only_etag: return result.etag ...
Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache
def _DetermineOperatingSystem(self, searcher): """Tries to determine the underlying operating system. Args: searcher (dfvfs.FileSystemSearcher): file system searcher. Returns: str: operating system for example "Windows". This should be one of the values in definitions.OPERATING_SYSTE...
Tries to determine the underlying operating system. Args: searcher (dfvfs.FileSystemSearcher): file system searcher. Returns: str: operating system for example "Windows". This should be one of the values in definitions.OPERATING_SYSTEM_FAMILIES.
def get_words(self): """ Returns the document words. :return: Document words. :rtype: list """ words = [] block = self.document().findBlockByLineNumber(0) while block.isValid(): blockWords = foundations.strings.get_words(foundations.strings.t...
Returns the document words. :return: Document words. :rtype: list
def InterpolateValue(self, value, type_info_obj=type_info.String(), default_section=None, context=None): """Interpolate the value and parse it with the appropriate type.""" # It is only possible to interpolate strings......
Interpolate the value and parse it with the appropriate type.
async def connect(self): """Establish a connection to the chat server. Returns when an error has occurred, or :func:`disconnect` has been called. """ proxy = os.environ.get('HTTP_PROXY') self._session = http_utils.Session(self._cookies, proxy=proxy) try: ...
Establish a connection to the chat server. Returns when an error has occurred, or :func:`disconnect` has been called.
def rates_for_location(self, postal_code, location_deets=None): """Shows the sales tax rates for a given location.""" request = self._get("rates/" + postal_code, location_deets) return self.responder(request)
Shows the sales tax rates for a given location.
def load(self): """ Loads the user's SDB inventory Raises parseException """ self.inventory = SDBInventory(self.usr) self.forms = self.inventory.forms
Loads the user's SDB inventory Raises parseException
def _update_index(self, axis, key, value): """Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>> self._update_...
Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>> self._update_index("x0", 0) >>> self._update_index("dx", 0)...
def set_calibrators(self, parameter, calibrators): """ Apply an ordered set of calibrators for the specified parameter. This replaces existing calibrators (if any). Each calibrator may have a context, which indicates when it its effects may be applied. Only the first matching ca...
Apply an ordered set of calibrators for the specified parameter. This replaces existing calibrators (if any). Each calibrator may have a context, which indicates when it its effects may be applied. Only the first matching calibrator is applied. A calibrator with context ``None`...
def convert_norm(node, **kwargs): """Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = attrs.get("axis", None) axes = convert_string_to_list(str(mx_axis)) if mx_axis else ...
Map MXNet's norm operator attributes to onnx's ReduceL1 and ReduceL2 operators and return the created node.
def _does_require_deprecation(self): """ Check if we have to put the previous version into the deprecated list. """ for index, version_number in enumerate(self.current_version[0][:2]): # We loop through the 2 last elements of the version. if version_number > sel...
Check if we have to put the previous version into the deprecated list.