sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def amplifier_gain(self, channels=None):
"""
Get the amplifier gain used for the specified channel(s).
The amplifier gain for channel "n" is extracted from the $PnG
parameter, if available.
Parameters
----------
channels : int, str, list of int, list of str
... | Get the amplifier gain used for the specified channel(s).
The amplifier gain for channel "n" is extracted from the $PnG
parameter, if available.
Parameters
----------
channels : int, str, list of int, list of str
Channel(s) for which to get the amplifier gain. If No... | entailment |
def range(self, channels=None):
"""
Get the range of the specified channel(s).
The range is a two-element list specifying the smallest and largest
values that an event in a channel should have. Note that with
floating point data, some events could have values outside the
... | Get the range of the specified channel(s).
The range is a two-element list specifying the smallest and largest
values that an event in a channel should have. Note that with
floating point data, some events could have values outside the
range in either direction due to instrument compens... | entailment |
def resolution(self, channels=None):
"""
Get the resolution of the specified channel(s).
The resolution specifies the number of different values that the
events can take. The resolution is directly obtained from the $PnR
parameter.
Parameters
----------
... | Get the resolution of the specified channel(s).
The resolution specifies the number of different values that the
events can take. The resolution is directly obtained from the $PnR
parameter.
Parameters
----------
channels : int, str, list of int, list of str
... | entailment |
def hist_bins(self, channels=None, nbins=None, scale='logicle', **kwargs):
"""
Get histogram bin edges for the specified channel(s).
These cover the range specified in ``FCSData.range(channels)`` with
a number of bins `nbins`, with linear, logarithmic, or logicle
spacing.
... | Get histogram bin edges for the specified channel(s).
These cover the range specified in ``FCSData.range(channels)`` with
a number of bins `nbins`, with linear, logarithmic, or logicle
spacing.
Parameters
----------
channels : int, str, list of int, list of str
... | entailment |
def _parse_time_string(time_str):
"""
Get a datetime.time object from a string time representation.
The start and end of acquisition are stored in the optional keyword
parameters $BTIM and $ETIM. The following formats are used
according to the FCS standard:
- FCS 2.0... | Get a datetime.time object from a string time representation.
The start and end of acquisition are stored in the optional keyword
parameters $BTIM and $ETIM. The following formats are used
according to the FCS standard:
- FCS 2.0: 'hh:mm:ss'
- FCS 3.0: 'hh:mm:ss[:tt]', w... | entailment |
def _parse_date_string(date_str):
"""
Get a datetime.date object from a string date representation.
The FCS standard includes an optional keyword parameter $DATE in
which the acquistion date is stored. In FCS 2.0, the date is saved
as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the ... | Get a datetime.date object from a string date representation.
The FCS standard includes an optional keyword parameter $DATE in
which the acquistion date is stored. In FCS 2.0, the date is saved
as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as
'dd-mmm-yyyy'.
This ... | entailment |
def _name_to_index(self, channels):
"""
Return the channel indices for the specified channel names.
Integers contained in `channel` are returned unmodified, if they
are within the range of ``self.channels``.
Parameters
----------
channels : int or str or list of... | Return the channel indices for the specified channel names.
Integers contained in `channel` are returned unmodified, if they
are within the range of ``self.channels``.
Parameters
----------
channels : int or str or list of int or list of str
Name(s) of the channel(s... | entailment |
def find_version(file_path):
"""
Scrape version information from specified file path.
"""
with open(file_path, 'r') as f:
file_contents = f.read()
version_match = re.search(r"^__version__\s*=\s*['\"]([^'\"]*)['\"]",
file_contents, re.M)
if version_match:
... | Scrape version information from specified file path. | entailment |
def start_end(data, num_start=250, num_end=100, full_output=False):
"""
Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_en... | Gate out first and last events.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
num_start, num_end : int, optional
Number of events to gate out from beginning and end of... | entailment |
def high_low(data, channels=None, high=None, low=None, full_output=False):
"""
Gate out high and low values across all specified channels.
Gate out events in `data` with values in the specified channels which
are larger than or equal to `high` or less than or equal to `low`.
Parameters
-------... | Gate out high and low values across all specified channels.
Gate out events in `data` with values in the specified channels which
are larger than or equal to `high` or less than or equal to `low`.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the nu... | entailment |
def ellipse(data, channels,
center, a, b, theta=0,
log=False, full_output=False):
"""
Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates... | Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates of the event list, after
substracting `center` and rotating by -`theta`. This is mathematically
equivalent to... | entailment |
def density2d(data,
channels=[0,1],
bins=1024,
gate_fraction=0.65,
xscale='logicle',
yscale='logicle',
sigma=10.0,
full_output=False):
"""
Gate that preserves events in the region with highest density.
Gate ou... | Gate that preserves events in the region with highest density.
Gate out all events in `data` but those near regions of highest
density for the two specified channels.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
... | entailment |
def transform(data, channels, transform_fxn, def_channels = None):
"""
Apply some transformation function to flow cytometry data.
This function is a template transformation function, intended to be
used by other specific transformation functions. It performs basic
checks on `channels` and `data`. I... | Apply some transformation function to flow cytometry data.
This function is a template transformation function, intended to be
used by other specific transformation functions. It performs basic
checks on `channels` and `data`. It then applies `transform_fxn` to the
specified channels. Finally, it resca... | entailment |
def to_rfi(data,
channels=None,
amplification_type=None,
amplifier_gain=None,
resolution=None):
"""
Transform flow cytometry data to Relative Fluorescence Units (RFI).
If ``amplification_type[0]`` is different from zero, data has been
taken using a log amplif... | Transform flow cytometry data to Relative Fluorescence Units (RFI).
If ``amplification_type[0]`` is different from zero, data has been
taken using a log amplifier. Therefore, to transform to RFI, the
following operation is applied::
y = a[1]*10^(a[0] * (x/r))
Where ``x`` and ``y`` are the ori... | entailment |
def to_mef(data, channels, sc_list, sc_channels = None):
"""
Transform flow cytometry data using a standard curve function.
This function accepts a list of standard curves (`sc_list`) and a list
of channels to which those standard curves should be applied
(`sc_channels`). `to_mef` automatically che... | Transform flow cytometry data using a standard curve function.
This function accepts a list of standard curves (`sc_list`) and a list
of channels to which those standard curves should be applied
(`sc_channels`). `to_mef` automatically checks whether a standard curve
is available for each channel specif... | entailment |
def hist1d(data_list,
channel=0,
xscale='logicle',
bins=256,
histtype='stepfilled',
normed_area=False,
normed_height=False,
xlabel=None,
ylabel=None,
xlim=None,
ylim=None,
title=None,
lege... | Plot one 1D histogram from one or more flow cytometry data sets.
Parameters
----------
data_list : FCSData or numpy array or list of FCSData or numpy array
Flow cytometry data to plot.
channel : int or str, optional
Channel from where to take the events to plot. If ndim == 1,
ch... | entailment |
def density2d(data,
channels=[0,1],
bins=1024,
mode='mesh',
normed=False,
smooth=True,
sigma=10.0,
colorbar=False,
xscale='logicle',
yscale='logicle',
xlabel=None,
y... | Plot a 2D density plot from two channels of a flow cytometry data set.
`density2d` has two plotting modes which are selected using the `mode`
argument. With ``mode=='mesh'``, this function plots the data as a true
2D histogram, in which a plane is divided into bins and the color of
each bin is directly... | entailment |
def scatter2d(data_list,
channels=[0,1],
xscale='logicle',
yscale='logicle',
xlabel=None,
ylabel=None,
xlim=None,
ylim=None,
title=None,
color=None,
savefig=None,
**... | Plot 2D scatter plot from one or more FCSData objects or numpy arrays.
Parameters
----------
data_list : array or FCSData or list of array or list of FCSData
Flow cytometry data to plot.
channels : list of int, list of str
Two channels to use for the plot.
savefig : str, optional
... | entailment |
def scatter3d(data_list,
channels=[0,1,2],
xscale='logicle',
yscale='logicle',
zscale='logicle',
xlabel=None,
ylabel=None,
zlabel=None,
xlim=None,
ylim=None,
zlim=None,
... | Plot 3D scatter plot from one or more FCSData objects or numpy arrays.
Parameters
----------
data_list : array or FCSData or list of array or list of FCSData
Flow cytometry data to plot.
channels : list of int, list of str
Three channels to use for the plot.
savefig : str, optional
... | entailment |
def density_and_hist(data,
gated_data=None,
gate_contour=None,
density_channels=None,
density_params={},
hist_channels=None,
hist_params={},
figsize=None,
... | Make a combined density/histogram plot of a FCSData object.
This function calls `hist1d` and `density2d` to plot a density diagram
and a number of histograms in different subplots of the same plot using
one single function call. Setting `density_channels` to None will not
produce a density diagram, and... | entailment |
def scatter3d_and_projections(data_list,
channels=[0,1,2],
xscale='logicle',
yscale='logicle',
zscale='logicle',
xlabel=None,
ylabel=None,
... | Plot a 3D scatter plot and 2D projections from FCSData objects.
`scatter3d_and_projections` creates a 3D scatter plot and three 2D
projected scatter plots in four different axes for each FCSData object
in `data_list`, in the same figure.
Parameters
----------
data_list : FCSData object, or lis... | entailment |
def transform_non_affine(self, x, mask_out_of_range=True):
"""
Transform a Nx1 numpy array.
Parameters
----------
x : array
Data to be transformed.
mask_out_of_range : bool, optional
Whether to mask input values out of range.
Return
... | Transform a Nx1 numpy array.
Parameters
----------
x : array
Data to be transformed.
mask_out_of_range : bool, optional
Whether to mask input values out of range.
Return
------
array or masked array
Transformed data. | entailment |
def transform_non_affine(self, s):
"""
Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transformed data, in data value u... | Apply transformation to a Nx1 numpy array.
Parameters
----------
s : array
Data to be transformed in display scale units.
Return
------
array or masked array
Transformed data, in data value units. | entailment |
def set_params(self, subs=None, numticks=None):
"""
Set parameters within this locator.
Parameters
----------
subs : array, optional
Subtick values, as multiples of the main ticks.
numticks : array, optional
Number of ticks.
"""
i... | Set parameters within this locator.
Parameters
----------
subs : array, optional
Subtick values, as multiples of the main ticks.
numticks : array, optional
Number of ticks. | entailment |
def tick_values(self, vmin, vmax):
"""
Get a set of tick values properly spaced for logicle axis.
"""
# Extract base from transform object
b = self._transform.base
# The logicle domain is divided into two regions: A "linear" region,
# which may include negative n... | Get a set of tick values properly spaced for logicle axis. | entailment |
def view_limits(self, vmin, vmax):
"""
Try to choose the view limits intelligently.
"""
b = self._transform.base
if vmax < vmin:
vmin, vmax = vmax, vmin
if not matplotlib.ticker.is_decade(abs(vmin), b):
if vmin < 0:
vmin = -matplo... | Try to choose the view limits intelligently. | entailment |
def get_transform(self):
"""
Get a new object to perform the scaling transformation.
"""
return _InterpolatedInverseTransform(transform=self._transform,
smin=0,
smax=self._transform._M) | Get a new object to perform the scaling transformation. | entailment |
def set_default_locators_and_formatters(self, axis):
"""
Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters.
"""
axis.set_major_locator(_LogicleLocator(self._tra... | Set up the locators and formatters for the scale.
Parameters
----------
axis: matplotlib.axis
Axis for which to set locators and formatters. | entailment |
def limit_range_for_scale(self, vmin, vmax, minpos):
"""
Return minimum and maximum bounds for the logicle axis.
Parameters
----------
vmin : float
Minimum data value.
vmax : float
Maximum data value.
minpos : float
Minimum pos... | Return minimum and maximum bounds for the logicle axis.
Parameters
----------
vmin : float
Minimum data value.
vmax : float
Maximum data value.
minpos : float
Minimum positive value in the data. Ignored by this function.
Return
... | entailment |
def mean(data, channels=None):
"""
Calculate the mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list o... | Calculate the mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chan... | entailment |
def gmean(data, channels=None):
"""
Calculate the geometric mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or st... | Calculate the geometric mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
... | entailment |
def median(data, channels=None):
"""
Calculate the median of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or li... | Calculate the median of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Ch... | entailment |
def mode(data, channels=None):
"""
Calculate the mode of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list o... | Calculate the mode of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chan... | entailment |
def std(data, channels=None):
"""
Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or ... | Calculate the standard deviation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optiona... | entailment |
def cv(data, channels=None):
"""
Calculate the Coeff. of Variation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or ... | Calculate the Coeff. of Variation of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | entailment |
def gstd(data, channels=None):
"""
Calculate the geometric std. dev. of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int o... | Calculate the geometric std. dev. of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | entailment |
def gcv(data, channels=None):
"""
Calculate the geometric CV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or... | Calculate the geometric CV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
... | entailment |
def iqr(data, channels=None):
"""
Calculate the Interquartile Range of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or... | Calculate the Interquartile Range of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, option... | entailment |
def rcv(data, channels=None):
"""
Calculate the RCV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of ... | Calculate the RCV of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
Chann... | entailment |
def dados_qrcode(cfe):
"""Compila os dados que compõem o QRCode do CF-e-SAT, conforme a
documentação técnica oficial **Guia para Geração do QRCode pelo Aplicativo
Comercial**, a partir de uma instância de ``ElementTree`` que represente a
árvore do XML do CF-e-SAT.
:param cfe: Instância de :py:mod:`... | Compila os dados que compõem o QRCode do CF-e-SAT, conforme a
documentação técnica oficial **Guia para Geração do QRCode pelo Aplicativo
Comercial**, a partir de uma instância de ``ElementTree`` que represente a
árvore do XML do CF-e-SAT.
:param cfe: Instância de :py:mod:`xml.etree.ElementTree.ElementT... | entailment |
def partes(self, num_partes=11):
"""Particiona a chave do CF-e-SAT em uma lista de *n* segmentos.
:param int num_partes: O número de segmentos (partes) em que os digitos
da chave do CF-e-SAT serão particionados. **Esse número deverá
resultar em uma divisão inteira por 44 (o comp... | Particiona a chave do CF-e-SAT em uma lista de *n* segmentos.
:param int num_partes: O número de segmentos (partes) em que os digitos
da chave do CF-e-SAT serão particionados. **Esse número deverá
resultar em uma divisão inteira por 44 (o comprimento da chave)**.
Se não for ... | entailment |
def texto_decimal(valor, remover_zeros=True):
"""Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de
remover os zeros à direita não significativos. A conversão para texto irá
considerar o :py:module:`locale` para converter o texto pronto para
apresentação.
:param decimal.Decima... | Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de
remover os zeros à direita não significativos. A conversão para texto irá
considerar o :py:module:`locale` para converter o texto pronto para
apresentação.
:param decimal.Decimal valor: Valor a converter para texto.
:param boo... | entailment |
def modulo11(base):
"""Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int
"""
pes... | Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int | entailment |
def validar_casas_decimais(valor, minimo=1, maximo=2):
"""Valida o número de casas decimais. Se o número de casas decimais não
estiver dentro do mínimo e máximo, será lançada uma exceção do tipo
:py:exc:`ValueError`.
:param valor: Um objeto :py:class:`~decimal.Decimal`.
:param minimo: Valor inteir... | Valida o número de casas decimais. Se o número de casas decimais não
estiver dentro do mínimo e máximo, será lançada uma exceção do tipo
:py:exc:`ValueError`.
:param valor: Um objeto :py:class:`~decimal.Decimal`.
:param minimo: Valor inteiro maior ou igual a zero indicando o número
mínimo de c... | entailment |
def uf(sigla):
"""
Valida a sigla da Unidade Federativa. Se não for uma sigla de UF válida,
será lançada a exceção :exc:`UnidadeFederativaError`.
"""
if not sigla in [s for s, i, n, r in UNIDADES_FEDERACAO]:
raise UnidadeFederativaError('Estado (sigla) UF "%s" '
'inexistente'... | Valida a sigla da Unidade Federativa. Se não for uma sigla de UF válida,
será lançada a exceção :exc:`UnidadeFederativaError`. | entailment |
def uf_pelo_codigo(codigo_ibge):
"""Retorna a UF para o código do IBGE informado."""
idx = [i for s, i, n, r in UNIDADES_FEDERACAO].index(codigo_ibge)
return UNIDADES_FEDERACAO[idx][_UF_SIGLA] | Retorna a UF para o código do IBGE informado. | entailment |
def codigo_ibge_uf(sigla):
"""Retorna o código do IBGE para a UF informada."""
idx = [s for s, i, n, r in UNIDADES_FEDERACAO].index(sigla)
return UNIDADES_FEDERACAO[idx][_UF_CODIGO_IBGE] | Retorna o código do IBGE para a UF informada. | entailment |
def cnpj(numero):
"""Valida um número de CNPJ. O número deverá ser informado como uma string
contendo 14 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCNPJError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`."... | Valida um número de CNPJ. O número deverá ser informado como uma string
contendo 14 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCNPJError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`. | entailment |
def is_cnpj(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais carac... | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | entailment |
def as_cnpj(numero):
"""Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação.
"""
_num = digitos(numero)
if is_cnpj(_num):
return '{}.{}.{}/{}-{}'.format(
_num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:])
r... | Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação. | entailment |
def cpf(numero):
"""Valida um número de CPF. O número deverá ser informado como uma string
contendo 11 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCPFError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`.
... | Valida um número de CPF. O número deverá ser informado como uma string
contendo 11 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCPFError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`. | entailment |
def is_cpf(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caract... | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | entailment |
def as_cpf(numero):
"""Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação.
"""
_num = digitos(numero)
if is_cpf(_num):
return '{}.{}.{}-{}'.format(_num[:3], _num[3:6], _num[6:9], _num[9:])
return numero | Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação. | entailment |
def cnpjcpf(numero):
"""Valida um número de CNPJ ou CPF. Veja :func:`cnpj` e/ou :func:`cpf`."""
try:
cnpj(numero)
except NumeroCNPJError:
try:
cpf(numero)
except NumeroCPFError:
raise NumeroCNPJCPFError('numero "%s" nao valida como '
'CNPJ ... | Valida um número de CNPJ ou CPF. Veja :func:`cnpj` e/ou :func:`cpf`. | entailment |
def is_cnpjcpf(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais ca... | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | entailment |
def as_cnpjcpf(numero):
"""Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF
válidos apenas retorna o argumento sem qualquer modificação.
"""
if is_cnpj(numero):
return as_cnpj(numero)
elif is_cpf(numero):
return as_cpf(numero)
return numero | Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF
válidos apenas retorna o argumento sem qualquer modificação. | entailment |
def cep(numero):
"""Valida um número de CEP. O número deverá ser informado como uma string
contendo 8 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCEPError`.
.. warning::
Qualquer string que contenha 8 dígitos será considerada como um CEP
vál... | Valida um número de CEP. O número deverá ser informado como uma string
contendo 8 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCEPError`.
.. warning::
Qualquer string que contenha 8 dígitos será considerada como um CEP
válido, desde que os dígito... | entailment |
def is_cep(numero, estrito=False):
"""Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caract... | Uma versão conveniente para usar em testes condicionais. Apenas retorna
verdadeiro ou falso, conforme o argumento é validado.
:param bool estrito: Padrão ``False``, indica se apenas os dígitos do
número deverão ser considerados. Se verdadeiro, potenciais caracteres
que formam a máscara serão re... | entailment |
def as_cep(numero):
"""Formata um número de CEP. Se o argumento não for um CEP válido apenas
retorna o argumento sem qualquer modificação.
"""
_numero = digitos(numero)
if is_cep(_numero):
return '{}-{}'.format(_numero[:5], _numero[5:])
return numero | Formata um número de CEP. Se o argumento não for um CEP válido apenas
retorna o argumento sem qualquer modificação. | entailment |
def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None):
"""Recursively convert a potentially-multipart tree.
Returns a tuple of (the converted tree, whether any markdown was found)
"""
ct = message.get_content_type()
cs = message.get_content_subtype()
if charset is Non... | Recursively convert a potentially-multipart tree.
Returns a tuple of (the converted tree, whether any markdown was found) | entailment |
def smtp_connection(c):
"""Create an SMTP connection from a Config object"""
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls()
conn.e... | Create an SMTP connection from a Config object | entailment |
def issuers(self):
"""Return the list of available issuers for this payment method."""
issuers = self._get_property('issuers') or []
result = {
'_embedded': {
'issuers': issuers,
},
'count': len(issuers),
}
return List(result, I... | Return the list of available issuers for this payment method. | entailment |
def delete(self, payment_id, data=None):
"""Cancel payment and return the payment object.
Deleting a payment causes the payment status to change to canceled.
The updated payment object is returned.
"""
if not payment_id or not payment_id.startswith(self.RESOURCE_ID_PREFIX):
... | Cancel payment and return the payment object.
Deleting a payment causes the payment status to change to canceled.
The updated payment object is returned. | entailment |
def mandate(self):
"""Return the mandate for this payment."""
return self.client.customer_mandates.with_parent_id(self.customer_id).get(self.mandate_id) | Return the mandate for this payment. | entailment |
def subscription(self):
"""Return the subscription for this payment."""
return self.client.customer_subscriptions.with_parent_id(self.customer_id).get(self.subscription_id) | Return the subscription for this payment. | entailment |
def order(self):
"""Return the order for this payment. """
from ..resources.orders import Order
url = self._get_link('order')
if url:
resp = self.client.orders.perform_api_call(self.client.orders.REST_READ, url)
return Order(resp, self.client) | Return the order for this payment. | entailment |
def get_version():
"""
Read the version from a file (mollie/api/version.py) in the repository.
We can't import here since we might import from an installed version.
"""
try:
version_file = open(os.path.join(ROOT_DIR, 'mollie', 'api', 'version.py'), encoding='utf=8')
except TypeError:
... | Read the version from a file (mollie/api/version.py) in the repository.
We can't import here since we might import from an installed version. | entailment |
def create_refund(self, data=None, **params):
"""Create a refund for the order. When no data arg is given, a refund for all order lines is assumed."""
if data is None:
data = {'lines': []}
refund = OrderRefunds(self.client).on(self).create(data, **params)
return refund | Create a refund for the order. When no data arg is given, a refund for all order lines is assumed. | entailment |
def cancel_lines(self, data=None):
"""Cancel the lines given. When no lines are given, cancel all the lines.
Canceling an order line causes the order line status to change to canceled.
An empty dictionary will be returned.
"""
from ..resources.order_lines import OrderLines
... | Cancel the lines given. When no lines are given, cancel all the lines.
Canceling an order line causes the order line status to change to canceled.
An empty dictionary will be returned. | entailment |
def update_line(self, resource_id, data):
"""Update a line for an order."""
return OrderLines(self.client).on(self).update(resource_id, data) | Update a line for an order. | entailment |
def create_shipment(self, data=None):
"""Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed."""
if data is None:
data = {'lines': []}
return Shipments(self.client).on(self).create(data) | Create a shipment for an order. When no data arg is given, a shipment for all order lines is assumed. | entailment |
def get_shipment(self, resource_id):
"""Retrieve a single shipment by a shipment's ID."""
return Shipments(self.client).on(self).get(resource_id) | Retrieve a single shipment by a shipment's ID. | entailment |
def update_shipment(self, resource_id, data):
"""Update the tracking information of a shipment."""
return Shipments(self.client).on(self).update(resource_id, data) | Update the tracking information of a shipment. | entailment |
def create_payment(self, data):
""" Creates a new payment object for an order. """
return OrderPayments(self.client).on(self).create(data) | Creates a new payment object for an order. | entailment |
def delete(self, data, *args):
"""
Custom handling for deleting orderlines.
Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint,
with the orderline IDs and quantities in the request body.
"""
path = self.get_resource_name()
result = self.per... | Custom handling for deleting orderlines.
Orderlines are deleted by issuing a DELETE on the orders/*/lines endpoint,
with the orderline IDs and quantities in the request body. | entailment |
def update(self, resource_id, data=None, **params):
"""
Custom handling for updating orderlines.
The API returns an Order object. Since we are sending the request through an orderline object, it makes more
sense to convert the returned object to to the updated orderline object.
... | Custom handling for updating orderlines.
The API returns an Order object. Since we are sending the request through an orderline object, it makes more
sense to convert the returned object to to the updated orderline object.
If you wish to retrieve the order object, you can do so by using the or... | entailment |
def get_next(self):
"""Return the next set of objects in a list"""
url = self._get_link('next')
resource = self.object_type.get_resource_class(self.client)
resp = resource.perform_api_call(resource.REST_READ, url)
return List(resp, self.object_type, self.client) | Return the next set of objects in a list | entailment |
def delete(self, subscription_id, data=None):
"""Cancel subscription and return the subscription object.
Deleting a subscription causes the subscription status to changed to 'canceled'.
The updated subscription object is returned.
"""
if not subscription_id or not subscription_i... | Cancel subscription and return the subscription object.
Deleting a subscription causes the subscription status to changed to 'canceled'.
The updated subscription object is returned. | entailment |
def get(self, chargeback_id, **params):
"""Verify the chargeback ID and retrieve the chargeback from the API."""
if not chargeback_id or not chargeback_id.startswith(self.RESOURCE_ID_PREFIX):
raise IdentifierError(
"Invalid chargeback ID: '{id}'. A chargeback ID should start ... | Verify the chargeback ID and retrieve the chargeback from the API. | entailment |
def generate_querystring(params):
"""
Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sort... | Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sorted()` to work around a difference in iteration... | entailment |
def set_user_agent_component(self, key, value, sanitize=True):
"""Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multiple key/values are sepa... | Add or replace new user-agent component strings.
Given strings are formatted along the format agreed upon by Mollie and implementers:
- key and values are separated by a forward slash ("/").
- multiple key/values are separated by a space.
- keys are camel-cased, and cannot contain space... | entailment |
def user_agent(self):
"""Return the formatted user agent string."""
components = ["/".join(x) for x in self.user_agent_components.items()]
return " ".join(components) | Return the formatted user agent string. | entailment |
def factory(resp):
"""
Return a ResponseError subclass based on the API payload.
All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes
More exceptions should be added here when appropriate, and when useful examples of API errors are availabl... | Return a ResponseError subclass based on the API payload.
All errors are documented: https://docs.mollie.com/guides/handling-errors#all-possible-status-codes
More exceptions should be added here when appropriate, and when useful examples of API errors are available. | entailment |
def delete(self, order_id, data=None):
"""Cancel order and return the order object.
Deleting an order causes the order status to change to canceled.
The updated order object is returned.
"""
if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX):
raise I... | Cancel order and return the order object.
Deleting an order causes the order status to change to canceled.
The updated order object is returned. | entailment |
def customer(self):
"""Return the customer for this subscription."""
url = self._get_link('customer')
if url:
resp = self.client.customers.perform_api_call(self.client.customers.REST_READ, url)
return Customer(resp) | Return the customer for this subscription. | entailment |
def payments(self):
"""Return a list of payments for this subscription."""
payments = self.client.subscription_payments.on(self).list()
return payments | Return a list of payments for this subscription. | entailment |
def list_groups(self, filtr, url_prefix, auth, session, send_opts):
"""Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
url_prefix (string): Protocol ... | Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send ... | entailment |
def delete_group(self, name, url_prefix, auth, session, send_opts):
"""Delete given group.
Args:
name (string): Name of group.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session ... | Delete given group.
Args:
name (string): Name of group.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
send_opts (dic... | entailment |
def list_group_members(self, name, url_prefix, auth, session, send_opts):
"""Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Tok... | Get the members of a group (does not include maintainers).
Args:
name (string): Name of group to query.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP sessio... | entailment |
def list_permissions(self, group_name=None, resource=None,
url_prefix=None, auth=None, session=None, send_opts=None):
"""List the permission sets for the logged in user
Optionally filter by resource or group.
Args:
group_name (string): Name of group to filte... | List the permission sets for the logged in user
Optionally filter by resource or group.
Args:
group_name (string): Name of group to filter on
resource (intern.resource.boss.BossResource): Identifies which data model object to filter on
url_prefix (string): Protocol ... | entailment |
def add_permissions(self, group_name, resource, permissions, url_prefix, auth, session, send_opts):
"""
Args:
group_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List o... | Args:
group_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
permissions (list): List of permissions to add to the given resource.
url_prefix (string): Protocol + host such as https://api.theboss... | entailment |
def delete_permissions(self, grp_name, resource, url_prefix, auth, session, send_opts):
"""
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
url_prefix (string): Protocol + host suc... | Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
sess... | entailment |
def get_user_roles(self, user, url_prefix, auth, session, send_opts):
"""Get roles associated with the given user.
Args:
user (string): User name.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
... | Get roles associated with the given user.
Args:
user (string): User name.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session to use for request.
... | entailment |
def add_user(
self, user, first_name, last_name, email, password,
url_prefix, auth, session, send_opts):
"""Add a new user.
Args:
user (string): User name.
first_name (string): User's first name.
last_name (string): User's last name.
email... | Add a new user.
Args:
user (string): User name.
first_name (string): User's first name.
last_name (string): User's last name.
email: (string): User's email address.
password: (string): User's password.
url_prefix (string): Protocol + host ... | entailment |
def list(self, resource, url_prefix, auth, session, send_opts):
"""List all resources of the same type as the given resource.
Args:
resource (intern.resource.boss.BossResource): List resources of the same type as this..
url_prefix (string): Protocol + host such as https://api.th... | List all resources of the same type as the given resource.
Args:
resource (intern.resource.boss.BossResource): List resources of the same type as this..
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
... | entailment |
def update(self, resource_name, resource, url_prefix, auth, session, send_opts):
"""Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the resource is getting its name changed).
resource (intern.resou... | Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the resource is getting its name changed).
resource (intern.resource.boss.BossResource): New attributes for the resource.
url_prefix (string): Pr... | entailment |
def delete(self, resource, url_prefix, auth, session, send_opts):
"""Deletes the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to sen... | Deletes the entity described by the given resource.
Args:
resource (intern.resource.boss.BossResource)
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send in the request header.
session (requests.Session): HTTP session... | entailment |
def _get_resource_params(self, resource, for_update=False):
"""Get dictionary containing all parameters for the given resource.
When getting params for a coordinate frame update, only name and
description are returned because they are the only fields that can
be updated.
Args:
... | Get dictionary containing all parameters for the given resource.
When getting params for a coordinate frame update, only name and
description are returned because they are the only fields that can
be updated.
Args:
resource (intern.resource.boss.resource.BossResource): A su... | entailment |
def _create_resource_from_dict(self, resource, dict):
"""
Args:
resource (intern.resource.boss.BossResource): Used to determine type of resource to create.
dict (dictionary): JSON data returned by the Boss API.
Returns:
(intern.resource.boss.BossResource): In... | Args:
resource (intern.resource.boss.BossResource): Used to determine type of resource to create.
dict (dictionary): JSON data returned by the Boss API.
Returns:
(intern.resource.boss.BossResource): Instance populated with values from dict.
Raises:
KeyEr... | entailment |
def _get_resource_list(self, rsrc_dict):
"""Extracts list of resources from the HTTP response.
Args:
rsrc_dict (dict): HTTP response encoded in a dictionary.
Returns:
(list[string]): List of a type of resource (collections, experiments, etc).
Raises:
... | Extracts list of resources from the HTTP response.
Args:
rsrc_dict (dict): HTTP response encoded in a dictionary.
Returns:
(list[string]): List of a type of resource (collections, experiments, etc).
Raises:
(RuntimeError): If rsrc_dict does not contain any ... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.