sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def redistribute_threads(blockdimx, blockdimy, blockdimz,
dimx, dimy, dimz):
"""
Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary
"""
# Shift threads from the z dimension
# into the y dimension
... | Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary | entailment |
def register_default_dimensions(cube, slvr_cfg):
""" Register the default dimensions for a RIME solver """
import montblanc.src_types as mbs
# Pull out the configuration options for the basics
autocor = slvr_cfg['auto_correlations']
ntime = 10
na = 7
nbands = 1
nchan = 16
npol = 4... | Register the default dimensions for a RIME solver | entailment |
def get_ip_address(ifname):
""" Hack to get IP address from the interface """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24]) | Hack to get IP address from the interface | entailment |
def nvcc_compiler_settings():
""" Find nvcc and the CUDA installation """
search_paths = os.environ.get('PATH', '').split(os.pathsep)
nvcc_path = find_in_path('nvcc', search_paths)
default_cuda_path = os.path.join('usr', 'local', 'cuda')
cuda_path = os.environ.get('CUDA_PATH', default_cuda_path)
... | Find nvcc and the CUDA installation | entailment |
def inspect_cuda_version_and_devices(compiler, settings):
"""
Poor mans deviceQuery. Returns CUDA_VERSION information and
CUDA device information in JSON format
"""
try:
output = build_and_run(compiler, '''
#include <cuda.h>
#include <stdio.h>
__device__ ... | Poor mans deviceQuery. Returns CUDA_VERSION information and
CUDA device information in JSON format | entailment |
def customize_compiler_for_nvcc(compiler, nvcc_settings):
"""inject deep into distutils to customize gcc/nvcc dispatch """
# tell the compiler it can process .cu files
compiler.src_extensions.append('.cu')
# save references to the default compiler_so and _compile methods
default_compiler_so = comp... | inject deep into distutils to customize gcc/nvcc dispatch | entailment |
def inspect_cuda():
""" Return cuda device information and nvcc/cuda setup """
nvcc_settings = nvcc_compiler_settings()
sysconfig.get_config_vars()
nvcc_compiler = ccompiler.new_compiler()
sysconfig.customize_compiler(nvcc_compiler)
customize_compiler_for_nvcc(nvcc_compiler, nvcc_settings)
... | Return cuda device information and nvcc/cuda setup | entailment |
def template_dict(self):
"""
Returns a dictionary suitable for templating strings with
properties and dimensions related to this Solver object.
Used in templated GPU kernels.
"""
slvr = self
D = {
# Constants
'LIGHTSPEED': montblanc.const... | Returns a dictionary suitable for templating strings with
properties and dimensions related to this Solver object.
Used in templated GPU kernels. | entailment |
def rime_solver(slvr_cfg):
""" Factory function that produces a RIME solver """
from montblanc.impl.rime.tensorflow.RimeSolver import RimeSolver
return RimeSolver(slvr_cfg) | Factory function that produces a RIME solver | entailment |
def find_sources(obj, argspec=None):
"""
Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified.by argspec,
a list of argument specifiers. So for e.g. an argpsec of
:code:`[['self', 'context'], ['s', 'c']]` would match
methods looking lik... | Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified.by argspec,
a list of argument specifiers. So for e.g. an argpsec of
:code:`[['self', 'context'], ['s', 'c']]` would match
methods looking like:
.. code-block:: python
def f(sel... | entailment |
def sources(self):
"""
Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified by
(self, context) arguments on this object. For example:
.. code-block:: python
def f(self, context):
...
... | Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified by
(self, context) arguments on this object. For example:
.. code-block:: python
def f(self, context):
...
is a source method, but
... | entailment |
def parallactic_angles(times, antenna_positions, field_centre):
"""
Computes parallactic angles per timestep for the given
reference antenna position and field centre.
Arguments:
times: ndarray
Array of unique times with shape (ntime,),
obtained from TIME column of MS ta... | Computes parallactic angles per timestep for the given
reference antenna position and field centre.
Arguments:
times: ndarray
Array of unique times with shape (ntime,),
obtained from TIME column of MS table
antenna_positions: ndarray of shape (na, 3)
Antenna ... | entailment |
def setup_logging():
""" Setup logging configuration """
# Console formatter, mention name
cfmt = logging.Formatter(('%(name)s - %(levelname)s - %(message)s'))
# File formatter, mention time
ffmt = logging.Formatter(('%(asctime)s - %(levelname)s - %(message)s'))
# Console handler
ch = log... | Setup logging configuration | entailment |
def constant_cache(method):
"""
Caches constant arrays associated with an array name.
The intent of this decorator is to avoid the cost
of recreating and storing many arrays of constant data,
especially data created by np.zeros or np.ones.
Instead, a single array of the first given shape is cre... | Caches constant arrays associated with an array name.
The intent of this decorator is to avoid the cost
of recreating and storing many arrays of constant data,
especially data created by np.zeros or np.ones.
Instead, a single array of the first given shape is created
and any further requests for co... | entailment |
def chunk_cache(method):
"""
Caches chunks of default data.
This decorator caches generated default data so as to
avoid recomputing it on a subsequent queries to the
provider.
"""
@functools.wraps(method)
def wrapper(self, context):
# Defer to the method if no caching is enable... | Caches chunks of default data.
This decorator caches generated default data so as to
avoid recomputing it on a subsequent queries to the
provider. | entailment |
def _create_defaults_source_provider(cube, data_source):
"""
Create a DefaultsSourceProvider object. This provides default
data sources for each array defined on the hypercube. The data sources
may either by obtained from the arrays 'default' data source
or the 'test' data source.
"""
from m... | Create a DefaultsSourceProvider object. This provides default
data sources for each array defined on the hypercube. The data sources
may either by obtained from the arrays 'default' data source
or the 'test' data source. | entailment |
def _construct_tensorflow_expression(slvr_cfg, feed_data, device, shard):
""" Constructs a tensorflow expression for computing the RIME """
zero = tf.constant(0)
src_count = zero
src_ph_vars = feed_data.src_ph_vars
LSA = feed_data.local
polarisation_type = slvr_cfg['polarisation_type']
# ... | Constructs a tensorflow expression for computing the RIME | entailment |
def _get_data(data_source, context):
""" Get data from the data source, checking the return values """
try:
# Get data from the data source
data = data_source.source(context)
# Complain about None values
if data is None:
raise ValueError("'None' returned from "
... | Get data from the data source, checking the return values | entailment |
def _supply_data(data_sink, context):
""" Supply data to the data sink """
try:
data_sink.sink(context)
except Exception as e:
ex = ValueError("An exception occurred while "
"supplying data to data sink '{ds}'\n\n"
"{e}\n\n"
"{help}".format(ds=context.name... | Supply data to the data sink | entailment |
def _apply_source_provider_dim_updates(cube, source_providers, budget_dims):
"""
Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
... | Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
lower_extent is always set to 0. upper_extent is set to any reductions
(current upp... | entailment |
def _setup_hypercube(cube, slvr_cfg):
""" Sets up the hypercube given a solver configuration """
mbu.register_default_dimensions(cube, slvr_cfg)
# Configure the dimensions of the beam cube
cube.register_dimension('beam_lw', 2,
description='E Beam cube l width')
cube.reg... | Sets up the hypercube given a solver configuration | entailment |
def _partition(iter_dims, data_sources):
"""
Partition data sources into
1. Dictionary of data sources associated with radio sources.
2. List of data sources to feed multiple times.
3. List of data sources to feed once.
"""
src_nr_vars = set(source_var_types().values())
iter_dims = set... | Partition data sources into
1. Dictionary of data sources associated with radio sources.
2. List of data sources to feed multiple times.
3. List of data sources to feed once. | entailment |
def _feed(self, cube, data_sources, data_sinks, global_iter_args):
""" Feed stub """
try:
self._feed_impl(cube, data_sources, data_sinks, global_iter_args)
except Exception as e:
montblanc.log.exception("Feed Exception")
raise | Feed stub | entailment |
def _feed_impl(self, cube, data_sources, data_sinks, global_iter_args):
""" Implementation of staging_area feeding """
session = self._tf_session
FD = self._tf_feed_data
LSA = FD.local
# Get source strides out before the local sizes are modified during
# the source loops... | Implementation of staging_area feeding | entailment |
def _compute(self, feed_dict, shard):
""" Call the tensorflow compute """
try:
descriptor, enq = self._tfrun(self._tf_expr[shard], feed_dict=feed_dict)
self._inputs_waiting.decrement(shard)
except Exception as e:
montblanc.log.exception("Compute Exception")
... | Call the tensorflow compute | entailment |
def _consume(self, data_sinks, cube, global_iter_args):
""" Consume stub """
try:
return self._consume_impl(data_sinks, cube, global_iter_args)
except Exception as e:
montblanc.log.exception("Consumer Exception")
raise e, None, sys.exc_info()[2] | Consume stub | entailment |
def _consume_impl(self, data_sinks, cube, global_iter_args):
""" Consume """
LSA = self._tf_feed_data.local
output = self._tfrun(LSA.output.get_op)
# Expect the descriptor in the first tuple position
assert len(output) > 0
assert LSA.output.fed_arrays[0] == 'descriptor'... | Consume | entailment |
def rime_solver_cfg(**kwargs):
"""
Produces a SolverConfiguration object, inherited from
a simple python dict, and containing the options required
to configure the RIME Solver.
Keyword arguments
-----------------
Any keyword arguments are inserted into the
returned dict.
Returns
... | Produces a SolverConfiguration object, inherited from
a simple python dict, and containing the options required
to configure the RIME Solver.
Keyword arguments
-----------------
Any keyword arguments are inserted into the
returned dict.
Returns
-------
A SolverConfiguration object. | entailment |
def _create_filenames(filename_schema, feed_type):
"""
Returns a dictionary of beam filename pairs,
keyed on correlation,from the cartesian product
of correlations and real, imaginary pairs
Given 'beam_$(corr)_$(reim).fits' returns:
{
'xx' : ('beam_xx_re.fits', 'beam_xx_im.fits'),
'... | Returns a dictionary of beam filename pairs,
keyed on correlation,from the cartesian product
of correlations and real, imaginary pairs
Given 'beam_$(corr)_$(reim).fits' returns:
{
'xx' : ('beam_xx_re.fits', 'beam_xx_im.fits'),
'xy' : ('beam_xy_re.fits', 'beam_xy_im.fits'),
...
'... | entailment |
def _open_fits_files(filenames):
"""
Given a {correlation: filename} mapping for filenames
returns a {correlation: file handle} mapping
"""
kw = { 'mode' : 'update', 'memmap' : False }
def _fh(fn):
""" Returns a filehandle or None if file does not exist """
return fits.open(fn, ... | Given a {correlation: filename} mapping for filenames
returns a {correlation: file handle} mapping | entailment |
def _create_axes(filenames, file_dict):
""" Create a FitsAxes object """
try:
# Loop through the file_dictionary, finding the
# first open FITS file.
f = iter(f for tup in file_dict.itervalues()
for f in tup if f is not None).next()
except StopIteration as e:
rai... | Create a FitsAxes object | entailment |
def _initialise(self, feed_type="linear"):
"""
Initialise the object by generating appropriate filenames,
opening associated file handles and inspecting the FITS axes
of these files.
"""
self._filenames = filenames = _create_filenames(self._filename_schema,
... | Initialise the object by generating appropriate filenames,
opening associated file handles and inspecting the FITS axes
of these files. | entailment |
def ebeam(self, context):
""" ebeam cube data source """
if context.shape != self.shape:
raise ValueError("Partial feeding of the "
"beam cube is not yet supported %s %s." % (context.shape, self.shape))
ebeam = np.empty(context.shape, context.dtype)
# Iterat... | ebeam cube data source | entailment |
def model_vis(self, context):
""" model visibility data sink """
column = self._vis_column
msshape = None
# Do we have a column descriptor for the supplied column?
try:
coldesc = self._manager.column_descriptors[column]
except KeyError as e:
colde... | model visibility data sink | entailment |
def _cache(method):
"""
Decorator for caching data source return values
Create a key index for the proxied array in the context.
Iterate over the array shape descriptor e.g. (ntime, nbl, 3)
returning tuples containing the lower and upper extents
of string dimensions. Takes (0, d) in the case of... | Decorator for caching data source return values
Create a key index for the proxied array in the context.
Iterate over the array shape descriptor e.g. (ntime, nbl, 3)
returning tuples containing the lower and upper extents
of string dimensions. Takes (0, d) in the case of an integer
dimensions. | entailment |
def _proxy(method):
"""
Decorator returning a method that proxies a data source.
"""
@functools.wraps(method)
def memoizer(self, context):
return method(context)
return memoizer | Decorator returning a method that proxies a data source. | entailment |
def start(self, start_context):
""" Perform any logic on solution start """
for p in self._providers:
p.start(start_context)
if self._clear_start:
self.clear_cache() | Perform any logic on solution start | entailment |
def stop(self, stop_context):
""" Perform any logic on solution stop """
for p in self._providers:
p.stop(stop_context)
if self._clear_stop:
self.clear_cache() | Perform any logic on solution stop | entailment |
def default_base_ant_pairs(self, context):
""" Compute base antenna pairs """
k = 0 if context.cfg['auto_correlations'] == True else 1
na = context.dim_global_size('na')
gen = (i.astype(context.dtype) for i in np.triu_indices(na, k))
# Cache np.triu_indices(na, k) as its likely that (na, k) will
... | Compute base antenna pairs | entailment |
def default_antenna1(self, context):
""" Default antenna1 values """
ant1, ant2 = default_base_ant_pairs(self, context)
(tl, tu), (bl, bu) = context.dim_extents('ntime', 'nbl')
ant1_result = np.empty(context.shape, context.dtype)
ant1_result[:,:] = ant1[np.newaxis,bl:bu]
return ant1_result | Default antenna1 values | entailment |
def default_antenna2(self, context):
""" Default antenna2 values """
ant1, ant2 = default_base_ant_pairs(self, context)
(tl, tu), (bl, bu) = context.dim_extents('ntime', 'nbl')
ant2_result = np.empty(context.shape, context.dtype)
ant2_result[:,:] = ant2[np.newaxis,bl:bu]
return ant2_result | Default antenna2 values | entailment |
def identity_on_pols(self, context):
"""
Returns [[1, 0], tiled up to other dimensions
[0, 1]]
"""
A = np.empty(context.shape, context.dtype)
A[:,:,:] = [[[1,0,0,1]]]
return A | Returns [[1, 0], tiled up to other dimensions
[0, 1]] | entailment |
def default_stokes(self, context):
"""
Returns [[1, 0], tiled up to other dimensions
[0, 0]]
"""
A = np.empty(context.shape, context.dtype)
A[:,:,:] = [[[1,0,0,0]]]
return A | Returns [[1, 0], tiled up to other dimensions
[0, 0]] | entailment |
def frequency(self, context):
""" Frequency data source """
channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ)
return channels.reshape(context.shape).astype(context.dtype) | Frequency data source | entailment |
def ref_frequency(self, context):
""" Reference frequency data source """
num_chans = self._manager.spectral_window_table.getcol(MS.NUM_CHAN)
ref_freqs = self._manager.spectral_window_table.getcol(MS.REF_FREQUENCY)
data = np.hstack((np.repeat(rf, bs) for bs, rf in zip(num_chans, ref_fre... | Reference frequency data source | entailment |
def uvw(self, context):
""" Per-antenna UVW coordinate data source """
# Hacky access of private member
cube = context._cube
# Create antenna1 source context
a1_actual = cube.array("antenna1", reify=True)
a1_ctx = SourceContext("antenna1", cube, context.cfg,
... | Per-antenna UVW coordinate data source | entailment |
def antenna1(self, context):
""" antenna1 data source """
lrow, urow = MS.uvw_row_extents(context)
antenna1 = self._manager.ordered_uvw_table.getcol(
MS.ANTENNA1, startrow=lrow, nrow=urow-lrow)
return antenna1.reshape(context.shape).astype(context.dtype) | antenna1 data source | entailment |
def antenna2(self, context):
""" antenna2 data source """
lrow, urow = MS.uvw_row_extents(context)
antenna2 = self._manager.ordered_uvw_table.getcol(
MS.ANTENNA2, startrow=lrow, nrow=urow-lrow)
return antenna2.reshape(context.shape).astype(context.dtype) | antenna2 data source | entailment |
def parallactic_angles(self, context):
""" parallactic angle data source """
# Time and antenna extents
(lt, ut), (la, ua) = context.dim_extents('ntime', 'na')
return (mbu.parallactic_angles(self._times[lt:ut],
self._antenna_positions[la:ua], self._phase_dir)
... | parallactic angle data source | entailment |
def observed_vis(self, context):
""" Observed visibility data source """
lrow, urow = MS.row_extents(context)
data = self._manager.ordered_main_table.getcol(
self._vis_column, startrow=lrow, nrow=urow-lrow)
return data.reshape(context.shape).astype(context.dtype) | Observed visibility data source | entailment |
def flag(self, context):
""" Flag data source """
lrow, urow = MS.row_extents(context)
flag = self._manager.ordered_main_table.getcol(
MS.FLAG, startrow=lrow, nrow=urow-lrow)
return flag.reshape(context.shape).astype(context.dtype) | Flag data source | entailment |
def weight(self, context):
""" Weight data source """
lrow, urow = MS.row_extents(context)
weight = self._manager.ordered_main_table.getcol(
MS.WEIGHT, startrow=lrow, nrow=urow-lrow)
# WEIGHT is applied across all channels
weight = np.repeat(weight, self._manager.ch... | Weight data source | entailment |
def load_tf_lib():
""" Load the tensorflow library """
from os.path import join as pjoin
import pkg_resources
import tensorflow as tf
path = pjoin('ext', 'rime.so')
rime_lib_path = pkg_resources.resource_filename("montblanc", path)
return tf.load_op_library(rime_lib_path) | Load the tensorflow library | entailment |
def raise_validator_errors(validator):
"""
Raise any errors associated with the validator.
Parameters
----------
validator : :class:`cerberus.Validator`
Validator
Raises
------
ValueError
Raised if errors existed on `validator`.
Message describing each error and... | Raise any errors associated with the validator.
Parameters
----------
validator : :class:`cerberus.Validator`
Validator
Raises
------
ValueError
Raised if errors existed on `validator`.
Message describing each error and information
associated with the configurat... | entailment |
def indented(text, level, indent=2):
"""Take a multiline text and indent it as a block"""
return "\n".join("%s%s" % (level * indent * " ", s) for s in text.splitlines()) | Take a multiline text and indent it as a block | entailment |
def dumped(text, level, indent=2):
"""Put curly brackets round an indented text"""
return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n" | Put curly brackets round an indented text | entailment |
def copy_file(
source_path,
target_path,
allow_undo=True,
no_confirm=False,
rename_on_collision=True,
silent=False,
extra_flags=0,
hWnd=None
):
"""Perform a shell-based file copy. Copying in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file"... | Perform a shell-based file copy. Copying in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file" animation during the copy.
The default options allow for undo, don't automatically
clobber on a name clash, automatically rename on collision
and display the animation. | entailment |
def move_file(
source_path,
target_path,
allow_undo=True,
no_confirm=False,
rename_on_collision=True,
silent=False,
extra_flags=0,
hWnd=None
):
"""Perform a shell-based file move. Moving in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file" ... | Perform a shell-based file move. Moving in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file" animation during the copy.
The default options allow for undo, don't automatically
clobber on a name clash, automatically rename on collision
and display the animation. | entailment |
def rename_file(
source_path,
target_path,
allow_undo=True,
no_confirm=False,
rename_on_collision=True,
silent=False,
extra_flags=0,
hWnd=None
):
"""Perform a shell-based file rename. Renaming in
this way allows the possibility of undo, auto-renaming,
and showing the "flying ... | Perform a shell-based file rename. Renaming in
this way allows the possibility of undo, auto-renaming,
and showing the "flying file" animation during the copy.
The default options allow for undo, don't automatically
clobber on a name clash, automatically rename on collision
and display the animatio... | entailment |
def delete_file(
source_path,
allow_undo=True,
no_confirm=False,
silent=False,
extra_flags=0,
hWnd=None
):
"""Perform a shell-based file delete. Deleting in
this way uses the system recycle bin, allows the
possibility of undo, and showing the "flying file"
animation during the de... | Perform a shell-based file delete. Deleting in
this way uses the system recycle bin, allows the
possibility of undo, and showing the "flying file"
animation during the delete.
The default options allow for undo, don't automatically
clobber on a name clash and display the animation. | entailment |
def structured_storage(filename):
"""Pick out info from MS documents with embedded
structured storage(typically MS Word docs etc.)
Returns a dictionary of information found
"""
if not pythoncom.StgIsStorageFile(filename):
return {}
flags = storagecon.STGM_READ | storagecon.STGM_SHARE... | Pick out info from MS documents with embedded
structured storage(typically MS Word docs etc.)
Returns a dictionary of information found | entailment |
def CreateShortcut(Path, Target, Arguments="", StartIn="", Icon=("", 0), Description=""):
"""Create a Windows shortcut:
Path - As what file should the shortcut be created?
Target - What command should the desktop use?
Arguments - What arguments should be supplied to the command?
StartIn - What fold... | Create a Windows shortcut:
Path - As what file should the shortcut be created?
Target - What command should the desktop use?
Arguments - What arguments should be supplied to the command?
StartIn - What folder should the command start in?
Icon -(filename, index) What icon should be used for the shor... | entailment |
def undelete(self, original_filepath):
"""Restore the most recent version of a filepath, returning
the filepath it was restored to(as rename-on-collision will
apply if a file already exists at that path).
"""
candidates = self.versions(original_filepath)
if not candidates... | Restore the most recent version of a filepath, returning
the filepath it was restored to(as rename-on-collision will
apply if a file already exists at that path). | entailment |
def _get_queue_types(fed_arrays, data_sources):
"""
Given a list of arrays to feed in fed_arrays, return
a list of associated queue types, obtained from tuples
in the data_sources dictionary
"""
try:
return [data_sources[n].dtype for n in fed_arrays]
except KeyError as e:
rai... | Given a list of arrays to feed in fed_arrays, return
a list of associated queue types, obtained from tuples
in the data_sources dictionary | entailment |
def create_queue_wrapper(name, queue_size, fed_arrays, data_sources, *args, **kwargs):
"""
Arguments
name: string
Name of the queue
queue_size: integer
Size of the queue
fed_arrays: list
array names that will be fed by this queue
data_sources: ... | Arguments
name: string
Name of the queue
queue_size: integer
Size of the queue
fed_arrays: list
array names that will be fed by this queue
data_sources: dict
(lambda/method, dtype) tuples, keyed on array names | entailment |
def parse_python_assigns(assign_str):
"""
Parses a string, containing assign statements
into a dictionary.
.. code-block:: python
h5 = katdal.open('123456789.h5')
kwargs = parse_python_assigns("spw=3; scans=[1,2];"
"targets='bpcal,radec';"
... | Parses a string, containing assign statements
into a dictionary.
.. code-block:: python
h5 = katdal.open('123456789.h5')
kwargs = parse_python_assigns("spw=3; scans=[1,2];"
"targets='bpcal,radec';"
"channels=slice(0,20... | entailment |
def find_sinks(obj):
"""
Returns a dictionary of sink methods found on this object,
keyed on method name. Sink methods are identified by
(self, context) arguments on this object. For example:
def f(self, context):
...
is a sink method, but
def f(self, ctx):
...
is not... | Returns a dictionary of sink methods found on this object,
keyed on method name. Sink methods are identified by
(self, context) arguments on this object. For example:
def f(self, context):
...
is a sink method, but
def f(self, ctx):
...
is not. | entailment |
def sinks(self):
"""
Returns a dictionary of sink methods found on this object,
keyed on method name. Sink methods are identified by
(self, context) arguments on this object. For example:
def f(self, context):
...
is a sink method, but
def f(self, c... | Returns a dictionary of sink methods found on this object,
keyed on method name. Sink methods are identified by
(self, context) arguments on this object. For example:
def f(self, context):
...
is a sink method, but
def f(self, ctx):
...
is not. | entailment |
def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna):
""" numba implementation of antenna_uvw """
if antenna1.ndim != 1:
raise ValueError("antenna1 shape should be (row,)")
if antenna2.ndim != 1:
raise ValueError("antenna2 shape should be (row,)")
if uvw.ndim != 2 or uvw.s... | numba implementation of antenna_uvw | entailment |
def _raise_decomposition_errors(uvw, antenna1, antenna2,
chunks, ant_uvw, max_err):
""" Raises informative exception for an invalid decomposition """
start = 0
problem_str = []
for ci, chunk in enumerate(chunks):
end = start + chunk
ant1 = antenna1[sta... | Raises informative exception for an invalid decomposition | entailment |
def _raise_missing_antenna_errors(ant_uvw, max_err):
""" Raises an informative error for missing antenna """
# Find antenna uvw coordinates where any UVW component was nan
# nan + real == nan
problems = np.nonzero(np.add.reduce(np.isnan(ant_uvw), axis=2))
problem_str = []
for c, a in zip(*prob... | Raises an informative error for missing antenna | entailment |
def antenna_uvw(uvw, antenna1, antenna2, chunks,
nr_of_antenna, check_missing=False,
check_decomposition=False, max_err=100):
"""
Computes per-antenna UVW coordinates from baseline ``uvw``,
``antenna1`` and ``antenna2`` coordinates logically grouped
into baseline chunks.
... | Computes per-antenna UVW coordinates from baseline ``uvw``,
``antenna1`` and ``antenna2`` coordinates logically grouped
into baseline chunks.
The example below illustrates two baseline chunks
of size 6 and 5, respectively.
.. code-block:: python
uvw = ...
ant1 = np.array([0, 0, 0,... | entailment |
def default_sources(**kwargs):
"""
Returns a dictionary mapping source types
to number of sources. If the number of sources
for the source type is supplied in the kwargs
these will be placed in the dictionary.
e.g. if we have 'point', 'gaussian' and 'sersic'
source types, then
default_... | Returns a dictionary mapping source types
to number of sources. If the number of sources
for the source type is supplied in the kwargs
these will be placed in the dictionary.
e.g. if we have 'point', 'gaussian' and 'sersic'
source types, then
default_sources(point=10, gaussian=20)
will re... | entailment |
def sources_to_nr_vars(sources):
"""
Converts a source type to number of sources mapping into
a source numbering variable to number of sources mapping.
If, for example, we have 'point', 'gaussian' and 'sersic'
source types, then passing the following dict as an argument
sources_to_nr_vars({'po... | Converts a source type to number of sources mapping into
a source numbering variable to number of sources mapping.
If, for example, we have 'point', 'gaussian' and 'sersic'
source types, then passing the following dict as an argument
sources_to_nr_vars({'point':10, 'gaussian': 20})
will return an... | entailment |
def source_range_tuple(start, end, nr_var_dict):
"""
Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing tuples of the start and end index
for each source variable type.
"""
starts = np.array([0 for nr_var in SOURCE... | Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing tuples of the start and end index
for each source variable type. | entailment |
def source_range(start, end, nr_var_dict):
"""
Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing tuples of the start and end index
for each source variable type.
"""
return OrderedDict((k, e-s)
for k, (s, ... | Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing tuples of the start and end index
for each source variable type. | entailment |
def source_range_slices(start, end, nr_var_dict):
"""
Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing slices for each source variable type.
"""
return OrderedDict((k, slice(s,e,1))
for k, (s, e)
in s... | Given a range of source numbers, as well as a dictionary
containing the numbers of each source, returns a dictionary
containing slices for each source variable type. | entailment |
def point_lm(self, context):
""" Return a lm coordinate array to montblanc """
lm = np.empty(context.shape, context.dtype)
# Print the array schema
montblanc.log.info(context.array_schema.shape)
# Print the space of iteration
montblanc.log.info(context.iter_args)
... | Return a lm coordinate array to montblanc | entailment |
def point_stokes(self, context):
""" Return a stokes parameter array to montblanc """
stokes = np.empty(context.shape, context.dtype)
stokes[:,:,0] = 1
stokes[:,:,1:4] = 0
return stokes | Return a stokes parameter array to montblanc | entailment |
def ref_frequency(self, context):
""" Return a reference frequency array to montblanc """
ref_freq = np.empty(context.shape, context.dtype)
ref_freq[:] = 1.415e9
return ref_freq | Return a reference frequency array to montblanc | entailment |
def update(self, scopes=[], add_scopes=[], rm_scopes=[], note='',
note_url=''):
"""Update this authorization.
:param list scopes: (optional), replaces the authorization scopes with
these
:param list add_scopes: (optional), scopes to be added
:param list rm_sco... | Update this authorization.
:param list scopes: (optional), replaces the authorization scopes with
these
:param list add_scopes: (optional), scopes to be added
:param list rm_scopes: (optional), scopes to be removed
:param str note: (optional), new note about authorization
... | entailment |
def iter_labels(self, number=-1, etag=None):
"""Iterate over the labels for every issue associated with this
milestone.
.. versionchanged:: 0.9
Add etag parameter.
:param int number: (optional), number of labels to return. Default: -1
returns all available labe... | Iterate over the labels for every issue associated with this
milestone.
.. versionchanged:: 0.9
Add etag parameter.
:param int number: (optional), number of labels to return. Default: -1
returns all available labels.
:param str etag: (optional), ETag header fro... | entailment |
def current_function(frame):
"""
Get reference to currently running function from inspect/trace stack frame.
Parameters
----------
frame : stack frame
Stack frame obtained via trace or inspect
Returns
-------
fnc : function reference
Currently running function
"""
... | Get reference to currently running function from inspect/trace stack frame.
Parameters
----------
frame : stack frame
Stack frame obtained via trace or inspect
Returns
-------
fnc : function reference
Currently running function | entailment |
def current_module_name(frame):
"""
Get name of module of currently running function from inspect/trace
stack frame.
Parameters
----------
frame : stack frame
Stack frame obtained via trace or inspect
Returns
-------
modname : string
Currently running function module na... | Get name of module of currently running function from inspect/trace
stack frame.
Parameters
----------
frame : stack frame
Stack frame obtained via trace or inspect
Returns
-------
modname : string
Currently running function module name | entailment |
def _trace(self, frame, event, arg):
"""
Build a record of called functions using the trace mechanism
"""
# Return if this is not a function call
if event != 'call':
return
# Filter calling and called functions by module names
src_mod = current_modul... | Build a record of called functions using the trace mechanism | entailment |
def stop(self):
"""Stop tracing"""
# Stop tracing
sys.settrace(None)
# Build group structure if group filter is defined
if self.grpflt is not None:
# Iterate over graph nodes (functions)
for k in self.fncts:
# Construct group identity str... | Stop tracing | entailment |
def _clrgen(n, h0, hr):
"""Default colour generating function
Parameters
----------
n : int
Number of colours to generate
h0 : float
Initial H value in HSV colour specification
hr : float
Size of H value range to use for colour generation
... | Default colour generating function
Parameters
----------
n : int
Number of colours to generate
h0 : float
Initial H value in HSV colour specification
hr : float
Size of H value range to use for colour generation
(final H value is h0 + hr)... | entailment |
def graph(self, fnm=None, size=None, fntsz=None, fntfm=None, clrgen=None,
rmsz=False, prog='dot'):
"""
Construct call graph
Parameters
----------
fnm : None or string, optional (default None)
Filename of graph file to be written. File type is determined b... | Construct call graph
Parameters
----------
fnm : None or string, optional (default None)
Filename of graph file to be written. File type is determined by
the file extentions (e.g. dot for 'graph.dot' and SVG for
'graph.svg'). If None, a file is not written.
... | entailment |
def create_review_comment(self, body, commit_id, path, position):
"""Create a review comment on this pull request.
All parameters are required by the GitHub API.
:param str body: The comment text itself
:param str commit_id: The SHA of the commit to comment on
:param str path: ... | Create a review comment on this pull request.
All parameters are required by the GitHub API.
:param str body: The comment text itself
:param str commit_id: The SHA of the commit to comment on
:param str path: The relative path of the file to comment on
:param int position: The ... | entailment |
def diff(self):
"""Return the diff"""
resp = self._get(self._api,
headers={'Accept': 'application/vnd.github.diff'})
return resp.content if self._boolean(resp, 200, 404) else None | Return the diff | entailment |
def is_merged(self):
"""Checks to see if the pull request was merged.
:returns: bool
"""
url = self._build_url('merge', base_url=self._api)
return self._boolean(self._get(url), 204, 404) | Checks to see if the pull request was merged.
:returns: bool | entailment |
def iter_comments(self, number=-1, etag=None):
"""Iterate over the comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same
... | Iterate over the comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`ReviewCo... | entailment |
def iter_files(self, number=-1, etag=None):
"""Iterate over the files associated with this pull request.
:param int number: (optional), number of files to return. Default:
-1 returns all available files.
:param str etag: (optional), ETag from a previous request to the same
... | Iterate over the files associated with this pull request.
:param int number: (optional), number of files to return. Default:
-1 returns all available files.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Pull... | entailment |
def iter_issue_comments(self, number=-1, etag=None):
"""Iterate over the issue comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the sam... | Iterate over the issue comments on this pull request.
:param int number: (optional), number of comments to return. Default:
-1 returns all available comments.
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Is... | entailment |
def merge(self, commit_message='', sha=None):
"""Merge this pull request.
:param str commit_message: (optional), message to be used for the
merge commit
:returns: bool
"""
parameters = {'commit_message': commit_message}
if sha:
parameters['sha'] =... | Merge this pull request.
:param str commit_message: (optional), message to be used for the
merge commit
:returns: bool | entailment |
def patch(self):
"""Return the patch"""
resp = self._get(self._api,
headers={'Accept': 'application/vnd.github.patch'})
return resp.content if self._boolean(resp, 200, 404) else None | Return the patch | entailment |
def update(self, title=None, body=None, state=None):
"""Update this pull request.
:param str title: (optional), title of the pull
:param str body: (optional), body of the pull request
:param str state: (optional), ('open', 'closed')
:returns: bool
"""
data = {'ti... | Update this pull request.
:param str title: (optional), title of the pull
:param str body: (optional), body of the pull request
:param str state: (optional), ('open', 'closed')
:returns: bool | entailment |
def reply(self, body):
"""Reply to this review comment with a new review comment.
:param str body: The text of the comment.
:returns: The created review comment.
:rtype: :class:`~github3.pulls.ReviewComment`
"""
url = self._build_url('comments', base_url=self.pull_reques... | Reply to this review comment with a new review comment.
:param str body: The text of the comment.
:returns: The created review comment.
:rtype: :class:`~github3.pulls.ReviewComment` | entailment |
def add_member(self, login):
"""Add ``login`` to this team.
:returns: bool
"""
warnings.warn(
'This is no longer supported by the GitHub API, see '
'https://developer.github.com/changes/2014-09-23-one-more-week'
'-before-the-add-team-member-api-breaki... | Add ``login`` to this team.
:returns: bool | entailment |
def add_repo(self, repo):
"""Add ``repo`` to this team.
:param str repo: (required), form: 'user/repo'
:returns: bool
"""
url = self._build_url('repos', repo, base_url=self._api)
return self._boolean(self._put(url), 204, 404) | Add ``repo`` to this team.
:param str repo: (required), form: 'user/repo'
:returns: bool | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.