INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
This method won t count the snaps in destroying state! | def has_snap(self):
""" This method won't count the snaps in "destroying" state!
:return: false if no snaps or all snaps are destroying.
"""
return len(list(filter(lambda s: s.state != SnapStateEnum.DESTROYING,
self.snapshots))) > 0 |
Return a 2D average of data_label over a season and label1 label2. | def median2D(const, bin1, label1, bin2, label2, data_label,
returnData=False):
"""Return a 2D average of data_label over a season and label1, label2.
Parameters
----------
const: Constellation or Instrument
bin#: [min, max, number of bins]
label#: string
i... |
get the list of resource list to collect based on clz list | def get_rsc_list_2(self, rsc_clz_list=None):
"""get the list of resource list to collect based on clz list
:param rsc_clz_list: the list of classes to collect
:return: filtered list of resource list,
like [VNXLunList(), VNXDiskList()]
"""
rsc_list_2 = self._defa... |
cosmic data load routine called by pysat | def load(cosmicFiles, tag=None, sat_id=None):
"""
cosmic data load routine, called by pysat
"""
import netCDF4
num = len(cosmicFiles)
# make sure there are files to read
if num != 0:
# call separate load_files routine, segemented for possible
# multiprocessor load, not in... |
Loads a list of COSMIC data files supplied by user. Returns a list of dicts a dict for each file. | def load_files(files, tag=None, sat_id=None):
'''Loads a list of COSMIC data files, supplied by user.
Returns a list of dicts, a dict for each file.
'''
output = [None]*len(files)
drop_idx = []
for (i,file) in enumerate(files):
try:
data = netCDF4.Dataset(file) ... |
Downloads data from Madrigal. The user s names should be provided in field user. John Malkovich should be entered as John + Malkovich The password field should be the user s email address. These parameters are passed to Madrigal when downloading. The affiliation field is set to pysat to enable tracking of pysat downloa... | def download(date_array, tag, sat_id, data_path=None, user=None, password=None):
"""Downloads data from Madrigal.
The user's names should be provided in field user. John Malkovich should be
entered as John+Malkovich
The password field should be the user's email address. These parameters
... |
Routine to return DMSP IVM data cleaned to the specified level | def clean(self):
"""Routine to return DMSP IVM data cleaned to the specified level
'Clean' enforces that both RPA and DM flags are <= 1
'Dusty' <= 2
'Dirty' <= 3
'None' None
Routine is called by pysat, and not by the end user directly.
Parameters
-----------
inst : (pysat.... |
Configures a remote system for remote replication. | def create(cls, cli, management_address,
local_username=None, local_password=None,
remote_username=None, remote_password=None,
connection_type=None):
"""
Configures a remote system for remote replication.
:param cls: this class.
:param cli: t... |
Modifies a remote system for remote replication. | def modify(self, management_address=None, username=None, password=None,
connection_type=None):
"""
Modifies a remote system for remote replication.
:param management_address: same as the one in `create` method.
:param username: username for accessing the remote system.
... |
Verifies and update the remote system settings. | def verify(self, connection_type=None):
"""
Verifies and update the remote system settings.
:param connection_type: same as the one in `create` method.
"""
req_body = self._cli.make_body(connectionType=connection_type)
resp = self.action('verify', **req_body)
re... |
Creates a replication interface. | def create(cls, cli, sp, ip_port, ip_address, netmask=None,
v6_prefix_length=None, gateway=None, vlan_id=None):
"""
Creates a replication interface.
:param cls: this class.
:param cli: the rest cli.
:param sp: `UnityStorageProcessor` object. Storage processor on w... |
Modifies a replication interface. | def modify(self, sp=None, ip_port=None, ip_address=None, netmask=None,
v6_prefix_length=None, gateway=None, vlan_id=None):
"""
Modifies a replication interface.
:param sp: same as the one in `create` method.
:param ip_port: same as the one in `create` method.
:par... |
return sp level values | def sp_sum_values(self):
"""
return sp level values
input:
"values": {
"spa": {
"19": "385",
"18": "0",
"20": "0",
"17": "0",
"16": "0"
},
"spb": {
"19": "... |
return system level values ( spa + spb ) | def sum_sp_values(self):
"""
return system level values (spa + spb)
input:
"values": {
"spa": 385,
"spb": 505
},
return:
"values": {
"0": 890
},
"""
if self.values is None:
ret = IdValues()
... |
numeric_values * sp_values | def combine_numeric_values(self, other):
"""
numeric_values * sp_values
"""
if self.values is None:
ret = IdValues()
else:
ret = sum([IdValues(
{k: int(v) * int(other.values[key]) for k, v in value.items()})
for key, value i... |
sp_values * sp_values | def combine_sp_values(self, other):
"""
sp_values * sp_values
"""
if self.values is None:
ret = IdValues()
else:
ret = IdValues({k: int(v) * int(other.values[k]) for k, v in
self.values.items()})
return ret |
sum ( sp_values * sp_values ) | def sum_combined_sp_values(self, other):
"""
sum(sp_values * sp_values)
"""
if self.values is None:
ret = IdValues()
else:
ret = IdValues({'0': sum(int(x) for x in
{k: int(v) * int(other.values[k]) for k, v
... |
Add a function to custom processing queue. Custom functions are applied automatically to associated pysat instrument whenever instrument. load command called. | def add(self, function, kind='add', at_pos='end',*args, **kwargs):
"""Add a function to custom processing queue.
Custom functions are applied automatically to associated
pysat instrument whenever instrument.load command called.
Parameters
----------
functio... |
Apply all of the custom functions to the satellite data object. | def _apply_all(self, sat):
"""
Apply all of the custom functions to the satellite data object.
"""
if len(self._functions) > 0:
for func, arg, kwarg, kind in zip(self._functions, self._args,
self._kwargs, self._kind):
... |
Clear custom function list. | def clear(self):
"""Clear custom function list."""
self._functions=[]
self._args=[]
self._kwargs=[]
self._kind=[] |
Return a Pandas Series of every file for chosen satellite data | def list_files(tag='north', sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string)
Denotes type of file to load. Accepted types are 'north' and 'south'.
(default='north')
sat_id : (strin... |
Download SuperDARN data from Virginia Tech organized for loading by pysat. | def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""
Download SuperDARN data from Virginia Tech organized for loading by pysat.
"""
import sys
import os
import pysftp
import davitpy
if user is None:
user = os.environ['DBREADUSER']
if password... |
filter self to the required number of disks with same size and type | def same_disks(self, count=2):
""" filter self to the required number of disks with same size and type
Select the disks with the same type and same size. If not
enough disks available, set self to empty.
:param count: number of disks to retrieve
:return: disk list
"""
... |
Sets boundaries for all instruments in constellation | def set_bounds(self, start, stop):
"""
Sets boundaries for all instruments in constellation
"""
for instrument in self.instruments:
instrument.bounds = (start, stop) |
Register a function to modify data of member Instruments. | def data_mod(self, *args, **kwargs):
"""
Register a function to modify data of member Instruments.
The function is not partially applied to modify member data.
When the Constellation receives a function call to register a function for data modification,
it passes the call to ea... |
Load instrument data into instrument object. data | def load(self, *args, **kwargs):
"""
Load instrument data into instrument object.data
(Wraps pysat.Instrument.load; documentation of that function is
reproduced here.)
Parameters
---------
yr : integer
Year for desired data
doy : integer
... |
Combines signals from multiple instruments within given bounds. | def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
"""
Combines signals from multiple instruments within
given bounds.
Parameters
----------
bounds1 : (min, max)
Bounds for selecting data on the axis of label1
D... |
Calculates the difference in signals from multiple instruments within the given bounds. | def difference(self, instrument1, instrument2, bounds, data_labels,
cost_function):
"""
Calculates the difference in signals from multiple
instruments within the given bounds.
Parameters
----------
instrument1 : Instrument
Information must ... |
2D Daily Occurrence Probability of data_label > gate over a season. If data_label is greater than gate at least once per day then a 100% occurrence probability results. Season delineated by the bounds attached to Instrument object. Prob = ( # of times with at least one hit )/ ( # of times in bin ) | def daily2D(inst, bin1, label1, bin2, label2, data_label, gate, returnBins=False):
"""2D Daily Occurrence Probability of data_label > gate over a season.
If data_label is greater than gate at least once per day,
then a 100% occurrence probability results.Season delineated by the bounds
attached to... |
2D Occurrence Probability of data_label orbit - by - orbit over a season. If data_label is greater than gate atleast once per orbit then a 100% occurrence probability results. Season delineated by the bounds attached to Instrument object. Prob = ( # of times with at least one hit )/ ( # of times in bin ) Parameters ---... | def by_orbit2D(inst, bin1, label1, bin2, label2, data_label, gate, returnBins=False):
"""2D Occurrence Probability of data_label orbit-by-orbit over a season.
If data_label is greater than gate atleast once per orbit, then a
100% occurrence probability results. Season delineated by the bounds
atta... |
3D Daily Occurrence Probability of data_label > gate over a season. If data_label is greater than gate atleast once per day then a 100% occurrence probability results. Season delineated by the bounds attached to Instrument object. Prob = ( # of times with at least one hit )/ ( # of times in bin ) | def daily3D(inst, bin1, label1, bin2, label2, bin3, label3,
data_label, gate, returnBins=False):
"""3D Daily Occurrence Probability of data_label > gate over a season.
If data_label is greater than gate atleast once per day,
then a 100% occurrence probability results. Season delineated by... |
Input Series of numbers Series or DataFrames repackaged for calculation. | def computational_form(data):
"""
Input Series of numbers, Series, or DataFrames repackaged
for calculation.
Parameters
----------
data : pandas.Series
Series of numbers, Series, DataFrames
Returns
-------
pandas.Series, DataFrame, or Panel
repacked data, aligned by... |
Set the top level directory pysat uses to look for data and reload. | def set_data_dir(path=None, store=None):
"""
Set the top level directory pysat uses to look for data and reload.
Parameters
----------
path : string
valid path to directory pysat uses to look for data
store : bool
if True, store data directory for future runs
"""
import ... |
Load netCDF - 3/ 4 file produced by pysat. | def load_netcdf4(fnames=None, strict_meta=False, file_format=None, epoch_name='Epoch',
units_label='units', name_label='long_name',
notes_label='notes', desc_label='desc',
plot_label='label', axis_label='axis',
scale_label='scale',
m... |
Return a tuple of year day of year for a supplied datetime object. | def getyrdoy(date):
"""Return a tuple of year, day of year for a supplied datetime object."""
try:
doy = date.toordinal()-datetime(date.year,1,1).toordinal()+1
except AttributeError:
raise AttributeError("Must supply a pandas datetime object or " +
"equivalent")... |
Return array of datetime objects using input frequency from start to stop | def season_date_range(start, stop, freq='D'):
"""
Return array of datetime objects using input frequency from start to stop
Supports single datetime object or list, tuple, ndarray of start and
stop dates.
freq codes correspond to pandas date_range codes, D daily, M monthly,
S secondly
"""... |
Create a timeseries index using supplied year month day and ut in seconds. | def create_datetime_index(year=None, month=None, day=None, uts=None):
"""Create a timeseries index using supplied year, month, day, and ut in
seconds.
Parameters
----------
year : array_like of ints
month : array_like of ints or None
day : array_like of ints
for day... |
NaN insensitive version of scipy s circular mean routine | def nan_circmean(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular mean routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
high: float or i... |
NaN insensitive version of scipy s circular standard deviation routine | def nan_circstd(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular standard deviation routine
Parameters
-----------
samples : array_like
Input array
low : float or int
Lower boundary for circular standard deviation range (default=0)
hig... |
Default routine to be applied when loading data. Removes redundant naming | def default(inst):
"""Default routine to be applied when loading data. Removes redundant naming
"""
import pysat.instruments.icon_ivm as icivm
inst.tag = 'level_2'
icivm.remove_icon_names(inst, target='ICON_L2_EUV_Daytime_OP_') |
Produce a list of ICON EUV files. | def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Produce a list of ICON EUV files.
Notes
-----
Currently fixed to level-2
"""
desc = None
level = tag
if level == 'level_1':
code = 'L1'
desc = None
elif level == 'level_2':
code = 'L... |
Return a copy of the resource with same raw data | def shadow_copy(self):
""" Return a copy of the resource with same raw data
:return: copy of the resource
"""
ret = self.__class__()
if not self._is_updated():
# before copy, make sure source is updated.
self.update()
ret._parsed_resource = self._... |
Loads data using pysat. utils. load_netcdf4. | def load(fnames, tag=None, sat_id=None, **kwargs):
"""Loads data using pysat.utils.load_netcdf4 .
This routine is called as needed by pysat. It is not intended
for direct user interaction.
Parameters
----------
fnames : array-like
iterable of filename strings, full path, to data fi... |
Produce a list of files corresponding to format_str located at data_path. | def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Produce a list of files corresponding to format_str located at data_path.
This routine is invoked by pysat and is not intended for direct use by the end user.
Multiple data levels may be supported via the 'tag' and 'sat_id' inp... |
indicate it s a command of naviseccli | def command(f):
""" indicate it's a command of naviseccli
:param f: function that returns the command in list
:return: command execution result
"""
@functools.wraps(f)
def func_wrapper(self, *argv, **kwargs):
if 'ip' in kwargs:
ip = kwargs['ip']
del kwargs['ip']... |
indicate it s a command need to be called on both SP | def duel_command(f):
""" indicate it's a command need to be called on both SP
:param f: function that returns the command in list
:return: command execution result on both sps (tuple of 2)
"""
@functools.wraps(f)
def func_wrapper(self, *argv, **kwargs):
commands = _get_commands(f, self... |
Return new size accounting for the metadata. | def supplement_filesystem(old_size, user_cap=False):
"""Return new size accounting for the metadata."""
new_size = old_size
if user_cap:
if old_size <= _GiB_to_Byte(1.5):
new_size = _GiB_to_Byte(3)
else:
new_size += _GiB_to_Byte(1.5)
return int(new_size) |
synchronize on obj if obj is supplied. | def synchronized(cls, obj=None):
""" synchronize on obj if obj is supplied.
:param obj: the obj to lock on. if none, lock to the function
:return: return of the func.
"""
def get_key(f, o):
if o is None:
key = hash(f)
else:
... |
Re - enqueue till reach max retries. | def re_enqueue(self, item):
"""Re-enqueue till reach max retries."""
if 'retries' in item:
retries = item['retries']
if retries >= self.MAX_RETRIES:
log.warn("Failed to execute {} after {} retries, give it "
" up.".format(item['method'], r... |
Internal decorator to define an criteria compare operations. | def _support_op(*args):
"""Internal decorator to define an criteria compare operations."""
def inner(func):
for one_arg in args:
_op_mapping_[one_arg] = func
return func
return inner |
Routine to return VEFI data cleaned to the specified level | def clean(inst):
"""Routine to return VEFI data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
... |
Removes leading text on ICON project variable names | def remove_icon_names(inst, target=None):
"""Removes leading text on ICON project variable names
Parameters
----------
inst : pysat.Instrument
ICON associated pysat.Instrument object
target : str
Leading string to remove. If none supplied,
ICON project standards are used to ... |
Return a Pandas Series of every file for chosen satellite data | def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (s... |
OMNI data is time - shifted to bow shock. Time shifted again to intersections with magnetic pole. | def time_shift_to_magnetic_poles(inst):
""" OMNI data is time-shifted to bow shock. Time shifted again
to intersections with magnetic pole.
Parameters
-----------
inst : Instrument class object
Instrument with OMNI HRO data
Notes
---------
Time shift calculated using distance t... |
Calculate IMF clock angle and magnitude of IMF in GSM Y - Z plane | def calculate_clock_angle(inst):
""" Calculate IMF clock angle and magnitude of IMF in GSM Y-Z plane
Parameters
-----------
inst : pysat.Instrument
Instrument with OMNI HRO data
"""
# Calculate clock angle in degrees
clock_angle = np.degrees(np.arctan2(inst['BY_GSM'], inst['BZ_... |
Calculate IMF steadiness using clock angle standard deviation and the coefficient of variation of the IMF magnitude in the GSM Y - Z plane | def calculate_imf_steadiness(inst, steady_window=15, min_window_frac=0.75,
max_clock_angle_std=90.0/np.pi, max_bmag_cv=0.5):
""" Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in the GSM Y-Z plane
Parameters
... |
Calculate the dayside reconnection rate ( Milan et al. 2014 ) | def calculate_dayside_reconnection(inst):
""" Calculate the dayside reconnection rate (Milan et al. 2014)
Parameters
-----------
inst : pysat.Instrument
Instrument with OMNI HRO data, requires BYZ_GSM and clock_angle
Notes
--------
recon_day = 3.8 Re (Vx / 4e5 m/s)^1/3 Vx B_yz (sin... |
clear all ace entries of the share | def clear_access(self, white_list=None):
""" clear all ace entries of the share
:param white_list: list of username whose access entry won't be cleared
:return: sid list of ace entries removed successfully
"""
access_entries = self.get_ace_list()
sid_list = access_entrie... |
delete ACE for the share | def delete_ace(self, domain=None, user=None, sid=None):
""" delete ACE for the share
delete ACE for the share. User could either supply the domain and
username or the sid of the user.
:param domain: domain of the user
:param user: username
:param sid: sid of the user o... |
Aggregator for ioclass_luns and ioclass_snapshots. | def luns(self):
"""Aggregator for ioclass_luns and ioclass_snapshots."""
lun_list, smp_list = [], []
if self.ioclass_luns:
lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name,
cli=self._cli), self.ioclass_luns)
if self.iocl... |
Returns policy which contains this ioclass. | def policy(self):
"""Returns policy which contains this ioclass."""
policies = VNXIOPolicy.get(cli=self._cli)
ret = None
for policy in policies:
contained = policy.ioclasses.name
if self._get_name() in contained:
ret = VNXIOPolicy.get(name=policy.n... |
Overwrite the current properties for a VNX ioclass. | def modify(self, new_name=None, iotype=None, lun_ids=None, smp_names=None,
ctrlmethod=None, minsize=None, maxsize=None):
"""Overwrite the current properties for a VNX ioclass.
:param new_name: new name for the ioclass
:param iotype: can be 'rw', 'r' or 'w'
:param lun_ids:... |
A wrapper for modify method. | def add_lun(self, luns):
"""A wrapper for modify method.
.. note:: This API only append luns to existing luns.
"""
curr_lun_ids, curr_smp_names = self._get_current_names()
luns = normalize_lun(luns, self._cli)
new_ids, new_smps = convert_lun(luns)
if new_ids:
... |
Add one VNXIOClass instance to policy. | def add_class(self, ioclass):
"""Add one VNXIOClass instance to policy.
.. note: due to the limitation of VNX, need to stop the policy first.
"""
current_ioclasses = self.ioclasses
if ioclass.name in current_ioclasses.name:
return
current_ioclasses.append(ioc... |
Remove VNXIOClass instance from policy. | def remove_class(self, ioclass):
"""Remove VNXIOClass instance from policy."""
current_ioclasses = self.ioclasses
new_ioclasses = filter(lambda x: x.name != ioclass.name,
current_ioclasses)
self.modify(new_ioclasses=new_ioclasses) |
Replaces the exiting LUNs to lun_list. | def replace_lun(self, *lun_list):
"""Replaces the exiting LUNs to lun_list."""
lun_add = self._prepare_luns_add(lun_list)
lun_remove = self._prepare_luns_remove(lun_list, False)
return self.modify(lun_add=lun_add, lun_remove=lun_remove) |
Updates the LUNs in CG adding the ones in add_luns and removing the ones in remove_luns | def update_lun(self, add_luns=None, remove_luns=None):
"""Updates the LUNs in CG, adding the ones in `add_luns` and removing
the ones in `remove_luns`"""
if not add_luns and not remove_luns:
log.debug("Empty add_luns and remove_luns passed in, "
"skip update_lun... |
Routine to return FPMU data cleaned to the specified level | def clean(inst):
"""Routine to return FPMU data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneType)
... |
Attaches info returned by instrument list_files routine to Instrument object. | def _attach_files(self, files_info):
"""Attaches info returned by instrument list_files routine to
Instrument object.
"""
if not files_info.empty:
if (len(files_info.index.unique()) != len(files_info)):
estr = 'WARNING! Duplicate datetimes in provided file '
... |
Store currently loaded filelist for instrument onto filesystem | def _store(self):
"""Store currently loaded filelist for instrument onto filesystem"""
name = self.stored_file_name
# check if current file data is different than stored file list
# if so, move file list to previous file list, store current to file
# if not, do nothing
s... |
Load stored filelist and return as Pandas Series | def _load(self, prev_version=False):
"""Load stored filelist and return as Pandas Series
Parameters
----------
prev_version : boolean
if True, will load previous version of file list
Returns
-------
pandas.Series
Full path file names are ... |
Update list of files if there are changes. Calls underlying list_rtn for the particular science instrument. Typically these routines search in the pysat provided path pysat_data_dir/ platform/ name/ tag/ where pysat_data_dir is set by pysat. utils. set_data_dir ( path = path ). | def refresh(self):
"""Update list of files, if there are changes.
Calls underlying list_rtn for the particular science instrument.
Typically, these routines search in the pysat provided path,
pysat_data_dir/platform/name/tag/,
where pysat_data_dir is set by pysat.utils.s... |
List new files since last recorded file state. pysat stores filenames in the user_home/. pysat directory. Returns a list of all new fileanmes since the last known change to files. Filenames are stored if there is a change and either update_files is True at instrument object level or files. refresh () is called. Returns... | def get_new(self):
"""List new files since last recorded file state.
pysat stores filenames in the user_home/.pysat directory. Returns
a list of all new fileanmes since the last known change to files.
Filenames are stored if there is a change and either update_files
is T... |
Return index for a given filename. Parameters ---------- fname: string filename Note ---- If fname not found in the file information already attached to the instrument. files instance then a files. refresh () call is made. | def get_index(self, fname):
"""Return index for a given filename.
Parameters
----------
fname : string
filename
Note
----
If fname not found in the file information already attached
to the instrument.files instance, then a f... |
Return a list of filenames between and including start and end. Parameters ---------- start: array_like or single string filenames for start of returned filelist stop: array_like or single string filenames inclusive end of list Returns ------- list of filenames between and including start and end over all intervals. | def get_file_array(self, start, end):
"""Return a list of filenames between and including start and end.
Parameters
----------
start: array_like or single string
filenames for start of returned filelist
stop: array_like or single string
... |
Remove the data directory path from filenames | def _remove_data_dir_path(self, inp=None):
# import string
"""Remove the data directory path from filenames"""
# need to add a check in here to make sure data_dir path is actually in
# the filename
if inp is not None:
split_str = os.path.join(self.data_path, '')
... |
Produces a list of files and and formats it for Files class. | def from_os(cls, data_path=None, format_str=None,
two_digit_year_break=None):
"""
Produces a list of files and and formats it for Files class.
Requires fixed_width filename
Parameters
----------
data_path : string
Top level directory... |
Adds metadata variables to self that are in other but not in self. Parameters ---------- other: pysat. Meta | def merge(self, other):
"""Adds metadata variables to self that are in other but not in self.
Parameters
----------
other : pysat.Meta
"""
for key in other.keys():
if key not in self:
# copies over both lower and high... |
Drops variables ( names ) from metadata. | def drop(self, names):
"""Drops variables (names) from metadata."""
# drop lower dimension data
self._data = self._data.drop(names, axis=0)
# drop higher dimension data
for name in names:
if name in self._ho_data:
_ = self._ho_data.pop(name) |
Keeps variables ( keep_names ) while dropping other parameters | def keep(self, keep_names):
"""Keeps variables (keep_names) while dropping other parameters"""
current_names = self._data.columns
drop_names = []
for name in current_names:
if name not in keep_names:
drop_names.append(name)
self.drop(drop_name... |
Applies labels for default meta labels from self onto other. Parameters ---------- other: Meta Meta object to have default labels applied Returns ------- Meta | def apply_default_labels(self, other):
"""Applies labels for default meta labels from self onto other.
Parameters
----------
other : Meta
Meta object to have default labels applied
Returns
-------
Meta
"""
oth... |
Applies labels for default meta labels from other onto self. Parameters ---------- other: Meta Meta object to take default labels from Returns ------- Meta | def accept_default_labels(self, other):
"""Applies labels for default meta labels from other onto self.
Parameters
----------
other : Meta
Meta object to take default labels from
Returns
-------
Meta
"""
self... |
Generalized setter of default meta attributes Parameters ---------- new_label: str New label to use in the Meta object current_label: str The hidden attribute to be updated that actually stores metadata default: Deafult setting to use for label if there is no attribute value use_names_default: bool if True MetaData var... | def _label_setter(self, new_label, current_label, attr_label, default=np.NaN, use_names_default=False):
"""Generalized setter of default meta attributes
Parameters
----------
new_label : str
New label to use in the Meta object
current_label : str
... |
Provides stored name ( case preserved ) for case insensitive input If name is not found ( case - insensitive check ) then name is returned as input. This function is intended to be used to help ensure the case of a given variable name is the same across the Meta object. Parameters ---------- name: str variable name in ... | def var_case_name(self, name):
"""Provides stored name (case preserved) for case insensitive input
If name is not found (case-insensitive check) then name is returned,
as input. This function is intended to be used to help ensure the
case of a given variable name is the same acr... |
Returns boolean indicating presence of given attribute name Case - insensitive check Notes ----- Does not check higher order meta objects Parameters ---------- name: str name of variable to get stored case form Returns ------- bool True if case - insesitive check for attribute name is True | def has_attr(self, name):
"""Returns boolean indicating presence of given attribute name
Case-insensitive check
Notes
-----
Does not check higher order meta objects
Parameters
----------
name : str
name of variable to... |
Returns preserved case name for case insensitive value of name. Checks first within standard attributes. If not found there checks attributes for higher order data structures. If not found returns supplied name as it is available for use. Intended to be used to help ensure that the same case is applied to all repetitio... | def attr_case_name(self, name):
"""Returns preserved case name for case insensitive value of name.
Checks first within standard attributes. If not found there, checks
attributes for higher order data structures. If not found, returns
supplied name as it is available for use. Int... |
Concats two metadata objects together. | def concat(self, other, strict=False):
"""Concats two metadata objects together.
Parameters
----------
other : Meta
Meta object to be concatenated
strict : bool
if True, ensure there are no duplicate variable names
Notes
-----
Use... |
Remove and return metadata about variable | def pop(self, name):
"""Remove and return metadata about variable
Parameters
----------
name : str
variable name
Returns
-------
pandas.Series
Series of metadata for variable
"""
# check if present
if name in self:... |
Transfer non - standard attributes in Meta to Instrument object. | def transfer_attributes_to_instrument(self, inst, strict_names=False):
"""Transfer non-standard attributes in Meta to Instrument object.
Pysat's load_netCDF and similar routines are only able to attach
netCDF4 attributes to a Meta object. This routine identifies these
attributes and rem... |
Create instrument metadata object from csv. | def from_csv(cls, name=None, col_names=None, sep=None, **kwargs):
"""Create instrument metadata object from csv.
Parameters
----------
name : string
absolute filename for csv file or name of file
stored in pandas instruments location
col_names : list-like... |
Routine to return C/ NOFS IVM data cleaned to the specified level | def clean(self):
"""Routine to return C/NOFS IVM data cleaned to the specified level
Parameters
-----------
inst : (pysat.Instrument)
Instrument class object, whose attribute clean_level is used to return
the desired level of data selectivity.
Returns
--------
Void : (NoneT... |
A signal receiver decorator that fetch the complete instance from db when it s passed as raw | def nonraw_instance(receiver):
"""
A signal receiver decorator that fetch the complete instance from db when
it's passed as raw
"""
@wraps(receiver)
def wrapper(sender, instance, raw, using, **kwargs):
if raw:
instance = sender._default_manager.using(using).get(pk=instance.pk... |
This is used to pass data required for deletion to the post_delete signal that is no more available thereafter. | def base_definition_pre_delete(sender, instance, **kwargs):
"""
This is used to pass data required for deletion to the post_delete
signal that is no more available thereafter.
"""
# see CASCADE_MARK_ORIGIN's docstring
cascade_deletion_origin = popattr(
instance._state, '_cascade_deletion... |
Make sure to delete fields inherited from an abstract model base. | def base_definition_post_delete(sender, instance, **kwargs):
"""
Make sure to delete fields inherited from an abstract model base.
"""
if hasattr(instance._state, '_deletion'):
# Make sure to flatten abstract bases since Django
# migrations can't deal with them.
model = popattr(i... |
When proxy field definitions are loaded from a fixture they re not passing through the field_definition_post_save signal. Make sure they are. | def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs):
"""
When proxy field definitions are loaded from a fixture they're not
passing through the `field_definition_post_save` signal. Make sure they
are.
"""
if raw:
model_class = instance.content_type.model_class()
... |
This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details | def field_definition_post_save(sender, instance, created, raw, **kwargs):
"""
This signal is connected by all FieldDefinition subclasses
see comment in FieldDefinitionBase for more details
"""
model_class = instance.model_def.model_class().render_state()
field = instance.construct_for_migrate()
... |
Useful for retrieving an object attr and removing it if it s part of it s dict while allowing retrieving from subclass. i. e. class A: a = a class B ( A ): b = b >>> popattr ( B a None ) a >>> A. a a | def popattr(obj, attr, default=NOT_PROVIDED):
"""
Useful for retrieving an object attr and removing it if it's part of it's
dict while allowing retrieving from subclass.
i.e.
class A:
a = 'a'
class B(A):
b = 'b'
>>> popattr(B, 'a', None)
'a'
>>> A.a
'a'
"""
... |
An helper that correctly deepcopy model cache state | def _app_cache_deepcopy(obj):
"""
An helper that correctly deepcopy model cache state
"""
if isinstance(obj, defaultdict):
return deepcopy(obj)
elif isinstance(obj, dict):
return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items())
elif isin... |
A context manager that restore model cache state as it was before entering context. | def app_cache_restorer():
"""
A context manager that restore model cache state as it was before
entering context.
"""
state = _app_cache_deepcopy(apps.__dict__)
try:
yield state
finally:
with apps_lock():
apps.__dict__ = state
# Rebind the app registry... |
Custom on_delete handler which sets _cascade_deletion_origin on the _state of the all relating objects that will deleted. We use this handler on ModelDefinitionAttribute. model_def so when we delete a ModelDefinition we can skip field_definition_post_delete and base_definition_post_delete and avoid an incremental colum... | def CASCADE_MARK_ORIGIN(collector, field, sub_objs, using):
"""
Custom on_delete handler which sets _cascade_deletion_origin on the _state
of the all relating objects that will deleted.
We use this handler on ModelDefinitionAttribute.model_def, so when we delete
a ModelDefinition we can skip field... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.