code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
logger_directory.info("enter list_files")
file_list = []
if path:
# list files from target directory
files = os.listdir(path)
for file in files:
if file.endswith(x) and not file.startswith(("$", "~", ".")):
# join the path and basename to create full ... | def list_files(x, path="") | Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on | 2.894035 | 2.808283 | 1.030536 |
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
try:
os.remove(f)
except Exception:
pass
return | def rm_files_in_dir(path) | Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none: | 2.32264 | 2.764801 | 0.840075 |
_full_path = os.path.join(path, filename)
if os.path.exists(_full_path):
os.remove(_full_path)
return | def rm_file_if_exists(path, filename) | Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none: | 2.254709 | 2.615638 | 0.862011 |
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-type' in data.headers and
'charset=' in data.headers['content-type']):
encoding = data.headers['content-type'].split('charset=')[-1]
else:
encoding = default_e... | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8') | Generate the languages Python module. | 3.078584 | 3.039245 | 1.012944 |
attribs = ', '.join(["%s=%r" % (k, v) for k, v in self.__dict__.items() if not k.startswith("_")])
wrap = "{self.__class__.__name__}({attribs})".format(self=self, attribs=attribs)
return wrap
cls.__repr__ = reprer
return cls | def give_repr(cls): # pragma: no cover
r
def reprer(self) | r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returned | 3.01101 | 3.750232 | 0.802886 |
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Upda... | def newton(power_sum, elementary_symmetric_polynomial, order) | r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates ... | 3.603604 | 1.282006 | 2.81091 |
r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
--------... | def vietes(coefficients) | r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
----------
... | 3.868292 | 1.549538 | 2.496416 |
max_n_variants = 0
for element, count in composition.items():
if element == "H+":
continue
try:
max_n_variants += count * periodic_table[element].max_neutron_shift()
except KeyError:
pass
return max_n_variants | def max_variants(composition) | Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int | 4.457982 | 4.717317 | 0.945025 |
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starti... | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON) | Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the ... | 4.881779 | 1.686636 | 2.894388 |
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# Create skybellpy instance.
skybell = s... | def call() | Execute command line helper. | 2.176626 | 2.157497 | 1.008866 |
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2))**.5)
zSig = (scale*fwhm[2]/vx_size[2]) / (2*(2*np.log(2))**.5)
... | def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2) | Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x | 2.676884 | 2.132277 | 1.255411 |
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5)
... | def iyang(imgIn, krnl, imgSeg, Cnt, itr=5) | partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5) | 4.352464 | 3.420699 | 1.27239 |
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwater = 0.096
... | def ct2mu(im) | HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images, | 6.23406 | 3.631143 | 1.716831 |
''' Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis.
'''
#> initialise centre of mass array
com = np.zeros(3, dty... | def centre_mass_img(imdct) | Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis. | 4.462935 | 3.050474 | 1.46303 |
''' 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):
dctnii = imio.getnii(nii, output='all')
fnii = nii
if isinstance(nii, dict) and 'im' in nii:
dctnii =... | 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). | 3.063584 | 2.774443 | 1.104216 |
'''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 matrix or a dictionary with all info.
----------
... | 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 matrix or a dictionary with all info.
----------
Return... | 4.131901 | 2.851487 | 1.449034 |
'''
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
for ci in range(len(... | def getnii_descr(fim) | Extracts the custom description header field to dictionary | 5.208303 | 3.995387 | 1.303579 |
'''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 description given to the file
'trsnp': transpose/permute the dimensio... | 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 description given to the file
'trsnp': transpose/permute the dimensions.
... | 4.779267 | 2.683934 | 1.780694 |
'''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()
for i in range(3):
... | def orientnii(imfile) | Get the orientation from NIfTI sform. Not fully functional yet. | 4.839782 | 3.915434 | 1.236078 |
'''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 uncompressed file data from 's' variab... | def nii_ugzip(imfile, outpath='') | Uncompress *.gz file | 3.06574 | 2.904762 | 1.055419 |
'''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 file data from 'd' variable
wi... | def nii_gzip(imfile, outpath='') | Compress *.gz file | 3.223416 | 3.033437 | 1.062628 |
''' 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 and os.path.isfile(m... | def pick_t1w(mri) | Pick the MR T1w from the dictionary for MR->PET registration. | 4.688324 | 4.196373 | 1.117232 |
''' 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(dcmvar, dcm.dataset.FileDataset):
... | def dcminfo(dcmvar, verbose=True) | Get basic info about the DICOM file/header. | 3.150053 | 3.124304 | 1.008241 |
''' 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(datain['mumapDCM'])
# acce... | def list_dcm_datain(datain) | List all DICOM file paths in the datain dictionary of input data. | 1.85016 | 1.771399 | 1.044463 |
''' 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):
dhdr = dcm.read_file(os.path.join(folder,... | def dcmsort(folder, copy_series=False, verbose=False) | Sort out the DICOM files in the folder according to the recorded series. | 2.415174 | 2.355077 | 1.025518 |
''' 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 that the output does not contain
all the ar... | 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 that the output does not contain
all the arrays corr... | 3.751861 | 3.053415 | 1.228743 |
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party software.
'''
# skip conversion if the output already exists and not force is selected
if os.path.isfile(fimout) and not force:
return fimout
if executable=='':
try:
import reso... | 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 software. | 3.915532 | 3.461898 | 1.131036 |
'''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
else:
env = ''
... | def path_niftypet_local() | Get the path to the local (home) folder for NiftyPET resources. | 3.097173 | 2.790048 | 1.110079 |
'''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
cuda_path =... | def find_cuda() | Locate the CUDA environment on the system. | 3.215147 | 3.116186 | 1.031757 |
'''
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.
path_install = os.... | def resources_setup() | This function checks CUDA devices, selects some and installs resources.py | 5.491058 | 4.82971 | 1.136933 |
@functools.wraps(f)
def _coroutine(*args, **kwargs):
def _resolver(resolve, reject):
try:
generator = f(*args, **kwargs)
except BaseException as e:
# Special case for a function that throws immediately
reject(e)
el... | 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 the result (or the error)
... | 2.921574 | 2.841815 | 1.028066 |
@functools.wraps(f)
def _no_coroutine(*args, **kwargs):
generator = f(*args, **kwargs)
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
return generator
previous = None
first = True
w... | 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.
It's basically the same as if ... | 2.887835 | 3.036396 | 0.951073 |
def _maybe_coroutine(f):
@functools.wraps(f)
def __maybe_coroutine(*args, **kwargs):
if decide(*args, **kwargs):
return coroutine(f)(*args, **kwargs)
else:
return no_coroutine(f)(*args, **kwargs)
return __maybe_coroutine
retur... | 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 should be a generator yielding either only P... | 2.087242 | 2.13276 | 0.978658 |
def _resolver(resolve, reject):
function(
lambda success, result: resolve(result) if success else reject(result),
*args,
**kwargs
)
return Promise(_resolver) | 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
- result : The result of the operation if success is True or th... | 4.121695 | 4.489928 | 0.917987 |
mass = 0.0
if mass_data is None:
mass_data = nist_mass
for element in composition:
try:
mass += (composition[element] * mass_data[element][0][0])
except KeyError:
match = re.search(r"(\S+)\[(\d+)\]", element)
if match:
element_... | 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 elements (the default
value is :py:data:`nist_m... | 2.355607 | 2.505295 | 0.940251 |
if not formula_pattern.match(formula):
raise ValueError("%r does not look like a formula" % (formula,))
composition = PyComposition()
for elem, isotope, number in atom_pattern.findall(formula):
composition[_make_isotope_string(elem, int(isotope) if isotope else 0)] += int(number)
re... | 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 | 5.283392 | 4.564401 | 1.157521 |
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 SkybellAuthenticationException(ERROR.USERNAME)
if self._password is... | def login(self, username=None, password=None) | Execute Skybell login. | 2.623127 | 2.451124 | 1.070173 |
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()
self._devices = None
... | def logout(self) | Explicit Skybell logout. | 14.004906 | 12.584159 | 1.1129 |
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)
response_object = json.loads(response.text)
_LOG... | def get_devices(self, refresh=False) | Get all devices from Abode. | 3.040751 | 2.954121 | 1.029325 |
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.ACCESS_TOKEN):
headers['Authorization'] = 'Bearer ' + \
self.cache(CONST.ACCESS_TOKEN)
headers['... | def send_request(self, method, url, headers=None,
json_data=None, retry=True) | Send requests to Skybell. | 3.09603 | 2.932902 | 1.05562 |
UTILS.update(self._cache, data)
self._save_cache() | def update_cache(self, data) | Update a cached value. | 10.151133 | 10.117853 | 1.003289 |
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 dev_cache(self, device, key=None) | Get a cached value for a device. | 3.837561 | 3.660513 | 1.048367 |
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | def update_dev_cache(self, device, data) | Update cached values for a device. | 7.775763 | 6.52829 | 1.191087 |
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:
loaded_cache = UTILS.load_cache(self._cache_path)
UTILS.up... | def _load_cache(self) | Load existing cache and merge for updating if required. | 2.631575 | 2.373145 | 1.108898 |
if per_jid_max < 1 and global_max < 1:
return
if per_jid_max < 1:
per_jid_max = None
if global_max < 1:
global_max = None
bare_jids = yield self._storage.listJIDs()
if not per_jid_max == None:
for bare_jid in bare_jids... | 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 any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also de... | 2.275307 | 2.238025 | 1.016658 |
if age_days < 1:
return
now = time.time()
bare_jids = yield self._storage.listJIDs()
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
delete_devices = []
for device, timestamp in list(devices.ite... | 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 you will
not be able to decrypt it. You are not allowed to del... | 2.628718 | 2.630553 | 0.999302 |
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
self.__inactive_global_max
)
yield self.deleteInactiveDevicesByAge(self.__inactive_max_age) | def runInactiveDeviceCleanup(self) | Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create. | 9.968255 | 6.424745 | 1.551541 |
result = {
"active" : {},
"inactive" : {}
}
devices = yield self.__loadActiveDevices(bare_jid)
for device in devices:
result["active"][device] = yield self.getTrustForDevice(bare_jid, device)
devices = yield self.__loadInactiveDe... | 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 the structure returned by getTrustForDevice. | 2.694167 | 2.093111 | 1.28716 |
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, None)
self.__devices_cache.pop(bare_jid, None)
self.__trust_cache.pop(bare_jid, None)
yield self._storage.deleteJID(bare_jid) | 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. | 5.089368 | 4.055147 | 1.255039 |
'''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['HMULIST'] = hrdwr_mu
... | def get_setup(Cnt = {}) | Return a dictionary of GPU, mu-map hardware and third party set-up. | 5.412994 | 4.480138 | 1.20822 |
''' 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 in chcklst:
output[itm] = False
# niftyreg reg_resample first... | 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' | 2.912754 | 2.448673 | 1.189523 |
'''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()
resources_file = os.pat... | def update_resources(Cnt) | Update resources.py with the paths to the new installed apps. | 4.049251 | 3.784557 | 1.06994 |
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadSessionsSync(bare_jid, device_ids) | 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. | 3.461536 | 3.243131 | 1.067344 |
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
else:
return self.__loadTrustsSync(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. | 3.199301 | 3.033112 | 1.054792 |
ik = backend.decodePublicKey(ik)[0]
spk["key"] = backend.decodePublicKey(spk["key"])[0]
otpks = list(map(lambda otpk: {
"key" : backend.decodePublicKey(otpk["key"])[0],
"id" : otpk["id"]
}, otpks))
return cls(ik, spk, spk_signature, otpks) | 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. | 2.556844 | 2.470039 | 1.035143 |
return {
"ik": backend.encodePublicKey(self.ik, "25519"),
"spk": {
"id" : self.spk["id"],
"key" : backend.encodePublicKey(self.spk["key"], "25519"),
},
"spk_signature": self.spk_signature,
"otpks": list(map(la... | 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
are structured the same way as the inputs of the c... | 2.891986 | 2.04831 | 1.411889 |
'''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
immsk[... | def imfill(immsk) | fill the empty patches of image mask 'immsk' | 2.64747 | 2.339139 | 1.131814 |
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = os.path.dirname(fimout)
if opth=='':
opth = os.path.dirname(fnii)
fimout = os.path.join(opth, fimout)
elif outpath=='':
opth = o... | 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 | 3.630959 | 3.458682 | 1.04981 |
''' 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 representing one ROI out of many in the parc... | 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 representing one ROI out of many in the parcellation... | 3.124459 | 2.044785 | 1.528014 |
''' 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 indexes for each ROI
Outputs a float number... | 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 indexes for each ROI
Outputs a float number represe... | 3.408898 | 2.344475 | 1.454013 |
return ''.join(
random.choice(
string.ascii_uppercase + string.ascii_lowercase + string.digits)
for _ in range(32)) | def gen_token() | Generate a new Skybellpy token. | 2.717456 | 2.680162 | 1.013915 |
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 SkybellException(ERROR.INVALID_SETTING_VALUE,
... | def _validate_setting(setting, value) | Validate the setting and value. | 1.712965 | 1.683462 | 1.017525 |
# 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.debug("Avatar Refresh Response: %s", new_avatar_json)
#... | def refresh(self) | Refresh the devices json object data. | 2.760186 | 2.630405 | 1.049339 |
if device_json:
UTILS.update(self._device_json, device_json)
if avatar_json:
UTILS.update(self._avatar_json, avatar_json)
if info_json:
UTILS.update(self._info_json, info_json)
if settings_json:
UTILS.update(self._settings_json,... | def update(self, device_json=None, info_json=None, settings_json=None,
avatar_json=None) | Update the internal device json data. | 1.746076 | 1.659327 | 1.05228 |
self._activities = self._activities_request()
_LOGGER.debug("Device Activities Response: %s", self._activities)
if not self._activities:
self._activities = []
elif not isinstance(self._activities, (list, tuple)):
self._activities = [self._activities]
... | def _update_activities(self) | Update stored activities and update caches as required. | 3.794774 | 3.413458 | 1.11171 |
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_event = events.get(event)
if old_event and created_at < old_event.get(... | def _update_events(self) | Update our cached list of latest activity events. | 4.278339 | 3.752373 | 1.140169 |
activities = self._activities or []
# Filter our activity array if requested
if event:
activities = list(
filter(
lambda activity:
activity[CONST.EVENT] == event, activities))
# Return the requested number
... | def activities(self, limit=1, event=None) | Return device activity information. | 7.617659 | 7.775053 | 0.979757 |
for key, value in settings.items():
_validate_setting(key, value)
try:
self._settings_request(method="patch", json_data=settings)
self.update(settings_json=settings)
except SkybellException as exc:
_LOGGER.warning("Exception changing set... | def _set_setting(self, settings) | Validate the settings and then send the PATCH request. | 5.888767 | 5.086924 | 1.157628 |
location = self._device_json.get(CONST.LOCATION, {})
return (location.get(CONST.LOCATION_LAT, 0),
location.get(CONST.LOCATION_LNG, 0)) | def location(self) | Return lat and lng tuple. | 5.213021 | 3.780916 | 1.378772 |
return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK) | def wifi_status(self) | Get the wifi status. | 15.777061 | 13.405313 | 1.176926 |
return bool(strtobool(str(self._settings_json.get(
CONST.SETTINGS_DO_NOT_DISTURB)))) | def do_not_disturb(self) | Get if do not disturb is enabled. | 9.771444 | 7.658597 | 1.275879 |
self._set_setting(
{
CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower()
}) | def do_not_disturb(self, enabled) | Set do not disturb. | 6.941731 | 6.117087 | 1.13481 |
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,
(CONST.SETTINGS_MOTION_POLICY, ena... | def motion_sensor(self, enabled) | Set the motion sensor state. | 4.085982 | 3.778987 | 1.081237 |
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) | Get devices LED color. | 2.798557 | 2.575749 | 1.086502 |
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.SETTINGS_LED_R: color[0],
CONST.SETTINGS_... | def led_rgb(self, color) | Set devices LED color. | 3.672337 | 3.590385 | 1.022825 |
if remote_base is not None:
self.remote_base = remote_base
self._remote = True
self.set_auth(username=username, password=password)
if self.auth.ready():
passman = HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, self.remote_base, s... | 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
password for local repository | 2.240943 | 2.51232 | 0.891981 |
path = self.full(filetype, **kwargs)
if path:
if self._remote:
self.download_url_to_path(self.url(filetype, **kwargs), path)
else:
print("There is no file with filetype=%r to access in the tree module loaded" % filetype) | 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 defined in $DIMAGE_DIR/data/dimage_paths.ini | 8.498687 | 7.736289 | 1.098548 |
path_exists = isfile(path)
if not path_exists or force:
dir = dirname(path)
if not exists(dir):
if self.verbose:
print("CREATE %s" % dir)
makedirs(dir)
try:
u = urlopen(url)
ex... | 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 | 2.269636 | 2.406725 | 0.943039 |
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)
self.set_remote_base(scheme="rsync") | def remote(self, username=None, password=None, inquire=None) | Configures remote access | 11.00194 | 10.918021 | 1.007686 |
''' 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 reset(self) | Reset all streams | 8.325898 | 8.306996 | 1.002275 |
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, **kwargs)
else:
destination = kwargs.get('full')
if location a... | def add(self, filetype, **kwargs) | Adds a filepath into the list of tasks to download | 7.570103 | 6.95857 | 1.087882 |
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.")
else:
self.stream = self.get_str... | def set_stream(self) | Sets the download streams | 4.714866 | 4.570616 | 1.03156 |
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.run_streamlets()
self.stream.reset_streamlet() | def commit(self, offset=None, limit=None, dryrun=False) | Start the rsync download | 7.432689 | 6.350061 | 1.170491 |
return sum_queryset(AccountEntry.objects.filter(account=self.account, timestamp__lte=self.timestamp).exclude(timestamp=self.timestamp, id__gt=self.id)) | def balance(self) -> Decimal | Returns account balance after this entry.
:return: Decimal | 6.857461 | 6.725972 | 1.019549 |
return sum_queryset(self.accountentry_set.all().filter(timestamp__lt=t)) | def get_balance(self, t: datetime) | Returns account balance before specified datetime (excluding entries on the datetime).
:param t: datetime
:return: Decimal | 16.654333 | 13.839982 | 1.203349 |
return e.type and e.type.is_settlement and e.account.id == self.id and e.settled_invoice and AccountEntry.objects.filter(parent=e).count() == 0 | 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)
:param e: AccountEntry (settlement)
:return: bool | 8.063182 | 4.85774 | 1.659863 |
row = AccountEntry.objects.filter(source_invoice=self).order_by('id').first()
return row.account if row else None | 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 | 7.471448 | 6.055995 | 1.233728 |
return cls.objects.filter(Q(account=acc) & (Q(source_invoice=self) | Q(settled_invoice=self))) if acc else cls.objects.none() | 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 | 5.610456 | 5.060316 | 1.108716 |
items = []
entries = self.get_entries(acc)
for item in entries.filter(source_invoice=self).order_by('id'):
assert isinstance(item, AccountEntry)
settlements = sum_queryset(entries.filter(settled_item=item))
bal = item.amount + settlements if item.amou... | 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 | 5.796628 | 4.578766 | 1.26598 |
unpaid_items = []
for item, bal in self.get_item_balances(acc):
assert isinstance(item, AccountEntry)
if self.type == INVOICE_DEFAULT:
if bal > Decimal(0):
unpaid_items.append((item.type.payback_priority, item, bal))
elif s... | 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 | 3.925925 | 3.162302 | 1.241477 |
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 MakeRanges(codes) | Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]] | 2.469752 | 2.231851 | 1.106593 |
print "static const %s %s[] = {" % (type, name,)
for lo, hi in ranges:
print "\t{ %d, %d }," % (lo, hi)
print "};" | def PrintRanges(type, name, ranges) | Print the ranges as an array of type named name. | 3.10512 | 2.790421 | 1.112778 |
# 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 = MakeRanges([c for c in codes if c >= 65536])
# Pull singleton ranges out of range16.
# code16 = [lo for lo, hi in range16 ... | def PrintGroup(name, codes) | Print the data structures for the group of codes.
Return a UGroup literal for the group. | 2.435988 | 2.351478 | 1.035939 |
invoice = settlement.settled_invoice
if settlement.amount < Decimal(0) and settlement.settled_invoice.type != INVOICE_CREDIT_NOTE:
raise ValidationError('Cannot target negative settlement {} to invoice {}'.format(settlement, settlement.settled_invoice))
if settlement.amount > Decimal(0) and set... | 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 'parent' field pointing to settlement, so that
if settlement is (ever) deleted the payment entries will get deleted as wel... | 2.746406 | 2.62339 | 1.046892 |
assert isinstance(credit_note, Invoice)
assert credit_note.type == INVOICE_CREDIT_NOTE
assert debit_note
assert debit_note.type == INVOICE_DEFAULT
credit = -credit_note.get_unpaid_amount()
balance = debit_note.get_unpaid_amount()
amt = min(balance, credit)
amount = kwargs.pop('amo... | 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' time of the credit note, can be overriden by kwargs.
:param credit_note: Credit note to settle
:param debit_note:... | 3.035684 | 2.856829 | 1.062606 |
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(self._pathfile))
return | def _input_templates(self) | Read the path template file. | 5.534868 | 4.418073 | 1.252779 |
''' 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 name'
assert name in sel... | 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 | 6.030308 | 4.194891 | 1.437536 |
''' 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:
A list of keyword arguments found in an... | 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:
A list of keyword arguments found in any special fu... | 6.557367 | 3.47558 | 1.886697 |
''' 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 inspect.getsource returns wr... | 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 inspect.getsource returns wrong method.
... | 4.927566 | 2.344998 | 2.101309 |
''' 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 isinstance(example, six.string_types)... | def extract(self, name, example) | Extract keywords from an example path | 4.638003 | 4.582639 | 1.012081 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.