Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
add_collision_mesh
Add a collision mesh to the planning scene. Parameters ---------- collision_mesh : :class:`compas_fab.robots.CollisionMesh` Object containing the collision mesh to be added. options : dict, optional Unused parameter. Returns ------- ``None``
from __future__ import absolute_import from __future__ import division from __future__ import print_function from compas.utilities import await_callback from compas_fab.backends.interfaces import AddCollisionMesh from compas_fab.backends.ros.messages import ApplyPlanningSceneRequest from compas_fab.backends.ros.messa...
def add_collision_mesh(self, collision_mesh, options=None): """Add a collision mesh to the planning scene. Parameters ---------- collision_mesh : :class:`compas_fab.robots.CollisionMesh` Object containing the collision mesh to be added. options : dict, optional ...
31
49
from __future__ import absolute_import from __future__ import division from __future__ import print_function from compas.utilities import await_callback from compas_fab.backends.interfaces import AddCollisionMesh from compas_fab.backends.ros.messages import ApplyPlanningSceneRequest from compas_fab.backends.ros.messa...
get_init_code
Gets initial latent codes as the start point for optimization. The input image is assumed to have already been preprocessed, meaning to have shape [self.G.image_channels, self.G.resolution, self.G.resolution], channel order `self.G.channel_order`, and pixel range [self.G.min_val, self.G.max_val].
# python 3.7 """Utility functions to invert a given image back to a latent code.""" from tqdm import tqdm import cv2 import numpy as np import torch from models.stylegan_generator import StyleGANGenerator from models.stylegan_encoder import StyleGANEncoder from models.perceptual_model import PerceptualModel __all__...
def get_init_code(self, image): """Gets initial latent codes as the start point for optimization. The input image is assumed to have already been preprocessed, meaning to have shape [self.G.image_channels, self.G.resolution, self.G.resolution], channel order `self.G.channel_order`, and pixel range [s...
131
142
# python 3.7 """Utility functions to invert a given image back to a latent code.""" from tqdm import tqdm import cv2 import numpy as np import torch from models.stylegan_generator import StyleGANGenerator from models.stylegan_encoder import StyleGANEncoder from models.perceptual_model import PerceptualModel __all__...
state
A decorator that identifies which methods are states. The presence of the farc_state attr, not the value of the attr, determines statehood. The Spy debugging system uses the farc_state attribute to determine which methods inside a class are actually states. Other uses of the attribute may come in the future.
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
def state(func): """A decorator that identifies which methods are states. The presence of the farc_state attr, not the value of the attr, determines statehood. The Spy debugging system uses the farc_state attribute to determine which methods inside a class are actually states...
168
183
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
subscribe
Adds the given Ahsm to the subscriber table list for the given signal. The argument, signame, is a string of the name of the Signal to which the Ahsm is subscribing. Using a string allows the Signal to be created in the registry if it is not already.
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
@staticmethod def subscribe(signame, act): """Adds the given Ahsm to the subscriber table list for the given signal. The argument, signame, is a string of the name of the Signal to which the Ahsm is subscribing. Using a string allows the Signal to be created in the registry if ...
439
449
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
timeEventCallback
The callback function for all TimeEvents. Posts the event to the event's target Ahsm. If the TimeEvent is periodic, re-insort the event in the list of active time events.
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
@staticmethod def timeEventCallback(tm_event, expiration): """The callback function for all TimeEvents. Posts the event to the event's target Ahsm. If the TimeEvent is periodic, re-insort the event in the list of active time events. """ assert expiration in Framew...
538
571
import asyncio import collections import math import signal import sys from functools import wraps class Spy(object): """Spy is the debugging system for farc. farc contains a handful of Spy.on_*() methods placed at useful locations in the framework. It is up to a Spy driver (such as the included VcdSp...
_apply_relativistic_doppler_shift
Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity` that is Doppler shifted by this amount. Note that the Doppler shift applied is the full relativistic one, so `SpectralQuantity` currently expressed in velocity and not using the relativistic convention will temporarily be converted to use the r...
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
def _apply_relativistic_doppler_shift(scoord, velocity): """ Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity` that is Doppler shifted by this amount. Note that the Doppler shift applied is the full relativistic one, so `SpectralQuantity` currently expressed in velocity and...
53
85
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
_validate_coordinate
Checks the type of the frame and whether a velocity differential and a distance has been defined on the frame object. If no distance is defined, the target is assumed to be "really far away", and the observer is assumed to be "in the solar system". Parameters ---------- coord : `~astropy.coordinates.BaseCoordinateFra...
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
@staticmethod def _validate_coordinate(coord, label=''): """ Checks the type of the frame and whether a velocity differential and a distance has been defined on the frame object. If no distance is defined, the target is assumed to be "really far away", and the observer i...
247
299
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
replicate
Return a replica of the `SpectralCoord`, optionally changing the values or attributes. Note that no conversion is carried out by this method - this keeps all the values and attributes the same, except for the ones explicitly passed to this method which are changed. If ``copy`` is set to `True` then a full copy of the...
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
def replicate(self, value=None, unit=None, observer=None, target=None, radial_velocity=None, redshift=None, doppler_convention=None, doppler_rest=None, copy=False): """ Return a replica of the `SpectralCoord`, optionally changin...
301
374
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
_normalized_position_vector
Calculate the normalized position vector between two frames. Parameters ---------- observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The observation frame or coordinate. target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The target fram...
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
@staticmethod def _normalized_position_vector(observer, target): """ Calculate the normalized position vector between two frames. Parameters ---------- observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord` The observation fr...
519
546
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
with_radial_velocity_shift
Apply a velocity shift to this spectral coordinate. The shift can be provided as a redshift (float value) or radial velocity (`~astropy.units.Quantity` with physical type of 'speed'). Parameters ---------- target_shift : float or `~astropy.units.Quantity` Shift value to apply to current target. observer_shift : f...
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
def with_radial_velocity_shift(self, target_shift=None, observer_shift=None): """ Apply a velocity shift to this spectral coordinate. The shift can be provided as a redshift (float value) or radial velocity (`~astropy.units.Quantity` with physical type of 'speed'). Paramete...
635
716
import warnings from textwrap import indent import astropy.units as u import numpy as np from astropy.constants import c from astropy.coordinates import (ICRS, CartesianDifferential, CartesianRepresentation, SkyCoord) from astropy.coordinates.spectral_q...
_compress
Set or check the compression of a :py:class:`pycdf.CDF` or :py:class:`pycdf.Var` @param obj: object on which to set or check compression @type obj: :py:class:`pycdf.CDF` or :py:class:`pycdf.Var` @param comptype: type of compression to change to, see CDF C reference manual section 4.10. Constants for t...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def _compress(obj, comptype=None, param=None): """Set or check the compression of a :py:class:`pycdf.CDF` or :py:class:`pycdf.Var` @param obj: object on which to set or check compression @type obj: :py:class:`pycdf.CDF` or :py:class:`pycdf.Var` @param comptype: type of compression to change to, see CDF...
1,283
1,356
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
_find_lib
Search for the CDF library Searches in likely locations for CDF libraries and attempts to load them. Stops at first successful load and, if fails, reports all the files that were tried as libraries. Returns ======= out : tuple This is either (path to library, loaded library) or, in the event of failure, (No...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
@staticmethod def _find_lib(): """ Search for the CDF library Searches in likely locations for CDF libraries and attempts to load them. Stops at first successful load and, if fails, reports all the files that were tried as libraries. Returns ======= ...
455
478
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
check_status
Raise exception or warning based on return status of CDF call Parameters ========== status : int status returned by the C library Other Parameters ================ ignore : sequence of ctypes.c_long CDF statuses to ignore. If any of these is returned by CDF library, any related warnings or exceptions will...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def check_status(self, status, ignore=()): """ Raise exception or warning based on return status of CDF call Parameters ========== status : int status returned by the C library Other Parameters ================ ignore : sequence of ctypes...
535
571
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
set_backward
Set backward compatibility mode for new CDFs Unless backward compatible mode is set, CDF files created by the version 3 library can not be read by V2. Parameters ========== backward : boolean Set backward compatible mode if True; clear it if False. Raises ====== ValueError : if backward=False and underlying CDF ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def set_backward(self, backward=True): """ Set backward compatibility mode for new CDFs Unless backward compatible mode is set, CDF files created by the version 3 library can not be read by V2. Parameters ========== backward : boolean Set backwar...
618
641
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
epoch_to_epoch16
Converts a CDF EPOCH to a CDF EPOCH16 value Parameters ========== epoch : double EPOCH to convert. Lists and numpy arrays are acceptable. Returns ======= out : (double, double) EPOCH16 corresponding to epoch
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def epoch_to_epoch16(self, epoch): """ Converts a CDF EPOCH to a CDF EPOCH16 value Parameters ========== epoch : double EPOCH to convert. Lists and numpy arrays are acceptable. Returns ======= out : (double, double) EPOCH16 co...
809
832
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
_datetime_to_tt2000_typepunned
Converts a Python datetime to a CDF TT2000 value Typepunned version that passes doubles as longlongs, to get around ARM calling convention oddness. Parameters ========== dt : :class:`datetime.datetime` date and time to convert Returns ======= out : int tt2000 corresponding to dt See Also ======== v_datetim...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def _datetime_to_tt2000_typepunned(self, dt): """ Converts a Python datetime to a CDF TT2000 value Typepunned version that passes doubles as longlongs, to get around ARM calling convention oddness. Parameters ========== dt : :class:`datetime.datetime` ...
969
1,014
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__init__
Create a CDF Exception Uses CDF C library to look up an appropriate error message. Parameters ========== status : ctypes.c_long CDF status
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __init__(self, status): """ Create a CDF Exception Uses CDF C library to look up an appropriate error message. Parameters ========== status : ctypes.c_long CDF status """ self.status = status self.string = 'CDF error ' + repr(...
1,216
1,241
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__init__
Open or create a CDF file. Parameters ========== pathname : string name of the file to open or create masterpath : string name of the master CDF file to use in creating a new file. If not provided, an existing file is opened; if provided but evaluates to ``False`` (e.g., ``''``), an empty new CDF i...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __init__(self, pathname, masterpath=None, create=None, readonly=None): """Open or create a CDF file. Parameters ========== pathname : string name of the file to open or create masterpath : string name of the master CDF file to use in creating ...
1,605
1,665
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
_open
Opens the CDF file (called on init) Will open an existing CDF file read/write. Raises ====== CDFError : if CDF library reports an error CDFWarning : if CDF library reports a warning and interpreter is set to error on warnings. .. note: Not intended for direct call; pass parameters to :py:class:`p...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def _open(self, readonly=True): """Opens the CDF file (called on init) Will open an existing CDF file read/write. Raises ====== CDFError : if CDF library reports an error CDFWarning : if CDF library reports a warning and interpreter is set to er...
1,819
1,837
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
readonly
Sets or check the readonly status of this CDF If the CDF has been changed since opening, setting readonly mode will have no effect. .. note:: Closing a CDF that has been opened readonly, or setting readonly False, may take a substantial amount of time if there are many variables in the CDF, as a (potentia...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def readonly(self, ro=None): """ Sets or check the readonly status of this CDF If the CDF has been changed since opening, setting readonly mode will have no effect. .. note:: Closing a CDF that has been opened readonly, or setting readonly False, may...
1,979
2,023
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
checksum
Set or check the checksum status of this CDF. If checksums are enabled, the checksum will be verified every time the file is opened. Other Parameters ================ new_val : boolean True to enable checksum, False to disable, or leave out to simply check. Returns ======= out : boolean True if the checks...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def checksum(self, new_val=None): """ Set or check the checksum status of this CDF. If checksums are enabled, the checksum will be verified every time the file is opened. Other Parameters ================ new_val : boolean True to enable checksum,...
2,025
2,050
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__init__
Create or locate a variable Parameters ========== cdf_file : :py:class:`pycdf.CDF` CDF file containing this variable var_name : string name of this variable Other Parameters ================ args additional arguments passed to :py:meth:`_create`. If none, opens an existing variable. If provided, creat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __init__(self, cdf_file, var_name, *args): """Create or locate a variable Parameters ========== cdf_file : :py:class:`pycdf.CDF` CDF file containing this variable var_name : string name of this variable Other Parameters ==========...
2,766
2,804
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
_create
Creates a new zVariable @param var_name: name of this variable @type var_name: string @param datatype: CDF data type @type datatype: ctypes.c_long @param n_elements: number of elements (should be 1 except for CDF_CHAR variables). @type n_elements: long @param dims: size of each dimension for multi-d...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def _create(self, var_name, datatype, n_elements = 1, dims = (), recVary = const.VARY, dimVarys = None): """Creates a new zVariable @param var_name: name of this variable @type var_name: string @param datatype: CDF data type @type datatype: ctypes.c_long ...
3,013
3,050
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
rv
Gets or sets whether this variable has record variance If the variance is unknown, True is assumed (this replicates the apparent behavior of the CDF library on variable creation). Other Parameters ================ new_rv : boolean True to change to record variance, False to change to NRV, unspecified to simpl...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def rv(self, new_rv=None): """ Gets or sets whether this variable has record variance If the variance is unknown, True is assumed (this replicates the apparent behavior of the CDF library on variable creation). Other Parameters ================ new_r...
3,177
3,201
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
dv
Gets or sets dimension variance of each dimension of variable. If the variance is unknown, True is assumed (this replicates the apparent behavior of the CDF library on variable creation). Parameters ========== new_dv : list of boolean Each element True to change that dimension to dimension variance, False to ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def dv(self, new_dv=None): """ Gets or sets dimension variance of each dimension of variable. If the variance is unknown, True is assumed (this replicates the apparent behavior of the CDF library on variable creation). Parameters ========== new_dv : ...
3,203
3,236
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__init__
Create a Hyperslice @param zvar: zVariable that this slices @type zvar: :py:class:`pycdf.Var` @param key: Python multi-dimensional slice as passed to __getitem__ @type key: tuple of slice and/or int @raise IndexError: if slice is out of range, mismatches dimensions, or otherwise unparsab...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __init__(self, zvar, key): """Create a Hyperslice @param zvar: zVariable that this slices @type zvar: :py:class:`pycdf.Var` @param key: Python multi-dimensional slice as passed to __getitem__ @type key: tuple of slice and/or int @raise IndexEr...
3,510
3,571
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
expand
Expands the record dimension of this slice to hold a set of data If the length of data (outermost dimension) is larger than the record count (counts[0]) for this slice, expand the slice to hold all the data. This requires that the record dimension of the slice not be degenerate, and also that it not have been complete...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def expand(self, data): """Expands the record dimension of this slice to hold a set of data If the length of data (outermost dimension) is larger than the record count (counts[0]) for this slice, expand the slice to hold all the data. This requires that the record dimension of the s...
3,583
3,607
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__init__
Initialize this attribute @param cdf_file: CDF file containing this attribute @type cdf_file: :py:class:`pycdf.CDF` @param attr_name: Name of this attribute @type attr_name: str @param create: True to create attribute, False to look up existing. @type create: bool
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __init__(self, cdf_file, attr_name, create=False): """Initialize this attribute @param cdf_file: CDF file containing this attribute @type cdf_file: :py:class:`pycdf.CDF` @param attr_name: Name of this attribute @type attr_name: str @param create: True to create a...
4,040
4,085
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__getitem__
Return a slice of Entries. Because Attributes may be sparse, a multi-element slice will return None for those elements which do not have associated Entries. @param key: index or range of Entry number to return @type key: slice or int @return: a list of entries, appropriate type. @raise IndexError: if L{key} is an int...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __getitem__(self, key): """Return a slice of Entries. Because Attributes may be sparse, a multi-element slice will return None for those elements which do not have associated Entries. @param key: index or range of Entry number to return @type key: slice or int @...
4,087
4,109
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
__len__
Number of Entries for this Attr. NOT same as max Entry number. @return: Number of Entries @rtype: int
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def __len__(self): """Number of Entries for this Attr. NOT same as max Entry number. @return: Number of Entries @rtype: int """ count = ctypes.c_long(0) self._call(const.GET_, self.ATTR_NUMENTRIES_, ctypes.byref(count)) return count.value
4,287
4,295
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
type
Find or change the CDF type of a zEntry in this zVar @param name: name of the zAttr to check or change @type name: str @param new_type: type to change it to, see :py:mod:`pycdf.const` @type new_type: ctypes.c_long @return: CDF variable type, see :py:mod:`pycdf.const` @rtype: int @note: If changing types, old and new m...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
def type(self, name, new_type=None): """Find or change the CDF type of a zEntry in this zVar @param name: name of the zAttr to check or change @type name: str @param new_type: type to change it to, see :py:mod:`pycdf.const` @type new_type: ctypes.c_long @return: CDF ...
5,290
5,307
#!/usr/bin/env python # -*- coding: utf-8 -*- """ das developers note: This a is modification of the original SpacePy pycdf package. All refereneces to the greater spacepy package have been removed to create a small standalone module. --cwp 2018-10-18 The libcdf.so location code has been changed to f...
dot
This operator calculates inner product for vectors. .. note:: Support 1-d and 2-d Tensor. When it is 2d, the first dimension of this matrix is the batch dimension, which means that the vectors of multiple batches are dotted. Parameters: x(Tensor): 1-D or 2-D ``Tensor``. Its dtype should be ``float32``, ``fl...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def dot(x, y, name=None): """ This operator calculates inner product for vectors. .. note:: Support 1-d and 2-d Tensor. When it is 2d, the first dimension of this matrix is the batch dimension, which means that the vectors of multiple batches are dotted. Parameters: x(Tensor): 1-...
871
925
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
t
Transpose <=2-D tensor. 0-D and 1-D tensors are returned as it is and 2-D tensor is equal to the paddle.transpose function which perm dimensions set 0 and 1. Args: input (Tensor): The input Tensor. It is a N-D (N<=2) Tensor of data types float16, float32, float64, int32. name(str, optional): The default value ...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def t(input, name=None): """ Transpose <=2-D tensor. 0-D and 1-D tensors are returned as it is and 2-D tensor is equal to the paddle.transpose function which perm dimensions set 0 and 1. Args: input (Tensor): The input Tensor. It is a N-D (N<=2) Tensor of data types float16, float32, float6...
1,041
1,112
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
bmm
Applies batched matrix multiplication to two tensors. Both of the two input tensors must be three-dementional and share the same batch size. if x is a (b, m, k) tensor, y is a (b, k, n) tensor, the output will be a (b, m, n) tensor. Args: x (Tensor): The input Tensor. y (Tensor): The input Tensor. name(s...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def bmm(x, y, name=None): """ Applies batched matrix multiplication to two tensors. Both of the two input tensors must be three-dementional and share the same batch size. if x is a (b, m, k) tensor, y is a (b, k, n) tensor, the output will be a (b, m, n) tensor. Args: x (Tensor): The inpu...
1,315
1,373
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
histogram
Computes the histogram of a tensor. The elements are sorted into equal width bins between min and max. If min and max are both zero, the minimum and maximum values of the data are used. Args: input (Tensor): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` . The data type of the input Tensor s...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def histogram(input, bins=100, min=0, max=0, name=None): """ Computes the histogram of a tensor. The elements are sorted into equal width bins between min and max. If min and max are both zero, the minimum and maximum values of the data are used. Args: input (Tensor): A Tensor(or LoDTensor) wit...
1,376
1,414
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
bincount
Computes frequency of each value in the input tensor. Args: x (Tensor): A Tensor with non-negative integer. Should be 1-D tensor. weights (Tensor, optional): Weight for each value in the input tensor. Should have the same shape as input. Default is None. minlength (int, optional): Minimum number of bins. ...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def bincount(x, weights=None, minlength=0, name=None): """ Computes frequency of each value in the input tensor. Args: x (Tensor): A Tensor with non-negative integer. Should be 1-D tensor. weights (Tensor, optional): Weight for each value in the input tensor. Should have the same shape as ...
1,417
1,467
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
eig
This API performs the eigenvalue decomposition of a square matrix or a batch of square matrices. .. note:: If the matrix is a Hermitian or a real symmetric matrix, please use :ref:`paddle.linalg.eigh` instead, which is much faster. If only eigenvalues is needed, please use :ref:`paddle.linalg.eigvals` instead....
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def eig(x, name=None): """ This API performs the eigenvalue decomposition of a square matrix or a batch of square matrices. .. note:: If the matrix is a Hermitian or a real symmetric matrix, please use :ref:`paddle.linalg.eigh` instead, which is much faster. If only eigenvalues is needed, p...
2,039
2,102
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
eigh
Compute the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[*, N, N]` , The data type of the input Tensor x should be one of float32, float64, complex64, complex128. UPLO(str, optional): (string, default...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def eigh(x, UPLO='L', name=None): """ Compute the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[*, N, N]` , The data type of the input Tensor x should be one of float32, float64, co...
2,245
2,311
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
eigvalsh
Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x should be one of float32, float64, complex64, complex128. UPLO(str, optional): Lower triangular part of a (‘L’...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def eigvalsh(x, UPLO='L', name=None): """ Computes the eigenvalues of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. Args: x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x should be one of float32, float64, complex64, co...
2,766
2,830
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
lstsq
Computes a solution to the least squares problem of a system of linear equations. Args: x (Tensor): A tensor with shape ``(*, M, N)`` , the data type of the input Tensor ``x`` should be one of float32, float64. y (Tensor): A tensor with shape ``(*, M, K)`` , the data type of the input Tensor ``y`` ...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def lstsq(x, y, rcond=None, driver=None, name=None): """ Computes a solution to the least squares problem of a system of linear equations. Args: x (Tensor): A tensor with shape ``(*, M, N)`` , the data type of the input Tensor ``x`` should be one of float32, float64. y (Tens...
2,833
3,005
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
frobenius_norm
The frobenius norm OP is to calculate the frobenius norm of certain two dimensions of Tensor `input`. Args: input (Variable): Tensor, data type float32, float64. dim (list, optional): None for last two dimensions. keepdim (bool, optional): Whether keep the dimensions as the `input`, Default False.
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def frobenius_norm(input, dim=None, keepdim=False, name=None): """ The frobenius norm OP is to calculate the frobenius norm of certain two dimensions of Tensor `input`. Args: input (Variable): Tensor, data type float32, float64. dim (list, optional): None for last two dim...
242
275
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
vector_norm
Calculate the p-order vector norm for certain dimension of Tensor `input`. Args: input (Variable): Tensor, data type float32, float64. porder (float, optional): None for porder=2.0. axis (int, optional): None for last dimension. keepdim (bool, optional): Whether keep the dimensions as the `input`, Default Fals...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def vector_norm(input, porder=None, axis=None, keepdim=False, asvector=False, name=None): """ Calculate the p-order vector norm for certain dimension of Tensor `input`. Args: input ...
277
318
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
on_off_command
Send an on or off command to an appliance Sends the specified command to the homevision through netio interface to control the specified appliance. Args: details: {"appliance": string, "state": string}
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
def on_off_command(self, details): """Send an on or off command to an appliance Sends the specified command to the homevision through netio interface to control the specified appliance. Args: details: {"appliance": string, "state": string} """ if "appliance" not in details: ...
61
84
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
action_command
Send an action command Sends the specified command to the homevision through netio interface. Args: details: {"command": string}
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
def action_command(self, details): """Send an action command Sends the specified command to the homevision through netio interface. Args: details: {"command": string} """ if "command" not in details: raise Exception("Command not specified") if details["command"] not in ...
86
100
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
start_stop_command
Starts or stops a process Sends the specified command to the homevision through netio interface to control the specified process. Args: details: {"action": string, "process": string}
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
def start_stop_command(self, details): """Starts or stops a process Sends the specified command to the homevision through netio interface to control the specified process. Args: details: {"action": string, "process": string} """ if "action" not in details: raise Exception("a...
102
123
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
var_query
Returns the answer to a query on variable Returns the answer to a query on the specified variable using netio Args: details: {"query": string}
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
def var_query(self, details): """Returns the answer to a query on variable Returns the answer to a query on the specified variable using netio Args: details: {"query": string} """ if "query" not in details: raise Exception("query not specified") if details["query"] ...
142
164
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
flag_query
Returns the answer to a query on flag Returns the answer to a query on the specified variable using netio Args: details: {"query": string}
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
def flag_query(self, details): """Returns the answer to a query on flag Returns the answer to a query on the specified variable using netio Args: details: {"query": string} """ if "query" not in details: raise Exception("query not specified") if details["query"] not...
166
182
import socket class UserException(Exception): pass def user_exception(s): raise UserException(s) class Macro: """Represents a macro to be run""" def __init__(self, code): """code: int - index of macro to run""" self.code = code class Command: """Represents a macro to be run""" def __init__(self, ...
_find_files
Find files in directory with optional extensions. Args: directory (string) keywords (list): e.g. ["SelfpacedRota", "ButtonPress] (optional) extensions (list): e.g. [".json" or "tsv"] (optional) verbose (bool): verbosity level (optional, default=True)
"""Define abstract base classes to construct FileFinder classes.""" import os import shutil from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Sequence, Union import mne_bids @dataclass class FileFinder(ABC): """Basic representation...
def _find_files( self, directory: Union[Path, str], extensions: Optional[Union[list, str]] = None, ) -> None: """Find files in directory with optional extensions. Args: directory (string) keywords (list): e.g. ["SelfpacedRota", "ButtonPress] (opti...
88
108
"""Define abstract base classes to construct FileFinder classes.""" import os import shutil from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Sequence, Union import mne_bids @dataclass class FileFinder(ABC): """Basic representation...
irfft2
Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input tensor s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over which to compute the inverse fft. Default is the last two axes. norm : {None, "ortho"}, o...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
def irfft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input tensor s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over ...
31
67
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
_send_notification
Send a notification to a specific node_id This version of the overriden method includes the necessary crypto headers for the notification. :type notification: autopush.utils.WebPushNotification
"""WebPush Style Autopush Router This router handles notifications that should be dispatched to an Autopush node, or stores each individual message, along with its data, in a Message table for retrieval by the client. """ import json import time from StringIO import StringIO from typing import Any # noqa from botoc...
def _send_notification(self, uaid, node_id, notification): """Send a notification to a specific node_id This version of the overriden method includes the necessary crypto headers for the notification. :type notification: autopush.utils.WebPushNotification """ paylo...
179
197
"""WebPush Style Autopush Router This router handles notifications that should be dispatched to an Autopush node, or stores each individual message, along with its data, in a Message table for retrieval by the client. """ import json import time from StringIO import StringIO from typing import Any # noqa from botoc...
_save_notification
Saves a notification, returns a deferred. This version of the overridden method saves each individual message to the message table along with relevant request headers if available. :type uaid_data: dict
"""WebPush Style Autopush Router This router handles notifications that should be dispatched to an Autopush node, or stores each individual message, along with its data, in a Message table for retrieval by the client. """ import json import time from StringIO import StringIO from typing import Any # noqa from botoc...
def _save_notification(self, uaid_data, notification): """Saves a notification, returns a deferred. This version of the overridden method saves each individual message to the message table along with relevant request headers if available. :type uaid_data: dict """ ...
207
239
"""WebPush Style Autopush Router This router handles notifications that should be dispatched to an Autopush node, or stores each individual message, along with its data, in a Message table for retrieval by the client. """ import json import time from StringIO import StringIO from typing import Any # noqa from botoc...
_recursive_apply
This function is "applied" to every child in the block. This function in turn registers the forward hook to each module. It helps logging the input output tensors of that module.
# Third Party import mxnet as mx from mxnet.ndarray import NDArray # First Party from smdebug.core.collection import DEFAULT_MXNET_COLLECTIONS, CollectionKeys from smdebug.core.hook import CallbackHook from smdebug.core.json_config import DEFAULT_WORKER_NAME from smdebug.core.utils import FRAMEWORK, error_handling_age...
def _recursive_apply(self, block): """ This function is "applied" to every child in the block. This function in turn registers the forward hook to each module. It helps logging the input output tensors of that module. """ # Check if the hook is already registered for ...
185
196
# Third Party import mxnet as mx from mxnet.ndarray import NDArray # First Party from smdebug.core.collection import DEFAULT_MXNET_COLLECTIONS, CollectionKeys from smdebug.core.hook import CallbackHook from smdebug.core.json_config import DEFAULT_WORKER_NAME from smdebug.core.utils import FRAMEWORK, error_handling_age...
register_block
This function registers the forward hook. If user wants to register the hook for every child in the given block, then the function calls "apply" API for registration of the hook. The hook is registered recursively, if user has specified the collections that are more than the default collectors viz. gradients, weight an...
# Third Party import mxnet as mx from mxnet.ndarray import NDArray # First Party from smdebug.core.collection import DEFAULT_MXNET_COLLECTIONS, CollectionKeys from smdebug.core.hook import CallbackHook from smdebug.core.json_config import DEFAULT_WORKER_NAME from smdebug.core.utils import FRAMEWORK, error_handling_age...
@error_handling_agent.catch_smdebug_errors() def register_block(self, block): """ This function registers the forward hook. If user wants to register the hook for every child in the given block, then the function calls "apply" API for registration of the hook. The hook is...
224
258
# Third Party import mxnet as mx from mxnet.ndarray import NDArray # First Party from smdebug.core.collection import DEFAULT_MXNET_COLLECTIONS, CollectionKeys from smdebug.core.hook import CallbackHook from smdebug.core.json_config import DEFAULT_WORKER_NAME from smdebug.core.utils import FRAMEWORK, error_handling_age...
step
Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
""" """ from __future__ import division from torch.optim.optimizer import Optimizer, required import numpy as np import torch from typing import NamedTuple, List from dataclasses import dataclass from enum import Enum from typing import Union, Tuple # from scipy.sparse.linalg import svds from scipy.optimize import mi...
def step(self, closure: callable = None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closur...
432
473
""" """ from __future__ import division from torch.optim.optimizer import Optimizer, required import numpy as np import torch from typing import NamedTuple, List from dataclasses import dataclass from enum import Enum from typing import Union, Tuple # from scipy.sparse.linalg import svds from scipy.optimize import mi...
get_value
Returns the displayed text for the desired column in this row. The formula or input which generated the displayed value is not accessible through the list feed, to see the user's input, use the cells feed. If a column is not present in this spreadsheet, or there is no value for a column in this row, this method will ...
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found he...
def get_value(self, column_name): """Returns the displayed text for the desired column in this row. The formula or input which generated the displayed value is not accessible through the list feed, to see the user's input, use the cells feed. If a column is not present in this spre...
244
256
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found he...
set_value
Changes the value of cell in this row under the desired column name. Warning: if the cell contained a formula, it will be wiped out by setting the value using the list feed since the list feed only works with displayed values. No client side checking is performed on the column_name, you need to ensure that the column...
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found he...
def set_value(self, column_name, value): """Changes the value of cell in this row under the desired column name. Warning: if the cell contained a formula, it will be wiped out by setting the value using the list feed since the list feed only works with displayed values. No ...
258
279
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found he...
__getattribute__
Attribute lookup method for custom class attributes. ReFrame test variables are descriptors injected at the class level. If a variable descriptor has already been injected into the class, do not return the descriptor object and return the default value associated with that variable instead. .. warning:: .. versio...
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
def __getattribute__(cls, name): '''Attribute lookup method for custom class attributes. ReFrame test variables are descriptors injected at the class level. If a variable descriptor has already been injected into the class, do not return the descriptor object and return the default ...
446
471
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
__getattr__
Backup attribute lookup method into custom namespaces. Some ReFrame built-in types are stored under their own sub-namespaces. This method will perform an attribute lookup on these sub-namespaces if a call to the default :func:`__getattribute__` method fails to retrieve the requested class attribute.
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
def __getattr__(cls, name): '''Backup attribute lookup method into custom namespaces. Some ReFrame built-in types are stored under their own sub-namespaces. This method will perform an attribute lookup on these sub-namespaces if a call to the default :func:`__getattribute__` method ...
473
500
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
performance_function
Decorate a function to extract a performance variable. The ``units`` argument indicates the units of the performance variable to be extracted. The ``perf_key`` optional arg will be used as the name of the performance variable. If not provided, the function name will be used as the performance variable name.
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
def performance_function(units, *, perf_key=None): '''Decorate a function to extract a performance variable. The ``units`` argument indicates the units of the performance variable to be extracted. The ``perf_key`` optional arg will be used as the name of the ...
293
325
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
create_test_server
Wrapper utility that returns a test server. This wrapper utility calls the common create test server and returns a test server. The purpose of this wrapper is to minimize the impact on the code of the tests already using this function. :param validatable: Whether the server will be pingable or sshable. :param volume_...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
@classmethod def create_test_server(cls, validatable=False, volume_backed=False, validation_resources=None, clients=None, **kwargs): """Wrapper utility that returns a test server. This wrapper utility calls the common create test server and returns a test serv...
232
284
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
recreate_server
Destroy an existing class level server and creates a new one Some test classes use a test server that can be used by multiple tests. This is done to optimise runtime and test load. If something goes wrong with the test server, it can be rebuilt using this helper. This helper can also be used for the initial provision...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
@classmethod def recreate_server(cls, server_id, validatable=False, **kwargs): """Destroy an existing class level server and creates a new one Some test classes use a test server that can be used by multiple tests. This is done to optimise runtime and test load. If something goe...
402
434
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
create_volume
Create a volume and wait for it to become 'available'. :param image_ref: Specify an image id to create a bootable volume. :param kwargs: other parameters to create volume. :returns: The available volume.
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
@classmethod def create_volume(cls, image_ref=None, **kwargs): """Create a volume and wait for it to become 'available'. :param image_ref: Specify an image id to create a bootable volume. :param kwargs: other parameters to create volume. :returns: The available volume. "...
503
529
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
attach_volume
Attaches volume to server and waits for 'in-use' volume status. The volume will be detached when the test tears down. :param server: The server to which the volume will be attached. :param volume: The volume to attach. :param device: Optional mountpoint for the attached volume. Note that this is not guaranteed fo...
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
def attach_volume(self, server, volume, device=None, tag=None): """Attaches volume to server and waits for 'in-use' volume status. The volume will be detached when the test tears down. :param server: The server to which the volume will be attached. :param volume: The volume to atta...
548
585
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
list
This method is a generator which yields queue objects. This is almost the copy of list method of resource.Resource class. The only difference is the request header now includes `Client-ID` and `X-PROJECT-ID` fields which are required by Zaqar v2 API.
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
@classmethod def list(cls, session, paginated=False, **params): """This method is a generator which yields queue objects. This is almost the copy of list method of resource.Resource class. The only difference is the request header now includes `Client-ID` and `X-PROJECT-ID` fiel...
67
106
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
ComputeConvOutputShape
Computes output shape for convolution and pooling layers. If `in_shape` is a dynamic shape, the output will be Tensors, while if `in_shape` is a list of ints then the output will also be a list of ints. Args: in_shape: A length 4 Tensor or list representing the input shape. t_stride: The stride along the time dim...
# Lint as: python2, python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
def ComputeConvOutputShape(in_shape, t_stride, f_stride, outc=None, padding='SAME'): """Computes output shape for convolution and pooling layers. If `in_shape` is a dynamic shape, the output will be Tensors,...
30
67
# Lint as: python2, python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
ComputeConvOutputPadding
Computes paddings for convolution and pooling output. out_padding[i] == 1 iff any in_padding corresponding to that output is 1. Args: paddings: The paddings tensor. It is expected to be of shape [batch, time]. window: The size of the windows. stride: The time-stride between adjacent windows. padding_algorithm...
# Lint as: python2, python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
def ComputeConvOutputPadding(paddings, window, stride, padding_algorithm='SAME'): """Computes paddings for convolution and pooling output. out_padding[i] == 1 iff any in_padding corresponding to that output is 1. Args: paddings: The paddings tensor. It is expected to be of shape...
70
99
# Lint as: python2, python3 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
list_topic_keys
Namespace/ServiceBus Connection String API Version: 2017-04-01. :param str authorization_rule_name: The authorization rule name. :param str namespace_name: The namespace name :param str resource_group_name: Name of the Resource group within the Azure subscription. :param str topic_name: The topic name.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
def list_topic_keys(authorization_rule_name: Optional[str] = None, namespace_name: Optional[str] = None, resource_group_name: Optional[str] = None, topic_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableL...
117
150
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
__init__
Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.compute_v1.types.AggregatedListTargetInstancesRequest): The initial request object. response (google.cloud.compute_v1.types.TargetInstanceAggregate...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
def __init__( self, method: Callable[..., compute.TargetInstanceAggregatedList], request: compute.AggregatedListTargetInstancesRequest, response: compute.TargetInstanceAggregatedList, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager....
48
71
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
__init__
Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.compute_v1.types.ListTargetInstancesRequest): The initial request object. response (google.cloud.compute_v1.types.TargetInstanceList): The ...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
def __init__( self, method: Callable[..., compute.TargetInstanceList], request: compute.ListTargetInstancesRequest, response: compute.TargetInstanceList, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: me...
113
136
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
__init__
Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by a comma. Each new line is a different sample. Example below: /path/to/audio.wav,/path/to/audio.txt ... :param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds :param ...
import os import subprocess from tempfile import NamedTemporaryFile from torch.distributed import get_rank from torch.distributed import get_world_size from torch.utils.data.sampler import Sampler import librosa import numpy as np import scipy.signal import torch from scipy.io.wavfile import read import math from tor...
def __init__(self, audio_conf, manifest_filepath, labels, normalize=False, speed_volume_perturb=False, spec_augment=False): """ Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by a comma. Each new line is a different sample. Example below: ...
172
199
import os import subprocess from tempfile import NamedTemporaryFile from torch.distributed import get_rank from torch.distributed import get_world_size from torch.utils.data.sampler import Sampler import librosa import numpy as np import scipy.signal import torch from scipy.io.wavfile import read import math from tor...
validate_meta_info
Validate meta information Adds 'BIDS.NA' if no BIDS info present Adds 'BIDS.valid' and 'BIDS.error_message' to communicate to user if values are valid Currently, validation is only checking if mandatory properties are non-empty strings Could add the following checks: Are the values alpha numeric?
import argparse import logging import json import os import tempfile import sys import re import flywheel from .supporting_files import bidsify_flywheel, utils, templates from .supporting_files.project_tree import get_project_tree logging.basicConfig(level=logging.INFO) logger = logging.getLogger('curate-bids') def...
def validate_meta_info(container, template): """ Validate meta information Adds 'BIDS.NA' if no BIDS info present Adds 'BIDS.valid' and 'BIDS.error_message' to communicate to user if values are valid Currently, validation is only checking if mandatory properties are non-empty strings ...
27
78
import argparse import logging import json import os import tempfile import sys import re import flywheel from .supporting_files import bidsify_flywheel, utils, templates from .supporting_files.project_tree import get_project_tree logging.basicConfig(level=logging.INFO) logger = logging.getLogger('curate-bids') def...
__add
:param name: 系列名称,用于 tooltip 的显示,legend 的图例筛选。 :param x_axis: x 坐标轴数据。 :param y_axis: y 坐标轴数据。数据中,每一行是一个『数据项』,每一列属于一个『维度』。 数据项具体为 [open, close, lowest, highest] (即:[开盘值, 收盘值, 最低值, 最高值])。 :param kwargs:
# coding=utf-8 from pyecharts.chart import Chart def kline_tooltip_formatter(params): text = ( params[0].seriesName + "<br/>" + "- open:" + params[0].data[1] + "<br/>" + "- close:" + params[0].data[2] + "<br/>" + "- lowest:" + params...
def __add(self, name, x_axis, y_axis, **kwargs): """ :param name: 系列名称,用于 tooltip 的显示,legend 的图例筛选。 :param x_axis: x 坐标轴数据。 :param y_axis: y 坐标轴数据。数据中,每一行是一个『数据项』,每一列属于一个『维度』。 数据项具体为 [open, close, lowest, highest] (即:[开盘值, 收盘值, ...
39
77
# coding=utf-8 from pyecharts.chart import Chart def kline_tooltip_formatter(params): text = ( params[0].seriesName + "<br/>" + "- open:" + params[0].data[1] + "<br/>" + "- close:" + params[0].data[2] + "<br/>" + "- lowest:" ...
PsdArray2Noise_1d
Generates a noise pattern whose Power Spectral density is given by Psd. Parameters --------------------- Psd : 1d array Contains the numeric Psd (treated as evenly spaced array) Semiaxis : 0 : does nothing 1 : halvens Pds, then replicates the halven part for left frequencies, ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 07 14:08:31 2016 @author: Mic """ from __future__ import division from wiselib2.must import * import numpy as np import wiselib2.Rayman as rm Gauss1d = lambda x ,y : None from scipy import interpolate as interpolate from matplotlib import pyplot as plt class PsdFuns: ...
def PsdArray2Noise_1d(PsdArray, N, Semiaxis = True, Real = True): ''' Generates a noise pattern whose Power Spectral density is given by Psd. Parameters --------------------- Psd : 1d array Contains the numeric Psd (treated as evenly spaced array) Semiaxis : 0 : does nothing 1 : halvens Pds, then replica...
136
177
# -*- coding: utf-8 -*- """ Created on Thu Jul 07 14:08:31 2016 @author: Mic """ from __future__ import division from wiselib2.must import * import numpy as np import wiselib2.Rayman as rm Gauss1d = lambda x ,y : None from scipy import interpolate as interpolate from matplotlib import pyplot as plt class PsdFuns: ...
MakeProfile
Evaluates the psd according to .PsdType, .PsdParams and .Options directives Returns an evenly-spaced array. If PsdType = NumericArray, linear interpolation is performed. :PARAM: N: # of samples :PARAM: dx: grid spacing (spatial frequency) returns: 1d arr
# -*- coding: utf-8 -*- """ Created on Thu Jul 07 14:08:31 2016 @author: Mic """ from __future__ import division from wiselib2.must import * import numpy as np import wiselib2.Rayman as rm Gauss1d = lambda x ,y : None from scipy import interpolate as interpolate from matplotlib import pyplot as plt class PsdFuns: ...
def MakeProfile(self, L,N): ''' Evaluates the psd according to .PsdType, .PsdParams and .Options directives Returns an evenly-spaced array. If PsdType = NumericArray, linear interpolation is performed. :PARAM: N: # of samples :PARAM: dx: grid spacing (spatial frequency) returns: 1d arr ''' ...
393
413
# -*- coding: utf-8 -*- """ Created on Thu Jul 07 14:08:31 2016 @author: Mic """ from __future__ import division from wiselib2.must import * import numpy as np import wiselib2.Rayman as rm Gauss1d = lambda x ,y : None from scipy import interpolate as interpolate from matplotlib import pyplot as plt class PsdFuns: ...
__getitem__
Get the procedure params according to the index. Create the register when it does not exist. :param index: :return: ProcedureParamStorage
#!/usr/bin/python3 # -*- coding: utf8 -*- # Copyright (c) 2020 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
def __getitem__(self, index): """ Get the procedure params according to the index. Create the register when it does not exist. :param index: :return: ProcedureParamStorage """ value = self.paramsDict.get(index) if value is not None: retu...
35
50
#!/usr/bin/python3 # -*- coding: utf8 -*- # Copyright (c) 2020 Baidu, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE...
build_model
Build DCE using the initialized attributes Args: norm: boolean, wheher to add a normalization layer at the begining of the autoencoder act: string, keras activation function name for autoencoder
""" DeepChEmbed (DCE) Models """ from dimreducer import DeepAutoEncoder from cluster import KMeansLayer from cluster import KMeans from keras import Model from keras import optimizers from keras.utils import normalize import numpy as np class DCE(): """ The class to build a deep chemical embedding model. ...
def build_model(self, norm=True, act='relu'): """Build DCE using the initialized attributes Args: norm: boolean, wheher to add a normalization layer at the begining of the autoencoder act: string, keras activation function name for autoencoder """ ...
52
68
""" DeepChEmbed (DCE) Models """ from dimreducer import DeepAutoEncoder from cluster import KMeansLayer from cluster import KMeans from keras import Model from keras import optimizers from keras.utils import normalize import numpy as np class DCE(): """ The class to build a deep chemical embedding model. ...
hardening
hardening distribution P and return Q Args: q: input distributions. h_func: input harderning function. strength: hardening strength. returns: p: hardened and normatlized distributions.
""" DeepChEmbed (DCE) Models """ from dimreducer import DeepAutoEncoder from cluster import KMeansLayer from cluster import KMeans from keras import Model from keras import optimizers from keras.utils import normalize import numpy as np class DCE(): """ The class to build a deep chemical embedding model. ...
@staticmethod def hardening(q, h_func, stength): """hardening distribution P and return Q Args: q: input distributions. h_func: input harderning function. strength: hardening strength. returns: p: hardened and normatlized distributions. ...
207
222
""" DeepChEmbed (DCE) Models """ from dimreducer import DeepAutoEncoder from cluster import KMeansLayer from cluster import KMeans from keras import Model from keras import optimizers from keras.utils import normalize import numpy as np class DCE(): """ The class to build a deep chemical embedding model. ...
authenticate_active
Generate a WLS 'success' response based on interaction with the user This function creates a WLS response specifying that the principal was authenticated based on 'fresh' interaction with the user (e.g. input of a username and password). Args: request (AuthRequest): the original WAA request principal (AuthPri...
import datetime from . import status from .errors import InvalidAuthRequest, ProtocolVersionUnsupported, NoMutualAuthType from .signing import Key from .response import AuthResponse class AuthPrincipal: def __init__(self, userid, auth_methods, ptags=None, session_expiry=None): self.userid = userid ...
def authenticate_active(self, request, principal, auth, life=None, sign=True, skip_handling_check=False, *args, **kwargs): """Generate a WLS 'success' response based on interaction with the user This function creates a WLS response specifying that the principal was ...
68
108
import datetime from . import status from .errors import InvalidAuthRequest, ProtocolVersionUnsupported, NoMutualAuthType from .signing import Key from .response import AuthResponse class AuthPrincipal: def __init__(self, userid, auth_methods, ptags=None, session_expiry=None): self.userid = userid ...
authenticate_passive
Generate a WLS 'success' response based on a pre-existing identity This function creates a WLS response specifying that the principal was authenticated based on previous successful authentication (e.g. an existing WLS session cookie). Args: request (AuthRequest): the original WAA request principal (AuthPrinci...
import datetime from . import status from .errors import InvalidAuthRequest, ProtocolVersionUnsupported, NoMutualAuthType from .signing import Key from .response import AuthResponse class AuthPrincipal: def __init__(self, userid, auth_methods, ptags=None, session_expiry=None): self.userid = userid ...
def authenticate_passive(self, request, principal, sso=[], sign=True, skip_handling_check=False, *args, **kwargs): """Generate a WLS 'success' response based on a pre-existing identity This function creates a WLS response specifying that the principal was authen...
110
158
import datetime from . import status from .errors import InvalidAuthRequest, ProtocolVersionUnsupported, NoMutualAuthType from .signing import Key from .response import AuthResponse class AuthPrincipal: def __init__(self, userid, auth_methods, ptags=None, session_expiry=None): self.userid = userid ...
__init__
:param bool enable_magnetic_store_writes: A flag to enable magnetic store writes. :param 'TableMagneticStoreWritePropertiesMagneticStoreRejectedDataLocationArgs' magnetic_store_rejected_data_location: The location to write error reports for records rejected asynchronously during magnetic store writes. See Magnetic Stor...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
def __init__(__self__, *, enable_magnetic_store_writes: Optional[bool] = None, magnetic_store_rejected_data_location: Optional['outputs.TableMagneticStoreWritePropertiesMagneticStoreRejectedDataLocation'] = None): """ :param bool enable_magnetic_store_writes: A flag...
40
50
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
__init__
:param str bucket_name: Bucket name of the customer S3 bucket. :param str encryption_option: Encryption option for the customer s3 location. Options are S3 server side encryption with an S3-managed key or KMS managed key. Valid values are `SSE_KMS` and `SSE_S3`. :param str kms_key_id: KMS key arn for the customer s3 lo...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
def __init__(__self__, *, bucket_name: Optional[str] = None, encryption_option: Optional[str] = None, kms_key_id: Optional[str] = None, object_key_prefix: Optional[str] = None): """ :param str bucket_name: Bucket name of the custome...
130
148
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
post
Handle the POST request and sign up the user if form validation passes Returns: A redirect or a template with the validation errors
from flask import render_template, flash, redirect, url_for, request from flask.views import MethodView from app.middleware import auth from app.models.user import User from app.validators.register_form import RegisterForm from app.services import avatar_service class RegisterController(MethodView): @auth.optional...
@auth.optional def post(self): """ Handle the POST request and sign up the user if form validation passes Returns: A redirect or a template with the validation errors """ form = RegisterForm() if form.validate_on_submit(): form.validate_username(form.username) avatar = '...
21
45
from flask import render_template, flash, redirect, url_for, request from flask.views import MethodView from app.middleware import auth from app.models.user import User from app.validators.register_form import RegisterForm from app.services import avatar_service class RegisterController(MethodView): @auth.optional...
__init__
Initializer for linear model. Args: num_inputs: the dimension of input data. num_hidden_layers: the number of hidden layers. num_inner_features: the number of features in the hidden layers
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ # MASKED: __init__ function (lines 14-29) def forwar...
def __init__(self, num_inputs, num_hidden_layers, num_inner_features): """Initializer for linear model. Args: num_inputs: the dimension of input data. num_hidden_layers: the number of hidden layers. num_inner_features: the number of features in the hidden layers ...
14
29
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
forward
Forward pass on the neural network model. Args: input_tensor: the input tensor. Returns: Tensor with model results.
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
def forward(self, input_tensor): """Forward pass on the neural network model. Args: input_tensor: the input tensor. Returns: Tensor with model results. """ output = F.relu(self.input_layer(input_tensor)) output = self.hidden_layers(output) ...
31
43
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
__init__
Initializer for model class. Args: learning_rate: the learning rate of the model. num_hidden_layers: number of hidden layers in the network. num_inner_features: number of features in the hidden layers.
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
def __init__(self, learning_rate=1e-3, num_hidden_layers=1, num_inner_features=100): """Initializer for model class. Args: learning_rate: the learning rate of the model. num_hidden_layers: number of hidden layers in the network. num_inner_features: number of feat...
51
67
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
_predict
Use provided information to make a prediction. Args: state_action_tensor: pytorch tensor with state-action values. Returns: Predicted values for observation-action tensors.
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
def _predict(self, state_action_tensor): """Use provided information to make a prediction. Args: state_action_tensor: pytorch tensor with state-action values. Returns: Predicted values for observation-action tensors. """ if self.model is None: ...
78
89
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
_train
Train the model for 1 epoch. Args: state_action_tensor: pytorch tensor with state-action expected_values. expected_values: pytorch tensor with expected values for each state-action. Returns: The loss before trainig.
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
def _train(self, state_action_tensor, expected_values_tensor): """Train the model for 1 epoch. Args: state_action_tensor: pytorch tensor with state-action expected_values. expected_values: pytorch tensor with expected values for each state-action. Returns: ...
91
110
"""Polynomial model class used by agents for building stuff. """ from torch import nn, optim import torch import torch.nn.functional as F from stock_trading_backend.agent.model import Model class NNModel(nn.Module): """Torch neural network model. """ def __init__(self, num_inputs, num_hidden_layers, num...
getNetworkCellularGatewaySettingsDhcp
**List common DHCP settings of MGs** https://developer.cisco.com/meraki/api/#!get-network-cellular-gateway-settings-dhcp - networkId (string)
class MGDHCPSettings(object): def __init__(self, session): super(MGDHCPSettings, self).__init__() self._session = session # MASKED: getNetworkCellularGatewaySettingsDhcp function (lines 6-20) def updateNetworkCellularGatewaySettingsDhcp(self, networkId: str, **kwargs): """ ...
def getNetworkCellularGatewaySettingsDhcp(self, networkId: str): """ **List common DHCP settings of MGs** https://developer.cisco.com/meraki/api/#!get-network-cellular-gateway-settings-dhcp - networkId (string) """ metadata = { 'tags': ['MG DHCP ...
6
20
class MGDHCPSettings(object): def __init__(self, session): super(MGDHCPSettings, self).__init__() self._session = session def getNetworkCellularGatewaySettingsDhcp(self, networkId: str): """ **List common DHCP settings of MGs** https://developer.cisco.com/meraki/api/...
blend
Blend image1 and image2 using 'factor'. A value of factor 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "extrapolates" the difference between the two pixel values, an...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. A value of factor 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "extrapolates"...
25
45
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
get_book_quote_page
Find the ``<a>`` element pointing to the quote page of a book. Args: soup (bs4.element.Tag): Returns:
""" Scrape quotes, books and authors from ``Good Reads`` website. """ import bs4 from .utils import * def get_author_name(soup): """Get the author's name from its main page. Args: soup (bs4.element.Tag): connection to the author page. Returns: string: name of the author. Examples::...
def get_book_quote_page(soup): """Find the ``<a>`` element pointing to the quote page of a book. Args: soup (bs4.element.Tag): Returns: """ quote_div = soup.findAll('div', attrs={'class': ' clearFloats bigBox'}) if quote_div: return quote_div[-1].find('a') return None
380
392
""" Scrape quotes, books and authors from ``Good Reads`` website. """ import bs4 from .utils import * def get_author_name(soup): """Get the author's name from its main page. Args: soup (bs4.element.Tag): connection to the author page. Returns: string: name of the author. Examples::...
find_generator
The order of any element in a group can be divided by p-1. Step 1: Calculate all Divisors. Step 2: Test for a random element e of G wether e to the power of a Divisor is 1. if neither is one but e to the power of p-1, a generator is found.
""" This file implements the signature scheme from "Unique Ring Signatures: A Practical Construction" by Matthew Franklin and Haibin Zhang """ import sys import math from random import randint import hashlib from libsig.AbstractRingSignatureScheme import AbstractRingSignatureScheme #from AbstractRingSignatureScheme im...
def find_generator(p): ''' The order of any element in a group can be divided by p-1. Step 1: Calculate all Divisors. Step 2: Test for a random element e of G wether e to the power of a Divisor is 1. if neither is one but e to the power of p-1, a generator is found. ''' # Init #...
34
69
""" This file implements the signature scheme from "Unique Ring Signatures: A Practical Construction" by Matthew Franklin and Haibin Zhang """ import sys import math from random import randint import hashlib from libsig.AbstractRingSignatureScheme import AbstractRingSignatureScheme #from AbstractRingSignatureScheme im...
children
Get childen nodes of this node. Arguments: depth: Number of levels of children to traverse. 0 returns only this node. include_self: Includes this node in the results. include_parents: Includes nodes that match in the results, when they also have child nodes that match. include_children: If True...
#!/usr/bin/python3 import functools from copy import deepcopy from .grammar import BASE_NODE_TYPES class NodeBase: """Represents a node within the solidity AST. Attributes: depth: Number of nodes between this node and the SourceUnit offset: Absolute source offsets as a (start, stop) tuple ...
def children( self, depth=None, include_self=False, include_parents=True, include_children=True, required_offset=None, offset_limits=None, filters=None, exclude_filter=None, ): """Get childen nodes of this node. Arguments: ...
71
114
#!/usr/bin/python3 import functools from copy import deepcopy from .grammar import BASE_NODE_TYPES class NodeBase: """Represents a node within the solidity AST. Attributes: depth: Number of nodes between this node and the SourceUnit offset: Absolute source offsets as a (start, stop) tuple ...
pqcost
Splits the gencost variable into two pieces if costs are given for Qg. Checks whether C{gencost} has cost information for reactive power generation (rows C{ng+1} to C{2*ng}). If so, it returns the first C{ng} rows in C{pcost} and the last C{ng} rows in C{qcost}. Otherwise, leaves C{qcost} empty. Also does some error c...
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Splits the gencost variable into two pieces if costs are given for Qg. """ from sys import stderr from numpy import array, arange # MASKED: pqcost function ...
def pqcost(gencost, ng, on=None): """Splits the gencost variable into two pieces if costs are given for Qg. Checks whether C{gencost} has cost information for reactive power generation (rows C{ng+1} to C{2*ng}). If so, it returns the first C{ng} rows in C{pcost} and the last C{ng} rows in C{qcost}. Oth...
13
37
# Copyright (c) 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Splits the gencost variable into two pieces if costs are given for Qg. """ from sys import stderr from numpy import array, arange def pqcost(gencost, ng, on...
thumbIncrementCheck
Checks whether your thumb is up or not. No matter what hand you use. returns 1 if thumb is up else 0
"""Python 3.9.5""" import cv2 import HandTrackingModule as htm # MASKED: thumbIncrementCheck function (lines 7-20) def textOutput(count, cc) -> str: """Returns an appropriate text output depending on `count` and `cc`.""" text = "NOTHING" if (count, cc) == (2, 2): text = "SCISSOR" elif c...
def thumbIncrementCheck(lmList: list[list[int]]) -> int: """Checks whether your thumb is up or not. No matter what hand you use. returns 1 if thumb is up else 0""" count = 0 t_x = lmList[4][1] p_x = lmList[17][1] if t_x > p_x: # If true: RIGHT hand if lmList[4][1] >= lmList[2][1]: ...
7
20
"""Python 3.9.5""" import cv2 import HandTrackingModule as htm def thumbIncrementCheck(lmList: list[list[int]]) -> int: """Checks whether your thumb is up or not. No matter what hand you use. returns 1 if thumb is up else 0""" count = 0 t_x = lmList[4][1] p_x = lmList[17][1] if t_x > p_x:...
_read_kit_data
Read epochs data. Returns ------- data : array, [channels x samples] the data matrix (channels x samples). times : array, [samples] returns the time values corresponding to the samples.
"""Conversion tool from SQD to FIF. RawKIT class is adapted from Denis Engemann et al.'s mne_bti2fiff.py. """ # Authors: Teon Brooks <teon.brooks@gmail.com> # Joan Massich <mailsik@gmail.com> # Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) from collections import defaul...
def _read_kit_data(self): """Read epochs data. Returns ------- data : array, [channels x samples] the data matrix (channels x samples). times : array, [samples] returns the time values corresponding to the samples. """ info = self._raw_...
427
454
"""Conversion tool from SQD to FIF. RawKIT class is adapted from Denis Engemann et al.'s mne_bti2fiff.py. """ # Authors: Teon Brooks <teon.brooks@gmail.com> # Joan Massich <mailsik@gmail.com> # Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) from collections import defaul...
get_home_envvars
Return dict with env variables to be adjusted for a new HOME Only variables found in current os.environ are adjusted. Parameters ---------- new_home: str or Path New home path, in native to OS "schema"
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
def get_home_envvars(new_home): """Return dict with env variables to be adjusted for a new HOME Only variables found in current os.environ are adjusted. Parameters ---------- new_home: str or Path New home path, in native to OS "schema" """ new_home = str(new_home) out = {'HOME':...
232
251
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
rmtree
To remove git-annex .git it is needed to make all files and directories writable again first Parameters ---------- path: Path or str Path to remove chmod_files : string or bool, optional Whether to make files writable also before removal. Usually it is just a matter of directories to have write permissions. ...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
def rmtree(path, chmod_files='auto', children_only=False, *args, **kwargs): """To remove git-annex .git it is needed to make all files and directories writable again first Parameters ---------- path: Path or str Path to remove chmod_files : string or bool, optional Whether to make fil...
469
518
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
ensure_bytes
Convert/encode unicode string to bytes. If `s` isn't a string, return it as is. Parameters ---------- encoding: str, optional Encoding to use. "utf-8" is the default
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
def ensure_bytes(s, encoding='utf-8'): """Convert/encode unicode string to bytes. If `s` isn't a string, return it as is. Parameters ---------- encoding: str, optional Encoding to use. "utf-8" is the default """ if not isinstance(s, str): return s return s.encode(encodin...
792
804
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
ensure_unicode
Convert/decode bytestring to unicode. If `s` isn't a bytestring, return it as is. Parameters ---------- encoding: str, optional Encoding to use. If None, "utf-8" is tried, and then if not a valid UTF-8, encoding will be guessed confidence: float, optional A value between 0 and 1, so if guessing of encoding is ...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
def ensure_unicode(s, encoding=None, confidence=None): """Convert/decode bytestring to unicode. If `s` isn't a bytestring, return it as is. Parameters ---------- encoding: str, optional Encoding to use. If None, "utf-8" is tried, and then if not a valid UTF-8, encoding will be guessed...
807
851
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
unique
Given a sequence return a list only with unique elements while maintaining order This is the fastest solution. See https://www.peterbe.com/plog/uniqifiers-benchmark and http://stackoverflow.com/a/480227/1265472 for more information. Enhancement -- added ability to compare for uniqueness using a key function Paramete...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
def unique(seq, key=None, reverse=False): """Given a sequence return a list only with unique elements while maintaining order This is the fastest solution. See https://www.peterbe.com/plog/uniqifiers-benchmark and http://stackoverflow.com/a/480227/1265472 for more information. Enhancement ...
900
933
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...