text stringlengths 18 773k |
|---|
def nii_modify(
nii,
fimout = '',
outpath = '',
fcomment = '',
voxel_range=[]):
''' Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path).
'''
if isinstance(nii, basestring) and os.path.isfile(nii):
d... |
def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) o... |
def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False):
'''
Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and... |
def getnii(fim, nan_replace=None, output='image'):
'''Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matri... |
def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
... |
def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]):
'''Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the descri... |
def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
... |
def nii_ugzip(imfile, outpath=''):
'''Uncompress *.gz file'''
import gzip
with gzip.open(imfile, 'rb') as f:
s = f.read()
# Now store the uncompressed data
if outpath=='':
fout = imfile[:-3]
else:
fout = os.path.join(outpath, os.path.basename(imfile)[:-3])
# store unc... |
def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed ... |
def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri a... |
def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(d... |
def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datai... |
def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containi... |
def dcmsort(folder, copy_series=False, verbose=False):
''' Sort out the DICOM files in the folder according to the recorded series.
'''
# list files in the input folder
files = os.listdir(folder)
srs = {}
for f in files:
if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext)... |
def niisort(
fims,
memlim=True
):
''' Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes t... |
def dcm2nii(
dcmpth,
fimout = '',
fprefix = 'converted-from-DICOM_',
fcomment = '',
outpath = '',
timestamp = True,
executable = '',
force = False,
):
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party soft... |
def dcm2im(fpth):
''' Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
'''
# possible DICOM file extensions
ext = ('dcm', 'DCM', 'ima', 'IMA')
# case when given a folder p... |
def path_niftypet_local():
'''Get the path to the local (home) folder for NiftyPET resources.'''
# if using conda put the resources in the folder with the environment name
if 'CONDA_DEFAULT_ENV' in os.environ:
env = os.environ['CONDA_DEFAULT_ENV']
print 'i> conda environment found:', env
... |
def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
... |
def dev_setup():
'''figure out what GPU devices are available and choose the supported ones.'''
# check first if NiftyPET was already installed and use the choice of GPU
path_resources = path_niftypet_local()
# if so, import the resources and get the constants
if os.path.isfile(os.path.join(path_re... |
def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.... |
def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends ... |
def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
... |
def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed sho... |
def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
... |
def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical... |
def parse_formula(formula):
"""Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern
"""
... |
def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise S... |
def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session... |
def get_devices(self, refresh=False):
"""Get all devices from Abode."""
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
_LOGGER.info("Updating all devices...")
response = self.send_request("get", CONST.DEVICES_URL)
... |
def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.AC... |
def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() |
def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache |
def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) |
def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache:
if os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
if os.path.getsize(self._cache_path) > 0:
... |
def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptog... |
def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If an... |
def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message yo... |
def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
... |
def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is ... |
def deleteJID(self, bare_jid):
"""
Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys.
"""
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, ... |
def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt[... |
def get_mmr_constants():
'''
Put all the constants together in a dictionary
'''
Cnt = {
'ISOTOPE':'F18',
'DCYCRR':DCYCRR,
'ALPHA':ALPHA,
'NRNG':NRNG,
'NSRNG':NSRNG,
'NCRS':NCRS,
'NCRSR':NCRSR,
'NBCKT':224,
'NSANGLES':A,
'NS... |
def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']):
''' Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst'
'''
# at start, assume that nothing is present yet
output = {}
for itm... |
def install_tool(app, Cnt):
''' Install the requested software from the git 'repo'
and check out the version given by 'sha1'.
'''
# get the current working directory
cwd = os.getcwd()
# pick the target installation folder for tools
if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='':
... |
def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
... |
def loadSessions(self, callback, bare_jid, device_ids):
"""
Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id.
"""
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
... |
def loadTrusts(self, callback, bare_jid, device_ids):
"""
Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id.
"""
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
... |
def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
... |
def serialize(self, backend):
"""
Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
... |
def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue... |
def create_mask(
fnii,
fimout = '',
outpath = '',
fill = 1,
dtype_fill = np.uint8,
thrsh = 0.,
fwhm = 0.,):
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = ... |
def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del... |
def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representin... |
def dice_coeff_multiclass(im1, im2, roi2ind):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value must be given as a dictionary of lists of index... |
def gen_token():
"""Generate a new Skybellpy token."""
return ''.join(
random.choice(
string.ascii_uppercase + string.ascii_lowercase + string.digits)
for _ in range(32)) |
def _validate_setting(setting, value):
"""Validate the setting and value."""
if setting not in CONST.ALL_SETTINGS:
raise SkybellException(ERROR.INVALID_SETTING, setting)
if setting == CONST.SETTINGS_DO_NOT_DISTURB:
if value not in CONST.SETTINGS_DO_NOT_DISTURB_VALUES:
raise Skyb... |
def refresh(self):
"""Refresh the devices json object data."""
# Update core device data
new_device_json = self._device_request()
_LOGGER.debug("Device Refresh Response: %s", new_device_json)
# Update avatar url
new_avatar_json = self._avatar_request()
_LOGGER.de... |
def update(self, device_json=None, info_json=None, settings_json=None,
avatar_json=None):
"""Update the internal device json data."""
if device_json:
UTILS.update(self._device_json, device_json)
if avatar_json:
UTILS.update(self._avatar_json, avatar_json)
... |
def _update_activities(self):
"""Update stored activities and update caches as required."""
self._activities = self._activities_request()
_LOGGER.debug("Device Activities Response: %s", self._activities)
if not self._activities:
self._activities = []
elif not isinsta... |
def _update_events(self):
"""Update our cached list of latest activity events."""
events = self._skybell.dev_cache(self, CONST.EVENT) or {}
for activity in self._activities:
event = activity.get(CONST.EVENT)
created_at = activity.get(CONST.CREATED_AT)
old_ev... |
def activities(self, limit=1, event=None):
"""Return device activity information."""
activities = self._activities or []
# Filter our activity array if requested
if event:
activities = list(
filter(
lambda activity:
act... |
def _set_setting(self, settings):
"""Validate the settings and then send the PATCH request."""
for key, value in settings.items():
_validate_setting(key, value)
try:
self._settings_request(method="patch", json_data=settings)
self.update(settings_json=setting... |
def location(self):
"""Return lat and lng tuple."""
location = self._device_json.get(CONST.LOCATION, {})
return (location.get(CONST.LOCATION_LAT, 0),
location.get(CONST.LOCATION_LNG, 0)) |
def wifi_status(self):
"""Get the wifi status."""
return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK) |
def do_not_disturb(self):
"""Get if do not disturb is enabled."""
return bool(strtobool(str(self._settings_json.get(
CONST.SETTINGS_DO_NOT_DISTURB)))) |
def do_not_disturb(self, enabled):
"""Set do not disturb."""
self._set_setting(
{
CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower()
}) |
def motion_sensor(self, enabled):
"""Set the motion sensor state."""
if enabled is True:
value = CONST.SETTINGS_MOTION_POLICY_ON
elif enabled is False:
value = CONST.SETTINGS_MOTION_POLICY_OFF
else:
raise SkybellException(ERROR.INVALID_SETTING_VALUE,
... |
def led_rgb(self):
"""Get devices LED color."""
return (int(self._settings_json.get(CONST.SETTINGS_LED_R)),
int(self._settings_json.get(CONST.SETTINGS_LED_G)),
int(self._settings_json.get(CONST.SETTINGS_LED_B))) |
def led_rgb(self, color):
"""Set devices LED color."""
if (not isinstance(color, (list, tuple)) or
not all(isinstance(item, int) for item in color)):
raise SkybellException(ERROR.COLOR_VALUE_NOT_VALID, color)
self._set_setting(
{
CONST.SET... |
def remote(self, remote_base=None, username=None, password=None):
"""
Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
... |
def get(self, filetype, **kwargs):
"""Returns file name, downloading if remote access configured.
Parameters
----------
filetype : str
type of file
keyword arguments :
keywords to fully specify path
Notes
-----
Path templates are... |
def download_url_to_path(self, url, path, force=False):
"""
Download a file from url via http, and put it at path
Parameters
----------
url : str
URL of file to download
path : str
local path to put file in
"""
path_exists = isf... |
def remote(self, username=None, password=None, inquire=None):
""" Configures remote access """
self.set_netloc(sdss=True) # simplifies things to have a single sdss machine in .netrc
self.set_auth(username=username, password=password, inquire=inquire)
self.set_netloc(dtn=not self.public... |
def reset(self):
''' Reset all streams '''
# reset the main stream
if self.stream:
self.stream.reset()
# reset the initial stream (otherwise old 'adds' remain in the new stream)
if self.initial_stream:
self.initial_stream.reset() |
def add(self, filetype, **kwargs):
""" Adds a filepath into the list of tasks to download"""
location = self.location(filetype, **kwargs)
source = self.url(filetype, sasdir='sas' if not self.public else '', **kwargs)
if 'full' not in kwargs:
destination = self.full(filetype,... |
def set_stream(self):
""" Sets the download streams """
if not self.auth:
raise AccessError("Please use the remote() method to set rsync authorization or use remote(public=True) for public data")
elif not self.initial_stream.task:
raise AccessError("No files to download.... |
def commit(self, offset=None, limit=None, dryrun=False):
""" Start the rsync download """
self.stream.command = "rsync -avRK --files-from={path} {source} {destination}"
self.stream.append_tasks_to_streamlets(offset=offset, limit=limit)
self.stream.commit_streamlets()
self.stream... |
def balance(self) -> Decimal:
"""
Returns account balance after this entry.
:return: Decimal
"""
return sum_queryset(AccountEntry.objects.filter(account=self.account, timestamp__lte=self.timestamp).exclude(timestamp=self.timestamp, id__gt=self.id)) |
def get_balance(self, t: datetime):
"""
Returns account balance before specified datetime (excluding entries on the datetime).
:param t: datetime
:return: Decimal
"""
return sum_queryset(self.accountentry_set.all().filter(timestamp__lt=t)) |
def needs_settling(self, e: AccountEntry) -> bool:
"""
Returns True if all of following conditions are True:
a) entry type is settlement
b) entry has been recorded to this account
c) invoice to be settled has been set
d) entry has not been settled (=child set empty)
... |
def receivables_account(self) -> Account:
"""
Returns receivables account. Receivables account is assumed to be the one were invoice rows were recorded.
:return: Account or None
"""
row = AccountEntry.objects.filter(source_invoice=self).order_by('id').first()
return row.a... |
def get_entries(self, acc: Account, cls=AccountEntry) -> QuerySet:
"""
Returns entries related to this invoice on specified account.
:param acc: Account
:param cls: AccountEntry class
:return: QuerySet
"""
return cls.objects.filter(Q(account=acc) & (Q(source_invoi... |
def get_item_balances(self, acc: Account) -> list:
"""
Returns balances of items of the invoice.
:param acc: Account
:return: list (AccountEntry, Decimal) in item id order
"""
items = []
entries = self.get_entries(acc)
for item in entries.filter(source_inv... |
def get_unpaid_items(self, acc: Account) -> list:
"""
Returns unpaid items of the invoice in payback priority order.
:param acc: Account
:return: list (AccountEntry, Decimal) in payback priority order
"""
unpaid_items = []
for item, bal in self.get_item_balances(a... |
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges |
def PrintRanges(type, name, ranges):
"""Print the ranges as an array of type named name."""
print "static const %s %s[] = {" % (type, name,)
for lo, hi in ranges:
print "\t{ %d, %d }," % (lo, hi)
print "};" |
def PrintGroup(name, codes):
"""Print the data structures for the group of codes.
Return a UGroup literal for the group."""
# See unicode_groups.h for a description of the data structure.
# Split codes into 16-bit ranges and 32-bit ranges.
range16 = MakeRanges([c for c in codes if c < 65536])
range32 = Ma... |
def settle_assigned_invoice(receivables_account: Account, settlement: AccountEntry, cls, **kwargs) -> list:
"""
Finds unpaid items in the invoice and generates entries to receivables account.
Settlement is matched to invoice items based on entry types payback order.
Generated payment entries have 'paren... |
def settle_credit_note(credit_note: Invoice, debit_note: Invoice, cls, account: Account, **kwargs) -> list:
"""
Settles credit note. Records settling account entries for both original invoice and the credit note
(negative entries for the credit note).
Default timestamp for account entries is 'created' t... |
def _input_templates(self):
"""Read the path template file.
"""
foo = self._config.read([self._pathfile])
if len(foo) == 1:
for k, v in self._config.items('paths'):
self.templates[k] = v
else:
raise ValueError("Could not read {0}!".format(s... |
def lookup_keys(self, name):
''' Lookup the keyword arguments needed for a given path name
Parameters:
name (str):
The name of the path
Returns:
A list of keywords needed for filepath generation
'''
assert name, 'Must specify a path nam... |
def _check_special_kwargs(self, name):
''' check special functions for kwargs
Checks the content of the special functions (%methodname) for
any keyword arguments referenced within
Parameters:
name (str):
A path key name
Returns:
... |
def _find_source(method):
''' find source code of a given method
Find and extract the source code of a given method in a module.
Uses inspect.findsource to get all source code and performs some
selection magic to identify method source code. Doing it this way
because in... |
def extract(self, name, example):
''' Extract keywords from an example path '''
# if pathlib not available do nothing
if not pathlib:
return None
# ensure example is a string
if isinstance(example, pathlib.Path):
example = str(example)
assert isi... |
def dir(self, filetype, **kwargs):
"""Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file.
"""
full = k... |
def name(self, filetype, **kwargs):
"""Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
name : str
Name of a file with no directory information.
"""
... |
def exists(self, filetype, remote=None, **kwargs):
'''Checks if the given type of file exists locally
Parameters
----------
filetype : str
File type parameter.
remote : bool
If True, checks for remote existence of the file
Returns
------... |
def expand(self, filetype, **kwargs):
''' Expand a wildcard path locally
Parameters
----------
filetype : str
File type parameter.
as_url: bool
Boolean to return SAS urls
refine: str
Regular expression string to filter the list of fi... |
def any(self, filetype, **kwargs):
''' Checks if the local directory contains any of the type of file
Parameters
----------
filetype : str
File type parameter.
Returns
-------
any : bool
Boolean indicating if the any files exist in the ex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.