body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
78196c5eb7d9451a9ed8387c310310ff631994bbd066f14d906a36feafba0ccf | @property
def countryCode(self):
'The country code associated with this phone number.\n (BNA lookups are currently only available in US)\n :rtype: str\n '
return self._country_code | The country code associated with this phone number.
(BNA lookups are currently only available in US)
:rtype: str | zang/domain/bna_lookup.py | countryCode | engasm89/zangasm | 1 | python | @property
def countryCode(self):
'The country code associated with this phone number.\n (BNA lookups are currently only available in US)\n :rtype: str\n '
return self._country_code | @property
def countryCode(self):
'The country code associated with this phone number.\n (BNA lookups are currently only available in US)\n :rtype: str\n '
return self._country_code<|docstring|>The country code associated with this phone number.
(BNA lookups are currently only available in US)
:rtype: str<|endoftext|> |
606c5cd98ff93172749748ecfb6637833df6fef36e13125c1f5891ccc37e3ec9 | @property
def price(self):
'The price to perform the lookup. If only the city and state of\n the number are looked up, you are charged $.01. If a full address\n lookup is successful you are charged $.15.\n :rtype: float\n '
return self._price | The price to perform the lookup. If only the city and state of
the number are looked up, you are charged $.01. If a full address
lookup is successful you are charged $.15.
:rtype: float | zang/domain/bna_lookup.py | price | engasm89/zangasm | 1 | python | @property
def price(self):
'The price to perform the lookup. If only the city and state of\n the number are looked up, you are charged $.01. If a full address\n lookup is successful you are charged $.15.\n :rtype: float\n '
return self._price | @property
def price(self):
'The price to perform the lookup. If only the city and state of\n the number are looked up, you are charged $.01. If a full address\n lookup is successful you are charged $.15.\n :rtype: float\n '
return self._price<|docstring|>The price to perform the lookup. If only the city and state of
the number are looked up, you are charged $.01. If a full address
lookup is successful you are charged $.15.
:rtype: float<|endoftext|> |
6c4098b38b075d1b49244e166f1872bcec158a0c48c7b7ba952a356c24c3e7ee | @property
def apiVersion(self):
'The API version being used when the carrier lookup was made.\n :rtype: str\n '
return self._api_version | The API version being used when the carrier lookup was made.
:rtype: str | zang/domain/bna_lookup.py | apiVersion | engasm89/zangasm | 1 | python | @property
def apiVersion(self):
'The API version being used when the carrier lookup was made.\n :rtype: str\n '
return self._api_version | @property
def apiVersion(self):
'The API version being used when the carrier lookup was made.\n :rtype: str\n '
return self._api_version<|docstring|>The API version being used when the carrier lookup was made.
:rtype: str<|endoftext|> |
55733fdd678eb85104a783f73ebbeb7858e2ce3500a64babd910ab8719d6951b | @property
def uri(self):
'The Uniform Resource Identifier to this resource.\n :rtype: str\n '
return self._uri | The Uniform Resource Identifier to this resource.
:rtype: str | zang/domain/bna_lookup.py | uri | engasm89/zangasm | 1 | python | @property
def uri(self):
'The Uniform Resource Identifier to this resource.\n :rtype: str\n '
return self._uri | @property
def uri(self):
'The Uniform Resource Identifier to this resource.\n :rtype: str\n '
return self._uri<|docstring|>The Uniform Resource Identifier to this resource.
:rtype: str<|endoftext|> |
f51a0e9104a9a44bb0602e25a38eecb42320e8667ede06e5c216c498d2fcbd5a | def __init__(self, hparams):
'\n\n Args:\n hparams (argparse.Namespace)\n '
super().__init__()
self.hparams.update(vars(hparams))
self.collate_fn = CustomCollate() | Args:
hparams (argparse.Namespace) | src/data_module.py | __init__ | shivammehta007/PyTorchLightningSkeleton | 1 | python | def __init__(self, hparams):
'\n\n Args:\n hparams (argparse.Namespace)\n '
super().__init__()
self.hparams.update(vars(hparams))
self.collate_fn = CustomCollate() | def __init__(self, hparams):
'\n\n Args:\n hparams (argparse.Namespace)\n '
super().__init__()
self.hparams.update(vars(hparams))
self.collate_fn = CustomCollate()<|docstring|>Args:
hparams (argparse.Namespace)<|endoftext|> |
4077e4609b86f50a35e448f6e6c7fe0088364ca9db38781b5bb6eb032a164584 | def prepare_data(self):
'\n Data preparation / Download Dataset\n ' | Data preparation / Download Dataset | src/data_module.py | prepare_data | shivammehta007/PyTorchLightningSkeleton | 1 | python | def prepare_data(self):
'\n \n ' | def prepare_data(self):
'\n \n '<|docstring|>Data preparation / Download Dataset<|endoftext|> |
bfd646a47635294c5c27690a7d021cf8096a13093783db1928f28c52b3592d77 | def setup(self, stage=None):
'\n Set train, val and test dataset here\n\n Args:\n stage (string, optional): fit, test based on plt.Trainer state. \n Defaults to None.\n '
raise NotImplementedError('Add your dataloaders first and remove this line')
self.train_data = CustomDataset()
self.val_data = CustomDataset()
self.test_data = CustomDataset() | Set train, val and test dataset here
Args:
stage (string, optional): fit, test based on plt.Trainer state.
Defaults to None. | src/data_module.py | setup | shivammehta007/PyTorchLightningSkeleton | 1 | python | def setup(self, stage=None):
'\n Set train, val and test dataset here\n\n Args:\n stage (string, optional): fit, test based on plt.Trainer state. \n Defaults to None.\n '
raise NotImplementedError('Add your dataloaders first and remove this line')
self.train_data = CustomDataset()
self.val_data = CustomDataset()
self.test_data = CustomDataset() | def setup(self, stage=None):
'\n Set train, val and test dataset here\n\n Args:\n stage (string, optional): fit, test based on plt.Trainer state. \n Defaults to None.\n '
raise NotImplementedError('Add your dataloaders first and remove this line')
self.train_data = CustomDataset()
self.val_data = CustomDataset()
self.test_data = CustomDataset()<|docstring|>Set train, val and test dataset here
Args:
stage (string, optional): fit, test based on plt.Trainer state.
Defaults to None.<|endoftext|> |
b014fdcdb557c2370fbb5cf560f3dd0366dda2ce208d7915f436aecbbb44d87d | def train_dataloader(self):
'\n Load trainset dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Train Dataloader\n '
return DataLoader(self.train_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | Load trainset dataloader
Returns:
(torch.utils.data.DataLoader): Train Dataloader | src/data_module.py | train_dataloader | shivammehta007/PyTorchLightningSkeleton | 1 | python | def train_dataloader(self):
'\n Load trainset dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Train Dataloader\n '
return DataLoader(self.train_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | def train_dataloader(self):
'\n Load trainset dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Train Dataloader\n '
return DataLoader(self.train_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True)<|docstring|>Load trainset dataloader
Returns:
(torch.utils.data.DataLoader): Train Dataloader<|endoftext|> |
d9075a29bf414f0391e90c5c009b7030671874488a5e71d2184f69a267853057 | def val_dataloader(self):
'\n Load Validation dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Validation Dataloader\n '
return DataLoader(self.val_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | Load Validation dataloader
Returns:
(torch.utils.data.DataLoader): Validation Dataloader | src/data_module.py | val_dataloader | shivammehta007/PyTorchLightningSkeleton | 1 | python | def val_dataloader(self):
'\n Load Validation dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Validation Dataloader\n '
return DataLoader(self.val_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | def val_dataloader(self):
'\n Load Validation dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Validation Dataloader\n '
return DataLoader(self.val_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True)<|docstring|>Load Validation dataloader
Returns:
(torch.utils.data.DataLoader): Validation Dataloader<|endoftext|> |
569927302375cf1deec1c340d2f693fb2d812ca492c2afe7d0c3ecf1811882af | def test_dataloader(self):
'\n Load Test dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Test Dataloader\n '
return DataLoader(self.test_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | Load Test dataloader
Returns:
(torch.utils.data.DataLoader): Test Dataloader | src/data_module.py | test_dataloader | shivammehta007/PyTorchLightningSkeleton | 1 | python | def test_dataloader(self):
'\n Load Test dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Test Dataloader\n '
return DataLoader(self.test_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True) | def test_dataloader(self):
'\n Load Test dataloader\n\n Returns:\n (torch.utils.data.DataLoader): Test Dataloader\n '
return DataLoader(self.test_data, batch_size=self.hparams.batch_size, collate_fn=self.collate_fn, num_workers=self.hparams.num_workers, pin_memory=True)<|docstring|>Load Test dataloader
Returns:
(torch.utils.data.DataLoader): Test Dataloader<|endoftext|> |
5e9c858201858ad0c892780e57aabab264bf765efd90058eec93d8fa883cda3f | def __init__(self, pixel_grid, psf, supersampling_factor=1, compute_mode='regular', supersampling_convolution=False, supersampling_kernel_size=5, flux_evaluate_indexes=None, supersampled_indexes=None, compute_indexes=None, point_source_supersampling_factor=1, convolution_kernel_size=None, convolution_type='fft_static', truncation=4):
"\n\n :param pixel_grid: PixelGrid() class instance\n :param psf: PSF() class instance\n :param compute_mode: options are: 'regular', 'adaptive'\n :param supersampling_factor: int, factor of higher resolution sub-pixel sampling of surface brightness\n :param supersampling_convolution: bool, if True, performs (part of) the convolution on the super-sampled\n grid/pixels\n :param supersampling_kernel_size: int (odd number), size (in regular pixel units) of the super-sampled\n convolution\n :param flux_evaluate_indexes: boolean 2d array of size of image (or None, then initiated as gird of True's).\n Pixels indicated with True will be used to perform the surface brightness computation (and possible lensing\n ray-shooting). Pixels marked as False will be assigned a flux value of zero (or ignored in the adaptive\n convolution)\n :param supersampled_indexes: 2d boolean array (only used in mode='adaptive') of pixels to be supersampled (in\n surface brightness and if supersampling_convolution=True also in convolution). All other pixels not set to =True\n will not be super-sampled.\n :param compute_indexes: 2d boolean array (only used in compute_mode='adaptive'), marks pixel that the response after\n convolution is computed (all others =0). This can be set to likelihood_mask in the Likelihood module for\n consistency.\n :param point_source_supersampling_factor: super-sampling resolution of the point source placing\n :param convolution_kernel_size: int, odd number, size of convolution kernel. If None, takes size of point_source_kernel\n :param convolution_type: string, 'fft', 'grid', 'fft_static' mode of 2d convolution\n "
if (compute_mode not in ['regular', 'adaptive']):
raise ValueError('compute_mode specified as %s not valid. Options are "adaptive", "regular"')
self._psf_type = psf.psf_type
if (not isinstance(supersampling_factor, int)):
raise TypeError(('supersampling_factor needs to be an integer! Current type is %s' % type(supersampling_factor)))
if (supersampling_factor == 1):
supersampling_convolution = False
self._pixel_width = pixel_grid.pixel_width
(nx, ny) = pixel_grid.num_pixel_axes
transform_pix2angle = pixel_grid.transform_pix2angle
(ra_at_xy_0, dec_at_xy_0) = pixel_grid.radec_at_xy_0
if (supersampled_indexes is None):
supersampled_indexes = np.zeros((nx, ny), dtype=bool)
if (compute_mode == 'adaptive'):
self._grid = AdaptiveGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampled_indexes, supersampling_factor, flux_evaluate_indexes)
else:
self._grid = RegularGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampling_factor, flux_evaluate_indexes)
if (self._psf_type == 'PIXEL'):
if ((compute_mode == 'adaptive') and (supersampling_convolution is True)):
from lenstronomy.ImSim.Numerics.adaptive_numerics import AdaptiveConvolution
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = AdaptiveConvolution(kernel_super, supersampling_factor, conv_supersample_pixels=supersampled_indexes, supersampling_kernel_size=supersampling_kernel_size, compute_pixels=compute_indexes, nopython=True, cache=True, parallel=False)
elif ((compute_mode == 'regular') and (supersampling_convolution is True)):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
if (convolution_kernel_size is not None):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = SubgridKernelConvolution(kernel_super, supersampling_factor, supersampling_kernel_size=supersampling_kernel_size, convolution_type=convolution_type)
else:
kernel = psf.kernel_point_source
kernel = self._supersampling_cut_kernel(kernel, convolution_kernel_size, supersampling_factor=1)
self._conv = PixelKernelConvolution(kernel, convolution_type=convolution_type)
elif (self._psf_type == 'GAUSSIAN'):
pixel_scale = pixel_grid.pixel_width
fwhm = psf.fwhm
sigma = util.fwhm2sigma(fwhm)
sigma_list = [sigma]
fraction_list = [1]
self._conv = MultiGaussianConvolution(sigma_list, fraction_list, pixel_scale, supersampling_factor, supersampling_convolution, truncation=truncation)
elif (self._psf_type == 'NONE'):
self._conv = None
else:
raise ValueError(('psf_type %s not valid! Chose either NONE, GAUSSIAN or PIXEL.' % self._psf_type))
super(Numerics, self).__init__(pixel_grid=pixel_grid, supersampling_factor=point_source_supersampling_factor, psf=psf)
if (supersampling_convolution is True):
self._high_res_return = True
else:
self._high_res_return = False | :param pixel_grid: PixelGrid() class instance
:param psf: PSF() class instance
:param compute_mode: options are: 'regular', 'adaptive'
:param supersampling_factor: int, factor of higher resolution sub-pixel sampling of surface brightness
:param supersampling_convolution: bool, if True, performs (part of) the convolution on the super-sampled
grid/pixels
:param supersampling_kernel_size: int (odd number), size (in regular pixel units) of the super-sampled
convolution
:param flux_evaluate_indexes: boolean 2d array of size of image (or None, then initiated as gird of True's).
Pixels indicated with True will be used to perform the surface brightness computation (and possible lensing
ray-shooting). Pixels marked as False will be assigned a flux value of zero (or ignored in the adaptive
convolution)
:param supersampled_indexes: 2d boolean array (only used in mode='adaptive') of pixels to be supersampled (in
surface brightness and if supersampling_convolution=True also in convolution). All other pixels not set to =True
will not be super-sampled.
:param compute_indexes: 2d boolean array (only used in compute_mode='adaptive'), marks pixel that the response after
convolution is computed (all others =0). This can be set to likelihood_mask in the Likelihood module for
consistency.
:param point_source_supersampling_factor: super-sampling resolution of the point source placing
:param convolution_kernel_size: int, odd number, size of convolution kernel. If None, takes size of point_source_kernel
:param convolution_type: string, 'fft', 'grid', 'fft_static' mode of 2d convolution | lenstronomy/ImSim/Numerics/numerics.py | __init__ | ohannuks/lenstronomy | 107 | python | def __init__(self, pixel_grid, psf, supersampling_factor=1, compute_mode='regular', supersampling_convolution=False, supersampling_kernel_size=5, flux_evaluate_indexes=None, supersampled_indexes=None, compute_indexes=None, point_source_supersampling_factor=1, convolution_kernel_size=None, convolution_type='fft_static', truncation=4):
"\n\n :param pixel_grid: PixelGrid() class instance\n :param psf: PSF() class instance\n :param compute_mode: options are: 'regular', 'adaptive'\n :param supersampling_factor: int, factor of higher resolution sub-pixel sampling of surface brightness\n :param supersampling_convolution: bool, if True, performs (part of) the convolution on the super-sampled\n grid/pixels\n :param supersampling_kernel_size: int (odd number), size (in regular pixel units) of the super-sampled\n convolution\n :param flux_evaluate_indexes: boolean 2d array of size of image (or None, then initiated as gird of True's).\n Pixels indicated with True will be used to perform the surface brightness computation (and possible lensing\n ray-shooting). Pixels marked as False will be assigned a flux value of zero (or ignored in the adaptive\n convolution)\n :param supersampled_indexes: 2d boolean array (only used in mode='adaptive') of pixels to be supersampled (in\n surface brightness and if supersampling_convolution=True also in convolution). All other pixels not set to =True\n will not be super-sampled.\n :param compute_indexes: 2d boolean array (only used in compute_mode='adaptive'), marks pixel that the response after\n convolution is computed (all others =0). This can be set to likelihood_mask in the Likelihood module for\n consistency.\n :param point_source_supersampling_factor: super-sampling resolution of the point source placing\n :param convolution_kernel_size: int, odd number, size of convolution kernel. If None, takes size of point_source_kernel\n :param convolution_type: string, 'fft', 'grid', 'fft_static' mode of 2d convolution\n "
if (compute_mode not in ['regular', 'adaptive']):
raise ValueError('compute_mode specified as %s not valid. Options are "adaptive", "regular"')
self._psf_type = psf.psf_type
if (not isinstance(supersampling_factor, int)):
raise TypeError(('supersampling_factor needs to be an integer! Current type is %s' % type(supersampling_factor)))
if (supersampling_factor == 1):
supersampling_convolution = False
self._pixel_width = pixel_grid.pixel_width
(nx, ny) = pixel_grid.num_pixel_axes
transform_pix2angle = pixel_grid.transform_pix2angle
(ra_at_xy_0, dec_at_xy_0) = pixel_grid.radec_at_xy_0
if (supersampled_indexes is None):
supersampled_indexes = np.zeros((nx, ny), dtype=bool)
if (compute_mode == 'adaptive'):
self._grid = AdaptiveGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampled_indexes, supersampling_factor, flux_evaluate_indexes)
else:
self._grid = RegularGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampling_factor, flux_evaluate_indexes)
if (self._psf_type == 'PIXEL'):
if ((compute_mode == 'adaptive') and (supersampling_convolution is True)):
from lenstronomy.ImSim.Numerics.adaptive_numerics import AdaptiveConvolution
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = AdaptiveConvolution(kernel_super, supersampling_factor, conv_supersample_pixels=supersampled_indexes, supersampling_kernel_size=supersampling_kernel_size, compute_pixels=compute_indexes, nopython=True, cache=True, parallel=False)
elif ((compute_mode == 'regular') and (supersampling_convolution is True)):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
if (convolution_kernel_size is not None):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = SubgridKernelConvolution(kernel_super, supersampling_factor, supersampling_kernel_size=supersampling_kernel_size, convolution_type=convolution_type)
else:
kernel = psf.kernel_point_source
kernel = self._supersampling_cut_kernel(kernel, convolution_kernel_size, supersampling_factor=1)
self._conv = PixelKernelConvolution(kernel, convolution_type=convolution_type)
elif (self._psf_type == 'GAUSSIAN'):
pixel_scale = pixel_grid.pixel_width
fwhm = psf.fwhm
sigma = util.fwhm2sigma(fwhm)
sigma_list = [sigma]
fraction_list = [1]
self._conv = MultiGaussianConvolution(sigma_list, fraction_list, pixel_scale, supersampling_factor, supersampling_convolution, truncation=truncation)
elif (self._psf_type == 'NONE'):
self._conv = None
else:
raise ValueError(('psf_type %s not valid! Chose either NONE, GAUSSIAN or PIXEL.' % self._psf_type))
super(Numerics, self).__init__(pixel_grid=pixel_grid, supersampling_factor=point_source_supersampling_factor, psf=psf)
if (supersampling_convolution is True):
self._high_res_return = True
else:
self._high_res_return = False | def __init__(self, pixel_grid, psf, supersampling_factor=1, compute_mode='regular', supersampling_convolution=False, supersampling_kernel_size=5, flux_evaluate_indexes=None, supersampled_indexes=None, compute_indexes=None, point_source_supersampling_factor=1, convolution_kernel_size=None, convolution_type='fft_static', truncation=4):
"\n\n :param pixel_grid: PixelGrid() class instance\n :param psf: PSF() class instance\n :param compute_mode: options are: 'regular', 'adaptive'\n :param supersampling_factor: int, factor of higher resolution sub-pixel sampling of surface brightness\n :param supersampling_convolution: bool, if True, performs (part of) the convolution on the super-sampled\n grid/pixels\n :param supersampling_kernel_size: int (odd number), size (in regular pixel units) of the super-sampled\n convolution\n :param flux_evaluate_indexes: boolean 2d array of size of image (or None, then initiated as gird of True's).\n Pixels indicated with True will be used to perform the surface brightness computation (and possible lensing\n ray-shooting). Pixels marked as False will be assigned a flux value of zero (or ignored in the adaptive\n convolution)\n :param supersampled_indexes: 2d boolean array (only used in mode='adaptive') of pixels to be supersampled (in\n surface brightness and if supersampling_convolution=True also in convolution). All other pixels not set to =True\n will not be super-sampled.\n :param compute_indexes: 2d boolean array (only used in compute_mode='adaptive'), marks pixel that the response after\n convolution is computed (all others =0). This can be set to likelihood_mask in the Likelihood module for\n consistency.\n :param point_source_supersampling_factor: super-sampling resolution of the point source placing\n :param convolution_kernel_size: int, odd number, size of convolution kernel. If None, takes size of point_source_kernel\n :param convolution_type: string, 'fft', 'grid', 'fft_static' mode of 2d convolution\n "
if (compute_mode not in ['regular', 'adaptive']):
raise ValueError('compute_mode specified as %s not valid. Options are "adaptive", "regular"')
self._psf_type = psf.psf_type
if (not isinstance(supersampling_factor, int)):
raise TypeError(('supersampling_factor needs to be an integer! Current type is %s' % type(supersampling_factor)))
if (supersampling_factor == 1):
supersampling_convolution = False
self._pixel_width = pixel_grid.pixel_width
(nx, ny) = pixel_grid.num_pixel_axes
transform_pix2angle = pixel_grid.transform_pix2angle
(ra_at_xy_0, dec_at_xy_0) = pixel_grid.radec_at_xy_0
if (supersampled_indexes is None):
supersampled_indexes = np.zeros((nx, ny), dtype=bool)
if (compute_mode == 'adaptive'):
self._grid = AdaptiveGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampled_indexes, supersampling_factor, flux_evaluate_indexes)
else:
self._grid = RegularGrid(nx, ny, transform_pix2angle, ra_at_xy_0, dec_at_xy_0, supersampling_factor, flux_evaluate_indexes)
if (self._psf_type == 'PIXEL'):
if ((compute_mode == 'adaptive') and (supersampling_convolution is True)):
from lenstronomy.ImSim.Numerics.adaptive_numerics import AdaptiveConvolution
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = AdaptiveConvolution(kernel_super, supersampling_factor, conv_supersample_pixels=supersampled_indexes, supersampling_kernel_size=supersampling_kernel_size, compute_pixels=compute_indexes, nopython=True, cache=True, parallel=False)
elif ((compute_mode == 'regular') and (supersampling_convolution is True)):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
if (convolution_kernel_size is not None):
kernel_super = psf.kernel_point_source_supersampled(supersampling_factor)
kernel_super = self._supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor)
self._conv = SubgridKernelConvolution(kernel_super, supersampling_factor, supersampling_kernel_size=supersampling_kernel_size, convolution_type=convolution_type)
else:
kernel = psf.kernel_point_source
kernel = self._supersampling_cut_kernel(kernel, convolution_kernel_size, supersampling_factor=1)
self._conv = PixelKernelConvolution(kernel, convolution_type=convolution_type)
elif (self._psf_type == 'GAUSSIAN'):
pixel_scale = pixel_grid.pixel_width
fwhm = psf.fwhm
sigma = util.fwhm2sigma(fwhm)
sigma_list = [sigma]
fraction_list = [1]
self._conv = MultiGaussianConvolution(sigma_list, fraction_list, pixel_scale, supersampling_factor, supersampling_convolution, truncation=truncation)
elif (self._psf_type == 'NONE'):
self._conv = None
else:
raise ValueError(('psf_type %s not valid! Chose either NONE, GAUSSIAN or PIXEL.' % self._psf_type))
super(Numerics, self).__init__(pixel_grid=pixel_grid, supersampling_factor=point_source_supersampling_factor, psf=psf)
if (supersampling_convolution is True):
self._high_res_return = True
else:
self._high_res_return = False<|docstring|>:param pixel_grid: PixelGrid() class instance
:param psf: PSF() class instance
:param compute_mode: options are: 'regular', 'adaptive'
:param supersampling_factor: int, factor of higher resolution sub-pixel sampling of surface brightness
:param supersampling_convolution: bool, if True, performs (part of) the convolution on the super-sampled
grid/pixels
:param supersampling_kernel_size: int (odd number), size (in regular pixel units) of the super-sampled
convolution
:param flux_evaluate_indexes: boolean 2d array of size of image (or None, then initiated as gird of True's).
Pixels indicated with True will be used to perform the surface brightness computation (and possible lensing
ray-shooting). Pixels marked as False will be assigned a flux value of zero (or ignored in the adaptive
convolution)
:param supersampled_indexes: 2d boolean array (only used in mode='adaptive') of pixels to be supersampled (in
surface brightness and if supersampling_convolution=True also in convolution). All other pixels not set to =True
will not be super-sampled.
:param compute_indexes: 2d boolean array (only used in compute_mode='adaptive'), marks pixel that the response after
convolution is computed (all others =0). This can be set to likelihood_mask in the Likelihood module for
consistency.
:param point_source_supersampling_factor: super-sampling resolution of the point source placing
:param convolution_kernel_size: int, odd number, size of convolution kernel. If None, takes size of point_source_kernel
:param convolution_type: string, 'fft', 'grid', 'fft_static' mode of 2d convolution<|endoftext|> |
85e269f35d0b25dc17603a038d86a5127f8f43da9749d5101b9d9ae7924337fd | def re_size_convolve(self, flux_array, unconvolved=False):
'\n\n :param flux_array: 1d array, flux values corresponding to coordinates_evaluate\n :param unconvolved: boolean, if True, does not apply a convolution\n :return: convolved image on regular pixel grid, 2d array\n '
(image_low_res, image_high_res_partial) = self._grid.flux_array2image_low_high(flux_array, high_res_return=self._high_res_return)
if ((unconvolved is True) or (self._psf_type == 'NONE')):
image_conv = image_low_res
else:
image_conv = self._conv.re_size_convolve(image_low_res, image_high_res_partial)
return (image_conv * (self._pixel_width ** 2)) | :param flux_array: 1d array, flux values corresponding to coordinates_evaluate
:param unconvolved: boolean, if True, does not apply a convolution
:return: convolved image on regular pixel grid, 2d array | lenstronomy/ImSim/Numerics/numerics.py | re_size_convolve | ohannuks/lenstronomy | 107 | python | def re_size_convolve(self, flux_array, unconvolved=False):
'\n\n :param flux_array: 1d array, flux values corresponding to coordinates_evaluate\n :param unconvolved: boolean, if True, does not apply a convolution\n :return: convolved image on regular pixel grid, 2d array\n '
(image_low_res, image_high_res_partial) = self._grid.flux_array2image_low_high(flux_array, high_res_return=self._high_res_return)
if ((unconvolved is True) or (self._psf_type == 'NONE')):
image_conv = image_low_res
else:
image_conv = self._conv.re_size_convolve(image_low_res, image_high_res_partial)
return (image_conv * (self._pixel_width ** 2)) | def re_size_convolve(self, flux_array, unconvolved=False):
'\n\n :param flux_array: 1d array, flux values corresponding to coordinates_evaluate\n :param unconvolved: boolean, if True, does not apply a convolution\n :return: convolved image on regular pixel grid, 2d array\n '
(image_low_res, image_high_res_partial) = self._grid.flux_array2image_low_high(flux_array, high_res_return=self._high_res_return)
if ((unconvolved is True) or (self._psf_type == 'NONE')):
image_conv = image_low_res
else:
image_conv = self._conv.re_size_convolve(image_low_res, image_high_res_partial)
return (image_conv * (self._pixel_width ** 2))<|docstring|>:param flux_array: 1d array, flux values corresponding to coordinates_evaluate
:param unconvolved: boolean, if True, does not apply a convolution
:return: convolved image on regular pixel grid, 2d array<|endoftext|> |
2b9607aba7768b1c97fd6e34b04bfdae9451a8a1b0a543b9f9ed0a0d08ed8114 | @property
def grid_supersampling_factor(self):
'\n\n :return: supersampling factor set for higher resolution sub-pixel sampling of surface brightness\n '
return self._grid.supersampling_factor | :return: supersampling factor set for higher resolution sub-pixel sampling of surface brightness | lenstronomy/ImSim/Numerics/numerics.py | grid_supersampling_factor | ohannuks/lenstronomy | 107 | python | @property
def grid_supersampling_factor(self):
'\n\n \n '
return self._grid.supersampling_factor | @property
def grid_supersampling_factor(self):
'\n\n \n '
return self._grid.supersampling_factor<|docstring|>:return: supersampling factor set for higher resolution sub-pixel sampling of surface brightness<|endoftext|> |
05ad27fda09cccb743f0b20daa5ebbfa16f1e9913edb49b4c801a9e00d1c074f | @property
def coordinates_evaluate(self):
'\n\n :return: 1d array of all coordinates being evaluated to perform the image computation\n '
return self._grid.coordinates_evaluate | :return: 1d array of all coordinates being evaluated to perform the image computation | lenstronomy/ImSim/Numerics/numerics.py | coordinates_evaluate | ohannuks/lenstronomy | 107 | python | @property
def coordinates_evaluate(self):
'\n\n \n '
return self._grid.coordinates_evaluate | @property
def coordinates_evaluate(self):
'\n\n \n '
return self._grid.coordinates_evaluate<|docstring|>:return: 1d array of all coordinates being evaluated to perform the image computation<|endoftext|> |
837fbbc5f34d8f0e5e45e3a8a4d0dcc80be9a14db970693927b487a50a21954d | @staticmethod
def _supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor):
'\n\n :param kernel_super: super-sampled kernel\n :param convolution_kernel_size: size of convolution kernel in units of regular pixels (odd)\n :param supersampling_factor: super-sampling factor of convolution kernel\n :return: cut out kernel in super-sampling size\n '
if (convolution_kernel_size is not None):
size = (convolution_kernel_size * supersampling_factor)
if ((size % 2) == 0):
size += 1
kernel_cut = kernel_util.cut_psf(kernel_super, size)
return kernel_cut
else:
return kernel_super | :param kernel_super: super-sampled kernel
:param convolution_kernel_size: size of convolution kernel in units of regular pixels (odd)
:param supersampling_factor: super-sampling factor of convolution kernel
:return: cut out kernel in super-sampling size | lenstronomy/ImSim/Numerics/numerics.py | _supersampling_cut_kernel | ohannuks/lenstronomy | 107 | python | @staticmethod
def _supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor):
'\n\n :param kernel_super: super-sampled kernel\n :param convolution_kernel_size: size of convolution kernel in units of regular pixels (odd)\n :param supersampling_factor: super-sampling factor of convolution kernel\n :return: cut out kernel in super-sampling size\n '
if (convolution_kernel_size is not None):
size = (convolution_kernel_size * supersampling_factor)
if ((size % 2) == 0):
size += 1
kernel_cut = kernel_util.cut_psf(kernel_super, size)
return kernel_cut
else:
return kernel_super | @staticmethod
def _supersampling_cut_kernel(kernel_super, convolution_kernel_size, supersampling_factor):
'\n\n :param kernel_super: super-sampled kernel\n :param convolution_kernel_size: size of convolution kernel in units of regular pixels (odd)\n :param supersampling_factor: super-sampling factor of convolution kernel\n :return: cut out kernel in super-sampling size\n '
if (convolution_kernel_size is not None):
size = (convolution_kernel_size * supersampling_factor)
if ((size % 2) == 0):
size += 1
kernel_cut = kernel_util.cut_psf(kernel_super, size)
return kernel_cut
else:
return kernel_super<|docstring|>:param kernel_super: super-sampled kernel
:param convolution_kernel_size: size of convolution kernel in units of regular pixels (odd)
:param supersampling_factor: super-sampling factor of convolution kernel
:return: cut out kernel in super-sampling size<|endoftext|> |
539b0af9794559bd5432c2da90b5123ef909233b6df088e4cf8407fb705de57a | @property
def convolution_class(self):
'\n\n :return: convolution class (can be SubgridKernelConvolution, PixelKernelConvolution, MultiGaussianConvolution, ...)\n '
return self._conv | :return: convolution class (can be SubgridKernelConvolution, PixelKernelConvolution, MultiGaussianConvolution, ...) | lenstronomy/ImSim/Numerics/numerics.py | convolution_class | ohannuks/lenstronomy | 107 | python | @property
def convolution_class(self):
'\n\n \n '
return self._conv | @property
def convolution_class(self):
'\n\n \n '
return self._conv<|docstring|>:return: convolution class (can be SubgridKernelConvolution, PixelKernelConvolution, MultiGaussianConvolution, ...)<|endoftext|> |
7c5cce9bead774d3b1fdee520cba00468cc8c245c8d71bbbfd91fff02cdcce2b | @property
def grid_class(self):
'\n\n :return: grid class (can be RegularGrid, AdaptiveGrid)\n '
return self._grid | :return: grid class (can be RegularGrid, AdaptiveGrid) | lenstronomy/ImSim/Numerics/numerics.py | grid_class | ohannuks/lenstronomy | 107 | python | @property
def grid_class(self):
'\n\n \n '
return self._grid | @property
def grid_class(self):
'\n\n \n '
return self._grid<|docstring|>:return: grid class (can be RegularGrid, AdaptiveGrid)<|endoftext|> |
9500d5b1e268d83eaf80350cf944c7381c00f4ac10d969a477a531bb7c0eeb54 | def get_components(self) -> Dict[(str, autoPyTorchComponent)]:
'Returns the available scheduler components\n\n Args:\n None\n\n Returns:\n Dict[str, autoPyTorchComponent]: all baseScheduler components available\n as choices for learning rate scheduling\n '
components = OrderedDict()
components.update(_schedulers)
components.update(_addons.components)
return components | Returns the available scheduler components
Args:
None
Returns:
Dict[str, autoPyTorchComponent]: all baseScheduler components available
as choices for learning rate scheduling | autoPyTorch/pipeline/components/setup/lr_scheduler/__init__.py | get_components | ravinkohli/Auto-PyTorch | 1 | python | def get_components(self) -> Dict[(str, autoPyTorchComponent)]:
'Returns the available scheduler components\n\n Args:\n None\n\n Returns:\n Dict[str, autoPyTorchComponent]: all baseScheduler components available\n as choices for learning rate scheduling\n '
components = OrderedDict()
components.update(_schedulers)
components.update(_addons.components)
return components | def get_components(self) -> Dict[(str, autoPyTorchComponent)]:
'Returns the available scheduler components\n\n Args:\n None\n\n Returns:\n Dict[str, autoPyTorchComponent]: all baseScheduler components available\n as choices for learning rate scheduling\n '
components = OrderedDict()
components.update(_schedulers)
components.update(_addons.components)
return components<|docstring|>Returns the available scheduler components
Args:
None
Returns:
Dict[str, autoPyTorchComponent]: all baseScheduler components available
as choices for learning rate scheduling<|endoftext|> |
9b1cd9a5c466e68a56b0fb5bfe8c83d5a1c8f82641552b9f2ffc2ac129f1e4bb | def get_available_components(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, include: List[str]=None, exclude: List[str]=None) -> Dict[(str, autoPyTorchComponent)]:
'Filters out components based on user provided\n include/exclude directives, as well as the dataset properties\n\n Args:\n include (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to honor when creating the configuration space\n exclude (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to remove from the configuration space\n dataset_properties (Optional[Dict[str, BaseDatasetPropertiesType]]): Caracteristics\n of the dataset to guide the pipeline choices of components\n\n Returns:\n Dict[str, autoPyTorchComponent]: A filtered dict of learning\n rate schedulers\n\n '
if (dataset_properties is None):
dataset_properties = {}
if ((include is not None) and (exclude is not None)):
raise ValueError('The argument include and exclude cannot be used together.')
available_comp = self.get_components()
if (include is not None):
for incl in include:
if (incl not in available_comp):
raise ValueError(('Trying to include unknown component: %s' % incl))
components_dict = OrderedDict()
for name in available_comp:
if ((include is not None) and (name not in include)):
continue
elif ((exclude is not None) and (name in exclude)):
continue
entry = available_comp[name]
if ((entry == SchedulerChoice) or hasattr(entry, 'get_components')):
continue
components_dict[name] = entry
return components_dict | Filters out components based on user provided
include/exclude directives, as well as the dataset properties
Args:
include (Optional[Dict[str, Any]]): what hyper-parameter configurations
to honor when creating the configuration space
exclude (Optional[Dict[str, Any]]): what hyper-parameter configurations
to remove from the configuration space
dataset_properties (Optional[Dict[str, BaseDatasetPropertiesType]]): Caracteristics
of the dataset to guide the pipeline choices of components
Returns:
Dict[str, autoPyTorchComponent]: A filtered dict of learning
rate schedulers | autoPyTorch/pipeline/components/setup/lr_scheduler/__init__.py | get_available_components | ravinkohli/Auto-PyTorch | 1 | python | def get_available_components(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, include: List[str]=None, exclude: List[str]=None) -> Dict[(str, autoPyTorchComponent)]:
'Filters out components based on user provided\n include/exclude directives, as well as the dataset properties\n\n Args:\n include (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to honor when creating the configuration space\n exclude (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to remove from the configuration space\n dataset_properties (Optional[Dict[str, BaseDatasetPropertiesType]]): Caracteristics\n of the dataset to guide the pipeline choices of components\n\n Returns:\n Dict[str, autoPyTorchComponent]: A filtered dict of learning\n rate schedulers\n\n '
if (dataset_properties is None):
dataset_properties = {}
if ((include is not None) and (exclude is not None)):
raise ValueError('The argument include and exclude cannot be used together.')
available_comp = self.get_components()
if (include is not None):
for incl in include:
if (incl not in available_comp):
raise ValueError(('Trying to include unknown component: %s' % incl))
components_dict = OrderedDict()
for name in available_comp:
if ((include is not None) and (name not in include)):
continue
elif ((exclude is not None) and (name in exclude)):
continue
entry = available_comp[name]
if ((entry == SchedulerChoice) or hasattr(entry, 'get_components')):
continue
components_dict[name] = entry
return components_dict | def get_available_components(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, include: List[str]=None, exclude: List[str]=None) -> Dict[(str, autoPyTorchComponent)]:
'Filters out components based on user provided\n include/exclude directives, as well as the dataset properties\n\n Args:\n include (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to honor when creating the configuration space\n exclude (Optional[Dict[str, Any]]): what hyper-parameter configurations\n to remove from the configuration space\n dataset_properties (Optional[Dict[str, BaseDatasetPropertiesType]]): Caracteristics\n of the dataset to guide the pipeline choices of components\n\n Returns:\n Dict[str, autoPyTorchComponent]: A filtered dict of learning\n rate schedulers\n\n '
if (dataset_properties is None):
dataset_properties = {}
if ((include is not None) and (exclude is not None)):
raise ValueError('The argument include and exclude cannot be used together.')
available_comp = self.get_components()
if (include is not None):
for incl in include:
if (incl not in available_comp):
raise ValueError(('Trying to include unknown component: %s' % incl))
components_dict = OrderedDict()
for name in available_comp:
if ((include is not None) and (name not in include)):
continue
elif ((exclude is not None) and (name in exclude)):
continue
entry = available_comp[name]
if ((entry == SchedulerChoice) or hasattr(entry, 'get_components')):
continue
components_dict[name] = entry
return components_dict<|docstring|>Filters out components based on user provided
include/exclude directives, as well as the dataset properties
Args:
include (Optional[Dict[str, Any]]): what hyper-parameter configurations
to honor when creating the configuration space
exclude (Optional[Dict[str, Any]]): what hyper-parameter configurations
to remove from the configuration space
dataset_properties (Optional[Dict[str, BaseDatasetPropertiesType]]): Caracteristics
of the dataset to guide the pipeline choices of components
Returns:
Dict[str, autoPyTorchComponent]: A filtered dict of learning
rate schedulers<|endoftext|> |
0978d01a6f8a30579f5eabe024807d01cb941891092ccdf99357cacf696836ad | def get_hyperparameter_search_space(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, default: Optional[str]=None, include: Optional[List[str]]=None, exclude: Optional[List[str]]=None) -> ConfigurationSpace:
'Returns the configuration space of the current chosen components\n\n Args:\n dataset_properties (Optional[Dict[str, str]]): Describes the dataset to work on\n default (Optional[str]): Default scheduler to use\n include: Optional[Dict[str, Any]]: what components to include. It is an exhaustive\n list, and will exclusively use this components.\n exclude: Optional[Dict[str, Any]]: which components to skip\n\n Returns:\n ConfigurationSpace: the configuration space of the hyper-parameters of the\n chosen component\n '
cs = ConfigurationSpace()
if (dataset_properties is None):
dataset_properties = {}
available_schedulers = self.get_available_components(dataset_properties=dataset_properties, include=include, exclude=exclude)
if (len(available_schedulers) == 0):
raise ValueError('No scheduler found')
if (default is None):
defaults = ['ReduceLROnPlateau', 'CosineAnnealingLR', 'no_LRScheduler', 'LambdaLR', 'StepLR', 'ExponentialLR']
for default_ in defaults:
if (default_ in available_schedulers):
default = default_
break
updates = self._get_search_space_updates()
if ('__choice__' in updates.keys()):
choice_hyperparameter = updates['__choice__']
if (not set(choice_hyperparameter.value_range).issubset(available_schedulers)):
raise ValueError('Expected given update for {} to have choices in {} got {}'.format(self.__class__.__name__, available_schedulers, choice_hyperparameter.value_range))
scheduler = CSH.CategoricalHyperparameter('__choice__', choice_hyperparameter.value_range, default_value=choice_hyperparameter.default_value)
else:
scheduler = CSH.CategoricalHyperparameter('__choice__', list(available_schedulers.keys()), default_value=default)
cs.add_hyperparameter(scheduler)
for name in scheduler.choices:
updates = self._get_search_space_updates(prefix=name)
config_space = available_schedulers[name].get_hyperparameter_search_space(dataset_properties, **updates)
parent_hyperparameter = {'parent': scheduler, 'value': name}
cs.add_configuration_space(name, config_space, parent_hyperparameter=parent_hyperparameter)
self.configuration_space_ = cs
self.dataset_properties_ = dataset_properties
return cs | Returns the configuration space of the current chosen components
Args:
dataset_properties (Optional[Dict[str, str]]): Describes the dataset to work on
default (Optional[str]): Default scheduler to use
include: Optional[Dict[str, Any]]: what components to include. It is an exhaustive
list, and will exclusively use this components.
exclude: Optional[Dict[str, Any]]: which components to skip
Returns:
ConfigurationSpace: the configuration space of the hyper-parameters of the
chosen component | autoPyTorch/pipeline/components/setup/lr_scheduler/__init__.py | get_hyperparameter_search_space | ravinkohli/Auto-PyTorch | 1 | python | def get_hyperparameter_search_space(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, default: Optional[str]=None, include: Optional[List[str]]=None, exclude: Optional[List[str]]=None) -> ConfigurationSpace:
'Returns the configuration space of the current chosen components\n\n Args:\n dataset_properties (Optional[Dict[str, str]]): Describes the dataset to work on\n default (Optional[str]): Default scheduler to use\n include: Optional[Dict[str, Any]]: what components to include. It is an exhaustive\n list, and will exclusively use this components.\n exclude: Optional[Dict[str, Any]]: which components to skip\n\n Returns:\n ConfigurationSpace: the configuration space of the hyper-parameters of the\n chosen component\n '
cs = ConfigurationSpace()
if (dataset_properties is None):
dataset_properties = {}
available_schedulers = self.get_available_components(dataset_properties=dataset_properties, include=include, exclude=exclude)
if (len(available_schedulers) == 0):
raise ValueError('No scheduler found')
if (default is None):
defaults = ['ReduceLROnPlateau', 'CosineAnnealingLR', 'no_LRScheduler', 'LambdaLR', 'StepLR', 'ExponentialLR']
for default_ in defaults:
if (default_ in available_schedulers):
default = default_
break
updates = self._get_search_space_updates()
if ('__choice__' in updates.keys()):
choice_hyperparameter = updates['__choice__']
if (not set(choice_hyperparameter.value_range).issubset(available_schedulers)):
raise ValueError('Expected given update for {} to have choices in {} got {}'.format(self.__class__.__name__, available_schedulers, choice_hyperparameter.value_range))
scheduler = CSH.CategoricalHyperparameter('__choice__', choice_hyperparameter.value_range, default_value=choice_hyperparameter.default_value)
else:
scheduler = CSH.CategoricalHyperparameter('__choice__', list(available_schedulers.keys()), default_value=default)
cs.add_hyperparameter(scheduler)
for name in scheduler.choices:
updates = self._get_search_space_updates(prefix=name)
config_space = available_schedulers[name].get_hyperparameter_search_space(dataset_properties, **updates)
parent_hyperparameter = {'parent': scheduler, 'value': name}
cs.add_configuration_space(name, config_space, parent_hyperparameter=parent_hyperparameter)
self.configuration_space_ = cs
self.dataset_properties_ = dataset_properties
return cs | def get_hyperparameter_search_space(self, dataset_properties: Optional[Dict[(str, BaseDatasetPropertiesType)]]=None, default: Optional[str]=None, include: Optional[List[str]]=None, exclude: Optional[List[str]]=None) -> ConfigurationSpace:
'Returns the configuration space of the current chosen components\n\n Args:\n dataset_properties (Optional[Dict[str, str]]): Describes the dataset to work on\n default (Optional[str]): Default scheduler to use\n include: Optional[Dict[str, Any]]: what components to include. It is an exhaustive\n list, and will exclusively use this components.\n exclude: Optional[Dict[str, Any]]: which components to skip\n\n Returns:\n ConfigurationSpace: the configuration space of the hyper-parameters of the\n chosen component\n '
cs = ConfigurationSpace()
if (dataset_properties is None):
dataset_properties = {}
available_schedulers = self.get_available_components(dataset_properties=dataset_properties, include=include, exclude=exclude)
if (len(available_schedulers) == 0):
raise ValueError('No scheduler found')
if (default is None):
defaults = ['ReduceLROnPlateau', 'CosineAnnealingLR', 'no_LRScheduler', 'LambdaLR', 'StepLR', 'ExponentialLR']
for default_ in defaults:
if (default_ in available_schedulers):
default = default_
break
updates = self._get_search_space_updates()
if ('__choice__' in updates.keys()):
choice_hyperparameter = updates['__choice__']
if (not set(choice_hyperparameter.value_range).issubset(available_schedulers)):
raise ValueError('Expected given update for {} to have choices in {} got {}'.format(self.__class__.__name__, available_schedulers, choice_hyperparameter.value_range))
scheduler = CSH.CategoricalHyperparameter('__choice__', choice_hyperparameter.value_range, default_value=choice_hyperparameter.default_value)
else:
scheduler = CSH.CategoricalHyperparameter('__choice__', list(available_schedulers.keys()), default_value=default)
cs.add_hyperparameter(scheduler)
for name in scheduler.choices:
updates = self._get_search_space_updates(prefix=name)
config_space = available_schedulers[name].get_hyperparameter_search_space(dataset_properties, **updates)
parent_hyperparameter = {'parent': scheduler, 'value': name}
cs.add_configuration_space(name, config_space, parent_hyperparameter=parent_hyperparameter)
self.configuration_space_ = cs
self.dataset_properties_ = dataset_properties
return cs<|docstring|>Returns the configuration space of the current chosen components
Args:
dataset_properties (Optional[Dict[str, str]]): Describes the dataset to work on
default (Optional[str]): Default scheduler to use
include: Optional[Dict[str, Any]]: what components to include. It is an exhaustive
list, and will exclusively use this components.
exclude: Optional[Dict[str, Any]]: which components to skip
Returns:
ConfigurationSpace: the configuration space of the hyper-parameters of the
chosen component<|endoftext|> |
a0e6965a0c90c76b03c7ba31fd09b16ae448983820cf86c82d2718039f920120 | def isSymmetric(self, root):
'\n :type root: TreeNode\n :rtype: bool\n '
if (not root):
return True
def same_tree(t1, t2):
if ((t1 is None) or (t2 is None)):
return (t1 == t2)
if (t1.val != t2.val):
return False
return (same_tree(t1.left, t2.left) and same_tree(t1.right, t2.right))
return same_tree(root.left, root.right) | :type root: TreeNode
:rtype: bool | 101-symmetric-tree.py | isSymmetric | daicang/Leetcode | 0 | python | def isSymmetric(self, root):
'\n :type root: TreeNode\n :rtype: bool\n '
if (not root):
return True
def same_tree(t1, t2):
if ((t1 is None) or (t2 is None)):
return (t1 == t2)
if (t1.val != t2.val):
return False
return (same_tree(t1.left, t2.left) and same_tree(t1.right, t2.right))
return same_tree(root.left, root.right) | def isSymmetric(self, root):
'\n :type root: TreeNode\n :rtype: bool\n '
if (not root):
return True
def same_tree(t1, t2):
if ((t1 is None) or (t2 is None)):
return (t1 == t2)
if (t1.val != t2.val):
return False
return (same_tree(t1.left, t2.left) and same_tree(t1.right, t2.right))
return same_tree(root.left, root.right)<|docstring|>:type root: TreeNode
:rtype: bool<|endoftext|> |
cfd5c6518f3f97d9cc0120f767361a7bfb753b5df5125d01c6f1f8ec19c5aecd | def create_func_delete_files(paths):
'\n Create function to delete files that created after tests.\n '
def wrapper():
for path in paths:
path = create_correct_path(path, True)
if ((path is not None) and os.path.isdir(path)):
shutil.rmtree(path)
return wrapper | Create function to delete files that created after tests. | test/unit/utilities/test_chain_import_export.py | create_func_delete_files | Kwentar/FEDOT | 0 | python | def create_func_delete_files(paths):
'\n \n '
def wrapper():
for path in paths:
path = create_correct_path(path, True)
if ((path is not None) and os.path.isdir(path)):
shutil.rmtree(path)
return wrapper | def create_func_delete_files(paths):
'\n \n '
def wrapper():
for path in paths:
path = create_correct_path(path, True)
if ((path is not None) and os.path.isdir(path)):
shutil.rmtree(path)
return wrapper<|docstring|>Create function to delete files that created after tests.<|endoftext|> |
cc1162ff9662f8479fbb9452d1f32a99d5211ec0337e1e68c535ead6317556d3 | def create_correct_path(path: str, dirname_flag: bool=False):
'\n Create path with time which was created during the testing process.\n '
for dirname in next(os.walk(os.path.curdir))[1]:
if dirname.endswith(path):
if dirname_flag:
return dirname
else:
file = os.path.join(dirname, (path + '.json'))
return file
return None | Create path with time which was created during the testing process. | test/unit/utilities/test_chain_import_export.py | create_correct_path | Kwentar/FEDOT | 0 | python | def create_correct_path(path: str, dirname_flag: bool=False):
'\n \n '
for dirname in next(os.walk(os.path.curdir))[1]:
if dirname.endswith(path):
if dirname_flag:
return dirname
else:
file = os.path.join(dirname, (path + '.json'))
return file
return None | def create_correct_path(path: str, dirname_flag: bool=False):
'\n \n '
for dirname in next(os.walk(os.path.curdir))[1]:
if dirname.endswith(path):
if dirname_flag:
return dirname
else:
file = os.path.join(dirname, (path + '.json'))
return file
return None<|docstring|>Create path with time which was created during the testing process.<|endoftext|> |
7d85542f546c515160229d5592592b29c4cef988f886937f2ae7d1cec5d92732 | def create_json_models_files():
"\n Creating JSON's files for test before tests.\n "
chain = create_chain()
chain.save('test_chain_convert_to_json')
chain_fitted = create_fitted_chain()
chain_fitted.save('test_fitted_chain_convert_to_json')
chain_empty = Chain()
chain_empty.save('test_empty_chain_convert_to_json') | Creating JSON's files for test before tests. | test/unit/utilities/test_chain_import_export.py | create_json_models_files | Kwentar/FEDOT | 0 | python | def create_json_models_files():
"\n \n "
chain = create_chain()
chain.save('test_chain_convert_to_json')
chain_fitted = create_fitted_chain()
chain_fitted.save('test_fitted_chain_convert_to_json')
chain_empty = Chain()
chain_empty.save('test_empty_chain_convert_to_json') | def create_json_models_files():
"\n \n "
chain = create_chain()
chain.save('test_chain_convert_to_json')
chain_fitted = create_fitted_chain()
chain_fitted.save('test_fitted_chain_convert_to_json')
chain_empty = Chain()
chain_empty.save('test_empty_chain_convert_to_json')<|docstring|>Creating JSON's files for test before tests.<|endoftext|> |
deb9f5aad8b67a83cc2362e2185e05aa6d106c559e77d8d0082e67970b75b286 | def test_export_import_for_one_chain_object_correctly():
'\n This test checks whether it is possible to upload a new model to the same object. In other words,\n apply a sequence of commands to the chain object:\n - load_chain(path_first)\n - load_chain(path_second)\n - load_chain(path_third)\n and the last command will rewrite the chain object correctly.\n '
chain_fitted = create_fitted_chain()
json_first = chain_fitted.save('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after = create_chain()
chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_1')
json_path_load_2 = create_correct_path('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after.load(json_path_load_2)
json_second = chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_3')
assert (json_first == json_second) | This test checks whether it is possible to upload a new model to the same object. In other words,
apply a sequence of commands to the chain object:
- load_chain(path_first)
- load_chain(path_second)
- load_chain(path_third)
and the last command will rewrite the chain object correctly. | test/unit/utilities/test_chain_import_export.py | test_export_import_for_one_chain_object_correctly | Kwentar/FEDOT | 0 | python | def test_export_import_for_one_chain_object_correctly():
'\n This test checks whether it is possible to upload a new model to the same object. In other words,\n apply a sequence of commands to the chain object:\n - load_chain(path_first)\n - load_chain(path_second)\n - load_chain(path_third)\n and the last command will rewrite the chain object correctly.\n '
chain_fitted = create_fitted_chain()
json_first = chain_fitted.save('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after = create_chain()
chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_1')
json_path_load_2 = create_correct_path('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after.load(json_path_load_2)
json_second = chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_3')
assert (json_first == json_second) | def test_export_import_for_one_chain_object_correctly():
'\n This test checks whether it is possible to upload a new model to the same object. In other words,\n apply a sequence of commands to the chain object:\n - load_chain(path_first)\n - load_chain(path_second)\n - load_chain(path_third)\n and the last command will rewrite the chain object correctly.\n '
chain_fitted = create_fitted_chain()
json_first = chain_fitted.save('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after = create_chain()
chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_1')
json_path_load_2 = create_correct_path('test_export_import_for_one_chain_object_correctly_2')
chain_fitted_after.load(json_path_load_2)
json_second = chain_fitted_after.save('test_export_import_for_one_chain_object_correctly_3')
assert (json_first == json_second)<|docstring|>This test checks whether it is possible to upload a new model to the same object. In other words,
apply a sequence of commands to the chain object:
- load_chain(path_first)
- load_chain(path_second)
- load_chain(path_third)
and the last command will rewrite the chain object correctly.<|endoftext|> |
4ee839a3e7a6ae8c22966869ac809da4d5358b2e682f39eb194315a9d97b0732 | def set_alpha(self, a):
'\n Set the alpha value for the calibrated camera solution. The alpha\n value is a zoom, and ranges from 0 (zoomed in, all pixels in\n calibrated image are valid) to 1 (zoomed out, all pixels in\n original image are in calibrated image).\n '
self.alpha = a
if (a is not None):
(ncm, _) = cv2.getOptimalNewCameraMatrix(self.intrinsics, self.distortion, self.size, a)
else:
ncm = self.intrinsics
for j in range(3):
for i in range(3):
self.P[(j, i)] = ncm[(j, i)]
self.fx = self.P[(0, 0)]
self.fy = self.P[(1, 1)]
self.cx = self.P[(0, 2)]
self.cy = self.P[(1, 2)]
(self.mapx, self.mapy) = cv2.initUndistortRectifyMap(self.intrinsics, self.distortion, self.R, ncm, self.size, cv2.CV_32FC1) | Set the alpha value for the calibrated camera solution. The alpha
value is a zoom, and ranges from 0 (zoomed in, all pixels in
calibrated image are valid) to 1 (zoomed out, all pixels in
original image are in calibrated image). | pylib/src/util/stereo.py | set_alpha | HaiDang9719/pixel_link_VMNDOC | 1 | python | def set_alpha(self, a):
'\n Set the alpha value for the calibrated camera solution. The alpha\n value is a zoom, and ranges from 0 (zoomed in, all pixels in\n calibrated image are valid) to 1 (zoomed out, all pixels in\n original image are in calibrated image).\n '
self.alpha = a
if (a is not None):
(ncm, _) = cv2.getOptimalNewCameraMatrix(self.intrinsics, self.distortion, self.size, a)
else:
ncm = self.intrinsics
for j in range(3):
for i in range(3):
self.P[(j, i)] = ncm[(j, i)]
self.fx = self.P[(0, 0)]
self.fy = self.P[(1, 1)]
self.cx = self.P[(0, 2)]
self.cy = self.P[(1, 2)]
(self.mapx, self.mapy) = cv2.initUndistortRectifyMap(self.intrinsics, self.distortion, self.R, ncm, self.size, cv2.CV_32FC1) | def set_alpha(self, a):
'\n Set the alpha value for the calibrated camera solution. The alpha\n value is a zoom, and ranges from 0 (zoomed in, all pixels in\n calibrated image are valid) to 1 (zoomed out, all pixels in\n original image are in calibrated image).\n '
self.alpha = a
if (a is not None):
(ncm, _) = cv2.getOptimalNewCameraMatrix(self.intrinsics, self.distortion, self.size, a)
else:
ncm = self.intrinsics
for j in range(3):
for i in range(3):
self.P[(j, i)] = ncm[(j, i)]
self.fx = self.P[(0, 0)]
self.fy = self.P[(1, 1)]
self.cx = self.P[(0, 2)]
self.cy = self.P[(1, 2)]
(self.mapx, self.mapy) = cv2.initUndistortRectifyMap(self.intrinsics, self.distortion, self.R, ncm, self.size, cv2.CV_32FC1)<|docstring|>Set the alpha value for the calibrated camera solution. The alpha
value is a zoom, and ranges from 0 (zoomed in, all pixels in
calibrated image are valid) to 1 (zoomed out, all pixels in
original image are in calibrated image).<|endoftext|> |
20ec8b90a30d35be922efa011c5846dbedf06a36a71c7192b65f3141b0582133 | def undistort_points(self, points):
'\n points: N source pixel points (u,v) as an Nx2 matrix\n '
points = np.asarray(points, dtype=np.float32)
if (len(points.shape) == 2):
assert (points.shape[1] == 2)
points = np.expand_dims(points, axis=1)
assert (points.shape[1] == 1)
return cv2.undistortPoints(points, self.intrinsics, self.distortion, R=self.R, P=self.P) | points: N source pixel points (u,v) as an Nx2 matrix | pylib/src/util/stereo.py | undistort_points | HaiDang9719/pixel_link_VMNDOC | 1 | python | def undistort_points(self, points):
'\n \n '
points = np.asarray(points, dtype=np.float32)
if (len(points.shape) == 2):
assert (points.shape[1] == 2)
points = np.expand_dims(points, axis=1)
assert (points.shape[1] == 1)
return cv2.undistortPoints(points, self.intrinsics, self.distortion, R=self.R, P=self.P) | def undistort_points(self, points):
'\n \n '
points = np.asarray(points, dtype=np.float32)
if (len(points.shape) == 2):
assert (points.shape[1] == 2)
points = np.expand_dims(points, axis=1)
assert (points.shape[1] == 1)
return cv2.undistortPoints(points, self.intrinsics, self.distortion, R=self.R, P=self.P)<|docstring|>points: N source pixel points (u,v) as an Nx2 matrix<|endoftext|> |
0589e5b967a8df42e8c35778e05bba253e8726443415568d6136d897a5cd910a | def remap(self, src):
'\n :param src: source image\n :type src: :class:`cvMat`\n\n Apply the post-calibration undistortion to the source image\n '
return cv2.remap(src, self.mapx, self.mapy, cv2.INTER_LINEAR) | :param src: source image
:type src: :class:`cvMat`
Apply the post-calibration undistortion to the source image | pylib/src/util/stereo.py | remap | HaiDang9719/pixel_link_VMNDOC | 1 | python | def remap(self, src):
'\n :param src: source image\n :type src: :class:`cvMat`\n\n Apply the post-calibration undistortion to the source image\n '
return cv2.remap(src, self.mapx, self.mapy, cv2.INTER_LINEAR) | def remap(self, src):
'\n :param src: source image\n :type src: :class:`cvMat`\n\n Apply the post-calibration undistortion to the source image\n '
return cv2.remap(src, self.mapx, self.mapy, cv2.INTER_LINEAR)<|docstring|>:param src: source image
:type src: :class:`cvMat`
Apply the post-calibration undistortion to the source image<|endoftext|> |
353a972346932c7992e316950232812a28904744559f7238d12f3ea9cfe536c8 | def min_visible_distance(self):
'\n the min visible distance of binocular system\n '
return min_bino_visible_distance(self.left_camera_model.fx, self.left_camera_model.w, self.B) | the min visible distance of binocular system | pylib/src/util/stereo.py | min_visible_distance | HaiDang9719/pixel_link_VMNDOC | 1 | python | def min_visible_distance(self):
'\n \n '
return min_bino_visible_distance(self.left_camera_model.fx, self.left_camera_model.w, self.B) | def min_visible_distance(self):
'\n \n '
return min_bino_visible_distance(self.left_camera_model.fx, self.left_camera_model.w, self.B)<|docstring|>the min visible distance of binocular system<|endoftext|> |
eede03d38f76bdde21d857e352e7e77ed16b0b14ad7e043a223c260a70c42362 | def authenticate(ome_ip_address: str, ome_username: str, ome_password: str) -> dict:
'\n Authenticates with OME and creates a session\n\n Args:\n ome_ip_address: IP address of the OME server\n ome_username: Username for OME\n ome_password: OME password\n\n Returns: A dictionary of HTTP headers\n\n Raises:\n Exception: A generic exception in the event of a failure to connect.\n '
authenticated_headers = {'content-type': 'application/json'}
session_url = ('https://%s/api/SessionService/Sessions' % ome_ip_address)
user_details = {'UserName': ome_username, 'Password': ome_password, 'SessionType': 'API'}
try:
session_info = requests.post(session_url, verify=False, data=json.dumps(user_details), headers=authenticated_headers)
except requests.exceptions.ConnectionError:
print('Failed to connect to OME. This typically indicates a network connectivity problem. Can you ping OME?')
sys.exit(0)
if (session_info.status_code == 201):
authenticated_headers['X-Auth-Token'] = session_info.headers['X-Auth-Token']
return authenticated_headers
print('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?')
raise Exception('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?') | Authenticates with OME and creates a session
Args:
ome_ip_address: IP address of the OME server
ome_username: Username for OME
ome_password: OME password
Returns: A dictionary of HTTP headers
Raises:
Exception: A generic exception in the event of a failure to connect. | Python/get_audit_logs.py | authenticate | jzcmyz/OpenManage-Enterprise | 61 | python | def authenticate(ome_ip_address: str, ome_username: str, ome_password: str) -> dict:
'\n Authenticates with OME and creates a session\n\n Args:\n ome_ip_address: IP address of the OME server\n ome_username: Username for OME\n ome_password: OME password\n\n Returns: A dictionary of HTTP headers\n\n Raises:\n Exception: A generic exception in the event of a failure to connect.\n '
authenticated_headers = {'content-type': 'application/json'}
session_url = ('https://%s/api/SessionService/Sessions' % ome_ip_address)
user_details = {'UserName': ome_username, 'Password': ome_password, 'SessionType': 'API'}
try:
session_info = requests.post(session_url, verify=False, data=json.dumps(user_details), headers=authenticated_headers)
except requests.exceptions.ConnectionError:
print('Failed to connect to OME. This typically indicates a network connectivity problem. Can you ping OME?')
sys.exit(0)
if (session_info.status_code == 201):
authenticated_headers['X-Auth-Token'] = session_info.headers['X-Auth-Token']
return authenticated_headers
print('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?')
raise Exception('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?') | def authenticate(ome_ip_address: str, ome_username: str, ome_password: str) -> dict:
'\n Authenticates with OME and creates a session\n\n Args:\n ome_ip_address: IP address of the OME server\n ome_username: Username for OME\n ome_password: OME password\n\n Returns: A dictionary of HTTP headers\n\n Raises:\n Exception: A generic exception in the event of a failure to connect.\n '
authenticated_headers = {'content-type': 'application/json'}
session_url = ('https://%s/api/SessionService/Sessions' % ome_ip_address)
user_details = {'UserName': ome_username, 'Password': ome_password, 'SessionType': 'API'}
try:
session_info = requests.post(session_url, verify=False, data=json.dumps(user_details), headers=authenticated_headers)
except requests.exceptions.ConnectionError:
print('Failed to connect to OME. This typically indicates a network connectivity problem. Can you ping OME?')
sys.exit(0)
if (session_info.status_code == 201):
authenticated_headers['X-Auth-Token'] = session_info.headers['X-Auth-Token']
return authenticated_headers
print('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?')
raise Exception('There was a problem authenticating with OME. Are you sure you have the right username, password, and IP?')<|docstring|>Authenticates with OME and creates a session
Args:
ome_ip_address: IP address of the OME server
ome_username: Username for OME
ome_password: OME password
Returns: A dictionary of HTTP headers
Raises:
Exception: A generic exception in the event of a failure to connect.<|endoftext|> |
eecbc4e0c4b299852d92fb4a2d2ac08569a722f813b1cac906016978a9dc57fc | def get_data(authenticated_headers: dict, url: str, odata_filter: str=None, max_pages: int=None) -> dict:
'\n This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below\n handles pagination. This is the equivalent in the UI of a list of results that require you to go to different\n pages to get a complete listing.\n\n Args:\n authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME\n url: The API url against which you would like to make a request\n odata_filter: An optional parameter for providing an odata filter to run against the API endpoint.\n max_pages: The maximum number of pages you would like to return\n\n Returns: Returns a dictionary of data received from OME\n\n '
next_link_url = None
if odata_filter:
count_data = requests.get(((url + '?$filter=') + odata_filter), headers=authenticated_headers, verify=False)
if (count_data.status_code == 400):
print(((('Received an error while retrieving data from %s:' % url) + '?$filter=') + odata_filter))
pprint(count_data.json()['error'])
return {}
count_data = count_data.json()
if (count_data['@odata.count'] <= 0):
print('No results found!')
return {}
else:
count_data = requests.get(url, headers=authenticated_headers, verify=False).json()
if ('value' in count_data):
data = count_data['value']
else:
data = count_data
if ('@odata.nextLink' in count_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + count_data['@odata.nextLink'])
i = 1
while (next_link_url is not None):
if max_pages:
if (i >= max_pages):
break
else:
i = (i + 1)
response = requests.get(next_link_url, headers=authenticated_headers, verify=False)
next_link_url = None
if (response.status_code == 200):
requested_data = response.json()
if (requested_data['@odata.count'] <= 0):
print('No results found!')
return {}
if ('@odata.nextLink' in requested_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + requested_data['@odata.nextLink'])
if ('value' in requested_data):
data += requested_data['value']
else:
data += requested_data
else:
print(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
raise Exception(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
return data | This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below
handles pagination. This is the equivalent in the UI of a list of results that require you to go to different
pages to get a complete listing.
Args:
authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME
url: The API url against which you would like to make a request
odata_filter: An optional parameter for providing an odata filter to run against the API endpoint.
max_pages: The maximum number of pages you would like to return
Returns: Returns a dictionary of data received from OME | Python/get_audit_logs.py | get_data | jzcmyz/OpenManage-Enterprise | 61 | python | def get_data(authenticated_headers: dict, url: str, odata_filter: str=None, max_pages: int=None) -> dict:
'\n This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below\n handles pagination. This is the equivalent in the UI of a list of results that require you to go to different\n pages to get a complete listing.\n\n Args:\n authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME\n url: The API url against which you would like to make a request\n odata_filter: An optional parameter for providing an odata filter to run against the API endpoint.\n max_pages: The maximum number of pages you would like to return\n\n Returns: Returns a dictionary of data received from OME\n\n '
next_link_url = None
if odata_filter:
count_data = requests.get(((url + '?$filter=') + odata_filter), headers=authenticated_headers, verify=False)
if (count_data.status_code == 400):
print(((('Received an error while retrieving data from %s:' % url) + '?$filter=') + odata_filter))
pprint(count_data.json()['error'])
return {}
count_data = count_data.json()
if (count_data['@odata.count'] <= 0):
print('No results found!')
return {}
else:
count_data = requests.get(url, headers=authenticated_headers, verify=False).json()
if ('value' in count_data):
data = count_data['value']
else:
data = count_data
if ('@odata.nextLink' in count_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + count_data['@odata.nextLink'])
i = 1
while (next_link_url is not None):
if max_pages:
if (i >= max_pages):
break
else:
i = (i + 1)
response = requests.get(next_link_url, headers=authenticated_headers, verify=False)
next_link_url = None
if (response.status_code == 200):
requested_data = response.json()
if (requested_data['@odata.count'] <= 0):
print('No results found!')
return {}
if ('@odata.nextLink' in requested_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + requested_data['@odata.nextLink'])
if ('value' in requested_data):
data += requested_data['value']
else:
data += requested_data
else:
print(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
raise Exception(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
return data | def get_data(authenticated_headers: dict, url: str, odata_filter: str=None, max_pages: int=None) -> dict:
'\n This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below\n handles pagination. This is the equivalent in the UI of a list of results that require you to go to different\n pages to get a complete listing.\n\n Args:\n authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME\n url: The API url against which you would like to make a request\n odata_filter: An optional parameter for providing an odata filter to run against the API endpoint.\n max_pages: The maximum number of pages you would like to return\n\n Returns: Returns a dictionary of data received from OME\n\n '
next_link_url = None
if odata_filter:
count_data = requests.get(((url + '?$filter=') + odata_filter), headers=authenticated_headers, verify=False)
if (count_data.status_code == 400):
print(((('Received an error while retrieving data from %s:' % url) + '?$filter=') + odata_filter))
pprint(count_data.json()['error'])
return {}
count_data = count_data.json()
if (count_data['@odata.count'] <= 0):
print('No results found!')
return {}
else:
count_data = requests.get(url, headers=authenticated_headers, verify=False).json()
if ('value' in count_data):
data = count_data['value']
else:
data = count_data
if ('@odata.nextLink' in count_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + count_data['@odata.nextLink'])
i = 1
while (next_link_url is not None):
if max_pages:
if (i >= max_pages):
break
else:
i = (i + 1)
response = requests.get(next_link_url, headers=authenticated_headers, verify=False)
next_link_url = None
if (response.status_code == 200):
requested_data = response.json()
if (requested_data['@odata.count'] <= 0):
print('No results found!')
return {}
if ('@odata.nextLink' in requested_data):
next_link_url = ('{uri.scheme}://{uri.netloc}'.format(uri=urlparse(url)) + requested_data['@odata.nextLink'])
if ('value' in requested_data):
data += requested_data['value']
else:
data += requested_data
else:
print(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
raise Exception(((('Unknown error occurred. Received HTTP response code: ' + str(response.status_code)) + ' with error: ') + response.text))
return data<|docstring|>This function retrieves data from a specified URL. Get requests from OME return paginated data. The code below
handles pagination. This is the equivalent in the UI of a list of results that require you to go to different
pages to get a complete listing.
Args:
authenticated_headers: A dictionary of HTTP headers generated from an authenticated session with OME
url: The API url against which you would like to make a request
odata_filter: An optional parameter for providing an odata filter to run against the API endpoint.
max_pages: The maximum number of pages you would like to return
Returns: Returns a dictionary of data received from OME<|endoftext|> |
d7657e5d5bdd3bd7acf3bd1d99061f0189dea4067d808c65a74289dfb1877a5a | def get_files_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get files changed from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dicts\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/files'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
dict_pr = {'filename': res_json['filename'].split('/')[(- 1)], 'path_to_file': res_json['filename'], 'pr_number': pr_number, 'repo': repo, 'status': res_json['status'], 'additions': res_json['additions'], 'deletions': res_json['deletions'], 'changes': res_json['changes']}
list_dict_pr.append(dict_pr)
return list_dict_pr | Get files changed from specific PR.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
List[dict]: List of dicts | code/github_pr.py | get_files_from_pr | dyvenia/gitflow | 0 | python | def get_files_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get files changed from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dicts\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/files'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
dict_pr = {'filename': res_json['filename'].split('/')[(- 1)], 'path_to_file': res_json['filename'], 'pr_number': pr_number, 'repo': repo, 'status': res_json['status'], 'additions': res_json['additions'], 'deletions': res_json['deletions'], 'changes': res_json['changes']}
list_dict_pr.append(dict_pr)
return list_dict_pr | def get_files_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get files changed from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dicts\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/files'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
dict_pr = {'filename': res_json['filename'].split('/')[(- 1)], 'path_to_file': res_json['filename'], 'pr_number': pr_number, 'repo': repo, 'status': res_json['status'], 'additions': res_json['additions'], 'deletions': res_json['deletions'], 'changes': res_json['changes']}
list_dict_pr.append(dict_pr)
return list_dict_pr<|docstring|>Get files changed from specific PR.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
List[dict]: List of dicts<|endoftext|> |
93e49abc93065044ea13f12328bfba44261a71238fe38c056032d77a7aa381d5 | def files_to_df(self, files: List[dict]=None) -> pd.DataFrame:
'\n Get all changed files for pull request and convert to DF.\n '
return pd.DataFrame(files) | Get all changed files for pull request and convert to DF. | code/github_pr.py | files_to_df | dyvenia/gitflow | 0 | python | def files_to_df(self, files: List[dict]=None) -> pd.DataFrame:
'\n \n '
return pd.DataFrame(files) | def files_to_df(self, files: List[dict]=None) -> pd.DataFrame:
'\n \n '
return pd.DataFrame(files)<|docstring|>Get all changed files for pull request and convert to DF.<|endoftext|> |
f6ab87a8a2f85f25bd0f86e1f0b6afe4b1fda74c36ed65ccba6f7547a0eb887f | def get_commits_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get info about commits from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dictionaries\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/commits'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
commit = res_json['commit']
dict_pr = {'author': commit['author']['name'], 'pr_number': pr_number, 'date_commit': commit['author']['date'], 'message': commit['message'], 'comment_count': commit['comment_count']}
list_dict_pr.append(dict_pr)
return list_dict_pr | Get info about commits from specific PR.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
List[dict]: List of dictionaries | code/github_pr.py | get_commits_from_pr | dyvenia/gitflow | 0 | python | def get_commits_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get info about commits from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dictionaries\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/commits'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
commit = res_json['commit']
dict_pr = {'author': commit['author']['name'], 'pr_number': pr_number, 'date_commit': commit['author']['date'], 'message': commit['message'], 'comment_count': commit['comment_count']}
list_dict_pr.append(dict_pr)
return list_dict_pr | def get_commits_from_pr(self, repo: str=None, pr_number: int=None) -> List[dict]:
'\n Get info about commits from specific PR.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n List[dict]: List of dictionaries\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}/commits'
result = request_to_json((BASE_URL + url))
list_dict_pr = []
for i in range(len(result)):
res_json = result[i]
commit = res_json['commit']
dict_pr = {'author': commit['author']['name'], 'pr_number': pr_number, 'date_commit': commit['author']['date'], 'message': commit['message'], 'comment_count': commit['comment_count']}
list_dict_pr.append(dict_pr)
return list_dict_pr<|docstring|>Get info about commits from specific PR.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
List[dict]: List of dictionaries<|endoftext|> |
06d20c35db46d8b2ae39c654caf3f588dec5f9f7783aaee65af04917de649956 | def commits_to_df(self, commits: List[dict]=None) -> pd.DataFrame:
'\n Get all commits for pull request and convert to DF.\n '
return pd.DataFrame(commits) | Get all commits for pull request and convert to DF. | code/github_pr.py | commits_to_df | dyvenia/gitflow | 0 | python | def commits_to_df(self, commits: List[dict]=None) -> pd.DataFrame:
'\n \n '
return pd.DataFrame(commits) | def commits_to_df(self, commits: List[dict]=None) -> pd.DataFrame:
'\n \n '
return pd.DataFrame(commits)<|docstring|>Get all commits for pull request and convert to DF.<|endoftext|> |
26094a107c04f5e53e423e42ebdccc24b2bd3b9064ebf095c37fdfe537a25dc1 | def str_to_datetime(self, date_str: str=None) -> datetime:
'\n Convert string to datetime.\n\n Args:\n date_str (str, optional): Date in string format. Defaults to None.\n\n Returns:\n datetime: Date in datetime format\n '
date_str_new = ' '.join(date_str.split('T'))
return datetime.fromisoformat(date_str_new[:(- 1)]) | Convert string to datetime.
Args:
date_str (str, optional): Date in string format. Defaults to None.
Returns:
datetime: Date in datetime format | code/github_pr.py | str_to_datetime | dyvenia/gitflow | 0 | python | def str_to_datetime(self, date_str: str=None) -> datetime:
'\n Convert string to datetime.\n\n Args:\n date_str (str, optional): Date in string format. Defaults to None.\n\n Returns:\n datetime: Date in datetime format\n '
date_str_new = ' '.join(date_str.split('T'))
return datetime.fromisoformat(date_str_new[:(- 1)]) | def str_to_datetime(self, date_str: str=None) -> datetime:
'\n Convert string to datetime.\n\n Args:\n date_str (str, optional): Date in string format. Defaults to None.\n\n Returns:\n datetime: Date in datetime format\n '
date_str_new = ' '.join(date_str.split('T'))
return datetime.fromisoformat(date_str_new[:(- 1)])<|docstring|>Convert string to datetime.
Args:
date_str (str, optional): Date in string format. Defaults to None.
Returns:
datetime: Date in datetime format<|endoftext|> |
d6dfda9b6a0e0d42d56f0a54c53efa7656fba087bfcb676f4d055906f6b41332 | def combine_pr_info_to_df(self, repo: str=None, pr_number: int=None) -> pd.DataFrame:
'\n Collect information about pull request. PR info, how long have been opened, create and close date.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n pd.DataFrame: Dataframe with information about pull request.\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}'
result = request_to_json((BASE_URL + url))
if (result['closed_at'] is not None):
created = self.str_to_datetime(result['created_at'])
closed = self.str_to_datetime(result['closed_at'])
duration_days = (closed - created).days
else:
duration_days = 0
dict_general = {'pr_name': result['title'], 'pr_number': pr_number, 'state': result['state'], 'created_at': result['created_at'], 'updated_at': result['updated_at'], 'closed_at': result['closed_at'], 'merged_at': result['merged_at'], 'duration_days': duration_days}
return pd.DataFrame(dict_general, index=[0]) | Collect information about pull request. PR info, how long have been opened, create and close date.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
pd.DataFrame: Dataframe with information about pull request. | code/github_pr.py | combine_pr_info_to_df | dyvenia/gitflow | 0 | python | def combine_pr_info_to_df(self, repo: str=None, pr_number: int=None) -> pd.DataFrame:
'\n Collect information about pull request. PR info, how long have been opened, create and close date.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n pd.DataFrame: Dataframe with information about pull request.\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}'
result = request_to_json((BASE_URL + url))
if (result['closed_at'] is not None):
created = self.str_to_datetime(result['created_at'])
closed = self.str_to_datetime(result['closed_at'])
duration_days = (closed - created).days
else:
duration_days = 0
dict_general = {'pr_name': result['title'], 'pr_number': pr_number, 'state': result['state'], 'created_at': result['created_at'], 'updated_at': result['updated_at'], 'closed_at': result['closed_at'], 'merged_at': result['merged_at'], 'duration_days': duration_days}
return pd.DataFrame(dict_general, index=[0]) | def combine_pr_info_to_df(self, repo: str=None, pr_number: int=None) -> pd.DataFrame:
'\n Collect information about pull request. PR info, how long have been opened, create and close date.\n\n Args:\n repo (str, optional): Repository name. Defaults to None.\n pr_number (int, optional): Pull request number. Defaults to None.\n\n Returns:\n pd.DataFrame: Dataframe with information about pull request.\n '
repo = (repo or self.repo)
pr_number = (pr_number or self.pr_number)
url = f'repos/dyvenia/{repo}/pulls/{pr_number}'
result = request_to_json((BASE_URL + url))
if (result['closed_at'] is not None):
created = self.str_to_datetime(result['created_at'])
closed = self.str_to_datetime(result['closed_at'])
duration_days = (closed - created).days
else:
duration_days = 0
dict_general = {'pr_name': result['title'], 'pr_number': pr_number, 'state': result['state'], 'created_at': result['created_at'], 'updated_at': result['updated_at'], 'closed_at': result['closed_at'], 'merged_at': result['merged_at'], 'duration_days': duration_days}
return pd.DataFrame(dict_general, index=[0])<|docstring|>Collect information about pull request. PR info, how long have been opened, create and close date.
Args:
repo (str, optional): Repository name. Defaults to None.
pr_number (int, optional): Pull request number. Defaults to None.
Returns:
pd.DataFrame: Dataframe with information about pull request.<|endoftext|> |
23682c6cf9b983956dea354d9f29499b3c23fbadf5573b06462aa47ac807d603 | def combine_all_pr_info(self) -> pd.DataFrame:
'\n Combine all informations from PR into one data frame.\n\n Returns:\n pd.DataFrame: DF containing information about commits and files.\n '
commits_df = self.commits_to_df(self.get_commits_from_pr())
files_df = self.files_to_df(self.get_files_from_pr())
combined_df = self.union_dfs_task([files_df, commits_df])
return combined_df | Combine all informations from PR into one data frame.
Returns:
pd.DataFrame: DF containing information about commits and files. | code/github_pr.py | combine_all_pr_info | dyvenia/gitflow | 0 | python | def combine_all_pr_info(self) -> pd.DataFrame:
'\n Combine all informations from PR into one data frame.\n\n Returns:\n pd.DataFrame: DF containing information about commits and files.\n '
commits_df = self.commits_to_df(self.get_commits_from_pr())
files_df = self.files_to_df(self.get_files_from_pr())
combined_df = self.union_dfs_task([files_df, commits_df])
return combined_df | def combine_all_pr_info(self) -> pd.DataFrame:
'\n Combine all informations from PR into one data frame.\n\n Returns:\n pd.DataFrame: DF containing information about commits and files.\n '
commits_df = self.commits_to_df(self.get_commits_from_pr())
files_df = self.files_to_df(self.get_files_from_pr())
combined_df = self.union_dfs_task([files_df, commits_df])
return combined_df<|docstring|>Combine all informations from PR into one data frame.
Returns:
pd.DataFrame: DF containing information about commits and files.<|endoftext|> |
32bf603b408461c6e375cb8dba9366cdaa94111f8d2e2f01e9fdb27dc5f2f4bb | def __init__(self, path, snap_name, host_npart, sat_npart, component, com, prop):
"\n parameters:\n ----------\n\n path : str\n path to simulation\n snap_name : str\n name of the snapshot\n host_npart : int\n Number of *Dark Matter* particles of the host galaxy.\n sat_npart : int\n Number of *Dark Matter* particles of the satellite galaxy.\n component : str\n Component to analyze (host_dm, disk, bulge, sat_dm)\n com : str\n What coordinates center to use. \n 'com_host': com of the host\n 'com_sat' : com of the satellite\n 'com_xyz' : com at the 0,0,0 point.\n 'com_host_disk' : com at the host disk using its potential\n prop : str\n What properties of the particles to return ('pos', 'vel', 'pot','mass', 'ids')\n\n "
self.path = path
self.snap = snap_name
self.host_npart = host_npart
self.sat_npart = sat_npart
self.snap_name = snap_name
self.component = component
self.com = com
self.prop = prop | parameters:
----------
path : str
path to simulation
snap_name : str
name of the snapshot
host_npart : int
Number of *Dark Matter* particles of the host galaxy.
sat_npart : int
Number of *Dark Matter* particles of the satellite galaxy.
component : str
Component to analyze (host_dm, disk, bulge, sat_dm)
com : str
What coordinates center to use.
'com_host': com of the host
'com_sat' : com of the satellite
'com_xyz' : com at the 0,0,0 point.
'com_host_disk' : com at the host disk using its potential
prop : str
What properties of the particles to return ('pos', 'vel', 'pot','mass', 'ids') | jellyfish/reading_snapshots.py | __init__ | ekta1224/jellyfish | 0 | python | def __init__(self, path, snap_name, host_npart, sat_npart, component, com, prop):
"\n parameters:\n ----------\n\n path : str\n path to simulation\n snap_name : str\n name of the snapshot\n host_npart : int\n Number of *Dark Matter* particles of the host galaxy.\n sat_npart : int\n Number of *Dark Matter* particles of the satellite galaxy.\n component : str\n Component to analyze (host_dm, disk, bulge, sat_dm)\n com : str\n What coordinates center to use. \n 'com_host': com of the host\n 'com_sat' : com of the satellite\n 'com_xyz' : com at the 0,0,0 point.\n 'com_host_disk' : com at the host disk using its potential\n prop : str\n What properties of the particles to return ('pos', 'vel', 'pot','mass', 'ids')\n\n "
self.path = path
self.snap = snap_name
self.host_npart = host_npart
self.sat_npart = sat_npart
self.snap_name = snap_name
self.component = component
self.com = com
self.prop = prop | def __init__(self, path, snap_name, host_npart, sat_npart, component, com, prop):
"\n parameters:\n ----------\n\n path : str\n path to simulation\n snap_name : str\n name of the snapshot\n host_npart : int\n Number of *Dark Matter* particles of the host galaxy.\n sat_npart : int\n Number of *Dark Matter* particles of the satellite galaxy.\n component : str\n Component to analyze (host_dm, disk, bulge, sat_dm)\n com : str\n What coordinates center to use. \n 'com_host': com of the host\n 'com_sat' : com of the satellite\n 'com_xyz' : com at the 0,0,0 point.\n 'com_host_disk' : com at the host disk using its potential\n prop : str\n What properties of the particles to return ('pos', 'vel', 'pot','mass', 'ids')\n\n "
self.path = path
self.snap = snap_name
self.host_npart = host_npart
self.sat_npart = sat_npart
self.snap_name = snap_name
self.component = component
self.com = com
self.prop = prop<|docstring|>parameters:
----------
path : str
path to simulation
snap_name : str
name of the snapshot
host_npart : int
Number of *Dark Matter* particles of the host galaxy.
sat_npart : int
Number of *Dark Matter* particles of the satellite galaxy.
component : str
Component to analyze (host_dm, disk, bulge, sat_dm)
com : str
What coordinates center to use.
'com_host': com of the host
'com_sat' : com of the satellite
'com_xyz' : com at the 0,0,0 point.
'com_host_disk' : com at the host disk using its potential
prop : str
What properties of the particles to return ('pos', 'vel', 'pot','mass', 'ids')<|endoftext|> |
10b55eae0a0a360fa944dceafd87dcf00dab2ffb5192bb4ffbbbb6aa9eacdabd | def host_particles(self, pids, N_host_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n\n Parameters:\n -----------\n pids: particles ids\n \n Returns:\n --------\n host_indices : numpy.array \n index of the host galaxies\n\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[N_host_particles]
host_indices = np.where((pids < N_cut))[0]
return host_indices | Function that return the host and the sat particles
positions and velocities.
Parameters:
-----------
pids: particles ids
Returns:
--------
host_indices : numpy.array
index of the host galaxies | jellyfish/reading_snapshots.py | host_particles | ekta1224/jellyfish | 0 | python | def host_particles(self, pids, N_host_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n\n Parameters:\n -----------\n pids: particles ids\n \n Returns:\n --------\n host_indices : numpy.array \n index of the host galaxies\n\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[N_host_particles]
host_indices = np.where((pids < N_cut))[0]
return host_indices | def host_particles(self, pids, N_host_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n\n Parameters:\n -----------\n pids: particles ids\n \n Returns:\n --------\n host_indices : numpy.array \n index of the host galaxies\n\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[N_host_particles]
host_indices = np.where((pids < N_cut))[0]
return host_indices<|docstring|>Function that return the host and the sat particles
positions and velocities.
Parameters:
-----------
pids: particles ids
Returns:
--------
host_indices : numpy.array
index of the host galaxies<|endoftext|> |
9789bfed2636d8a2ad8704e5f6a5dbe9cb1b5f803d244aef1e4a9d9b1d74ee4e | def sat_particles(self, pids, Nhost_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n Parameters:\n -----------\n pids: particles ids\n Nhost_particles: Number of host particles in the snapshot\n Returns:\n --------\n sat_indices : numpy.array\n Array with the indices of the satellite galaxy.\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[Nhost_particles]
sat_indices = np.where((pids >= N_cut))[0]
return sat_indices | Function that return the host and the sat particles
positions and velocities.
Parameters:
-----------
pids: particles ids
Nhost_particles: Number of host particles in the snapshot
Returns:
--------
sat_indices : numpy.array
Array with the indices of the satellite galaxy. | jellyfish/reading_snapshots.py | sat_particles | ekta1224/jellyfish | 0 | python | def sat_particles(self, pids, Nhost_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n Parameters:\n -----------\n pids: particles ids\n Nhost_particles: Number of host particles in the snapshot\n Returns:\n --------\n sat_indices : numpy.array\n Array with the indices of the satellite galaxy.\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[Nhost_particles]
sat_indices = np.where((pids >= N_cut))[0]
return sat_indices | def sat_particles(self, pids, Nhost_particles):
'\n Function that return the host and the sat particles\n positions and velocities.\n Parameters:\n -----------\n pids: particles ids\n Nhost_particles: Number of host particles in the snapshot\n Returns:\n --------\n sat_indices : numpy.array\n Array with the indices of the satellite galaxy.\n '
sort_indexes = np.sort(pids)
N_cut = sort_indexes[Nhost_particles]
sat_indices = np.where((pids >= N_cut))[0]
return sat_indices<|docstring|>Function that return the host and the sat particles
positions and velocities.
Parameters:
-----------
pids: particles ids
Nhost_particles: Number of host particles in the snapshot
Returns:
--------
sat_indices : numpy.array
Array with the indices of the satellite galaxy.<|endoftext|> |
a3732cdac9f92b866b166a19297e38e517d5ea23b8d27f910da3d953db2e60f1 | def COM(self, xyz, vxyz, m):
'\n Returns the COM positions and velocities. \n\n \x0bec{R} = \\sum_i^N m_i \x0bec{r_i} / N\n \n '
N = sum(m)
xCOM = (np.sum((xyz[(:, 0)] * m)) / N)
yCOM = (np.sum((xyz[(:, 1)] * m)) / N)
zCOM = (np.sum((xyz[(:, 2)] * m)) / N)
vxCOM = (np.sum((vxyz[(:, 0)] * m)) / N)
vyCOM = (np.sum((vxyz[(:, 1)] * m)) / N)
vzCOM = (np.sum((vxyz[(:, 2)] * m)) / N)
return ([xCOM, yCOM, zCOM], [vxCOM, vyCOM, vzCOM]) | Returns the COM positions and velocities.
ec{R} = \sum_i^N m_i ec{r_i} / N | jellyfish/reading_snapshots.py | COM | ekta1224/jellyfish | 0 | python | def COM(self, xyz, vxyz, m):
'\n Returns the COM positions and velocities. \n\n \x0bec{R} = \\sum_i^N m_i \x0bec{r_i} / N\n \n '
N = sum(m)
xCOM = (np.sum((xyz[(:, 0)] * m)) / N)
yCOM = (np.sum((xyz[(:, 1)] * m)) / N)
zCOM = (np.sum((xyz[(:, 2)] * m)) / N)
vxCOM = (np.sum((vxyz[(:, 0)] * m)) / N)
vyCOM = (np.sum((vxyz[(:, 1)] * m)) / N)
vzCOM = (np.sum((vxyz[(:, 2)] * m)) / N)
return ([xCOM, yCOM, zCOM], [vxCOM, vyCOM, vzCOM]) | def COM(self, xyz, vxyz, m):
'\n Returns the COM positions and velocities. \n\n \x0bec{R} = \\sum_i^N m_i \x0bec{r_i} / N\n \n '
N = sum(m)
xCOM = (np.sum((xyz[(:, 0)] * m)) / N)
yCOM = (np.sum((xyz[(:, 1)] * m)) / N)
zCOM = (np.sum((xyz[(:, 2)] * m)) / N)
vxCOM = (np.sum((vxyz[(:, 0)] * m)) / N)
vyCOM = (np.sum((vxyz[(:, 1)] * m)) / N)
vzCOM = (np.sum((vxyz[(:, 2)] * m)) / N)
return ([xCOM, yCOM, zCOM], [vxCOM, vyCOM, vzCOM])<|docstring|>Returns the COM positions and velocities.
ec{R} = \sum_i^N m_i ec{r_i} / N<|endoftext|> |
b15ce9de84f4f40f00bd778baa744e4368fde25155a552ff940c0bdcf2f2e78a | def com_shrinking_sphere(self, m, delta=0.025):
'\n Compute the center of mass coordinates and velocities of a halo\n using the Shrinking Sphere Method Power et al 2003.\n It iterates in radii until reach a convergence given by delta\n or 1% of the total number of particles.\n\n Parameters:\n -----------\n xyz: cartesian coordinates with shape (n,3)\n vxys: cartesian velocities with shape (n,3)\n delta(optional): Precision of the CM, D=0.025\n\n Returns:\n --------\n rcm, vcm: 2 arrays containing the coordinates and velocities of\n the center of mass with reference to a (0,0,0) point.\n\n '
xCM = 0.0
yCM = 0.0
zCM = 0.0
xyz = self.pos
vxyz = self.vel
N_i = len(xyz)
N = N_i
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
while (((np.sqrt(((((xCM_new - xCM) ** 2) + ((yCM_new - yCM) ** 2)) + ((zCM_new - zCM) ** 2))) > delta) & (N > (N_i * 0.01))) | (N > 1000)):
xCM = xCM_new
yCM = yCM_new
zCM = zCM_new
R = np.sqrt(((((xyz[(:, 0)] - xCM_new) ** 2) + ((xyz[(:, 1)] - yCM_new) ** 2)) + ((xyz[(:, 2)] - zCM_new) ** 2)))
Rmax = np.max(R)
index = np.where((R < (Rmax * 0.75)))[0]
xyz = xyz[index]
vxyz = vxyz[index]
m = m[index]
N = len(xyz)
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
if (self.prop == 'pos'):
(i_com, j_com, k_com) = (xCM_new, yCM_new, zCM_new)
elif (self.prop == 'vel'):
print('this is not implemented yet')
return np.array([i_com, j_com, k_com]) | Compute the center of mass coordinates and velocities of a halo
using the Shrinking Sphere Method Power et al 2003.
It iterates in radii until reach a convergence given by delta
or 1% of the total number of particles.
Parameters:
-----------
xyz: cartesian coordinates with shape (n,3)
vxys: cartesian velocities with shape (n,3)
delta(optional): Precision of the CM, D=0.025
Returns:
--------
rcm, vcm: 2 arrays containing the coordinates and velocities of
the center of mass with reference to a (0,0,0) point. | jellyfish/reading_snapshots.py | com_shrinking_sphere | ekta1224/jellyfish | 0 | python | def com_shrinking_sphere(self, m, delta=0.025):
'\n Compute the center of mass coordinates and velocities of a halo\n using the Shrinking Sphere Method Power et al 2003.\n It iterates in radii until reach a convergence given by delta\n or 1% of the total number of particles.\n\n Parameters:\n -----------\n xyz: cartesian coordinates with shape (n,3)\n vxys: cartesian velocities with shape (n,3)\n delta(optional): Precision of the CM, D=0.025\n\n Returns:\n --------\n rcm, vcm: 2 arrays containing the coordinates and velocities of\n the center of mass with reference to a (0,0,0) point.\n\n '
xCM = 0.0
yCM = 0.0
zCM = 0.0
xyz = self.pos
vxyz = self.vel
N_i = len(xyz)
N = N_i
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
while (((np.sqrt(((((xCM_new - xCM) ** 2) + ((yCM_new - yCM) ** 2)) + ((zCM_new - zCM) ** 2))) > delta) & (N > (N_i * 0.01))) | (N > 1000)):
xCM = xCM_new
yCM = yCM_new
zCM = zCM_new
R = np.sqrt(((((xyz[(:, 0)] - xCM_new) ** 2) + ((xyz[(:, 1)] - yCM_new) ** 2)) + ((xyz[(:, 2)] - zCM_new) ** 2)))
Rmax = np.max(R)
index = np.where((R < (Rmax * 0.75)))[0]
xyz = xyz[index]
vxyz = vxyz[index]
m = m[index]
N = len(xyz)
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
if (self.prop == 'pos'):
(i_com, j_com, k_com) = (xCM_new, yCM_new, zCM_new)
elif (self.prop == 'vel'):
print('this is not implemented yet')
return np.array([i_com, j_com, k_com]) | def com_shrinking_sphere(self, m, delta=0.025):
'\n Compute the center of mass coordinates and velocities of a halo\n using the Shrinking Sphere Method Power et al 2003.\n It iterates in radii until reach a convergence given by delta\n or 1% of the total number of particles.\n\n Parameters:\n -----------\n xyz: cartesian coordinates with shape (n,3)\n vxys: cartesian velocities with shape (n,3)\n delta(optional): Precision of the CM, D=0.025\n\n Returns:\n --------\n rcm, vcm: 2 arrays containing the coordinates and velocities of\n the center of mass with reference to a (0,0,0) point.\n\n '
xCM = 0.0
yCM = 0.0
zCM = 0.0
xyz = self.pos
vxyz = self.vel
N_i = len(xyz)
N = N_i
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
while (((np.sqrt(((((xCM_new - xCM) ** 2) + ((yCM_new - yCM) ** 2)) + ((zCM_new - zCM) ** 2))) > delta) & (N > (N_i * 0.01))) | (N > 1000)):
xCM = xCM_new
yCM = yCM_new
zCM = zCM_new
R = np.sqrt(((((xyz[(:, 0)] - xCM_new) ** 2) + ((xyz[(:, 1)] - yCM_new) ** 2)) + ((xyz[(:, 2)] - zCM_new) ** 2)))
Rmax = np.max(R)
index = np.where((R < (Rmax * 0.75)))[0]
xyz = xyz[index]
vxyz = vxyz[index]
m = m[index]
N = len(xyz)
(rCOM, vCOM) = self.COM(xyz, vxyz, m)
(xCM_new, yCM_new, zCM_new) = rCOM
(vxCM_new, vyCM_new, vzCM_new) = vCOM
if (self.prop == 'pos'):
(i_com, j_com, k_com) = (xCM_new, yCM_new, zCM_new)
elif (self.prop == 'vel'):
print('this is not implemented yet')
return np.array([i_com, j_com, k_com])<|docstring|>Compute the center of mass coordinates and velocities of a halo
using the Shrinking Sphere Method Power et al 2003.
It iterates in radii until reach a convergence given by delta
or 1% of the total number of particles.
Parameters:
-----------
xyz: cartesian coordinates with shape (n,3)
vxys: cartesian velocities with shape (n,3)
delta(optional): Precision of the CM, D=0.025
Returns:
--------
rcm, vcm: 2 arrays containing the coordinates and velocities of
the center of mass with reference to a (0,0,0) point.<|endoftext|> |
914d32861ecc6e62cf8c1dacef0c9e5c6dc883ab5b92909bfa392a5a2fbff771 | def com_disk_potential(self, v_rad=2):
'\n Function to compute the COM of the disk using the most bound particles\n within a sphere of 2 kpc.\n \n Parameters:\n ----------\n v_rad : float\n Radius of the sphere in kpc (default : 2 kpc)\n\n '
min_pot = np.where((self.pot_disk == min(self.pot_disk)))[0]
x_min = self.pos_disk[(min_pot, 0)]
y_min = self.pos_disk[(min_pot, 1)]
z_min = self.pos_disk[(min_pot, 2)]
avg_particles = np.where((np.sqrt(((((self.pos_disk[(:, 0)] - x_min) ** 2.0) + ((self.pos_disk[(:, 1)] - y_min) ** 2.0)) + ((self.pos_disk[(:, 2)] - z_min) ** 2.0))) < v_rad))[0]
vx_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
vy_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
vz_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
if (self.prop == 'pos'):
i_cm = (sum(self.pos_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.pos_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.pos_disk[(avg_particles, 2)]) / len(avg_particles))
elif (self.prop == 'vel'):
i_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
return np.array([i_cm, j_cm, k_cm]) | Function to compute the COM of the disk using the most bound particles
within a sphere of 2 kpc.
Parameters:
----------
v_rad : float
Radius of the sphere in kpc (default : 2 kpc) | jellyfish/reading_snapshots.py | com_disk_potential | ekta1224/jellyfish | 0 | python | def com_disk_potential(self, v_rad=2):
'\n Function to compute the COM of the disk using the most bound particles\n within a sphere of 2 kpc.\n \n Parameters:\n ----------\n v_rad : float\n Radius of the sphere in kpc (default : 2 kpc)\n\n '
min_pot = np.where((self.pot_disk == min(self.pot_disk)))[0]
x_min = self.pos_disk[(min_pot, 0)]
y_min = self.pos_disk[(min_pot, 1)]
z_min = self.pos_disk[(min_pot, 2)]
avg_particles = np.where((np.sqrt(((((self.pos_disk[(:, 0)] - x_min) ** 2.0) + ((self.pos_disk[(:, 1)] - y_min) ** 2.0)) + ((self.pos_disk[(:, 2)] - z_min) ** 2.0))) < v_rad))[0]
vx_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
vy_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
vz_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
if (self.prop == 'pos'):
i_cm = (sum(self.pos_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.pos_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.pos_disk[(avg_particles, 2)]) / len(avg_particles))
elif (self.prop == 'vel'):
i_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
return np.array([i_cm, j_cm, k_cm]) | def com_disk_potential(self, v_rad=2):
'\n Function to compute the COM of the disk using the most bound particles\n within a sphere of 2 kpc.\n \n Parameters:\n ----------\n v_rad : float\n Radius of the sphere in kpc (default : 2 kpc)\n\n '
min_pot = np.where((self.pot_disk == min(self.pot_disk)))[0]
x_min = self.pos_disk[(min_pot, 0)]
y_min = self.pos_disk[(min_pot, 1)]
z_min = self.pos_disk[(min_pot, 2)]
avg_particles = np.where((np.sqrt(((((self.pos_disk[(:, 0)] - x_min) ** 2.0) + ((self.pos_disk[(:, 1)] - y_min) ** 2.0)) + ((self.pos_disk[(:, 2)] - z_min) ** 2.0))) < v_rad))[0]
vx_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
vy_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
vz_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
if (self.prop == 'pos'):
i_cm = (sum(self.pos_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.pos_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.pos_disk[(avg_particles, 2)]) / len(avg_particles))
elif (self.prop == 'vel'):
i_cm = (sum(self.vel_disk[(avg_particles, 0)]) / len(avg_particles))
j_cm = (sum(self.vel_disk[(avg_particles, 1)]) / len(avg_particles))
k_cm = (sum(self.vel_disk[(avg_particles, 2)]) / len(avg_particles))
return np.array([i_cm, j_cm, k_cm])<|docstring|>Function to compute the COM of the disk using the most bound particles
within a sphere of 2 kpc.
Parameters:
----------
v_rad : float
Radius of the sphere in kpc (default : 2 kpc)<|endoftext|> |
e0739df7120261df547663e1ad07dab5c487a79b739f6b590f932ff4a7df5cd5 | def re_center(self, vec, com):
'\n Re center vector to a given com.\n '
vec_new = np.copy(vec)
vec_new[(:, 0)] = (vec[(:, 0)] - com[0])
vec_new[(:, 1)] = (vec[(:, 1)] - com[1])
vec_new[(:, 2)] = (vec[(:, 2)] - com[2])
return vec_new | Re center vector to a given com. | jellyfish/reading_snapshots.py | re_center | ekta1224/jellyfish | 0 | python | def re_center(self, vec, com):
'\n \n '
vec_new = np.copy(vec)
vec_new[(:, 0)] = (vec[(:, 0)] - com[0])
vec_new[(:, 1)] = (vec[(:, 1)] - com[1])
vec_new[(:, 2)] = (vec[(:, 2)] - com[2])
return vec_new | def re_center(self, vec, com):
'\n \n '
vec_new = np.copy(vec)
vec_new[(:, 0)] = (vec[(:, 0)] - com[0])
vec_new[(:, 1)] = (vec[(:, 1)] - com[1])
vec_new[(:, 2)] = (vec[(:, 2)] - com[2])
return vec_new<|docstring|>Re center vector to a given com.<|endoftext|> |
f534b9bb5eddfa3f86a370a7528100031350e394269461fa9bedf4de45a99d47 | def read_MW_snap_com_coordinates(self, delta=0.025):
'\n Returns the MW properties.\n \n Parameters:\n path : str\n Path to the simulations\n snap : name of the snapshot\n LMC : boolean\n True or False if LMC is present on the snapshot.\n N_halo_part : int\n Number of particles in the MW halo.\n pot : boolean\n True or False if you want the potential back.\n \n Returns:\n --------\n MWpos : \n MWvel : \n MWpot : \n \n\n '
if ((self.component == 'host_dm') | (self.component == 'sat_dm')):
pos = readsnap((self.path + self.snap), 'pos', 'dm')
vel = readsnap((self.path + self.snap), 'vel', 'dm')
ids = readsnap((self.path + self.snap), 'pid', 'dm')
y = readsnap((self.path + self.snap), self.prop, 'dm')
if (self.component == 'host_dm'):
ids_host = self.host_particles(ids, self.host_npart)
x = y[ids_host]
elif (self.component == 'sat_dm'):
ids_sat = self.sat_particles(ids, self.host_npart)
x = y[ids_sat]
else:
x = readsnap((self.path + self.snap), self.prop, self.component)
if (self.com == 'com_host_disk'):
self.pos_disk = readsnap((self.path + self.snap), 'pos', 'disk')
self.vel_disk = readsnap((self.path + self.snap), 'vel', 'disk')
self.pot_disk = readsnap((self.path + self.snap), 'pot', 'disk')
com = self.com_disk_potential()
x = self.re_center(x, com)
elif (self.com == 'com_sat'):
print('Computing COM of the Satellite using Shrinking Sphere Algorithm')
self.pos = readsnap((self.path + self.snap), 'pos', 'dm')
self.vel = readsnap((self.path + self.snap), 'vel', 'dm')
com = self.com_shrinking_sphere(m=np.ones(len(self.pos)), delta=delta)
print('Satellite COM computed with the Shrinking Sphere Algorithm at', com)
x = self.re_center(x, com)
elif (type(self.com) != str):
x = self.re_center(x, self.com)
return x | Returns the MW properties.
Parameters:
path : str
Path to the simulations
snap : name of the snapshot
LMC : boolean
True or False if LMC is present on the snapshot.
N_halo_part : int
Number of particles in the MW halo.
pot : boolean
True or False if you want the potential back.
Returns:
--------
MWpos :
MWvel :
MWpot : | jellyfish/reading_snapshots.py | read_MW_snap_com_coordinates | ekta1224/jellyfish | 0 | python | def read_MW_snap_com_coordinates(self, delta=0.025):
'\n Returns the MW properties.\n \n Parameters:\n path : str\n Path to the simulations\n snap : name of the snapshot\n LMC : boolean\n True or False if LMC is present on the snapshot.\n N_halo_part : int\n Number of particles in the MW halo.\n pot : boolean\n True or False if you want the potential back.\n \n Returns:\n --------\n MWpos : \n MWvel : \n MWpot : \n \n\n '
if ((self.component == 'host_dm') | (self.component == 'sat_dm')):
pos = readsnap((self.path + self.snap), 'pos', 'dm')
vel = readsnap((self.path + self.snap), 'vel', 'dm')
ids = readsnap((self.path + self.snap), 'pid', 'dm')
y = readsnap((self.path + self.snap), self.prop, 'dm')
if (self.component == 'host_dm'):
ids_host = self.host_particles(ids, self.host_npart)
x = y[ids_host]
elif (self.component == 'sat_dm'):
ids_sat = self.sat_particles(ids, self.host_npart)
x = y[ids_sat]
else:
x = readsnap((self.path + self.snap), self.prop, self.component)
if (self.com == 'com_host_disk'):
self.pos_disk = readsnap((self.path + self.snap), 'pos', 'disk')
self.vel_disk = readsnap((self.path + self.snap), 'vel', 'disk')
self.pot_disk = readsnap((self.path + self.snap), 'pot', 'disk')
com = self.com_disk_potential()
x = self.re_center(x, com)
elif (self.com == 'com_sat'):
print('Computing COM of the Satellite using Shrinking Sphere Algorithm')
self.pos = readsnap((self.path + self.snap), 'pos', 'dm')
self.vel = readsnap((self.path + self.snap), 'vel', 'dm')
com = self.com_shrinking_sphere(m=np.ones(len(self.pos)), delta=delta)
print('Satellite COM computed with the Shrinking Sphere Algorithm at', com)
x = self.re_center(x, com)
elif (type(self.com) != str):
x = self.re_center(x, self.com)
return x | def read_MW_snap_com_coordinates(self, delta=0.025):
'\n Returns the MW properties.\n \n Parameters:\n path : str\n Path to the simulations\n snap : name of the snapshot\n LMC : boolean\n True or False if LMC is present on the snapshot.\n N_halo_part : int\n Number of particles in the MW halo.\n pot : boolean\n True or False if you want the potential back.\n \n Returns:\n --------\n MWpos : \n MWvel : \n MWpot : \n \n\n '
if ((self.component == 'host_dm') | (self.component == 'sat_dm')):
pos = readsnap((self.path + self.snap), 'pos', 'dm')
vel = readsnap((self.path + self.snap), 'vel', 'dm')
ids = readsnap((self.path + self.snap), 'pid', 'dm')
y = readsnap((self.path + self.snap), self.prop, 'dm')
if (self.component == 'host_dm'):
ids_host = self.host_particles(ids, self.host_npart)
x = y[ids_host]
elif (self.component == 'sat_dm'):
ids_sat = self.sat_particles(ids, self.host_npart)
x = y[ids_sat]
else:
x = readsnap((self.path + self.snap), self.prop, self.component)
if (self.com == 'com_host_disk'):
self.pos_disk = readsnap((self.path + self.snap), 'pos', 'disk')
self.vel_disk = readsnap((self.path + self.snap), 'vel', 'disk')
self.pot_disk = readsnap((self.path + self.snap), 'pot', 'disk')
com = self.com_disk_potential()
x = self.re_center(x, com)
elif (self.com == 'com_sat'):
print('Computing COM of the Satellite using Shrinking Sphere Algorithm')
self.pos = readsnap((self.path + self.snap), 'pos', 'dm')
self.vel = readsnap((self.path + self.snap), 'vel', 'dm')
com = self.com_shrinking_sphere(m=np.ones(len(self.pos)), delta=delta)
print('Satellite COM computed with the Shrinking Sphere Algorithm at', com)
x = self.re_center(x, com)
elif (type(self.com) != str):
x = self.re_center(x, self.com)
return x<|docstring|>Returns the MW properties.
Parameters:
path : str
Path to the simulations
snap : name of the snapshot
LMC : boolean
True or False if LMC is present on the snapshot.
N_halo_part : int
Number of particles in the MW halo.
pot : boolean
True or False if you want the potential back.
Returns:
--------
MWpos :
MWvel :
MWpot :<|endoftext|> |
8d3d086dd24c265564904e5ee3db85b8b8351856a30ebd87adca75b872efdb09 | @manager.command
def create_db():
'\n Creates the db tables\n '
db.create_all() | Creates the db tables | manage.py | create_db | grickly-nyu/grickly | 3 | python | @manager.command
def create_db():
'\n \n '
db.create_all() | @manager.command
def create_db():
'\n \n '
db.create_all()<|docstring|>Creates the db tables<|endoftext|> |
c65d3b15c39cba9e7c59aa2f6a0f2c3756c928a92fe3f8130e4294135762db14 | @manager.command
def runserver():
'\n Run in test mode (localhost)\n '
socketio.run(app) | Run in test mode (localhost) | manage.py | runserver | grickly-nyu/grickly | 3 | python | @manager.command
def runserver():
'\n \n '
socketio.run(app) | @manager.command
def runserver():
'\n \n '
socketio.run(app)<|docstring|>Run in test mode (localhost)<|endoftext|> |
41eadbad9c3f2fb4b33faa56d640675f414891bae05361649ed67171e6e21826 | @manager.command
def deploy():
'\n For server deploy only; will let the server be discoverable by ip other than localhost\n '
socketio.run(app, host='0.0.0.0') | For server deploy only; will let the server be discoverable by ip other than localhost | manage.py | deploy | grickly-nyu/grickly | 3 | python | @manager.command
def deploy():
'\n \n '
socketio.run(app, host='0.0.0.0') | @manager.command
def deploy():
'\n \n '
socketio.run(app, host='0.0.0.0')<|docstring|>For server deploy only; will let the server be discoverable by ip other than localhost<|endoftext|> |
cf90ee40afd92d46276a5f3610540818253761a5afea509b7709aab435e79450 | def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
'\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n '
if normalize:
cm = (cm.astype('float') / cm.sum(axis=1)[(:, np.newaxis)])
print('Confusion matrix')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = ('.2f' if normalize else 'd')
thresh = (cm.max() / 2.0)
for (i, j) in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[(i, j)], fmt), horizontalalignment='center', color=('white' if (cm[(i, j)] > thresh) else 'black'))
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`. | tools/confusion.py | plot_confusion_matrix | phamducgiam/fasttext.js | 0 | python | def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
'\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n '
if normalize:
cm = (cm.astype('float') / cm.sum(axis=1)[(:, np.newaxis)])
print('Confusion matrix')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = ('.2f' if normalize else 'd')
thresh = (cm.max() / 2.0)
for (i, j) in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[(i, j)], fmt), horizontalalignment='center', color=('white' if (cm[(i, j)] > thresh) else 'black'))
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label') | def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
'\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n '
if normalize:
cm = (cm.astype('float') / cm.sum(axis=1)[(:, np.newaxis)])
print('Confusion matrix')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = ('.2f' if normalize else 'd')
thresh = (cm.max() / 2.0)
for (i, j) in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[(i, j)], fmt), horizontalalignment='center', color=('white' if (cm[(i, j)] > thresh) else 'black'))
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')<|docstring|>This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.<|endoftext|> |
c9c7581b41cc7e69acc632e214ff81122461cfb693b930d3a01011f95ae55d2d | def parse_labels(path):
'\n parse labels into a numpy array\n label column is the first\n label format is __label__NAME\n Currently there is a known issue\n @see https://stackoverflow.com/questions/54963463/python-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape\n '
with open(path, 'r') as f:
return np.array(list(map((lambda x: x[9:]), f.read().decode('utf8').split()))) | parse labels into a numpy array
label column is the first
label format is __label__NAME
Currently there is a known issue
@see https://stackoverflow.com/questions/54963463/python-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape | tools/confusion.py | parse_labels | phamducgiam/fasttext.js | 0 | python | def parse_labels(path):
'\n parse labels into a numpy array\n label column is the first\n label format is __label__NAME\n Currently there is a known issue\n @see https://stackoverflow.com/questions/54963463/python-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape\n '
with open(path, 'r') as f:
return np.array(list(map((lambda x: x[9:]), f.read().decode('utf8').split()))) | def parse_labels(path):
'\n parse labels into a numpy array\n label column is the first\n label format is __label__NAME\n Currently there is a known issue\n @see https://stackoverflow.com/questions/54963463/python-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape\n '
with open(path, 'r') as f:
return np.array(list(map((lambda x: x[9:]), f.read().decode('utf8').split())))<|docstring|>parse labels into a numpy array
label column is the first
label format is __label__NAME
Currently there is a known issue
@see https://stackoverflow.com/questions/54963463/python-valueerror-shape-mismatch-objects-cannot-be-broadcast-to-a-single-shape<|endoftext|> |
873da40651aabab87095a366f2be6d4b80346ffd4b3875ce322a3288b142eeb7 | @callback
def async_describe_on_off_states(hass: HomeAssistant, registry: GroupIntegrationRegistry) -> None:
'Describe group on off states.'
registry.on_off_states((set(HVAC_MODES) - {HVACMode.OFF}), STATE_OFF) | Describe group on off states. | homeassistant/components/climate/group.py | async_describe_on_off_states | a-p-z/core | 30,023 | python | @callback
def async_describe_on_off_states(hass: HomeAssistant, registry: GroupIntegrationRegistry) -> None:
registry.on_off_states((set(HVAC_MODES) - {HVACMode.OFF}), STATE_OFF) | @callback
def async_describe_on_off_states(hass: HomeAssistant, registry: GroupIntegrationRegistry) -> None:
registry.on_off_states((set(HVAC_MODES) - {HVACMode.OFF}), STATE_OFF)<|docstring|>Describe group on off states.<|endoftext|> |
59df437a1d14e186d86dcbea824bc964f3b9c5ba015c3eec62cf2a3848028917 | def download_audio(url):
"\n Uses youtube_dl to get info about the video and download the audio using requests\n :param url: YouTube's video url (include http:// )\n :return: (filename, info)\n "
info = get_info(url)
files = audio_urls(info)
file = files[(- 2)]
filename = download(file[2], '{}_{}.{}'.format(info['id'], file[1], file[3]))
with open((filename + '.json'), 'w') as f:
f.write(json.dumps(info))
return (filename, info) | Uses youtube_dl to get info about the video and download the audio using requests
:param url: YouTube's video url (include http:// )
:return: (filename, info) | yufonium/yufonium/__init__.py | download_audio | zuik/stuff | 0 | python | def download_audio(url):
"\n Uses youtube_dl to get info about the video and download the audio using requests\n :param url: YouTube's video url (include http:// )\n :return: (filename, info)\n "
info = get_info(url)
files = audio_urls(info)
file = files[(- 2)]
filename = download(file[2], '{}_{}.{}'.format(info['id'], file[1], file[3]))
with open((filename + '.json'), 'w') as f:
f.write(json.dumps(info))
return (filename, info) | def download_audio(url):
"\n Uses youtube_dl to get info about the video and download the audio using requests\n :param url: YouTube's video url (include http:// )\n :return: (filename, info)\n "
info = get_info(url)
files = audio_urls(info)
file = files[(- 2)]
filename = download(file[2], '{}_{}.{}'.format(info['id'], file[1], file[3]))
with open((filename + '.json'), 'w') as f:
f.write(json.dumps(info))
return (filename, info)<|docstring|>Uses youtube_dl to get info about the video and download the audio using requests
:param url: YouTube's video url (include http:// )
:return: (filename, info)<|endoftext|> |
c0cf624e84228a9251712314c742c85de768a75dbf0775ddcc233e4ce147fa75 | def parse_urls(soup, response_url):
' get urls from soup; return a list '
for a in soup.find_all('a'):
url = urljoin(response_url, a.get('href'))
if (('meinv' in url) and ('www.tupianzj.com' in url)):
(yield url) | get urls from soup; return a list | TupianzjSpider/spider.py | parse_urls | ruxtain/spiders | 3 | python | def parse_urls(soup, response_url):
' '
for a in soup.find_all('a'):
url = urljoin(response_url, a.get('href'))
if (('meinv' in url) and ('www.tupianzj.com' in url)):
(yield url) | def parse_urls(soup, response_url):
' '
for a in soup.find_all('a'):
url = urljoin(response_url, a.get('href'))
if (('meinv' in url) and ('www.tupianzj.com' in url)):
(yield url)<|docstring|>get urls from soup; return a list<|endoftext|> |
29f0e36837108a2f90a3ac67807ea19037a59766d0b1d6e93c74a3d067db9563 | async def init(urls_queue):
' 为队列添加第一个链接\n '
for url in starter.start_urls:
(await urls_queue.put(url)) | 为队列添加第一个链接 | TupianzjSpider/spider.py | init | ruxtain/spiders | 3 | python | async def init(urls_queue):
' \n '
for url in starter.start_urls:
(await urls_queue.put(url)) | async def init(urls_queue):
' \n '
for url in starter.start_urls:
(await urls_queue.put(url))<|docstring|>为队列添加第一个链接<|endoftext|> |
6947aa6e749f6c8032e6bc1a905a2c6a5c37fb8e4c5dd8c9d41723f751f4547a | def create_gemm_operator(tile_descriptions, data_type, alignment_constraints, swizzling_functor=SwizzlingFunctor.Identity8, batched=False):
'Exhaustively instantiate all kernels from a given configuration.'
ret = []
kernel_emitter = EmitGemmInstance()
profiler_emitter = GemmProfilerEmitter()
(element_a, element_b, element_c, element_epilogue) = data_type
if batched:
swizzling_functor = SwizzlingFunctor.Batched
layouts = [(LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.RowMajor)]
for layout in layouts:
for tile_description in tile_descriptions:
for alignment in alignment_constraints:
alignment_c = min(8, alignment)
A = TensorDescription(element_a, layout[0], alignment)
B = TensorDescription(element_b, layout[1], alignment)
C = TensorDescription(element_c, layout[2], alignment_c)
op_entry = {}
op = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombination, swizzling_functor)
op_bias = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationBias, swizzling_functor)
op_bias_relu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationRelu, swizzling_functor)
op_bias_gelu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationGelu, swizzling_functor)
op_entry['op'] = op
op_entry['name'] = op.procedural_name()
op_entry['opdef'] = kernel_emitter.emit(op, batched=batched)
op_entry['opdef_bias'] = kernel_emitter.emit(op_bias, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_relu'] = kernel_emitter.emit(op_bias_relu, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_gelu'] = kernel_emitter.emit(op_bias_gelu, batched=batched)
op_entry['src'] = profiler_emitter.emit(op.procedural_name(), kernel_emitter.emit(op, batched=False), DataTypeTag[element_a], DataTypeTag[element_b], DataTypeTag[element_c], op.leading_dim())
op_entry['runtime'] = 9999999
op_entry['tile_description'] = tile_description
op_entry['alignment'] = alignment
op_entry['data_type'] = data_type
ret.append(op_entry)
return ret | Exhaustively instantiate all kernels from a given configuration. | python/tvm/contrib/cutlass/gen_gemm.py | create_gemm_operator | sunwayforever/tvm | 8 | python | def create_gemm_operator(tile_descriptions, data_type, alignment_constraints, swizzling_functor=SwizzlingFunctor.Identity8, batched=False):
ret = []
kernel_emitter = EmitGemmInstance()
profiler_emitter = GemmProfilerEmitter()
(element_a, element_b, element_c, element_epilogue) = data_type
if batched:
swizzling_functor = SwizzlingFunctor.Batched
layouts = [(LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.RowMajor)]
for layout in layouts:
for tile_description in tile_descriptions:
for alignment in alignment_constraints:
alignment_c = min(8, alignment)
A = TensorDescription(element_a, layout[0], alignment)
B = TensorDescription(element_b, layout[1], alignment)
C = TensorDescription(element_c, layout[2], alignment_c)
op_entry = {}
op = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombination, swizzling_functor)
op_bias = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationBias, swizzling_functor)
op_bias_relu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationRelu, swizzling_functor)
op_bias_gelu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationGelu, swizzling_functor)
op_entry['op'] = op
op_entry['name'] = op.procedural_name()
op_entry['opdef'] = kernel_emitter.emit(op, batched=batched)
op_entry['opdef_bias'] = kernel_emitter.emit(op_bias, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_relu'] = kernel_emitter.emit(op_bias_relu, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_gelu'] = kernel_emitter.emit(op_bias_gelu, batched=batched)
op_entry['src'] = profiler_emitter.emit(op.procedural_name(), kernel_emitter.emit(op, batched=False), DataTypeTag[element_a], DataTypeTag[element_b], DataTypeTag[element_c], op.leading_dim())
op_entry['runtime'] = 9999999
op_entry['tile_description'] = tile_description
op_entry['alignment'] = alignment
op_entry['data_type'] = data_type
ret.append(op_entry)
return ret | def create_gemm_operator(tile_descriptions, data_type, alignment_constraints, swizzling_functor=SwizzlingFunctor.Identity8, batched=False):
ret = []
kernel_emitter = EmitGemmInstance()
profiler_emitter = GemmProfilerEmitter()
(element_a, element_b, element_c, element_epilogue) = data_type
if batched:
swizzling_functor = SwizzlingFunctor.Batched
layouts = [(LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.RowMajor)]
for layout in layouts:
for tile_description in tile_descriptions:
for alignment in alignment_constraints:
alignment_c = min(8, alignment)
A = TensorDescription(element_a, layout[0], alignment)
B = TensorDescription(element_b, layout[1], alignment)
C = TensorDescription(element_c, layout[2], alignment_c)
op_entry = {}
op = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombination, swizzling_functor)
op_bias = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationBias, swizzling_functor)
op_bias_relu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationRelu, swizzling_functor)
op_bias_gelu = GemmOperation(tile_description.minimum_compute_capability, tile_description, A, B, C, element_epilogue, EpilogueFunctor.LinearCombinationGelu, swizzling_functor)
op_entry['op'] = op
op_entry['name'] = op.procedural_name()
op_entry['opdef'] = kernel_emitter.emit(op, batched=batched)
op_entry['opdef_bias'] = kernel_emitter.emit(op_bias, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_relu'] = kernel_emitter.emit(op_bias_relu, no_beta_scaling=True, batched=batched)
op_entry['opdef_bias_gelu'] = kernel_emitter.emit(op_bias_gelu, batched=batched)
op_entry['src'] = profiler_emitter.emit(op.procedural_name(), kernel_emitter.emit(op, batched=False), DataTypeTag[element_a], DataTypeTag[element_b], DataTypeTag[element_c], op.leading_dim())
op_entry['runtime'] = 9999999
op_entry['tile_description'] = tile_description
op_entry['alignment'] = alignment
op_entry['data_type'] = data_type
ret.append(op_entry)
return ret<|docstring|>Exhaustively instantiate all kernels from a given configuration.<|endoftext|> |
92f7b48c6dcb58aea4902df3317911f99ac40f9a49616079e8f29614bbd365e9 | def check_align(self, op_name, M):
'Filter out kernels that cannot be supported.'
aligns = re.findall('align[1|2|4|8]', op_name)
assert (len(aligns) == 1)
align = int(aligns[0][(- 1)])
if ((M % align) != 0):
return False
return True | Filter out kernels that cannot be supported. | python/tvm/contrib/cutlass/gen_gemm.py | check_align | sunwayforever/tvm | 8 | python | def check_align(self, op_name, M):
aligns = re.findall('align[1|2|4|8]', op_name)
assert (len(aligns) == 1)
align = int(aligns[0][(- 1)])
if ((M % align) != 0):
return False
return True | def check_align(self, op_name, M):
aligns = re.findall('align[1|2|4|8]', op_name)
assert (len(aligns) == 1)
align = int(aligns[0][(- 1)])
if ((M % align) != 0):
return False
return True<|docstring|>Filter out kernels that cannot be supported.<|endoftext|> |
9f4424d64d9d22bd0bbbbf65ddde0fe51d9a0104e75eda15364fa0e07c57ad47 | def get_default(self, out_dtype, batched=False):
'Return the default kernel for the requested architecture.\n For now, the default kernel was picked arbitrary.\n '
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
default_kernel_name = DEFAULT_KERNELS[self.sm][out_dtype]
filtered = list(filter((lambda op: (op['name'] == default_kernel_name)), ops))
assert (len(filtered) == 1)
return filtered[0] | Return the default kernel for the requested architecture.
For now, the default kernel was picked arbitrary. | python/tvm/contrib/cutlass/gen_gemm.py | get_default | sunwayforever/tvm | 8 | python | def get_default(self, out_dtype, batched=False):
'Return the default kernel for the requested architecture.\n For now, the default kernel was picked arbitrary.\n '
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
default_kernel_name = DEFAULT_KERNELS[self.sm][out_dtype]
filtered = list(filter((lambda op: (op['name'] == default_kernel_name)), ops))
assert (len(filtered) == 1)
return filtered[0] | def get_default(self, out_dtype, batched=False):
'Return the default kernel for the requested architecture.\n For now, the default kernel was picked arbitrary.\n '
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
default_kernel_name = DEFAULT_KERNELS[self.sm][out_dtype]
filtered = list(filter((lambda op: (op['name'] == default_kernel_name)), ops))
assert (len(filtered) == 1)
return filtered[0]<|docstring|>Return the default kernel for the requested architecture.
For now, the default kernel was picked arbitrary.<|endoftext|> |
4794a04b741178cdca87abb619d34a7809750d549087c0ba2afdef248bcb2179 | def profile(self, M, N, K, out_dtype, profile_all=True, use_multiprocessing=False, batched=False):
'Profile and select the best kernel from candidate kernels.\n If profile_all is False, return immediately after the first applicable kernel is found.\n If use_multiprocessing is True, compile all profiler executables in parallel.\n '
if ((M, N, K) in self.cache):
return self.cache[(M, N, K)]
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
ops = list(filter((lambda op: self.check_align(op['name'], M)), ops))
for op in ops:
op['runtime'] = (- 1)
if profile_all:
self.engine.compile_all(ops, use_multiprocessing)
for op in ops:
out = self.engine.evaluate(op, [M, N, K])
op['runtime'] = out
if ((out > 0) and (profile_all is False)):
break
valid_ops = filter((lambda op: (op['runtime'] > 0)), ops)
output = sorted(valid_ops, key=(lambda i: i['runtime']))
self.cache[(M, N, K)] = output[0]
return output[0] | Profile and select the best kernel from candidate kernels.
If profile_all is False, return immediately after the first applicable kernel is found.
If use_multiprocessing is True, compile all profiler executables in parallel. | python/tvm/contrib/cutlass/gen_gemm.py | profile | sunwayforever/tvm | 8 | python | def profile(self, M, N, K, out_dtype, profile_all=True, use_multiprocessing=False, batched=False):
'Profile and select the best kernel from candidate kernels.\n If profile_all is False, return immediately after the first applicable kernel is found.\n If use_multiprocessing is True, compile all profiler executables in parallel.\n '
if ((M, N, K) in self.cache):
return self.cache[(M, N, K)]
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
ops = list(filter((lambda op: self.check_align(op['name'], M)), ops))
for op in ops:
op['runtime'] = (- 1)
if profile_all:
self.engine.compile_all(ops, use_multiprocessing)
for op in ops:
out = self.engine.evaluate(op, [M, N, K])
op['runtime'] = out
if ((out > 0) and (profile_all is False)):
break
valid_ops = filter((lambda op: (op['runtime'] > 0)), ops)
output = sorted(valid_ops, key=(lambda i: i['runtime']))
self.cache[(M, N, K)] = output[0]
return output[0] | def profile(self, M, N, K, out_dtype, profile_all=True, use_multiprocessing=False, batched=False):
'Profile and select the best kernel from candidate kernels.\n If profile_all is False, return immediately after the first applicable kernel is found.\n If use_multiprocessing is True, compile all profiler executables in parallel.\n '
if ((M, N, K) in self.cache):
return self.cache[(M, N, K)]
ops = GENERATOR_FUNC_TABLE[self.sm](out_dtype, op_creator=partial(create_gemm_operator, batched=batched))
ops = list(filter((lambda op: self.check_align(op['name'], M)), ops))
for op in ops:
op['runtime'] = (- 1)
if profile_all:
self.engine.compile_all(ops, use_multiprocessing)
for op in ops:
out = self.engine.evaluate(op, [M, N, K])
op['runtime'] = out
if ((out > 0) and (profile_all is False)):
break
valid_ops = filter((lambda op: (op['runtime'] > 0)), ops)
output = sorted(valid_ops, key=(lambda i: i['runtime']))
self.cache[(M, N, K)] = output[0]
return output[0]<|docstring|>Profile and select the best kernel from candidate kernels.
If profile_all is False, return immediately after the first applicable kernel is found.
If use_multiprocessing is True, compile all profiler executables in parallel.<|endoftext|> |
0fe607529f8b27c2bcb49196647939014b1ffe3a0ae46e2a38e8e81da8b11a55 | @app.route('/')
def index():
'Video streaming home page.'
return render_template('index.html') | Video streaming home page. | app.py | index | Brinon/flask-video-streaming | 0 | python | @app.route('/')
def index():
return render_template('index.html') | @app.route('/')
def index():
return render_template('index.html')<|docstring|>Video streaming home page.<|endoftext|> |
93dc5825ffc0192f62099d5c1e9c3a5e8908b33e98b5ef6e68c50f880f19ca88 | def gen(camera):
'Video streaming generator function.'
while True:
frame = camera.get_frame()
img = cv2.imdecode(np.fromstring(frame, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
print(img.shape)
(yield ((b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame) + b'\r\n')) | Video streaming generator function. | app.py | gen | Brinon/flask-video-streaming | 0 | python | def gen(camera):
while True:
frame = camera.get_frame()
img = cv2.imdecode(np.fromstring(frame, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
print(img.shape)
(yield ((b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame) + b'\r\n')) | def gen(camera):
while True:
frame = camera.get_frame()
img = cv2.imdecode(np.fromstring(frame, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
print(img.shape)
(yield ((b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame) + b'\r\n'))<|docstring|>Video streaming generator function.<|endoftext|> |
0ccc7957bfb3d195b1fa2db2a7b2f20d2a4a1a64dd91bad6d4a1e855e7697a18 | @app.route('/video_feed')
def video_feed():
'Video streaming route. Put this in the src attribute of an img tag.'
return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') | Video streaming route. Put this in the src attribute of an img tag. | app.py | video_feed | Brinon/flask-video-streaming | 0 | python | @app.route('/video_feed')
def video_feed():
return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') | @app.route('/video_feed')
def video_feed():
return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')<|docstring|>Video streaming route. Put this in the src attribute of an img tag.<|endoftext|> |
a056b40ae56be747ddbb0a0743f0cba0c9fd0b9e5df8b958304897c741bd3987 | @app.route('/frame')
def frame():
' returns the latest frame as a str '
frame_str = Camera().get_frame()
return jsonify({'frame': frame_str, 'encoding': 'jpeg'}) | returns the latest frame as a str | app.py | frame | Brinon/flask-video-streaming | 0 | python | @app.route('/frame')
def frame():
' '
frame_str = Camera().get_frame()
return jsonify({'frame': frame_str, 'encoding': 'jpeg'}) | @app.route('/frame')
def frame():
' '
frame_str = Camera().get_frame()
return jsonify({'frame': frame_str, 'encoding': 'jpeg'})<|docstring|>returns the latest frame as a str<|endoftext|> |
f207c1dc821c59004226f9c88231d9de8e620c115d6f09393478ddcc12715b96 | def __init__(self, crypto_key, hash_key, server_iv, client_iv):
'\n Initialize Auxiliary Stream Crypto-context.\n '
self._encrypt_key = crypto_key
self._hash_key = hash_key
self._server_iv = server_iv
self._client_iv = client_iv
self._server_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._server_iv), backend=AuxiliaryStreamCrypto._backend)
self._server_encryptor = self._server_cipher.encryptor()
self._server_decryptor = self._server_cipher.decryptor()
self._client_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._client_iv), backend=AuxiliaryStreamCrypto._backend)
self._client_encryptor = self._client_cipher.encryptor()
self._client_decryptor = self._client_cipher.decryptor() | Initialize Auxiliary Stream Crypto-context. | xbox/auxiliary/crypto.py | __init__ | yomeaqu/OpenXboxj | 66 | python | def __init__(self, crypto_key, hash_key, server_iv, client_iv):
'\n \n '
self._encrypt_key = crypto_key
self._hash_key = hash_key
self._server_iv = server_iv
self._client_iv = client_iv
self._server_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._server_iv), backend=AuxiliaryStreamCrypto._backend)
self._server_encryptor = self._server_cipher.encryptor()
self._server_decryptor = self._server_cipher.decryptor()
self._client_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._client_iv), backend=AuxiliaryStreamCrypto._backend)
self._client_encryptor = self._client_cipher.encryptor()
self._client_decryptor = self._client_cipher.decryptor() | def __init__(self, crypto_key, hash_key, server_iv, client_iv):
'\n \n '
self._encrypt_key = crypto_key
self._hash_key = hash_key
self._server_iv = server_iv
self._client_iv = client_iv
self._server_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._server_iv), backend=AuxiliaryStreamCrypto._backend)
self._server_encryptor = self._server_cipher.encryptor()
self._server_decryptor = self._server_cipher.decryptor()
self._client_cipher = Cipher(algorithms.AES(self._encrypt_key), modes.CBC(self._client_iv), backend=AuxiliaryStreamCrypto._backend)
self._client_encryptor = self._client_cipher.encryptor()
self._client_decryptor = self._client_cipher.decryptor()<|docstring|>Initialize Auxiliary Stream Crypto-context.<|endoftext|> |
a468e5c9f9ccb8b164bdbecf6a7690588b2178fb8579c427cdc315da20873303 | @classmethod
def from_connection_info(cls, connection_info):
'\n Initialize Crypto context via AuxiliaryStream-message\n connection info.\n '
return cls(connection_info.crypto_key, connection_info.sign_hash, connection_info.server_iv, connection_info.client_iv) | Initialize Crypto context via AuxiliaryStream-message
connection info. | xbox/auxiliary/crypto.py | from_connection_info | yomeaqu/OpenXboxj | 66 | python | @classmethod
def from_connection_info(cls, connection_info):
'\n Initialize Crypto context via AuxiliaryStream-message\n connection info.\n '
return cls(connection_info.crypto_key, connection_info.sign_hash, connection_info.server_iv, connection_info.client_iv) | @classmethod
def from_connection_info(cls, connection_info):
'\n Initialize Crypto context via AuxiliaryStream-message\n connection info.\n '
return cls(connection_info.crypto_key, connection_info.sign_hash, connection_info.server_iv, connection_info.client_iv)<|docstring|>Initialize Crypto context via AuxiliaryStream-message
connection info.<|endoftext|> |
407019fb5d45d7cf013b8f3e64263696c32853cbbbe17c6b355efd62fa290595 | def encrypt(self, plaintext):
'\n Encrypts plaintext with AES-128-CBC\n\n No padding is added here, data has to be aligned to\n block size (16 bytes).\n\n Args:\n plaintext (bytes): The plaintext to encrypt.\n\n Returns:\n bytes: Encrypted Data\n '
return AuxiliaryStreamCrypto._crypt(self._client_encryptor, plaintext) | Encrypts plaintext with AES-128-CBC
No padding is added here, data has to be aligned to
block size (16 bytes).
Args:
plaintext (bytes): The plaintext to encrypt.
Returns:
bytes: Encrypted Data | xbox/auxiliary/crypto.py | encrypt | yomeaqu/OpenXboxj | 66 | python | def encrypt(self, plaintext):
'\n Encrypts plaintext with AES-128-CBC\n\n No padding is added here, data has to be aligned to\n block size (16 bytes).\n\n Args:\n plaintext (bytes): The plaintext to encrypt.\n\n Returns:\n bytes: Encrypted Data\n '
return AuxiliaryStreamCrypto._crypt(self._client_encryptor, plaintext) | def encrypt(self, plaintext):
'\n Encrypts plaintext with AES-128-CBC\n\n No padding is added here, data has to be aligned to\n block size (16 bytes).\n\n Args:\n plaintext (bytes): The plaintext to encrypt.\n\n Returns:\n bytes: Encrypted Data\n '
return AuxiliaryStreamCrypto._crypt(self._client_encryptor, plaintext)<|docstring|>Encrypts plaintext with AES-128-CBC
No padding is added here, data has to be aligned to
block size (16 bytes).
Args:
plaintext (bytes): The plaintext to encrypt.
Returns:
bytes: Encrypted Data<|endoftext|> |
c9f4a90c5f64c44209cd58057bc089f3b33291f5b1bf5cda0d36c750dc8a0327 | def decrypt(self, ciphertext):
'\n Decrypts ciphertext\n\n No padding is removed here.\n\n Args:\n ciphertext (bytes): Ciphertext to be decrypted\n\n Returns:\n bytes: Decrypted data\n '
return AuxiliaryStreamCrypto._crypt(self._server_decryptor, ciphertext) | Decrypts ciphertext
No padding is removed here.
Args:
ciphertext (bytes): Ciphertext to be decrypted
Returns:
bytes: Decrypted data | xbox/auxiliary/crypto.py | decrypt | yomeaqu/OpenXboxj | 66 | python | def decrypt(self, ciphertext):
'\n Decrypts ciphertext\n\n No padding is removed here.\n\n Args:\n ciphertext (bytes): Ciphertext to be decrypted\n\n Returns:\n bytes: Decrypted data\n '
return AuxiliaryStreamCrypto._crypt(self._server_decryptor, ciphertext) | def decrypt(self, ciphertext):
'\n Decrypts ciphertext\n\n No padding is removed here.\n\n Args:\n ciphertext (bytes): Ciphertext to be decrypted\n\n Returns:\n bytes: Decrypted data\n '
return AuxiliaryStreamCrypto._crypt(self._server_decryptor, ciphertext)<|docstring|>Decrypts ciphertext
No padding is removed here.
Args:
ciphertext (bytes): Ciphertext to be decrypted
Returns:
bytes: Decrypted data<|endoftext|> |
2315feadedd77b0a872a4e20e4d9fb90a5ee60670452c9bf813dc6ce453d078f | def hash(self, data):
'\n Securely hashes data with HMAC SHA-256\n\n Args:\n data (bytes): The data to securely hash.\n\n Returns:\n bytes: Hashed data\n '
return AuxiliaryStreamCrypto._secure_hash(self._hash_key, data) | Securely hashes data with HMAC SHA-256
Args:
data (bytes): The data to securely hash.
Returns:
bytes: Hashed data | xbox/auxiliary/crypto.py | hash | yomeaqu/OpenXboxj | 66 | python | def hash(self, data):
'\n Securely hashes data with HMAC SHA-256\n\n Args:\n data (bytes): The data to securely hash.\n\n Returns:\n bytes: Hashed data\n '
return AuxiliaryStreamCrypto._secure_hash(self._hash_key, data) | def hash(self, data):
'\n Securely hashes data with HMAC SHA-256\n\n Args:\n data (bytes): The data to securely hash.\n\n Returns:\n bytes: Hashed data\n '
return AuxiliaryStreamCrypto._secure_hash(self._hash_key, data)<|docstring|>Securely hashes data with HMAC SHA-256
Args:
data (bytes): The data to securely hash.
Returns:
bytes: Hashed data<|endoftext|> |
42186a82bf66d48398d99330abb3fcbf6276ae81500a0cce8dc7ee7ab4fe3fa8 | def verify(self, data, secure_hash):
'\n Verifies that the given data generates the given secure_hash\n\n Args:\n data (bytes): The data to validate.\n secure_hash (bytes): The secure hash to validate against.\n\n Returns:\n bool: True on success, False otherwise\n '
return (secure_hash == self.hash(data)) | Verifies that the given data generates the given secure_hash
Args:
data (bytes): The data to validate.
secure_hash (bytes): The secure hash to validate against.
Returns:
bool: True on success, False otherwise | xbox/auxiliary/crypto.py | verify | yomeaqu/OpenXboxj | 66 | python | def verify(self, data, secure_hash):
'\n Verifies that the given data generates the given secure_hash\n\n Args:\n data (bytes): The data to validate.\n secure_hash (bytes): The secure hash to validate against.\n\n Returns:\n bool: True on success, False otherwise\n '
return (secure_hash == self.hash(data)) | def verify(self, data, secure_hash):
'\n Verifies that the given data generates the given secure_hash\n\n Args:\n data (bytes): The data to validate.\n secure_hash (bytes): The secure hash to validate against.\n\n Returns:\n bool: True on success, False otherwise\n '
return (secure_hash == self.hash(data))<|docstring|>Verifies that the given data generates the given secure_hash
Args:
data (bytes): The data to validate.
secure_hash (bytes): The secure hash to validate against.
Returns:
bool: True on success, False otherwise<|endoftext|> |
21f5f48c666660c5baed37c1c82a77cb6f51f621f4f84f684918fc51e0e2da80 | def check_rstudio_connect() -> bool:
'Returns True if running in RStudio Connect'
checks = [(environ.get('RSTUDIO_PRODUCT') == 'CONNECT'), ('RSTUDIO_CONNECT_HASTE' in environ.keys()), (getcwd() == '/opt/rstudio-connect/mnt/app'), (environ.get('LOGNAME') == 'rstudio-connect'), (environ.get('TMPDIR') == '/opt/rstudio-connect/mnt/tmp')]
rstudio_connect = any(checks)
if rstudio_connect:
logger.debug('We seem to be running in RStudio Connect')
else:
logger.debug("We don't seem to be running in RStudio Connect")
return any(checks) | Returns True if running in RStudio Connect | fastapitableau/rstudio_connect.py | check_rstudio_connect | rstudio/fastapitableau | 2 | python | def check_rstudio_connect() -> bool:
checks = [(environ.get('RSTUDIO_PRODUCT') == 'CONNECT'), ('RSTUDIO_CONNECT_HASTE' in environ.keys()), (getcwd() == '/opt/rstudio-connect/mnt/app'), (environ.get('LOGNAME') == 'rstudio-connect'), (environ.get('TMPDIR') == '/opt/rstudio-connect/mnt/tmp')]
rstudio_connect = any(checks)
if rstudio_connect:
logger.debug('We seem to be running in RStudio Connect')
else:
logger.debug("We don't seem to be running in RStudio Connect")
return any(checks) | def check_rstudio_connect() -> bool:
checks = [(environ.get('RSTUDIO_PRODUCT') == 'CONNECT'), ('RSTUDIO_CONNECT_HASTE' in environ.keys()), (getcwd() == '/opt/rstudio-connect/mnt/app'), (environ.get('LOGNAME') == 'rstudio-connect'), (environ.get('TMPDIR') == '/opt/rstudio-connect/mnt/tmp')]
rstudio_connect = any(checks)
if rstudio_connect:
logger.debug('We seem to be running in RStudio Connect')
else:
logger.debug("We don't seem to be running in RStudio Connect")
return any(checks)<|docstring|>Returns True if running in RStudio Connect<|endoftext|> |
60badad3708be5d32b6d8bea1c226a504e2fe24497c7f1f42cd87189fc758d84 | def warning_message() -> Optional[str]:
'\n Generate a string of warning messages based on information gathered about our environment in RStudio Connect.\n '
if (not check_rstudio_connect()):
return None
message_list: List[str] = []
connect_server = environ.get('CONNECT_SERVER')
if (connect_server is None):
logger.warning('Could not find CONNECT_SERVER environment variable')
message_list.append('\n### The environment variable `CONNECT_SERVER` is not defined\n\nPossible Solutions:\n\n- Have your system administrator confirm `Applications.DefaultServerEnv` is enabled and that `Server.Address` has been defined within the `rstudio-connect.gcfg` file on the RStudio Connect server.,\n- Use the application settings for your content within the RStudio Connect dashboard to define the `CONNECT_SERVER` environment variable. It should be set to a reachable https or http address for the server.\n')
if (urlparse(connect_server).scheme is None):
logger.warning("The CONNECT_SERVER environment variable doesn't specify https:// or http://")
message_list.append(f'''### Environment Variable `CONNECT_SERVER` (value = `{connect_server}` ) does not specify the protocol (`https://` or `http://`)
Possible Solutions:
- Have your system administrator confirm that `Server.Address` has been configured with the proper format within the `rstudio-connect.gcfg` file on the RStudio Connect server.
- Use the application settings for your content within the RStudio Connect dashboard to define the CONNECT_SERVER` environment variable with the proper protocol.
''')
connect_api_key = environ.get('CONNECT_API_KEY')
if (connect_api_key is None):
logger.warning('Could not find CONNECT_API_KEY environment variable')
message_list.append('### The environment variable `CONNECT_API_KEY` is not defined\n\nPossible Solutions:\n\n- Have your administrator enable the `Applications.DefaultAPIKeyEnv` setting within the `rstudio-connect.gcfg` file on the RStudio Connect server.\n- Create an API key yourself and use the application settings for your content within the RStudio Connect dashboard to set the the `CONNECT_API_KEY` variable to its value.\n')
if (len(message_list) != 0):
messages = '\n\n---\n\n'.join(message_list)
return messages
try:
use_http = (environ.get('FASTAPITABLEAU_USE_HTTP', 'False').title() == 'True')
if use_http:
connect_server = urlparse(connect_server)._replace(scheme='http').geturl()
settings_url = (str(connect_server) + '__api__/server_settings')
headers = {'Authorization': ('Key ' + str(connect_api_key))}
response = requests.get(settings_url, headers=headers, verify=(not use_http))
except Exception as e:
logger.warning('Unable to access RStudio Connect settings API due to error: %s', e)
message_list.append(f'''### API request to {connect_server} has failed with error:
{e}
Possible Solutions:
- If you have specified an API key, confirm it is valid.
- Confirm there is connectivity between the server itself and the address assigned to it: {connect_server}.
- If using HTTPS along with self-signed certificates, you may need to allow the FastAPITableau package to use HTTP instead, by setting the environment variable `FASTAPITABLEAU_USE_HTTP` to `True` in the RStudio Connect application settings.''')
else:
if (response.status_code != 200):
logger.warning('Unable to access RStudio Connect settings API with status code: %s', response.status_code)
message_list.append(f'''### API request to {connect_server} has failed with error: {response.text}
Possible Solutions:
- If you have specified an API_KEY, confirm it is valid.
- Confirm the server can be reached at {connect_server}.
''')
else:
server_settings = response.json()
if ('tableau_integration_enabled' not in server_settings.keys()):
logger.warning('The Tableau integration feature flag is not available on this RStudio Connect server')
message_list.append('### Tableau Integration Feature Flag is not available on the RStudio Connect server.\n\nPossible Solution:\n\n- Please upgrade to the latest version of RStudio Connect.\n')
elif (server_settings['tableau_integration_enabled'] is False):
logger.warning('Tableau integration is disabled on this RStudio Connect server')
message_list.append('Tableau Integration has been disabled on the RStudio Connect server\n\nPossible Solution:\n\n- Please ask your administrator to set `TableauIntegration.Enabled` = `true` within `rstudio-connect.gcfg` file on the RStudio Connect server.\n')
if (len(message_list) != 0):
print(message_list)
messages = '\n\n---\n\n'.join(message_list)
return messages
else:
return None | Generate a string of warning messages based on information gathered about our environment in RStudio Connect. | fastapitableau/rstudio_connect.py | warning_message | rstudio/fastapitableau | 2 | python | def warning_message() -> Optional[str]:
'\n \n '
if (not check_rstudio_connect()):
return None
message_list: List[str] = []
connect_server = environ.get('CONNECT_SERVER')
if (connect_server is None):
logger.warning('Could not find CONNECT_SERVER environment variable')
message_list.append('\n### The environment variable `CONNECT_SERVER` is not defined\n\nPossible Solutions:\n\n- Have your system administrator confirm `Applications.DefaultServerEnv` is enabled and that `Server.Address` has been defined within the `rstudio-connect.gcfg` file on the RStudio Connect server.,\n- Use the application settings for your content within the RStudio Connect dashboard to define the `CONNECT_SERVER` environment variable. It should be set to a reachable https or http address for the server.\n')
if (urlparse(connect_server).scheme is None):
logger.warning("The CONNECT_SERVER environment variable doesn't specify https:// or http://")
message_list.append(f'### Environment Variable `CONNECT_SERVER` (value = `{connect_server}` ) does not specify the protocol (`https://` or `http://`)
Possible Solutions:
- Have your system administrator confirm that `Server.Address` has been configured with the proper format within the `rstudio-connect.gcfg` file on the RStudio Connect server.
- Use the application settings for your content within the RStudio Connect dashboard to define the CONNECT_SERVER` environment variable with the proper protocol.
')
connect_api_key = environ.get('CONNECT_API_KEY')
if (connect_api_key is None):
logger.warning('Could not find CONNECT_API_KEY environment variable')
message_list.append('### The environment variable `CONNECT_API_KEY` is not defined\n\nPossible Solutions:\n\n- Have your administrator enable the `Applications.DefaultAPIKeyEnv` setting within the `rstudio-connect.gcfg` file on the RStudio Connect server.\n- Create an API key yourself and use the application settings for your content within the RStudio Connect dashboard to set the the `CONNECT_API_KEY` variable to its value.\n')
if (len(message_list) != 0):
messages = '\n\n---\n\n'.join(message_list)
return messages
try:
use_http = (environ.get('FASTAPITABLEAU_USE_HTTP', 'False').title() == 'True')
if use_http:
connect_server = urlparse(connect_server)._replace(scheme='http').geturl()
settings_url = (str(connect_server) + '__api__/server_settings')
headers = {'Authorization': ('Key ' + str(connect_api_key))}
response = requests.get(settings_url, headers=headers, verify=(not use_http))
except Exception as e:
logger.warning('Unable to access RStudio Connect settings API due to error: %s', e)
message_list.append(f'### API request to {connect_server} has failed with error:
{e}
Possible Solutions:
- If you have specified an API key, confirm it is valid.
- Confirm there is connectivity between the server itself and the address assigned to it: {connect_server}.
- If using HTTPS along with self-signed certificates, you may need to allow the FastAPITableau package to use HTTP instead, by setting the environment variable `FASTAPITABLEAU_USE_HTTP` to `True` in the RStudio Connect application settings.')
else:
if (response.status_code != 200):
logger.warning('Unable to access RStudio Connect settings API with status code: %s', response.status_code)
message_list.append(f'### API request to {connect_server} has failed with error: {response.text}
Possible Solutions:
- If you have specified an API_KEY, confirm it is valid.
- Confirm the server can be reached at {connect_server}.
')
else:
server_settings = response.json()
if ('tableau_integration_enabled' not in server_settings.keys()):
logger.warning('The Tableau integration feature flag is not available on this RStudio Connect server')
message_list.append('### Tableau Integration Feature Flag is not available on the RStudio Connect server.\n\nPossible Solution:\n\n- Please upgrade to the latest version of RStudio Connect.\n')
elif (server_settings['tableau_integration_enabled'] is False):
logger.warning('Tableau integration is disabled on this RStudio Connect server')
message_list.append('Tableau Integration has been disabled on the RStudio Connect server\n\nPossible Solution:\n\n- Please ask your administrator to set `TableauIntegration.Enabled` = `true` within `rstudio-connect.gcfg` file on the RStudio Connect server.\n')
if (len(message_list) != 0):
print(message_list)
messages = '\n\n---\n\n'.join(message_list)
return messages
else:
return None | def warning_message() -> Optional[str]:
'\n \n '
if (not check_rstudio_connect()):
return None
message_list: List[str] = []
connect_server = environ.get('CONNECT_SERVER')
if (connect_server is None):
logger.warning('Could not find CONNECT_SERVER environment variable')
message_list.append('\n### The environment variable `CONNECT_SERVER` is not defined\n\nPossible Solutions:\n\n- Have your system administrator confirm `Applications.DefaultServerEnv` is enabled and that `Server.Address` has been defined within the `rstudio-connect.gcfg` file on the RStudio Connect server.,\n- Use the application settings for your content within the RStudio Connect dashboard to define the `CONNECT_SERVER` environment variable. It should be set to a reachable https or http address for the server.\n')
if (urlparse(connect_server).scheme is None):
logger.warning("The CONNECT_SERVER environment variable doesn't specify https:// or http://")
message_list.append(f'### Environment Variable `CONNECT_SERVER` (value = `{connect_server}` ) does not specify the protocol (`https://` or `http://`)
Possible Solutions:
- Have your system administrator confirm that `Server.Address` has been configured with the proper format within the `rstudio-connect.gcfg` file on the RStudio Connect server.
- Use the application settings for your content within the RStudio Connect dashboard to define the CONNECT_SERVER` environment variable with the proper protocol.
')
connect_api_key = environ.get('CONNECT_API_KEY')
if (connect_api_key is None):
logger.warning('Could not find CONNECT_API_KEY environment variable')
message_list.append('### The environment variable `CONNECT_API_KEY` is not defined\n\nPossible Solutions:\n\n- Have your administrator enable the `Applications.DefaultAPIKeyEnv` setting within the `rstudio-connect.gcfg` file on the RStudio Connect server.\n- Create an API key yourself and use the application settings for your content within the RStudio Connect dashboard to set the the `CONNECT_API_KEY` variable to its value.\n')
if (len(message_list) != 0):
messages = '\n\n---\n\n'.join(message_list)
return messages
try:
use_http = (environ.get('FASTAPITABLEAU_USE_HTTP', 'False').title() == 'True')
if use_http:
connect_server = urlparse(connect_server)._replace(scheme='http').geturl()
settings_url = (str(connect_server) + '__api__/server_settings')
headers = {'Authorization': ('Key ' + str(connect_api_key))}
response = requests.get(settings_url, headers=headers, verify=(not use_http))
except Exception as e:
logger.warning('Unable to access RStudio Connect settings API due to error: %s', e)
message_list.append(f'### API request to {connect_server} has failed with error:
{e}
Possible Solutions:
- If you have specified an API key, confirm it is valid.
- Confirm there is connectivity between the server itself and the address assigned to it: {connect_server}.
- If using HTTPS along with self-signed certificates, you may need to allow the FastAPITableau package to use HTTP instead, by setting the environment variable `FASTAPITABLEAU_USE_HTTP` to `True` in the RStudio Connect application settings.')
else:
if (response.status_code != 200):
logger.warning('Unable to access RStudio Connect settings API with status code: %s', response.status_code)
message_list.append(f'### API request to {connect_server} has failed with error: {response.text}
Possible Solutions:
- If you have specified an API_KEY, confirm it is valid.
- Confirm the server can be reached at {connect_server}.
')
else:
server_settings = response.json()
if ('tableau_integration_enabled' not in server_settings.keys()):
logger.warning('The Tableau integration feature flag is not available on this RStudio Connect server')
message_list.append('### Tableau Integration Feature Flag is not available on the RStudio Connect server.\n\nPossible Solution:\n\n- Please upgrade to the latest version of RStudio Connect.\n')
elif (server_settings['tableau_integration_enabled'] is False):
logger.warning('Tableau integration is disabled on this RStudio Connect server')
message_list.append('Tableau Integration has been disabled on the RStudio Connect server\n\nPossible Solution:\n\n- Please ask your administrator to set `TableauIntegration.Enabled` = `true` within `rstudio-connect.gcfg` file on the RStudio Connect server.\n')
if (len(message_list) != 0):
print(message_list)
messages = '\n\n---\n\n'.join(message_list)
return messages
else:
return None<|docstring|>Generate a string of warning messages based on information gathered about our environment in RStudio Connect.<|endoftext|> |
444713df0022619071d2b99f76d5f2a6ae368bd582fc401658a7056cd19157bc | def optim_iit_linear(hist_ref, hist_fit, bin_edges, init_pars=np.asarray([1.0, 0.0])):
'\n Given a reference histogram hist_ref, find best linear coefficients to match hist_fit.\n Optimization performed using Nelder-Mead method.\n :param hist_ref: list of reference histogram values\n :param hist_fit: list of histogram values for histogram to be transformed\n :param bin_edges: intensity bin edges\n :param init_pars: values of [Alpha, x] to initialize the Nelder-Mead process\n :return: minimized\n '
optim_out = optim.minimize(lbcc_funcs.get_hist_sse, init_pars, args=(hist_fit, hist_ref, bin_edges), method='Nelder-Mead')
if (optim_out.status != 0):
print('Warning: Nelder-Mead optimization of IIT coefficients failed with status', optim_out.status)
return optim_out | Given a reference histogram hist_ref, find best linear coefficients to match hist_fit.
Optimization performed using Nelder-Mead method.
:param hist_ref: list of reference histogram values
:param hist_fit: list of histogram values for histogram to be transformed
:param bin_edges: intensity bin edges
:param init_pars: values of [Alpha, x] to initialize the Nelder-Mead process
:return: minimized | chmap/data/corrections/iit/iit_utils.py | optim_iit_linear | predsci/CHD | 3 | python | def optim_iit_linear(hist_ref, hist_fit, bin_edges, init_pars=np.asarray([1.0, 0.0])):
'\n Given a reference histogram hist_ref, find best linear coefficients to match hist_fit.\n Optimization performed using Nelder-Mead method.\n :param hist_ref: list of reference histogram values\n :param hist_fit: list of histogram values for histogram to be transformed\n :param bin_edges: intensity bin edges\n :param init_pars: values of [Alpha, x] to initialize the Nelder-Mead process\n :return: minimized\n '
optim_out = optim.minimize(lbcc_funcs.get_hist_sse, init_pars, args=(hist_fit, hist_ref, bin_edges), method='Nelder-Mead')
if (optim_out.status != 0):
print('Warning: Nelder-Mead optimization of IIT coefficients failed with status', optim_out.status)
return optim_out | def optim_iit_linear(hist_ref, hist_fit, bin_edges, init_pars=np.asarray([1.0, 0.0])):
'\n Given a reference histogram hist_ref, find best linear coefficients to match hist_fit.\n Optimization performed using Nelder-Mead method.\n :param hist_ref: list of reference histogram values\n :param hist_fit: list of histogram values for histogram to be transformed\n :param bin_edges: intensity bin edges\n :param init_pars: values of [Alpha, x] to initialize the Nelder-Mead process\n :return: minimized\n '
optim_out = optim.minimize(lbcc_funcs.get_hist_sse, init_pars, args=(hist_fit, hist_ref, bin_edges), method='Nelder-Mead')
if (optim_out.status != 0):
print('Warning: Nelder-Mead optimization of IIT coefficients failed with status', optim_out.status)
return optim_out<|docstring|>Given a reference histogram hist_ref, find best linear coefficients to match hist_fit.
Optimization performed using Nelder-Mead method.
:param hist_ref: list of reference histogram values
:param hist_fit: list of histogram values for histogram to be transformed
:param bin_edges: intensity bin edges
:param init_pars: values of [Alpha, x] to initialize the Nelder-Mead process
:return: minimized<|endoftext|> |
6bb0fc10985aadbc477bf3c1f50bc356a8f70a03219abb288ffc0f01d8cc27ab | def iit_hist(lbcc_data, los_image, intensity_bin_edges, lat_band=[((- np.pi) / 2.4), (np.pi / 2.4)], log10=True):
'\n function to calculate 1D histogram for IIT\n '
intensity_min = min(intensity_bin_edges)
intensity_max = max(intensity_bin_edges)
lat_band_index = np.logical_and((los_image.lat <= max(lat_band)), (los_image.lat >= min(lat_band)))
use_data = lbcc_data[lat_band_index]
if log10:
use_data[(use_data < 0.0)] = 0.0
use_data = np.log10(use_data)
(hist_out, bin_edges) = np.histogram(use_data, bins=intensity_bin_edges)
return (hist_out, use_data) | function to calculate 1D histogram for IIT | chmap/data/corrections/iit/iit_utils.py | iit_hist | predsci/CHD | 3 | python | def iit_hist(lbcc_data, los_image, intensity_bin_edges, lat_band=[((- np.pi) / 2.4), (np.pi / 2.4)], log10=True):
'\n \n '
intensity_min = min(intensity_bin_edges)
intensity_max = max(intensity_bin_edges)
lat_band_index = np.logical_and((los_image.lat <= max(lat_band)), (los_image.lat >= min(lat_band)))
use_data = lbcc_data[lat_band_index]
if log10:
use_data[(use_data < 0.0)] = 0.0
use_data = np.log10(use_data)
(hist_out, bin_edges) = np.histogram(use_data, bins=intensity_bin_edges)
return (hist_out, use_data) | def iit_hist(lbcc_data, los_image, intensity_bin_edges, lat_band=[((- np.pi) / 2.4), (np.pi / 2.4)], log10=True):
'\n \n '
intensity_min = min(intensity_bin_edges)
intensity_max = max(intensity_bin_edges)
lat_band_index = np.logical_and((los_image.lat <= max(lat_band)), (los_image.lat >= min(lat_band)))
use_data = lbcc_data[lat_band_index]
if log10:
use_data[(use_data < 0.0)] = 0.0
use_data = np.log10(use_data)
(hist_out, bin_edges) = np.histogram(use_data, bins=intensity_bin_edges)
return (hist_out, use_data)<|docstring|>function to calculate 1D histogram for IIT<|endoftext|> |
f2145985d432082791d9a6c70d76c977c91afd2880dd8dae37924b9bffbd5d42 | def hashhex(s):
'Returns a heximal formated SHA1 hash of the input string.'
h = hashlib.sha1()
h.update(s.encode('utf-8'))
return h.hexdigest() | Returns a heximal formated SHA1 hash of the input string. | onmt/newssum/cnndm/resort_examples.py | hashhex | NaomiatLibrary/OpenNMT-kpg-release | 152 | python | def hashhex(s):
h = hashlib.sha1()
h.update(s.encode('utf-8'))
return h.hexdigest() | def hashhex(s):
h = hashlib.sha1()
h.update(s.encode('utf-8'))
return h.hexdigest()<|docstring|>Returns a heximal formated SHA1 hash of the input string.<|endoftext|> |
19ccdd5338dddee38641288c95f4489802e02cac78045c914e7910b0561776a5 | def almPlots(path, outDir, bundle, nside=128, lmax=500, filterband='i', raRange=[(- 50), 50], decRange=[(- 65), 5], subsetsToConsider=[[130, 165], [240, 300]], showPlots=True):
"\n\n Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. \n Automatically creates the output directories and saves the plots.\n\n Parameters\n -------------------\n * path: str: path to the main directory where output directory is saved\n * outDir: str: name of the main output directory\n * bundle: metricBundle object.\n \n Parameters\n -------------------\n * nside: int: HEALpix resolution parameter. Default: 128\n * lmax: int: upper limit on the multipole. Default: 500\n * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'\n * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-50,50]\n * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-65,5]\n * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.\n Currently built to handle five subsets (= number of colors built in).\n Default: [[130,165], [240, 300]]\n * showPlots: `bool`: set to True if want to show figures. Default: True\n\n "
outDir2 = ('almAnalysisPlots_%s<RA<%s_%s<Dec<%s' % (raRange[0], raRange[1], decRange[0], decRange[1]))
if (not os.path.exists(('%s%s/%s' % (path, outDir, outDir2)))):
os.makedirs(('%s%s/%s' % (path, outDir, outDir2)))
outDir3 = 'almSkymaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))
outDir4 = 'almCartviewMaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))
surveyMedianDict = {}
surveyStdDict = {}
for dither in bundle:
inSurvey = np.where((bundle[dither].metricValues.mask == False))[0]
outSurvey = np.where((bundle[dither].metricValues.mask == True))[0]
bundle[dither].metricValues.mask[outSurvey] = False
surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey])
surveyStd = np.std(bundle[dither].metricValues.data[inSurvey])
bundle[dither].metricValues.data[outSurvey] = surveyMedian
bundle[dither].metricValues.data[:] = (bundle[dither].metricValues.data[:] - surveyMedian)
surveyMedianDict[dither] = surveyMedian
surveyStdDict[dither] = surveyStd
for dither in bundle:
array = hp.anafast(bundle[dither].metricValues.filled(bundle[dither].slicer.badval), alm=True, lmax=500)
cl = array[0]
alm = array[1]
l = np.arange(len(cl))
lsubsets = {}
colorArray = ['y', 'r', 'g', 'm', 'c']
color = {}
for case in range(len(subsetsToConsider)):
lsubsets[case] = ((l > subsetsToConsider[case][0]) & (l < subsetsToConsider[case][1]))
color[case] = colorArray[case]
plt.clf()
plt.plot(l, (((cl * l) * (l + 1)) / (2.0 * np.pi)), color='b')
for key in list(lsubsets.keys()):
plt.plot(l[lsubsets[key]], (((cl[lsubsets[key]] * l[lsubsets[key]]) * (l[lsubsets[key]] + 1)) / (2.0 * np.pi)), color=color[key])
plt.title(dither)
plt.xlabel('$\\ell$')
plt.ylabel('$\\ell(\\ell+1)C_\\ell/(2\\pi)$')
filename = ('cls_%s.png' % dither)
plt.savefig(('%s%s/%s/%s' % (path, outDir, outDir2, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close()
surveyMedian = surveyMedianDict[dither]
surveyStd = surveyStdDict[dither]
nTicks = 5
colorMin = (surveyMedian - (1.5 * surveyStd))
colorMax = (surveyMedian + (1.5 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
ticks = np.arange((colorMin + increment), colorMax, increment)
hp.mollview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title='', cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title='', cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_Cartview_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
colorMin = (surveyMedian - (0.1 * surveyStd))
colorMax = (surveyMedian + (0.1 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
increment = (1.15 * increment)
ticks = np.arange((colorMin + increment), colorMax, increment)
for case in list(lsubsets.keys()):
index = []
lowLim = subsetsToConsider[case][0]
upLim = subsetsToConsider[case][1]
for ll in np.arange(lowLim, (upLim + 1)):
for mm in np.arange(0, (ll + 1)):
index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm))
alms1 = alm.copy()
alms1.fill(0)
alms1[index] = alm[index]
hp.mollview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title='', cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almSkymap_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title='', cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almCartview_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close('all') | Plot the skymaps/cartview plots corresponding to alms with specified l-ranges.
Automatically creates the output directories and saves the plots.
Parameters
-------------------
* path: str: path to the main directory where output directory is saved
* outDir: str: name of the main output directory
* bundle: metricBundle object.
Parameters
-------------------
* nside: int: HEALpix resolution parameter. Default: 128
* lmax: int: upper limit on the multipole. Default: 500
* filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'
* raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when
cartview= True. Default: [-50,50]
* decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when
cartview= True. Default: [-65,5]
* subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.
Currently built to handle five subsets (= number of colors built in).
Default: [[130,165], [240, 300]]
* showPlots: `bool`: set to True if want to show figures. Default: True | rubin_sim/maf/mafContrib/LSSObsStrategy/almPlots.py | almPlots | RileyWClarke/flarubin | 0 | python | def almPlots(path, outDir, bundle, nside=128, lmax=500, filterband='i', raRange=[(- 50), 50], decRange=[(- 65), 5], subsetsToConsider=[[130, 165], [240, 300]], showPlots=True):
"\n\n Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. \n Automatically creates the output directories and saves the plots.\n\n Parameters\n -------------------\n * path: str: path to the main directory where output directory is saved\n * outDir: str: name of the main output directory\n * bundle: metricBundle object.\n \n Parameters\n -------------------\n * nside: int: HEALpix resolution parameter. Default: 128\n * lmax: int: upper limit on the multipole. Default: 500\n * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'\n * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-50,50]\n * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-65,5]\n * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.\n Currently built to handle five subsets (= number of colors built in).\n Default: [[130,165], [240, 300]]\n * showPlots: `bool`: set to True if want to show figures. Default: True\n\n "
outDir2 = ('almAnalysisPlots_%s<RA<%s_%s<Dec<%s' % (raRange[0], raRange[1], decRange[0], decRange[1]))
if (not os.path.exists(('%s%s/%s' % (path, outDir, outDir2)))):
os.makedirs(('%s%s/%s' % (path, outDir, outDir2)))
outDir3 = 'almSkymaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))
outDir4 = 'almCartviewMaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))
surveyMedianDict = {}
surveyStdDict = {}
for dither in bundle:
inSurvey = np.where((bundle[dither].metricValues.mask == False))[0]
outSurvey = np.where((bundle[dither].metricValues.mask == True))[0]
bundle[dither].metricValues.mask[outSurvey] = False
surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey])
surveyStd = np.std(bundle[dither].metricValues.data[inSurvey])
bundle[dither].metricValues.data[outSurvey] = surveyMedian
bundle[dither].metricValues.data[:] = (bundle[dither].metricValues.data[:] - surveyMedian)
surveyMedianDict[dither] = surveyMedian
surveyStdDict[dither] = surveyStd
for dither in bundle:
array = hp.anafast(bundle[dither].metricValues.filled(bundle[dither].slicer.badval), alm=True, lmax=500)
cl = array[0]
alm = array[1]
l = np.arange(len(cl))
lsubsets = {}
colorArray = ['y', 'r', 'g', 'm', 'c']
color = {}
for case in range(len(subsetsToConsider)):
lsubsets[case] = ((l > subsetsToConsider[case][0]) & (l < subsetsToConsider[case][1]))
color[case] = colorArray[case]
plt.clf()
plt.plot(l, (((cl * l) * (l + 1)) / (2.0 * np.pi)), color='b')
for key in list(lsubsets.keys()):
plt.plot(l[lsubsets[key]], (((cl[lsubsets[key]] * l[lsubsets[key]]) * (l[lsubsets[key]] + 1)) / (2.0 * np.pi)), color=color[key])
plt.title(dither)
plt.xlabel('$\\ell$')
plt.ylabel('$\\ell(\\ell+1)C_\\ell/(2\\pi)$')
filename = ('cls_%s.png' % dither)
plt.savefig(('%s%s/%s/%s' % (path, outDir, outDir2, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close()
surveyMedian = surveyMedianDict[dither]
surveyStd = surveyStdDict[dither]
nTicks = 5
colorMin = (surveyMedian - (1.5 * surveyStd))
colorMax = (surveyMedian + (1.5 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
ticks = np.arange((colorMin + increment), colorMax, increment)
hp.mollview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_Cartview_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
colorMin = (surveyMedian - (0.1 * surveyStd))
colorMax = (surveyMedian + (0.1 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
increment = (1.15 * increment)
ticks = np.arange((colorMin + increment), colorMax, increment)
for case in list(lsubsets.keys()):
index = []
lowLim = subsetsToConsider[case][0]
upLim = subsetsToConsider[case][1]
for ll in np.arange(lowLim, (upLim + 1)):
for mm in np.arange(0, (ll + 1)):
index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm))
alms1 = alm.copy()
alms1.fill(0)
alms1[index] = alm[index]
hp.mollview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almSkymap_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almCartview_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close('all') | def almPlots(path, outDir, bundle, nside=128, lmax=500, filterband='i', raRange=[(- 50), 50], decRange=[(- 65), 5], subsetsToConsider=[[130, 165], [240, 300]], showPlots=True):
"\n\n Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. \n Automatically creates the output directories and saves the plots.\n\n Parameters\n -------------------\n * path: str: path to the main directory where output directory is saved\n * outDir: str: name of the main output directory\n * bundle: metricBundle object.\n \n Parameters\n -------------------\n * nside: int: HEALpix resolution parameter. Default: 128\n * lmax: int: upper limit on the multipole. Default: 500\n * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'\n * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-50,50]\n * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when \n cartview= True. Default: [-65,5]\n * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.\n Currently built to handle five subsets (= number of colors built in).\n Default: [[130,165], [240, 300]]\n * showPlots: `bool`: set to True if want to show figures. Default: True\n\n "
outDir2 = ('almAnalysisPlots_%s<RA<%s_%s<Dec<%s' % (raRange[0], raRange[1], decRange[0], decRange[1]))
if (not os.path.exists(('%s%s/%s' % (path, outDir, outDir2)))):
os.makedirs(('%s%s/%s' % (path, outDir, outDir2)))
outDir3 = 'almSkymaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir3)))
outDir4 = 'almCartviewMaps'
if (not os.path.exists(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))):
os.makedirs(('%s%s/%s/%s' % (path, outDir, outDir2, outDir4)))
surveyMedianDict = {}
surveyStdDict = {}
for dither in bundle:
inSurvey = np.where((bundle[dither].metricValues.mask == False))[0]
outSurvey = np.where((bundle[dither].metricValues.mask == True))[0]
bundle[dither].metricValues.mask[outSurvey] = False
surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey])
surveyStd = np.std(bundle[dither].metricValues.data[inSurvey])
bundle[dither].metricValues.data[outSurvey] = surveyMedian
bundle[dither].metricValues.data[:] = (bundle[dither].metricValues.data[:] - surveyMedian)
surveyMedianDict[dither] = surveyMedian
surveyStdDict[dither] = surveyStd
for dither in bundle:
array = hp.anafast(bundle[dither].metricValues.filled(bundle[dither].slicer.badval), alm=True, lmax=500)
cl = array[0]
alm = array[1]
l = np.arange(len(cl))
lsubsets = {}
colorArray = ['y', 'r', 'g', 'm', 'c']
color = {}
for case in range(len(subsetsToConsider)):
lsubsets[case] = ((l > subsetsToConsider[case][0]) & (l < subsetsToConsider[case][1]))
color[case] = colorArray[case]
plt.clf()
plt.plot(l, (((cl * l) * (l + 1)) / (2.0 * np.pi)), color='b')
for key in list(lsubsets.keys()):
plt.plot(l[lsubsets[key]], (((cl[lsubsets[key]] * l[lsubsets[key]]) * (l[lsubsets[key]] + 1)) / (2.0 * np.pi)), color=color[key])
plt.title(dither)
plt.xlabel('$\\ell$')
plt.ylabel('$\\ell(\\ell+1)C_\\ell/(2\\pi)$')
filename = ('cls_%s.png' % dither)
plt.savefig(('%s%s/%s/%s' % (path, outDir, outDir2, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close()
surveyMedian = surveyMedianDict[dither]
surveyStd = surveyStdDict[dither]
nTicks = 5
colorMin = (surveyMedian - (1.5 * surveyStd))
colorMax = (surveyMedian + (1.5 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
ticks = np.arange((colorMin + increment), colorMax, increment)
hp.mollview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alm, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title('Full Map')
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('alm_Cartview_FullMap_%s.png' % dither)
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
colorMin = (surveyMedian - (0.1 * surveyStd))
colorMax = (surveyMedian + (0.1 * surveyStd))
increment = ((colorMax - colorMin) / float(nTicks))
increment = (1.15 * increment)
ticks = np.arange((colorMin + increment), colorMax, increment)
for case in list(lsubsets.keys()):
index = []
lowLim = subsetsToConsider[case][0]
upLim = subsetsToConsider[case][1]
for ll in np.arange(lowLim, (upLim + 1)):
for mm in np.arange(0, (ll + 1)):
index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm))
alms1 = alm.copy()
alms1.fill(0)
alms1[index] = alm[index]
hp.mollview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), flip='astro', rot=(0, 0, 0), min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almSkymap_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir3, filename)), format='png', bbox_inches='tight')
hp.cartview((hp.alm2map(alms1, nside=nside, lmax=lmax) + surveyMedian), lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title=, cbar=False)
hp.graticule(dpar=20, dmer=20, verbose=False)
plt.title(('%s<$\\ell$<%s' % (lowLim, upLim)))
ax = plt.gca()
im = ax.get_images()[0]
fig = plt.gcf()
cbaxes = fig.add_axes([0.1, (- 0.05), 0.8, 0.04])
cb = plt.colorbar(im, orientation='horizontal', format='%.3f', ticks=ticks, cax=cbaxes)
cb.set_label(('$%s$-band Coadded Depth' % filterband))
filename = ('almCartview_%s<l<%s_%s.png' % (lowLim, upLim, dither))
plt.savefig(('%s%s/%s/%s/%s' % (path, outDir, outDir2, outDir4, filename)), format='png', bbox_inches='tight')
if showPlots:
plt.show()
else:
plt.close('all')<|docstring|>Plot the skymaps/cartview plots corresponding to alms with specified l-ranges.
Automatically creates the output directories and saves the plots.
Parameters
-------------------
* path: str: path to the main directory where output directory is saved
* outDir: str: name of the main output directory
* bundle: metricBundle object.
Parameters
-------------------
* nside: int: HEALpix resolution parameter. Default: 128
* lmax: int: upper limit on the multipole. Default: 500
* filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i'
* raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when
cartview= True. Default: [-50,50]
* decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when
cartview= True. Default: [-65,5]
* subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100.
Currently built to handle five subsets (= number of colors built in).
Default: [[130,165], [240, 300]]
* showPlots: `bool`: set to True if want to show figures. Default: True<|endoftext|> |
280884446da3fe6b3974a2399efc731eb2494e616d4eb4a2d9efc17ef2f23465 | @defer.inlineCallbacks
def test_cache_num_args(self):
'Only the first num_args arguments should matter to the cache'
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached(num_args=1)
def fn(self, arg1, arg2):
return self.mock(arg1, arg2)
obj = Cls()
obj.mock.return_value = 'fish'
r = (yield obj.fn(1, 2))
self.assertEqual(r, 'fish')
obj.mock.assert_called_once_with(1, 2)
obj.mock.reset_mock()
obj.mock.return_value = 'chips'
r = (yield obj.fn(2, 3))
self.assertEqual(r, 'chips')
obj.mock.assert_called_once_with(2, 3)
obj.mock.reset_mock()
r = (yield obj.fn(1, 4))
self.assertEqual(r, 'fish')
r = (yield obj.fn(2, 5))
self.assertEqual(r, 'chips')
obj.mock.assert_not_called() | Only the first num_args arguments should matter to the cache | tests/util/caches/test_descriptors.py | test_cache_num_args | bradjones1/synapse | 9,945 | python | @defer.inlineCallbacks
def test_cache_num_args(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached(num_args=1)
def fn(self, arg1, arg2):
return self.mock(arg1, arg2)
obj = Cls()
obj.mock.return_value = 'fish'
r = (yield obj.fn(1, 2))
self.assertEqual(r, 'fish')
obj.mock.assert_called_once_with(1, 2)
obj.mock.reset_mock()
obj.mock.return_value = 'chips'
r = (yield obj.fn(2, 3))
self.assertEqual(r, 'chips')
obj.mock.assert_called_once_with(2, 3)
obj.mock.reset_mock()
r = (yield obj.fn(1, 4))
self.assertEqual(r, 'fish')
r = (yield obj.fn(2, 5))
self.assertEqual(r, 'chips')
obj.mock.assert_not_called() | @defer.inlineCallbacks
def test_cache_num_args(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached(num_args=1)
def fn(self, arg1, arg2):
return self.mock(arg1, arg2)
obj = Cls()
obj.mock.return_value = 'fish'
r = (yield obj.fn(1, 2))
self.assertEqual(r, 'fish')
obj.mock.assert_called_once_with(1, 2)
obj.mock.reset_mock()
obj.mock.return_value = 'chips'
r = (yield obj.fn(2, 3))
self.assertEqual(r, 'chips')
obj.mock.assert_called_once_with(2, 3)
obj.mock.reset_mock()
r = (yield obj.fn(1, 4))
self.assertEqual(r, 'fish')
r = (yield obj.fn(2, 5))
self.assertEqual(r, 'chips')
obj.mock.assert_not_called()<|docstring|>Only the first num_args arguments should matter to the cache<|endoftext|> |
ec1e1199426f060e0e960689d3aa873604807c49a32a4911a2c14ded553978df | def test_cache_with_sync_exception(self):
'If the wrapped function throws synchronously, things should continue to work'
class Cls():
@cached()
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError) | If the wrapped function throws synchronously, things should continue to work | tests/util/caches/test_descriptors.py | test_cache_with_sync_exception | bradjones1/synapse | 9,945 | python | def test_cache_with_sync_exception(self):
class Cls():
@cached()
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError) | def test_cache_with_sync_exception(self):
class Cls():
@cached()
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError)<|docstring|>If the wrapped function throws synchronously, things should continue to work<|endoftext|> |
46cb17ba1f0ffcf1391aaca1795ff7422e93770bed6df702c705ee1891c17632 | def test_cache_with_async_exception(self):
'The wrapped function returns a failure'
class Cls():
result = None
call_count = 0
@cached()
def fn(self, arg1):
self.call_count += 1
return self.result
obj = Cls()
callbacks: Set[str] = set()
obj.result = origin_d = defer.Deferred()
d1 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d1')))
self.assertFalse(d1.called)
d2 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d2')))
self.assertFalse(d2.called)
self.assertEqual(obj.call_count, 1)
self.assertEqual(callbacks, set())
e = Exception('bzz')
origin_d.errback(e)
self.assertIs(self.failureResultOf(d1, Exception).value, e)
self.assertIs(self.failureResultOf(d2, Exception).value, e)
self.assertEqual(callbacks, {'d1', 'd2'})
self.assertEqual(len(obj.fn.cache.cache), 0)
obj.result = defer.succeed(100)
d3 = obj.fn(1)
self.assertEqual(self.successResultOf(d3), 100)
self.assertEqual(obj.call_count, 2) | The wrapped function returns a failure | tests/util/caches/test_descriptors.py | test_cache_with_async_exception | bradjones1/synapse | 9,945 | python | def test_cache_with_async_exception(self):
class Cls():
result = None
call_count = 0
@cached()
def fn(self, arg1):
self.call_count += 1
return self.result
obj = Cls()
callbacks: Set[str] = set()
obj.result = origin_d = defer.Deferred()
d1 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d1')))
self.assertFalse(d1.called)
d2 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d2')))
self.assertFalse(d2.called)
self.assertEqual(obj.call_count, 1)
self.assertEqual(callbacks, set())
e = Exception('bzz')
origin_d.errback(e)
self.assertIs(self.failureResultOf(d1, Exception).value, e)
self.assertIs(self.failureResultOf(d2, Exception).value, e)
self.assertEqual(callbacks, {'d1', 'd2'})
self.assertEqual(len(obj.fn.cache.cache), 0)
obj.result = defer.succeed(100)
d3 = obj.fn(1)
self.assertEqual(self.successResultOf(d3), 100)
self.assertEqual(obj.call_count, 2) | def test_cache_with_async_exception(self):
class Cls():
result = None
call_count = 0
@cached()
def fn(self, arg1):
self.call_count += 1
return self.result
obj = Cls()
callbacks: Set[str] = set()
obj.result = origin_d = defer.Deferred()
d1 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d1')))
self.assertFalse(d1.called)
d2 = obj.fn(1, on_invalidate=(lambda : callbacks.add('d2')))
self.assertFalse(d2.called)
self.assertEqual(obj.call_count, 1)
self.assertEqual(callbacks, set())
e = Exception('bzz')
origin_d.errback(e)
self.assertIs(self.failureResultOf(d1, Exception).value, e)
self.assertIs(self.failureResultOf(d2, Exception).value, e)
self.assertEqual(callbacks, {'d1', 'd2'})
self.assertEqual(len(obj.fn.cache.cache), 0)
obj.result = defer.succeed(100)
d3 = obj.fn(1)
self.assertEqual(self.successResultOf(d3), 100)
self.assertEqual(obj.call_count, 2)<|docstring|>The wrapped function returns a failure<|endoftext|> |
ef41f2b361189d5e905af569361b31e92fce331e0d14ceb676c98cbb56f3d727 | def test_cache_logcontexts(self):
'Check that logcontexts are set and restored correctly when\n using the cache.'
complete_lookup = defer.Deferred()
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
with PreserveLoggingContext():
(yield complete_lookup)
return 1
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
r = (yield obj.fn(1))
self.assertEqual(current_context(), c1)
return r
def check_result(r):
self.assertEqual(r, 1)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d1.addCallback(check_result)
d2 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d2.addCallback(check_result)
complete_lookup.callback(None)
return defer.gatherResults([d1, d2]) | Check that logcontexts are set and restored correctly when
using the cache. | tests/util/caches/test_descriptors.py | test_cache_logcontexts | bradjones1/synapse | 9,945 | python | def test_cache_logcontexts(self):
'Check that logcontexts are set and restored correctly when\n using the cache.'
complete_lookup = defer.Deferred()
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
with PreserveLoggingContext():
(yield complete_lookup)
return 1
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
r = (yield obj.fn(1))
self.assertEqual(current_context(), c1)
return r
def check_result(r):
self.assertEqual(r, 1)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d1.addCallback(check_result)
d2 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d2.addCallback(check_result)
complete_lookup.callback(None)
return defer.gatherResults([d1, d2]) | def test_cache_logcontexts(self):
'Check that logcontexts are set and restored correctly when\n using the cache.'
complete_lookup = defer.Deferred()
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
with PreserveLoggingContext():
(yield complete_lookup)
return 1
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
r = (yield obj.fn(1))
self.assertEqual(current_context(), c1)
return r
def check_result(r):
self.assertEqual(r, 1)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d1.addCallback(check_result)
d2 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
d2.addCallback(check_result)
complete_lookup.callback(None)
return defer.gatherResults([d1, d2])<|docstring|>Check that logcontexts are set and restored correctly when
using the cache.<|endoftext|> |
c7f3fb68c166ef6302a1738bb200b32e64fc819e5d45b1dafde499bc14a2752a | def test_cache_logcontexts_with_exception(self):
'Check that the cache sets and restores logcontexts correctly when\n the lookup function throws an exception'
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
(yield run_on_reactor())
raise SynapseError(400, 'blah')
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
try:
d = obj.fn(1)
self.assertEqual(current_context(), SENTINEL_CONTEXT)
(yield d)
self.fail('No exception thrown')
except SynapseError:
pass
self.assertEqual(current_context(), c1)
self.assertEqual(len(obj.fn.cache.cache), 0)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
return d1 | Check that the cache sets and restores logcontexts correctly when
the lookup function throws an exception | tests/util/caches/test_descriptors.py | test_cache_logcontexts_with_exception | bradjones1/synapse | 9,945 | python | def test_cache_logcontexts_with_exception(self):
'Check that the cache sets and restores logcontexts correctly when\n the lookup function throws an exception'
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
(yield run_on_reactor())
raise SynapseError(400, 'blah')
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
try:
d = obj.fn(1)
self.assertEqual(current_context(), SENTINEL_CONTEXT)
(yield d)
self.fail('No exception thrown')
except SynapseError:
pass
self.assertEqual(current_context(), c1)
self.assertEqual(len(obj.fn.cache.cache), 0)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
return d1 | def test_cache_logcontexts_with_exception(self):
'Check that the cache sets and restores logcontexts correctly when\n the lookup function throws an exception'
class Cls():
@descriptors.cached()
def fn(self, arg1):
@defer.inlineCallbacks
def inner_fn():
(yield run_on_reactor())
raise SynapseError(400, 'blah')
return inner_fn()
@defer.inlineCallbacks
def do_lookup():
with LoggingContext('c1') as c1:
try:
d = obj.fn(1)
self.assertEqual(current_context(), SENTINEL_CONTEXT)
(yield d)
self.fail('No exception thrown')
except SynapseError:
pass
self.assertEqual(current_context(), c1)
self.assertEqual(len(obj.fn.cache.cache), 0)
obj = Cls()
d1 = do_lookup()
self.assertEqual(current_context(), SENTINEL_CONTEXT)
return d1<|docstring|>Check that the cache sets and restores logcontexts correctly when
the lookup function throws an exception<|endoftext|> |
e390422618d8d5effeb48366cb42c2f187999f18e6d5a2fde668035189df9a43 | def test_cache_iterable_with_sync_exception(self):
'If the wrapped function throws synchronously, things should continue to work'
class Cls():
@descriptors.cached(iterable=True)
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError) | If the wrapped function throws synchronously, things should continue to work | tests/util/caches/test_descriptors.py | test_cache_iterable_with_sync_exception | bradjones1/synapse | 9,945 | python | def test_cache_iterable_with_sync_exception(self):
class Cls():
@descriptors.cached(iterable=True)
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError) | def test_cache_iterable_with_sync_exception(self):
class Cls():
@descriptors.cached(iterable=True)
def fn(self, arg1):
raise SynapseError(100, 'mai spoon iz too big!!1')
obj = Cls()
d = obj.fn(1)
self.failureResultOf(d, SynapseError)
self.assertEqual(len(obj.fn.cache.cache), 0)
d = obj.fn(1)
self.failureResultOf(d, SynapseError)<|docstring|>If the wrapped function throws synchronously, things should continue to work<|endoftext|> |
72a3ed7a017f01cb32540db7c53f8939173e551d228dd69e7621a2783c9720d0 | def test_invalidate_cascade(self):
'Invalidations should cascade up through cache contexts'
class Cls():
@cached(cache_context=True)
async def func1(self, key, cache_context):
return (await self.func2(key, on_invalidate=cache_context.invalidate))
@cached(cache_context=True)
async def func2(self, key, cache_context):
return self.func3(key, on_invalidate=cache_context.invalidate)
@lru_cache(cache_context=True)
def func3(self, key, cache_context):
self.invalidate = cache_context.invalidate
return 42
obj = Cls()
top_invalidate = mock.Mock()
r = get_awaitable_result(obj.func1('k1', on_invalidate=top_invalidate))
self.assertEqual(r, 42)
obj.invalidate()
top_invalidate.assert_called_once() | Invalidations should cascade up through cache contexts | tests/util/caches/test_descriptors.py | test_invalidate_cascade | bradjones1/synapse | 9,945 | python | def test_invalidate_cascade(self):
class Cls():
@cached(cache_context=True)
async def func1(self, key, cache_context):
return (await self.func2(key, on_invalidate=cache_context.invalidate))
@cached(cache_context=True)
async def func2(self, key, cache_context):
return self.func3(key, on_invalidate=cache_context.invalidate)
@lru_cache(cache_context=True)
def func3(self, key, cache_context):
self.invalidate = cache_context.invalidate
return 42
obj = Cls()
top_invalidate = mock.Mock()
r = get_awaitable_result(obj.func1('k1', on_invalidate=top_invalidate))
self.assertEqual(r, 42)
obj.invalidate()
top_invalidate.assert_called_once() | def test_invalidate_cascade(self):
class Cls():
@cached(cache_context=True)
async def func1(self, key, cache_context):
return (await self.func2(key, on_invalidate=cache_context.invalidate))
@cached(cache_context=True)
async def func2(self, key, cache_context):
return self.func3(key, on_invalidate=cache_context.invalidate)
@lru_cache(cache_context=True)
def func3(self, key, cache_context):
self.invalidate = cache_context.invalidate
return 42
obj = Cls()
top_invalidate = mock.Mock()
r = get_awaitable_result(obj.func1('k1', on_invalidate=top_invalidate))
self.assertEqual(r, 42)
obj.invalidate()
top_invalidate.assert_called_once()<|docstring|>Invalidations should cascade up through cache contexts<|endoftext|> |
832561eee2f9a7920e7101ab1b0ee0c781d7b30e69bf07b35e43385d7d1ac799 | def test_concurrent_lookups(self):
'All concurrent lookups should get the same result'
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1):
pass
@descriptors.cachedList('fn', 'args1')
def list_fn(self, args1) -> 'Deferred[dict]':
return self.mock(args1)
obj = Cls()
deferred_result = Deferred()
obj.mock.return_value = deferred_result
d1 = obj.list_fn([10])
d2 = obj.list_fn([10])
d3 = obj.list_fn([10])
obj.mock.assert_called_once_with((10,))
obj.mock.reset_mock()
self.assertFalse(d1.called)
self.assertFalse(d2.called)
self.assertFalse(d3.called)
deferred_result.callback({10: 'peas'})
self.assertEqual(self.successResultOf(d1), {10: 'peas'})
self.assertEqual(self.successResultOf(d2), {10: 'peas'})
self.assertEqual(self.successResultOf(d3), {10: 'peas'}) | All concurrent lookups should get the same result | tests/util/caches/test_descriptors.py | test_concurrent_lookups | bradjones1/synapse | 9,945 | python | def test_concurrent_lookups(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1):
pass
@descriptors.cachedList('fn', 'args1')
def list_fn(self, args1) -> 'Deferred[dict]':
return self.mock(args1)
obj = Cls()
deferred_result = Deferred()
obj.mock.return_value = deferred_result
d1 = obj.list_fn([10])
d2 = obj.list_fn([10])
d3 = obj.list_fn([10])
obj.mock.assert_called_once_with((10,))
obj.mock.reset_mock()
self.assertFalse(d1.called)
self.assertFalse(d2.called)
self.assertFalse(d3.called)
deferred_result.callback({10: 'peas'})
self.assertEqual(self.successResultOf(d1), {10: 'peas'})
self.assertEqual(self.successResultOf(d2), {10: 'peas'})
self.assertEqual(self.successResultOf(d3), {10: 'peas'}) | def test_concurrent_lookups(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1):
pass
@descriptors.cachedList('fn', 'args1')
def list_fn(self, args1) -> 'Deferred[dict]':
return self.mock(args1)
obj = Cls()
deferred_result = Deferred()
obj.mock.return_value = deferred_result
d1 = obj.list_fn([10])
d2 = obj.list_fn([10])
d3 = obj.list_fn([10])
obj.mock.assert_called_once_with((10,))
obj.mock.reset_mock()
self.assertFalse(d1.called)
self.assertFalse(d2.called)
self.assertFalse(d3.called)
deferred_result.callback({10: 'peas'})
self.assertEqual(self.successResultOf(d1), {10: 'peas'})
self.assertEqual(self.successResultOf(d2), {10: 'peas'})
self.assertEqual(self.successResultOf(d3), {10: 'peas'})<|docstring|>All concurrent lookups should get the same result<|endoftext|> |
cfa903aad9bcc6c23e213212de15c41aa7090b3425065f4218ba27558aa1b167 | @defer.inlineCallbacks
def test_invalidate(self):
'Make sure that invalidation callbacks are called.'
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1, arg2):
pass
@descriptors.cachedList('fn', 'args1')
async def list_fn(self, args1, arg2):
(await run_on_reactor())
return self.mock(args1, arg2)
obj = Cls()
invalidate0 = mock.Mock()
invalidate1 = mock.Mock()
obj.mock.return_value = {10: 'fish', 20: 'chips'}
r1 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0))
obj.mock.assert_called_once_with((10, 20), 2)
self.assertEqual(r1, {10: 'fish', 20: 'chips'})
obj.mock.reset_mock()
r2 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1))
obj.mock.assert_not_called()
self.assertEqual(r2, {10: 'fish', 20: 'chips'})
invalidate0.assert_not_called()
invalidate1.assert_not_called()
obj.fn.invalidate((10, 2))
invalidate0.assert_called_once()
invalidate1.assert_called_once() | Make sure that invalidation callbacks are called. | tests/util/caches/test_descriptors.py | test_invalidate | bradjones1/synapse | 9,945 | python | @defer.inlineCallbacks
def test_invalidate(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1, arg2):
pass
@descriptors.cachedList('fn', 'args1')
async def list_fn(self, args1, arg2):
(await run_on_reactor())
return self.mock(args1, arg2)
obj = Cls()
invalidate0 = mock.Mock()
invalidate1 = mock.Mock()
obj.mock.return_value = {10: 'fish', 20: 'chips'}
r1 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0))
obj.mock.assert_called_once_with((10, 20), 2)
self.assertEqual(r1, {10: 'fish', 20: 'chips'})
obj.mock.reset_mock()
r2 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1))
obj.mock.assert_not_called()
self.assertEqual(r2, {10: 'fish', 20: 'chips'})
invalidate0.assert_not_called()
invalidate1.assert_not_called()
obj.fn.invalidate((10, 2))
invalidate0.assert_called_once()
invalidate1.assert_called_once() | @defer.inlineCallbacks
def test_invalidate(self):
class Cls():
def __init__(self):
self.mock = mock.Mock()
@descriptors.cached()
def fn(self, arg1, arg2):
pass
@descriptors.cachedList('fn', 'args1')
async def list_fn(self, args1, arg2):
(await run_on_reactor())
return self.mock(args1, arg2)
obj = Cls()
invalidate0 = mock.Mock()
invalidate1 = mock.Mock()
obj.mock.return_value = {10: 'fish', 20: 'chips'}
r1 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate0))
obj.mock.assert_called_once_with((10, 20), 2)
self.assertEqual(r1, {10: 'fish', 20: 'chips'})
obj.mock.reset_mock()
r2 = (yield obj.list_fn([10, 20], 2, on_invalidate=invalidate1))
obj.mock.assert_not_called()
self.assertEqual(r2, {10: 'fish', 20: 'chips'})
invalidate0.assert_not_called()
invalidate1.assert_not_called()
obj.fn.invalidate((10, 2))
invalidate0.assert_called_once()
invalidate1.assert_called_once()<|docstring|>Make sure that invalidation callbacks are called.<|endoftext|> |
d0ec8c13c76c6bf0f7634333b4453b09d77a8d486e3673182f57dd0c1df6605b | def pie_chart_drawing(topic, party):
'\n In debugging mode, the commented code works fine because\n it is fine to dynamically draw the\n pie charts and sent to the front end. However, Matplotlib\n forbids opening a GUI window on the server trying to rendering\n the figure to a png and then shipping it to the user as the payload of a response.\n Thus, the solution is to draw all pie charts before hand and save to static folder.\n '
return_img_data = {'image_url': [(((('static/datamodel/pie_charts/' + topic) + '_') + party) + '.png')]}
return return_img_data | In debugging mode, the commented code works fine because
it is fine to dynamically draw the
pie charts and sent to the front end. However, Matplotlib
forbids opening a GUI window on the server trying to rendering
the figure to a png and then shipping it to the user as the payload of a response.
Thus, the solution is to draw all pie charts before hand and save to static folder. | main.py | pie_chart_drawing | CharlieZJG/Political-Sentiment-Analysis | 0 | python | def pie_chart_drawing(topic, party):
'\n In debugging mode, the commented code works fine because\n it is fine to dynamically draw the\n pie charts and sent to the front end. However, Matplotlib\n forbids opening a GUI window on the server trying to rendering\n the figure to a png and then shipping it to the user as the payload of a response.\n Thus, the solution is to draw all pie charts before hand and save to static folder.\n '
return_img_data = {'image_url': [(((('static/datamodel/pie_charts/' + topic) + '_') + party) + '.png')]}
return return_img_data | def pie_chart_drawing(topic, party):
'\n In debugging mode, the commented code works fine because\n it is fine to dynamically draw the\n pie charts and sent to the front end. However, Matplotlib\n forbids opening a GUI window on the server trying to rendering\n the figure to a png and then shipping it to the user as the payload of a response.\n Thus, the solution is to draw all pie charts before hand and save to static folder.\n '
return_img_data = {'image_url': [(((('static/datamodel/pie_charts/' + topic) + '_') + party) + '.png')]}
return return_img_data<|docstring|>In debugging mode, the commented code works fine because
it is fine to dynamically draw the
pie charts and sent to the front end. However, Matplotlib
forbids opening a GUI window on the server trying to rendering
the figure to a png and then shipping it to the user as the payload of a response.
Thus, the solution is to draw all pie charts before hand and save to static folder.<|endoftext|> |
ed77a181be0011a6519b37e90e95080132d021d2ace1d01b5632b7769b5a876c | def _get_encapsulation(self, connection_points):
'\n Obtains encapsulation for the vpls service from the connection_points\n FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is\n defined at the service level so only one can be assigned\n '
encapsulation = 'NONE'
for connection_point in connection_points:
if (connection_point.get('service_endpoint_encapsulation_type') == 'dot1q'):
encapsulation = 'VLAN'
break
return encapsulation | Obtains encapsulation for the vpls service from the connection_points
FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is
defined at the service level so only one can be assigned | RO-SDN-onos_vpls/osm_rosdn_onos_vpls/sdn_assist_onos_vpls.py | _get_encapsulation | TCSOSM-20/RO | 0 | python | def _get_encapsulation(self, connection_points):
'\n Obtains encapsulation for the vpls service from the connection_points\n FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is\n defined at the service level so only one can be assigned\n '
encapsulation = 'NONE'
for connection_point in connection_points:
if (connection_point.get('service_endpoint_encapsulation_type') == 'dot1q'):
encapsulation = 'VLAN'
break
return encapsulation | def _get_encapsulation(self, connection_points):
'\n Obtains encapsulation for the vpls service from the connection_points\n FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is\n defined at the service level so only one can be assigned\n '
encapsulation = 'NONE'
for connection_point in connection_points:
if (connection_point.get('service_endpoint_encapsulation_type') == 'dot1q'):
encapsulation = 'VLAN'
break
return encapsulation<|docstring|>Obtains encapsulation for the vpls service from the connection_points
FIXME: Encapsulation is defined for the connection points but for the VPLS service the encapsulation is
defined at the service level so only one can be assigned<|endoftext|> |
497f2d3d0f862cf001eea8d304ecc10e2d6f336f5a77ad5b0c0a8b3f7bd5ee5e | def _pop_last_update_time(self, onos_config):
'\n Needed before post when there are already configured vpls services to apply changes\n '
onos_config['apps']['org.onosproject.vpls']['vpls'].pop('lastUpdateTime', None) | Needed before post when there are already configured vpls services to apply changes | RO-SDN-onos_vpls/osm_rosdn_onos_vpls/sdn_assist_onos_vpls.py | _pop_last_update_time | TCSOSM-20/RO | 0 | python | def _pop_last_update_time(self, onos_config):
'\n \n '
onos_config['apps']['org.onosproject.vpls']['vpls'].pop('lastUpdateTime', None) | def _pop_last_update_time(self, onos_config):
'\n \n '
onos_config['apps']['org.onosproject.vpls']['vpls'].pop('lastUpdateTime', None)<|docstring|>Needed before post when there are already configured vpls services to apply changes<|endoftext|> |
9232666a7038c844a24dfc25b034267963e510f46907b58c836697f005065532 | def __init__(self, context=None, response_queue=None):
'\n Args:\n context(): Context of request\n response_queue(Queue): Queue to return to\n '
self.set_id(None)
self.context = context
self.response_queue = response_queue | Args:
context(): Context of request
response_queue(Queue): Queue to return to | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None):
'\n Args:\n context(): Context of request\n response_queue(Queue): Queue to return to\n '
self.set_id(None)
self.context = context
self.response_queue = response_queue | def __init__(self, context=None, response_queue=None):
'\n Args:\n context(): Context of request\n response_queue(Queue): Queue to return to\n '
self.set_id(None)
self.context = context
self.response_queue = response_queue<|docstring|>Args:
context(): Context of request
response_queue(Queue): Queue to return to<|endoftext|> |
bb8967618ddb670e782a6ddf7f01e1eb35abd5bcf26a26de8d5c7487f3625774 | def set_id(self, id_):
'\n Set the identifier for the request\n\n Args:\n id_(int): Unique identifier for request\n '
if (id_ is not None):
id_ = deserialize_object(id_, int)
self.set_endpoint_data('id', id_) | Set the identifier for the request
Args:
id_(int): Unique identifier for request | malcolm/core/request.py | set_id | dls-controls/github-publish-test | 0 | python | def set_id(self, id_):
'\n Set the identifier for the request\n\n Args:\n id_(int): Unique identifier for request\n '
if (id_ is not None):
id_ = deserialize_object(id_, int)
self.set_endpoint_data('id', id_) | def set_id(self, id_):
'\n Set the identifier for the request\n\n Args:\n id_(int): Unique identifier for request\n '
if (id_ is not None):
id_ = deserialize_object(id_, int)
self.set_endpoint_data('id', id_)<|docstring|>Set the identifier for the request
Args:
id_(int): Unique identifier for request<|endoftext|> |
7b5cfc6a65bc179786b24e83ff131be59e2978c8ce874091e6f5245b79badaf5 | def respond_with_return(self, value=None):
'\n Create a Return Response object to handle the request\n\n Args:\n value(): Value to set endpoint to\n '
response = Return(self.id, self.context, value=value)
self.response_queue.put(response) | Create a Return Response object to handle the request
Args:
value(): Value to set endpoint to | malcolm/core/request.py | respond_with_return | dls-controls/github-publish-test | 0 | python | def respond_with_return(self, value=None):
'\n Create a Return Response object to handle the request\n\n Args:\n value(): Value to set endpoint to\n '
response = Return(self.id, self.context, value=value)
self.response_queue.put(response) | def respond_with_return(self, value=None):
'\n Create a Return Response object to handle the request\n\n Args:\n value(): Value to set endpoint to\n '
response = Return(self.id, self.context, value=value)
self.response_queue.put(response)<|docstring|>Create a Return Response object to handle the request
Args:
value(): Value to set endpoint to<|endoftext|> |
4f1fc0020cec6cae066d807a3cf74507a363951829a92a1e4302e73daf257a02 | def respond_with_error(self, message):
'\n Create an Error Response object to handle the request\n\n Args:\n message(str): Message explaining error\n '
response = Error(self.id, self.context, message=message)
self.response_queue.put(response) | Create an Error Response object to handle the request
Args:
message(str): Message explaining error | malcolm/core/request.py | respond_with_error | dls-controls/github-publish-test | 0 | python | def respond_with_error(self, message):
'\n Create an Error Response object to handle the request\n\n Args:\n message(str): Message explaining error\n '
response = Error(self.id, self.context, message=message)
self.response_queue.put(response) | def respond_with_error(self, message):
'\n Create an Error Response object to handle the request\n\n Args:\n message(str): Message explaining error\n '
response = Error(self.id, self.context, message=message)
self.response_queue.put(response)<|docstring|>Create an Error Response object to handle the request
Args:
message(str): Message explaining error<|endoftext|> |
b4484f3d3cf0223931c8e1343812f1e3fb54fc500527f4ffa8eac2d18fa0f180 | def __init__(self, context=None, response_queue=None, endpoint=None):
'\n Args:\n context(): Context of Get\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n '
super(Get, self).__init__(context, response_queue)
self.set_endpoint(endpoint) | Args:
context(): Context of Get
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None, endpoint=None):
'\n Args:\n context(): Context of Get\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n '
super(Get, self).__init__(context, response_queue)
self.set_endpoint(endpoint) | def __init__(self, context=None, response_queue=None, endpoint=None):
'\n Args:\n context(): Context of Get\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n '
super(Get, self).__init__(context, response_queue)
self.set_endpoint(endpoint)<|docstring|>Args:
context(): Context of Get
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure<|endoftext|> |
668307b5dadfd6fa13f86f98b9ea068c6a3e4a2d7d182ee458705532ec95dd43 | def __init__(self, context=None, response_queue=None, endpoint=None, value=None):
'\n Args:\n context(): Context of Put\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n value(): Value to put to endpoint e.g. String, dict\n '
super(Put, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_value(value) | Args:
context(): Context of Put
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure
value(): Value to put to endpoint e.g. String, dict | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None, endpoint=None, value=None):
'\n Args:\n context(): Context of Put\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n value(): Value to put to endpoint e.g. String, dict\n '
super(Put, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_value(value) | def __init__(self, context=None, response_queue=None, endpoint=None, value=None):
'\n Args:\n context(): Context of Put\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n value(): Value to put to endpoint e.g. String, dict\n '
super(Put, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_value(value)<|docstring|>Args:
context(): Context of Put
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure
value(): Value to put to endpoint e.g. String, dict<|endoftext|> |
b91352ff25a988605d3cb68834f85846eefbeb0bd6d78ddd9c998a10d01cf78b | def __init__(self, context=None, response_queue=None, endpoint=None, parameters=None):
'\n Args:\n context(): Context of Post\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n parameters(dict): List of parameters to post to an endpoint\n e.g. arguments for a MethodMeta\n '
super(Post, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_parameters(parameters) | Args:
context(): Context of Post
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure
parameters(dict): List of parameters to post to an endpoint
e.g. arguments for a MethodMeta | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None, endpoint=None, parameters=None):
'\n Args:\n context(): Context of Post\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n parameters(dict): List of parameters to post to an endpoint\n e.g. arguments for a MethodMeta\n '
super(Post, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_parameters(parameters) | def __init__(self, context=None, response_queue=None, endpoint=None, parameters=None):
'\n Args:\n context(): Context of Post\n response_queue(Queue): Queue to return to\n endpoint(list[str]): Path to target Block substructure\n parameters(dict): List of parameters to post to an endpoint\n e.g. arguments for a MethodMeta\n '
super(Post, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_parameters(parameters)<|docstring|>Args:
context(): Context of Post
response_queue(Queue): Queue to return to
endpoint(list[str]): Path to target Block substructure
parameters(dict): List of parameters to post to an endpoint
e.g. arguments for a MethodMeta<|endoftext|> |
67b000e7393d1e98c8456838443205e19e3e1c947dd80ef9a400c837d8c9349c | def __init__(self, context=None, response_queue=None, endpoint=None, delta=False):
'\n Args:\n context: Context of Subscribe\n response_queue (Queue): Queue to return to\n endpoint (list[str]): Path to target\n delta (bool): Notify of differences only (default False)\n '
super(Subscribe, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_delta(delta) | Args:
context: Context of Subscribe
response_queue (Queue): Queue to return to
endpoint (list[str]): Path to target
delta (bool): Notify of differences only (default False) | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None, endpoint=None, delta=False):
'\n Args:\n context: Context of Subscribe\n response_queue (Queue): Queue to return to\n endpoint (list[str]): Path to target\n delta (bool): Notify of differences only (default False)\n '
super(Subscribe, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_delta(delta) | def __init__(self, context=None, response_queue=None, endpoint=None, delta=False):
'\n Args:\n context: Context of Subscribe\n response_queue (Queue): Queue to return to\n endpoint (list[str]): Path to target\n delta (bool): Notify of differences only (default False)\n '
super(Subscribe, self).__init__(context, response_queue)
self.set_endpoint(endpoint)
self.set_delta(delta)<|docstring|>Args:
context: Context of Subscribe
response_queue (Queue): Queue to return to
endpoint (list[str]): Path to target
delta (bool): Notify of differences only (default False)<|endoftext|> |
bed84b5ecf9b1e7b4ce4b59a61892856b3f1770cd311bebf81d154b08ba0d4f2 | def respond_with_update(self, value):
'\n Create an Update Response object to handle the request\n\n Args:\n value (dict): Dictionary describing the new structure\n '
response = Update(self.id, self.context, value=value)
self.response_queue.put(response) | Create an Update Response object to handle the request
Args:
value (dict): Dictionary describing the new structure | malcolm/core/request.py | respond_with_update | dls-controls/github-publish-test | 0 | python | def respond_with_update(self, value):
'\n Create an Update Response object to handle the request\n\n Args:\n value (dict): Dictionary describing the new structure\n '
response = Update(self.id, self.context, value=value)
self.response_queue.put(response) | def respond_with_update(self, value):
'\n Create an Update Response object to handle the request\n\n Args:\n value (dict): Dictionary describing the new structure\n '
response = Update(self.id, self.context, value=value)
self.response_queue.put(response)<|docstring|>Create an Update Response object to handle the request
Args:
value (dict): Dictionary describing the new structure<|endoftext|> |
d9ee789643e10a7506b279e128a8c9a4a2d7534b66aaf12be9b69cf6856f5f61 | def respond_with_delta(self, changes):
'\n Create a Delta Response object to handle the request\n\n Args:\n changes (list): list of [[path], value] pairs for changed values\n '
response = Delta(self.id, self.context, changes=changes)
self.response_queue.put(response) | Create a Delta Response object to handle the request
Args:
changes (list): list of [[path], value] pairs for changed values | malcolm/core/request.py | respond_with_delta | dls-controls/github-publish-test | 0 | python | def respond_with_delta(self, changes):
'\n Create a Delta Response object to handle the request\n\n Args:\n changes (list): list of [[path], value] pairs for changed values\n '
response = Delta(self.id, self.context, changes=changes)
self.response_queue.put(response) | def respond_with_delta(self, changes):
'\n Create a Delta Response object to handle the request\n\n Args:\n changes (list): list of [[path], value] pairs for changed values\n '
response = Delta(self.id, self.context, changes=changes)
self.response_queue.put(response)<|docstring|>Create a Delta Response object to handle the request
Args:
changes (list): list of [[path], value] pairs for changed values<|endoftext|> |
389eec6daa6d4acaf96018d85bcb01a3772f32168406611804f0cf88bfe97637 | def __init__(self, context=None, response_queue=None):
'\n Args:\n context: Context of the Unsubscribe\n response_queue (Queue): Queue to return to\n '
super(Unsubscribe, self).__init__(context, response_queue) | Args:
context: Context of the Unsubscribe
response_queue (Queue): Queue to return to | malcolm/core/request.py | __init__ | dls-controls/github-publish-test | 0 | python | def __init__(self, context=None, response_queue=None):
'\n Args:\n context: Context of the Unsubscribe\n response_queue (Queue): Queue to return to\n '
super(Unsubscribe, self).__init__(context, response_queue) | def __init__(self, context=None, response_queue=None):
'\n Args:\n context: Context of the Unsubscribe\n response_queue (Queue): Queue to return to\n '
super(Unsubscribe, self).__init__(context, response_queue)<|docstring|>Args:
context: Context of the Unsubscribe
response_queue (Queue): Queue to return to<|endoftext|> |
5966162a86660f2b3fc8b4808a281d9023d1aff52145e5234c531fdb49db6ac8 | def title_case_property(key):
'\n Simple property for title casing a mapped value\n\n TODO remove this? It makes a broad assumption that organization names and\n job titles can be title cased when there are many edge cases.\n '
return property((lambda self: self.get_mapped_value(key).title())) | Simple property for title casing a mapped value
TODO remove this? It makes a broad assumption that organization names and
job titles can be title cased when there are many edge cases. | tx_salaries/utils/transformers/mixins.py | title_case_property | texastribune/tx_salaries | 6 | python | def title_case_property(key):
'\n Simple property for title casing a mapped value\n\n TODO remove this? It makes a broad assumption that organization names and\n job titles can be title cased when there are many edge cases.\n '
return property((lambda self: self.get_mapped_value(key).title())) | def title_case_property(key):
'\n Simple property for title casing a mapped value\n\n TODO remove this? It makes a broad assumption that organization names and\n job titles can be title cased when there are many edge cases.\n '
return property((lambda self: self.get_mapped_value(key).title()))<|docstring|>Simple property for title casing a mapped value
TODO remove this? It makes a broad assumption that organization names and
job titles can be title cased when there are many edge cases.<|endoftext|> |
ad1b37d951ec1f2d5035b86017a96ffa625f8f644ccd8545afce1ffc6594aef7 | @property
def generate_random_ua(self):
'\n 生成随机User-Agent\n :return:\n '
headers = {'User-Agent': self.ua.random}
return headers | 生成随机User-Agent
:return: | qiushibaike/qiushibaike.py | generate_random_ua | jumploop/Python3_WebSpider | 1 | python | @property
def generate_random_ua(self):
'\n 生成随机User-Agent\n :return:\n '
headers = {'User-Agent': self.ua.random}
return headers | @property
def generate_random_ua(self):
'\n 生成随机User-Agent\n :return:\n '
headers = {'User-Agent': self.ua.random}
return headers<|docstring|>生成随机User-Agent
:return:<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.