repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
limix/limix-core | limix_core/covar/covar_base.py | Covariance.Kgrad_param_num | def Kgrad_param_num(self,i,h=1e-4):
"""
check discrepancies between numerical and analytical gradients
"""
params = self.getParams()
e = sp.zeros_like(params); e[i] = 1
self.setParams(params-h*e)
C_L = self.K()
self.setParams(params+h*e)
C_R = self.K()
self.setParams(params)
RV = (C_R-C_L)/(2*h)
return RV | python | def Kgrad_param_num(self,i,h=1e-4):
"""
check discrepancies between numerical and analytical gradients
"""
params = self.getParams()
e = sp.zeros_like(params); e[i] = 1
self.setParams(params-h*e)
C_L = self.K()
self.setParams(params+h*e)
C_R = self.K()
self.setParams(params)
RV = (C_R-C_L)/(2*h)
return RV | [
"def",
"Kgrad_param_num",
"(",
"self",
",",
"i",
",",
"h",
"=",
"1e-4",
")",
":",
"params",
"=",
"self",
".",
"getParams",
"(",
")",
"e",
"=",
"sp",
".",
"zeros_like",
"(",
"params",
")",
"e",
"[",
"i",
"]",
"=",
"1",
"self",
".",
"setParams",
... | check discrepancies between numerical and analytical gradients | [
"check",
"discrepancies",
"between",
"numerical",
"and",
"analytical",
"gradients"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/covar_base.py#L272-L284 |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py | parallel_snr_func | def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
phenomdwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`.
signal_type (list of str): List with types of SNR to calculate.
Options are `all` for full wavefrom,
`ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation.
"""
wave = phenomdwave(*binary_args)
out_vals = {}
for key in noise_interpolants:
hn_vals = noise_interpolants[key](wave.freqs)
snr_out = csnr(wave.freqs, wave.hc, hn_vals,
wave.fmrg, wave.fpeak, prefactor=prefactor)
if len(signal_type) == 1:
out_vals[key + '_' + signal_type[0]] = snr_out[signal_type[0]]
else:
for phase in signal_type:
out_vals[key + '_' + phase] = snr_out[phase]
if verbose > 0 and (num+1) % verbose == 0:
print('Process ', (num+1), 'is finished.')
return out_vals | python | def parallel_snr_func(num, binary_args, phenomdwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
phenomdwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`.
signal_type (list of str): List with types of SNR to calculate.
Options are `all` for full wavefrom,
`ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation.
"""
wave = phenomdwave(*binary_args)
out_vals = {}
for key in noise_interpolants:
hn_vals = noise_interpolants[key](wave.freqs)
snr_out = csnr(wave.freqs, wave.hc, hn_vals,
wave.fmrg, wave.fpeak, prefactor=prefactor)
if len(signal_type) == 1:
out_vals[key + '_' + signal_type[0]] = snr_out[signal_type[0]]
else:
for phase in signal_type:
out_vals[key + '_' + phase] = snr_out[phase]
if verbose > 0 and (num+1) % verbose == 0:
print('Process ', (num+1), 'is finished.')
return out_vals | [
"def",
"parallel_snr_func",
"(",
"num",
",",
"binary_args",
",",
"phenomdwave",
",",
"signal_type",
",",
"noise_interpolants",
",",
"prefactor",
",",
"verbose",
")",
":",
"wave",
"=",
"phenomdwave",
"(",
"*",
"binary_args",
")",
"out_vals",
"=",
"{",
"}",
"f... | SNR calulation with PhenomDWaveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
phenomdwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`.
signal_type (list of str): List with types of SNR to calculate.
Options are `all` for full wavefrom,
`ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation. | [
"SNR",
"calulation",
"with",
"PhenomDWaveforms"
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py#L102-L144 |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py | parallel_ecc_snr_func | def parallel_ecc_snr_func(num, binary_args, eccwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with eccentric waveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
eccwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.EccentricBinaries`.
signal_type (list of str): List with types of SNR to calculate.
`all` for quadrature sum of modes or `modes` for SNR from each mode.
This must be `all` if generating contour data with
:mod:`gwsnrcalc.generate_contour_data`.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation.
"""
wave = eccwave(*binary_args)
out_vals = {}
for key in noise_interpolants:
hn_vals = noise_interpolants[key](wave.freqs)
integrand = 1./wave.freqs * (wave.hc**2/hn_vals**2)
snr_squared_out = np.trapz(integrand, x=wave.freqs)
if 'modes' in signal_type:
out_vals[key + '_' + 'modes'] = prefactor*np.sqrt(snr_squared_out)
if 'all' in signal_type:
out_vals[key + '_' + 'all'] = prefactor*np.sqrt(np.sum(snr_squared_out, axis=-1))
if verbose > 0 and (num+1) % verbose == 0:
print('Process ', (num+1), 'is finished.')
return out_vals | python | def parallel_ecc_snr_func(num, binary_args, eccwave, signal_type,
noise_interpolants, prefactor, verbose):
"""SNR calulation with eccentric waveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
eccwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.EccentricBinaries`.
signal_type (list of str): List with types of SNR to calculate.
`all` for quadrature sum of modes or `modes` for SNR from each mode.
This must be `all` if generating contour data with
:mod:`gwsnrcalc.generate_contour_data`.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation.
"""
wave = eccwave(*binary_args)
out_vals = {}
for key in noise_interpolants:
hn_vals = noise_interpolants[key](wave.freqs)
integrand = 1./wave.freqs * (wave.hc**2/hn_vals**2)
snr_squared_out = np.trapz(integrand, x=wave.freqs)
if 'modes' in signal_type:
out_vals[key + '_' + 'modes'] = prefactor*np.sqrt(snr_squared_out)
if 'all' in signal_type:
out_vals[key + '_' + 'all'] = prefactor*np.sqrt(np.sum(snr_squared_out, axis=-1))
if verbose > 0 and (num+1) % verbose == 0:
print('Process ', (num+1), 'is finished.')
return out_vals | [
"def",
"parallel_ecc_snr_func",
"(",
"num",
",",
"binary_args",
",",
"eccwave",
",",
"signal_type",
",",
"noise_interpolants",
",",
"prefactor",
",",
"verbose",
")",
":",
"wave",
"=",
"eccwave",
"(",
"*",
"binary_args",
")",
"out_vals",
"=",
"{",
"}",
"for",... | SNR calulation with eccentric waveforms
Generate PhenomDWaveforms and calculate their SNR against sensitivity curves.
Args:
num (int): Process number. If only a single process, num=0.
binary_args (tuple): Binary arguments for
:meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`.
eccwave (obj): Initialized class of
:class:`gwsnrcalc.utils.waveforms.EccentricBinaries`.
signal_type (list of str): List with types of SNR to calculate.
`all` for quadrature sum of modes or `modes` for SNR from each mode.
This must be `all` if generating contour data with
:mod:`gwsnrcalc.generate_contour_data`.
noise_interpolants (dict): All the noise noise interpolants generated by
:mod:`gwsnrcalc.utils.sensitivity`.
prefactor (float): Prefactor to multiply SNR by (not SNR^2).
verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification.
Returns:
(dict): Dictionary with the SNR output from the calculation. | [
"SNR",
"calulation",
"with",
"eccentric",
"waveforms"
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py#L147-L190 |
mikekatz04/BOWIE | snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py | snr | def snr(*args, **kwargs):
"""Compute the SNR of binaries.
snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.
Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used at once. However,
you cannot input multiple arrays of different lengths.
Arguments:
*args: Arguments for :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
**kwargs: Keyword arguments related to
parallel generation (see :class:`gwsnrcalc.utils.parallel`),
waveforms (see :class:`gwsnrcalc.utils.pyphenomd`),
or sensitivity information (see :class:`gwsnrcalc.utils.sensitivity`).
Returns:
(dict or list of dict): Signal-to-Noise Ratio dictionary for requested phases.
"""
squeeze = False
max_length = 0
for arg in args:
try:
length = len(arg)
if length > max_length:
max_length = length
except TypeError:
pass
if max_length == 0:
squeeze = True
kwargs['length'] = max_length
snr_main = SNR(**kwargs)
if squeeze:
snr_out = snr_main(*args)
return {key: np.squeeze(snr_out[key]) for key in snr_out}
return snr_main(*args) | python | def snr(*args, **kwargs):
"""Compute the SNR of binaries.
snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.
Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used at once. However,
you cannot input multiple arrays of different lengths.
Arguments:
*args: Arguments for :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
**kwargs: Keyword arguments related to
parallel generation (see :class:`gwsnrcalc.utils.parallel`),
waveforms (see :class:`gwsnrcalc.utils.pyphenomd`),
or sensitivity information (see :class:`gwsnrcalc.utils.sensitivity`).
Returns:
(dict or list of dict): Signal-to-Noise Ratio dictionary for requested phases.
"""
squeeze = False
max_length = 0
for arg in args:
try:
length = len(arg)
if length > max_length:
max_length = length
except TypeError:
pass
if max_length == 0:
squeeze = True
kwargs['length'] = max_length
snr_main = SNR(**kwargs)
if squeeze:
snr_out = snr_main(*args)
return {key: np.squeeze(snr_out[key]) for key in snr_out}
return snr_main(*args) | [
"def",
"snr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"squeeze",
"=",
"False",
"max_length",
"=",
"0",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"length",
"=",
"len",
"(",
"arg",
")",
"if",
"length",
">",
"max_length",
":",
"max_l... | Compute the SNR of binaries.
snr is a function that takes binary parameters and sensitivity curves as inputs,
and returns snr for chosen phases.
Warning: All binary parameters must be either scalar, len-1 arrays,
or arrays of the same length. All of these can be used at once. However,
you cannot input multiple arrays of different lengths.
Arguments:
*args: Arguments for :meth:`gwsnrcalc.utils.pyphenomd.PhenomDWaveforms.__call__`
**kwargs: Keyword arguments related to
parallel generation (see :class:`gwsnrcalc.utils.parallel`),
waveforms (see :class:`gwsnrcalc.utils.pyphenomd`),
or sensitivity information (see :class:`gwsnrcalc.utils.sensitivity`).
Returns:
(dict or list of dict): Signal-to-Noise Ratio dictionary for requested phases. | [
"Compute",
"the",
"SNR",
"of",
"binaries",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/snr_calculator_folder/gwsnrcalc/gw_snr_calculator.py#L193-L234 |
ubccr/pinky | pinky/smiles/parser.py | smilin | def smilin(smiles, transforms=[figueras.sssr, aromaticity.aromatize]):
"""(smiles)->molecule
Convert a smiles string into a molecule representation"""
builder = BuildMol()
tokenize(smiles, builder)
mol = builder.mol
for transform in transforms:
mol = transform(mol)
## implicit hcount doesn't make any sense anymore...
for atom in mol.atoms:
if not atom.has_explicit_hcount:
atom.imp_hcount = atom.hcount - atom.explicit_hcount
return mol | python | def smilin(smiles, transforms=[figueras.sssr, aromaticity.aromatize]):
"""(smiles)->molecule
Convert a smiles string into a molecule representation"""
builder = BuildMol()
tokenize(smiles, builder)
mol = builder.mol
for transform in transforms:
mol = transform(mol)
## implicit hcount doesn't make any sense anymore...
for atom in mol.atoms:
if not atom.has_explicit_hcount:
atom.imp_hcount = atom.hcount - atom.explicit_hcount
return mol | [
"def",
"smilin",
"(",
"smiles",
",",
"transforms",
"=",
"[",
"figueras",
".",
"sssr",
",",
"aromaticity",
".",
"aromatize",
"]",
")",
":",
"builder",
"=",
"BuildMol",
"(",
")",
"tokenize",
"(",
"smiles",
",",
"builder",
")",
"mol",
"=",
"builder",
".",... | (smiles)->molecule
Convert a smiles string into a molecule representation | [
"(",
"smiles",
")",
"-",
">",
"molecule",
"Convert",
"a",
"smiles",
"string",
"into",
"a",
"molecule",
"representation"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/smiles/parser.py#L204-L220 |
chbrown/argv | argv/parsers/inferential.py | InferentialParser.parse | def parse(self, args=None):
'''Parse a list of arguments, returning a dict.
Flags are only boolean if they are not followed by a non-flag argument.
All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field.
'''
opts = dict()
if args is None:
import sys
# skip over the program name with the [1:] slice
args = sys.argv[1:]
# arglist is a tuple of (is_flag, name) pairs
arglist = peekable(parse_tokens(args))
for is_flag, name in arglist:
if is_flag is True:
# .peek will return the default argument iff there are no more entries
next_is_flag, next_name = arglist.peek(default=(None, None))
# next_is_flag will be None if there are no more items, but True/False if there is a next item
# if this argument looks for a subsequent (is set as boolean),
# and the subsequent is not a flag, consume it
if next_is_flag is False:
opts[name] = next_name
# finally, advance our iterator, but since we already have the next values, just discard it
arglist.next()
else:
# if there is no next thing, or the next thing is a flag,
# all the boolean=False's in the world can't save you then
opts[name] = True
else:
# add positional argument
opts.setdefault('_', []).append(name)
return opts | python | def parse(self, args=None):
'''Parse a list of arguments, returning a dict.
Flags are only boolean if they are not followed by a non-flag argument.
All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field.
'''
opts = dict()
if args is None:
import sys
# skip over the program name with the [1:] slice
args = sys.argv[1:]
# arglist is a tuple of (is_flag, name) pairs
arglist = peekable(parse_tokens(args))
for is_flag, name in arglist:
if is_flag is True:
# .peek will return the default argument iff there are no more entries
next_is_flag, next_name = arglist.peek(default=(None, None))
# next_is_flag will be None if there are no more items, but True/False if there is a next item
# if this argument looks for a subsequent (is set as boolean),
# and the subsequent is not a flag, consume it
if next_is_flag is False:
opts[name] = next_name
# finally, advance our iterator, but since we already have the next values, just discard it
arglist.next()
else:
# if there is no next thing, or the next thing is a flag,
# all the boolean=False's in the world can't save you then
opts[name] = True
else:
# add positional argument
opts.setdefault('_', []).append(name)
return opts | [
"def",
"parse",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"opts",
"=",
"dict",
"(",
")",
"if",
"args",
"is",
"None",
":",
"import",
"sys",
"# skip over the program name with the [1:] slice",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"... | Parse a list of arguments, returning a dict.
Flags are only boolean if they are not followed by a non-flag argument.
All positional arguments not associable with a flag will be added to the return dictionary's `['_']` field. | [
"Parse",
"a",
"list",
"of",
"arguments",
"returning",
"a",
"dict",
"."
] | train | https://github.com/chbrown/argv/blob/5e2b0424a060027c029ad9c16d90bd14a2ff53f8/argv/parsers/inferential.py#L9-L45 |
limix/limix-core | limix_core/linalg/dist.py | sq_dist | def sq_dist(X1,X2=None):
"""
computes a matrix of all pariwise squared distances
"""
if X2==None:
X2 = X1
assert X1.shape[1]==X2.shape[1], 'dimensions do not match'
n = X1.shape[0]
m = X2.shape[0]
d = X1.shape[1]
# (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2
X1sq = sp.reshape((X1**2).sum(1),n,1)
X2sq = sp.reshape((X2**2).sum(1),m,1)
K = sp.tile((X1*X1).sum(1),(m,1)).T + sp.tile((X2*X2).sum(1),(n,1)) - 2*sp.dot(X1,X2.T)
return K | python | def sq_dist(X1,X2=None):
"""
computes a matrix of all pariwise squared distances
"""
if X2==None:
X2 = X1
assert X1.shape[1]==X2.shape[1], 'dimensions do not match'
n = X1.shape[0]
m = X2.shape[0]
d = X1.shape[1]
# (X1 - X2)**2 = X1**2 + X2**2 - 2X1X2
X1sq = sp.reshape((X1**2).sum(1),n,1)
X2sq = sp.reshape((X2**2).sum(1),m,1)
K = sp.tile((X1*X1).sum(1),(m,1)).T + sp.tile((X2*X2).sum(1),(n,1)) - 2*sp.dot(X1,X2.T)
return K | [
"def",
"sq_dist",
"(",
"X1",
",",
"X2",
"=",
"None",
")",
":",
"if",
"X2",
"==",
"None",
":",
"X2",
"=",
"X1",
"assert",
"X1",
".",
"shape",
"[",
"1",
"]",
"==",
"X2",
".",
"shape",
"[",
"1",
"]",
",",
"'dimensions do not match'",
"n",
"=",
"X1... | computes a matrix of all pariwise squared distances | [
"computes",
"a",
"matrix",
"of",
"all",
"pariwise",
"squared",
"distances"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/linalg/dist.py#L5-L21 |
ubccr/pinky | pinky/mol/bond.py | Bond.setdbo | def setdbo(self, bond1, bond2, dboval):
"""Set the double bond orientation for bond1 and bond2
based on this bond"""
# this bond must be a double bond
if self.bondtype != 2:
raise FrownsError("To set double bond order, center bond must be double!")
assert dboval in [DX_CHI_CIS, DX_CHI_TRANS, DX_CHI_NO_DBO], "bad dboval value"
self.dbo.append(bond1, bond2, dboval) | python | def setdbo(self, bond1, bond2, dboval):
"""Set the double bond orientation for bond1 and bond2
based on this bond"""
# this bond must be a double bond
if self.bondtype != 2:
raise FrownsError("To set double bond order, center bond must be double!")
assert dboval in [DX_CHI_CIS, DX_CHI_TRANS, DX_CHI_NO_DBO], "bad dboval value"
self.dbo.append(bond1, bond2, dboval) | [
"def",
"setdbo",
"(",
"self",
",",
"bond1",
",",
"bond2",
",",
"dboval",
")",
":",
"# this bond must be a double bond",
"if",
"self",
".",
"bondtype",
"!=",
"2",
":",
"raise",
"FrownsError",
"(",
"\"To set double bond order, center bond must be double!\"",
")",
"ass... | Set the double bond orientation for bond1 and bond2
based on this bond | [
"Set",
"the",
"double",
"bond",
"orientation",
"for",
"bond1",
"and",
"bond2",
"based",
"on",
"this",
"bond"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/bond.py#L80-L88 |
ubccr/pinky | pinky/mol/bond.py | Bond.set_symbol | def set_symbol(self, symbol):
"""(symbol, bondorder) -> set the bondsymbol
of the molecule"""
raise "Deprecated"
self.symbol, self.bondtype, bondorder, self.equiv_class = \
BONDLOOKUP[symbol]
if self.bondtype == 4:
self.aromatic = 1
else:
self.aromatic = 0 | python | def set_symbol(self, symbol):
"""(symbol, bondorder) -> set the bondsymbol
of the molecule"""
raise "Deprecated"
self.symbol, self.bondtype, bondorder, self.equiv_class = \
BONDLOOKUP[symbol]
if self.bondtype == 4:
self.aromatic = 1
else:
self.aromatic = 0 | [
"def",
"set_symbol",
"(",
"self",
",",
"symbol",
")",
":",
"raise",
"\"Deprecated\"",
"self",
".",
"symbol",
",",
"self",
".",
"bondtype",
",",
"bondorder",
",",
"self",
".",
"equiv_class",
"=",
"BONDLOOKUP",
"[",
"symbol",
"]",
"if",
"self",
".",
"bondt... | (symbol, bondorder) -> set the bondsymbol
of the molecule | [
"(",
"symbol",
"bondorder",
")",
"-",
">",
"set",
"the",
"bondsymbol",
"of",
"the",
"molecule"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/bond.py#L104-L113 |
ubccr/pinky | pinky/mol/bond.py | Bond.xatom | def xatom(self, atom):
"""(atom)->return the atom at the other end of this bond
or None if atom is not part of this bond"""
handle = atom.handle
if handle == self.atoms[0].handle:
return self.atoms[1]
elif handle == self.atoms[1].handle:
return self.atoms[0]
return None | python | def xatom(self, atom):
"""(atom)->return the atom at the other end of this bond
or None if atom is not part of this bond"""
handle = atom.handle
if handle == self.atoms[0].handle:
return self.atoms[1]
elif handle == self.atoms[1].handle:
return self.atoms[0]
return None | [
"def",
"xatom",
"(",
"self",
",",
"atom",
")",
":",
"handle",
"=",
"atom",
".",
"handle",
"if",
"handle",
"==",
"self",
".",
"atoms",
"[",
"0",
"]",
".",
"handle",
":",
"return",
"self",
".",
"atoms",
"[",
"1",
"]",
"elif",
"handle",
"==",
"self"... | (atom)->return the atom at the other end of this bond
or None if atom is not part of this bond | [
"(",
"atom",
")",
"-",
">",
"return",
"the",
"atom",
"at",
"the",
"other",
"end",
"of",
"this",
"bond",
"or",
"None",
"if",
"atom",
"is",
"not",
"part",
"of",
"this",
"bond"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/bond.py#L129-L138 |
wangsix/vmo | vmo/io.py | save_segments | def save_segments(outfile, boundaries, beat_intervals, labels=None):
"""Save detected segments to a .lab file.
:parameters:
- outfile : str
Path to output file
- boundaries : list of int
Beat indices of detected segment boundaries
- beat_intervals : np.ndarray [shape=(n, 2)]
Intervals of beats
- labels : None or list of str
Labels of detected segments
"""
if labels is None:
labels = [('Seg#%03d' % idx) for idx in range(1, len(boundaries))]
times = [beat_intervals[beat, 0] for beat in boundaries[:-1]]
times.append(beat_intervals[-1, -1])
with open(outfile, 'w') as f:
for idx, (start, end, lab) in enumerate(zip(times[:-1],
times[1:],
labels), 1):
f.write('%.3f\t%.3f\t%s\n' % (start, end, lab)) | python | def save_segments(outfile, boundaries, beat_intervals, labels=None):
"""Save detected segments to a .lab file.
:parameters:
- outfile : str
Path to output file
- boundaries : list of int
Beat indices of detected segment boundaries
- beat_intervals : np.ndarray [shape=(n, 2)]
Intervals of beats
- labels : None or list of str
Labels of detected segments
"""
if labels is None:
labels = [('Seg#%03d' % idx) for idx in range(1, len(boundaries))]
times = [beat_intervals[beat, 0] for beat in boundaries[:-1]]
times.append(beat_intervals[-1, -1])
with open(outfile, 'w') as f:
for idx, (start, end, lab) in enumerate(zip(times[:-1],
times[1:],
labels), 1):
f.write('%.3f\t%.3f\t%s\n' % (start, end, lab)) | [
"def",
"save_segments",
"(",
"outfile",
",",
"boundaries",
",",
"beat_intervals",
",",
"labels",
"=",
"None",
")",
":",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"[",
"(",
"'Seg#%03d'",
"%",
"idx",
")",
"for",
"idx",
"in",
"range",
"(",
"1",
... | Save detected segments to a .lab file.
:parameters:
- outfile : str
Path to output file
- boundaries : list of int
Beat indices of detected segment boundaries
- beat_intervals : np.ndarray [shape=(n, 2)]
Intervals of beats
- labels : None or list of str
Labels of detected segments | [
"Save",
"detected",
"segments",
"to",
"a",
".",
"lab",
"file",
"."
] | train | https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/io.py#L23-L50 |
mozilla/funfactory | funfactory/urlresolvers.py | reverse | def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
"""Wraps Django's reverse to prepend the correct locale."""
prefixer = get_url_prefix()
if prefixer:
prefix = prefix or '/'
url = django_reverse(viewname, urlconf, args, kwargs, prefix)
if prefixer:
url = prefixer.fix(url)
# Ensure any unicode characters in the URL are escaped.
return iri_to_uri(url) | python | def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
"""Wraps Django's reverse to prepend the correct locale."""
prefixer = get_url_prefix()
if prefixer:
prefix = prefix or '/'
url = django_reverse(viewname, urlconf, args, kwargs, prefix)
if prefixer:
url = prefixer.fix(url)
# Ensure any unicode characters in the URL are escaped.
return iri_to_uri(url) | [
"def",
"reverse",
"(",
"viewname",
",",
"urlconf",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"prefixer",
"=",
"get_url_prefix",
"(",
")",
"if",
"prefixer",
":",
"prefix",
"=",
"prefix",
"... | Wraps Django's reverse to prepend the correct locale. | [
"Wraps",
"Django",
"s",
"reverse",
"to",
"prepend",
"the",
"correct",
"locale",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/urlresolvers.py#L24-L35 |
mozilla/funfactory | funfactory/urlresolvers.py | split_path | def split_path(path_):
"""
Split the requested path into (locale, path).
locale will be empty if it isn't found.
"""
path = path_.lstrip('/')
# Use partitition instead of split since it always returns 3 parts
first, _, rest = path.partition('/')
lang = first.lower()
if lang in settings.LANGUAGE_URL_MAP:
return settings.LANGUAGE_URL_MAP[lang], rest
else:
supported = find_supported(first)
if len(supported):
return supported[0], rest
else:
return '', path | python | def split_path(path_):
"""
Split the requested path into (locale, path).
locale will be empty if it isn't found.
"""
path = path_.lstrip('/')
# Use partitition instead of split since it always returns 3 parts
first, _, rest = path.partition('/')
lang = first.lower()
if lang in settings.LANGUAGE_URL_MAP:
return settings.LANGUAGE_URL_MAP[lang], rest
else:
supported = find_supported(first)
if len(supported):
return supported[0], rest
else:
return '', path | [
"def",
"split_path",
"(",
"path_",
")",
":",
"path",
"=",
"path_",
".",
"lstrip",
"(",
"'/'",
")",
"# Use partitition instead of split since it always returns 3 parts",
"first",
",",
"_",
",",
"rest",
"=",
"path",
".",
"partition",
"(",
"'/'",
")",
"lang",
"="... | Split the requested path into (locale, path).
locale will be empty if it isn't found. | [
"Split",
"the",
"requested",
"path",
"into",
"(",
"locale",
"path",
")",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/urlresolvers.py#L47-L66 |
mozilla/funfactory | funfactory/urlresolvers.py | Prefixer.get_language | def get_language(self):
"""
Return a locale code we support on the site using the
user's Accept-Language header to determine which is best. This
mostly follows the RFCs but read bug 439568 for details.
"""
if 'lang' in self.request.GET:
lang = self.request.GET['lang'].lower()
if lang in settings.LANGUAGE_URL_MAP:
return settings.LANGUAGE_URL_MAP[lang]
if self.request.META.get('HTTP_ACCEPT_LANGUAGE'):
best = self.get_best_language(
self.request.META['HTTP_ACCEPT_LANGUAGE'])
if best:
return best
return settings.LANGUAGE_CODE | python | def get_language(self):
"""
Return a locale code we support on the site using the
user's Accept-Language header to determine which is best. This
mostly follows the RFCs but read bug 439568 for details.
"""
if 'lang' in self.request.GET:
lang = self.request.GET['lang'].lower()
if lang in settings.LANGUAGE_URL_MAP:
return settings.LANGUAGE_URL_MAP[lang]
if self.request.META.get('HTTP_ACCEPT_LANGUAGE'):
best = self.get_best_language(
self.request.META['HTTP_ACCEPT_LANGUAGE'])
if best:
return best
return settings.LANGUAGE_CODE | [
"def",
"get_language",
"(",
"self",
")",
":",
"if",
"'lang'",
"in",
"self",
".",
"request",
".",
"GET",
":",
"lang",
"=",
"self",
".",
"request",
".",
"GET",
"[",
"'lang'",
"]",
".",
"lower",
"(",
")",
"if",
"lang",
"in",
"settings",
".",
"LANGUAGE... | Return a locale code we support on the site using the
user's Accept-Language header to determine which is best. This
mostly follows the RFCs but read bug 439568 for details. | [
"Return",
"a",
"locale",
"code",
"we",
"support",
"on",
"the",
"site",
"using",
"the",
"user",
"s",
"Accept",
"-",
"Language",
"header",
"to",
"determine",
"which",
"is",
"best",
".",
"This",
"mostly",
"follows",
"the",
"RFCs",
"but",
"read",
"bug",
"439... | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/urlresolvers.py#L76-L92 |
mozilla/funfactory | funfactory/urlresolvers.py | Prefixer.get_best_language | def get_best_language(self, accept_lang):
"""Given an Accept-Language header, return the best-matching language."""
LUM = settings.LANGUAGE_URL_MAP
langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items())
# Add missing short locales to the list. This will automatically map
# en to en-GB (not en-US), es to es-AR (not es-ES), etc. in alphabetical
# order. To override this behavior, explicitly define a preferred locale
# map with the CANONICAL_LOCALES setting.
langs.update((k.split('-')[0], v) for k, v in LUM.items() if
k.split('-')[0] not in langs)
try:
ranked = parse_accept_lang_header(accept_lang)
except ValueError: # see https://code.djangoproject.com/ticket/21078
return
else:
for lang, _ in ranked:
lang = lang.lower()
if lang in langs:
return langs[lang]
pre = lang.split('-')[0]
if pre in langs:
return langs[pre] | python | def get_best_language(self, accept_lang):
"""Given an Accept-Language header, return the best-matching language."""
LUM = settings.LANGUAGE_URL_MAP
langs = dict(LUM.items() + settings.CANONICAL_LOCALES.items())
# Add missing short locales to the list. This will automatically map
# en to en-GB (not en-US), es to es-AR (not es-ES), etc. in alphabetical
# order. To override this behavior, explicitly define a preferred locale
# map with the CANONICAL_LOCALES setting.
langs.update((k.split('-')[0], v) for k, v in LUM.items() if
k.split('-')[0] not in langs)
try:
ranked = parse_accept_lang_header(accept_lang)
except ValueError: # see https://code.djangoproject.com/ticket/21078
return
else:
for lang, _ in ranked:
lang = lang.lower()
if lang in langs:
return langs[lang]
pre = lang.split('-')[0]
if pre in langs:
return langs[pre] | [
"def",
"get_best_language",
"(",
"self",
",",
"accept_lang",
")",
":",
"LUM",
"=",
"settings",
".",
"LANGUAGE_URL_MAP",
"langs",
"=",
"dict",
"(",
"LUM",
".",
"items",
"(",
")",
"+",
"settings",
".",
"CANONICAL_LOCALES",
".",
"items",
"(",
")",
")",
"# A... | Given an Accept-Language header, return the best-matching language. | [
"Given",
"an",
"Accept",
"-",
"Language",
"header",
"return",
"the",
"best",
"-",
"matching",
"language",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/urlresolvers.py#L94-L115 |
jbloomlab/phydms | setup.py | extensions | def extensions():
"""Returns list of `cython` extensions for `lazy_cythonize`."""
import numpy
from Cython.Build import cythonize
ext = [
Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'],
include_dirs=[numpy.get_include()],
extra_compile_args=['-Wno-unused-function']),
]
return cythonize(ext) | python | def extensions():
"""Returns list of `cython` extensions for `lazy_cythonize`."""
import numpy
from Cython.Build import cythonize
ext = [
Extension('phydmslib.numutils', ['phydmslib/numutils.pyx'],
include_dirs=[numpy.get_include()],
extra_compile_args=['-Wno-unused-function']),
]
return cythonize(ext) | [
"def",
"extensions",
"(",
")",
":",
"import",
"numpy",
"from",
"Cython",
".",
"Build",
"import",
"cythonize",
"ext",
"=",
"[",
"Extension",
"(",
"'phydmslib.numutils'",
",",
"[",
"'phydmslib/numutils.pyx'",
"]",
",",
"include_dirs",
"=",
"[",
"numpy",
".",
"... | Returns list of `cython` extensions for `lazy_cythonize`. | [
"Returns",
"list",
"of",
"cython",
"extensions",
"for",
"lazy_cythonize",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/setup.py#L58-L67 |
mikekatz04/BOWIE | bowie/make_plot.py | plot_main | def plot_main(pid, return_fig_ax=False):
"""Main function for creating these plots.
Reads in plot info dict from json file or dictionary in script.
Args:
return_fig_ax (bool, optional): Return figure and axes objects.
Returns:
2-element tuple containing
- **fig** (*obj*): Figure object for customization outside of those in this program.
- **ax** (*obj*): Axes object for customization outside of those in this program.
"""
global WORKING_DIRECTORY, SNR_CUT
if isinstance(pid, PlotInput):
pid = pid.return_dict()
WORKING_DIRECTORY = '.'
if 'WORKING_DIRECTORY' not in pid['general'].keys():
pid['general']['WORKING_DIRECTORY'] = '.'
SNR_CUT = 5.0
if 'SNR_CUT' not in pid['general'].keys():
pid['general']['SNR_CUT'] = SNR_CUT
if "switch_backend" in pid['general'].keys():
plt.switch_backend(pid['general']['switch_backend'])
running_process = MakePlotProcess(
**{**pid, **pid['general'], **pid['plot_info'], **pid['figure']})
running_process.input_data()
running_process.setup_figure()
running_process.create_plots()
# save or show figure
if 'save_figure' in pid['figure'].keys():
if pid['figure']['save_figure'] is True:
running_process.fig.savefig(
pid['general']['WORKING_DIRECTORY'] + '/' + pid['figure']['output_path'],
**pid['figure']['savefig_kwargs'])
if 'show_figure' in pid['figure'].keys():
if pid['figure']['show_figure'] is True:
plt.show()
if return_fig_ax is True:
return running_process.fig, running_process.ax
return | python | def plot_main(pid, return_fig_ax=False):
"""Main function for creating these plots.
Reads in plot info dict from json file or dictionary in script.
Args:
return_fig_ax (bool, optional): Return figure and axes objects.
Returns:
2-element tuple containing
- **fig** (*obj*): Figure object for customization outside of those in this program.
- **ax** (*obj*): Axes object for customization outside of those in this program.
"""
global WORKING_DIRECTORY, SNR_CUT
if isinstance(pid, PlotInput):
pid = pid.return_dict()
WORKING_DIRECTORY = '.'
if 'WORKING_DIRECTORY' not in pid['general'].keys():
pid['general']['WORKING_DIRECTORY'] = '.'
SNR_CUT = 5.0
if 'SNR_CUT' not in pid['general'].keys():
pid['general']['SNR_CUT'] = SNR_CUT
if "switch_backend" in pid['general'].keys():
plt.switch_backend(pid['general']['switch_backend'])
running_process = MakePlotProcess(
**{**pid, **pid['general'], **pid['plot_info'], **pid['figure']})
running_process.input_data()
running_process.setup_figure()
running_process.create_plots()
# save or show figure
if 'save_figure' in pid['figure'].keys():
if pid['figure']['save_figure'] is True:
running_process.fig.savefig(
pid['general']['WORKING_DIRECTORY'] + '/' + pid['figure']['output_path'],
**pid['figure']['savefig_kwargs'])
if 'show_figure' in pid['figure'].keys():
if pid['figure']['show_figure'] is True:
plt.show()
if return_fig_ax is True:
return running_process.fig, running_process.ax
return | [
"def",
"plot_main",
"(",
"pid",
",",
"return_fig_ax",
"=",
"False",
")",
":",
"global",
"WORKING_DIRECTORY",
",",
"SNR_CUT",
"if",
"isinstance",
"(",
"pid",
",",
"PlotInput",
")",
":",
"pid",
"=",
"pid",
".",
"return_dict",
"(",
")",
"WORKING_DIRECTORY",
"... | Main function for creating these plots.
Reads in plot info dict from json file or dictionary in script.
Args:
return_fig_ax (bool, optional): Return figure and axes objects.
Returns:
2-element tuple containing
- **fig** (*obj*): Figure object for customization outside of those in this program.
- **ax** (*obj*): Axes object for customization outside of those in this program. | [
"Main",
"function",
"for",
"creating",
"these",
"plots",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/make_plot.py#L46-L98 |
shawalli/psycopg2-pgevents | psycopg2_pgevents/sql.py | execute | def execute(connection: connection, statement: str) -> Optional[List[Tuple[str, ...]]]:
"""Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL statement to run against the database.
Returns
-------
response: list or None
List of tuples, where each tuple represents a formatted line of response from the database engine, where
each tuple item roughly corresponds to a column. For instance, while a raw SELECT response might include
the table headers, psycopg2 returns only the rows that matched. If no response was given, None is returned.
"""
response = list() # type: List
# See the following link for reasoning behind both with statements:
# http://initd.org/psycopg/docs/usage.html#with-statement
#
# Additionally, the with statement makes this library safer to use with
# higher-level libraries (e.g. SQLAlchemy) that don't inherently respect
# PostGreSQL's autocommit isolation-level, since the transaction is
# properly completed for each statement.
with connection:
with connection.cursor(cursor_factory=Psycopg2Cursor) as cursor:
cursor.execute(statement)
connection.commit()
# Get response
try:
response = cursor.fetchall()
if not response:
# Empty response list
log('<No Response>', logger_name=_LOGGER_NAME)
return None
except ProgrammingError as e:
if e.args and e.args[0] == 'no results to fetch':
# No response available (i.e. no response given)
log('<No Response>', logger_name=_LOGGER_NAME)
return None
# Some other programming error; re-raise
raise e
log('Response', logger_name=_LOGGER_NAME)
log('--------', logger_name=_LOGGER_NAME)
for line in response:
log(str(line), logger_name=_LOGGER_NAME)
return response | python | def execute(connection: connection, statement: str) -> Optional[List[Tuple[str, ...]]]:
"""Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL statement to run against the database.
Returns
-------
response: list or None
List of tuples, where each tuple represents a formatted line of response from the database engine, where
each tuple item roughly corresponds to a column. For instance, while a raw SELECT response might include
the table headers, psycopg2 returns only the rows that matched. If no response was given, None is returned.
"""
response = list() # type: List
# See the following link for reasoning behind both with statements:
# http://initd.org/psycopg/docs/usage.html#with-statement
#
# Additionally, the with statement makes this library safer to use with
# higher-level libraries (e.g. SQLAlchemy) that don't inherently respect
# PostGreSQL's autocommit isolation-level, since the transaction is
# properly completed for each statement.
with connection:
with connection.cursor(cursor_factory=Psycopg2Cursor) as cursor:
cursor.execute(statement)
connection.commit()
# Get response
try:
response = cursor.fetchall()
if not response:
# Empty response list
log('<No Response>', logger_name=_LOGGER_NAME)
return None
except ProgrammingError as e:
if e.args and e.args[0] == 'no results to fetch':
# No response available (i.e. no response given)
log('<No Response>', logger_name=_LOGGER_NAME)
return None
# Some other programming error; re-raise
raise e
log('Response', logger_name=_LOGGER_NAME)
log('--------', logger_name=_LOGGER_NAME)
for line in response:
log(str(line), logger_name=_LOGGER_NAME)
return response | [
"def",
"execute",
"(",
"connection",
":",
"connection",
",",
"statement",
":",
"str",
")",
"->",
"Optional",
"[",
"List",
"[",
"Tuple",
"[",
"str",
",",
"...",
"]",
"]",
"]",
":",
"response",
"=",
"list",
"(",
")",
"# type: List",
"# See the following li... | Execute PGSQL statement and fetches the statement response.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
statement: str
PGSQL statement to run against the database.
Returns
-------
response: list or None
List of tuples, where each tuple represents a formatted line of response from the database engine, where
each tuple item roughly corresponds to a column. For instance, while a raw SELECT response might include
the table headers, psycopg2 returns only the rows that matched. If no response was given, None is returned. | [
"Execute",
"PGSQL",
"statement",
"and",
"fetches",
"the",
"statement",
"response",
"."
] | train | https://github.com/shawalli/psycopg2-pgevents/blob/bf04c05839a27c56834b26748d227c71cd87257c/psycopg2_pgevents/sql.py#L37-L89 |
ubccr/pinky | pinky/canonicalization/smiles.py | SmilesTraversal.append | def append(self, traverse):
"""(traverse)->append the traverse to the current traverse"""
self.data.extend(traverse.data)
self.atoms.extend(traverse.atoms)
self.bonds.extend(traverse.bonds) | python | def append(self, traverse):
"""(traverse)->append the traverse to the current traverse"""
self.data.extend(traverse.data)
self.atoms.extend(traverse.atoms)
self.bonds.extend(traverse.bonds) | [
"def",
"append",
"(",
"self",
",",
"traverse",
")",
":",
"self",
".",
"data",
".",
"extend",
"(",
"traverse",
".",
"data",
")",
"self",
".",
"atoms",
".",
"extend",
"(",
"traverse",
".",
"atoms",
")",
"self",
".",
"bonds",
".",
"extend",
"(",
"trav... | (traverse)->append the traverse to the current traverse | [
"(",
"traverse",
")",
"-",
">",
"append",
"the",
"traverse",
"to",
"the",
"current",
"traverse"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/smiles.py#L127-L131 |
pyroscope/pyrobase | src/pyrobase/fmt.py | human_size | def human_size(size):
""" Return a human-readable representation of a byte size.
@param size: Number of bytes as an integer or string.
@return: String of length 10 with the formatted result.
"""
if isinstance(size, string_types):
size = int(size, 10)
if size < 0:
return "-??? bytes"
if size < 1024:
return "%4d bytes" % size
for unit in ("KiB", "MiB", "GiB"):
size /= 1024.0
if size < 1024:
return "%6.1f %s" % (size, unit)
return "%6.1f GiB" % size | python | def human_size(size):
""" Return a human-readable representation of a byte size.
@param size: Number of bytes as an integer or string.
@return: String of length 10 with the formatted result.
"""
if isinstance(size, string_types):
size = int(size, 10)
if size < 0:
return "-??? bytes"
if size < 1024:
return "%4d bytes" % size
for unit in ("KiB", "MiB", "GiB"):
size /= 1024.0
if size < 1024:
return "%6.1f %s" % (size, unit)
return "%6.1f GiB" % size | [
"def",
"human_size",
"(",
"size",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"string_types",
")",
":",
"size",
"=",
"int",
"(",
"size",
",",
"10",
")",
"if",
"size",
"<",
"0",
":",
"return",
"\"-??? bytes\"",
"if",
"size",
"<",
"1024",
":",
"r... | Return a human-readable representation of a byte size.
@param size: Number of bytes as an integer or string.
@return: String of length 10 with the formatted result. | [
"Return",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"byte",
"size",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L32-L51 |
pyroscope/pyrobase | src/pyrobase/fmt.py | iso_datetime | def iso_datetime(timestamp=None):
""" Convert UNIX timestamp to ISO datetime string.
@param timestamp: UNIX epoch value (default: the current time).
@return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS".
"""
if timestamp is None:
timestamp = time.time()
return datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:19] | python | def iso_datetime(timestamp=None):
""" Convert UNIX timestamp to ISO datetime string.
@param timestamp: UNIX epoch value (default: the current time).
@return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS".
"""
if timestamp is None:
timestamp = time.time()
return datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:19] | [
"def",
"iso_datetime",
"(",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
".",
"isoformat",
"... | Convert UNIX timestamp to ISO datetime string.
@param timestamp: UNIX epoch value (default: the current time).
@return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS". | [
"Convert",
"UNIX",
"timestamp",
"to",
"ISO",
"datetime",
"string",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L54-L62 |
pyroscope/pyrobase | src/pyrobase/fmt.py | human_duration | def human_duration(time1, time2=None, precision=0, short=False):
""" Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).
@param short: Use abbreviations, and right-justify the result to always the same length.
@return: Formatted duration.
"""
if time2 is None:
time2 = time.time()
duration = (time1 or 0) - time2
direction = (
" ago" if duration < 0 else
("+now" if short else " from now") if time2 else ""
)
duration = abs(duration)
parts = [
("weeks", duration // (7*86400)),
("days", duration // 86400 % 7),
("hours", duration // 3600 % 24),
("mins", duration // 60 % 60),
("secs", duration % 60),
]
# Kill leading zero parts
while len(parts) > 1 and parts[0][1] == 0:
parts = parts[1:]
# Limit to # of parts given by precision
if precision:
parts = parts[:precision]
numfmt = ("%d", "%d"), ("%4d", "%2d")
fmt = "%1.1s" if short else " %s"
sep = " " if short else ", "
result = sep.join((numfmt[bool(short)][bool(idx)] + fmt) % (val, key[:-1] if val == 1 else key)
for idx, (key, val) in enumerate(parts)
if val #or (short and precision)
) + direction
if not time1:
result = "never" if time2 else "N/A"
if precision and short:
return result.rjust(1 + precision*4 + (4 if time2 else 0))
else:
return result | python | def human_duration(time1, time2=None, precision=0, short=False):
""" Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).
@param short: Use abbreviations, and right-justify the result to always the same length.
@return: Formatted duration.
"""
if time2 is None:
time2 = time.time()
duration = (time1 or 0) - time2
direction = (
" ago" if duration < 0 else
("+now" if short else " from now") if time2 else ""
)
duration = abs(duration)
parts = [
("weeks", duration // (7*86400)),
("days", duration // 86400 % 7),
("hours", duration // 3600 % 24),
("mins", duration // 60 % 60),
("secs", duration % 60),
]
# Kill leading zero parts
while len(parts) > 1 and parts[0][1] == 0:
parts = parts[1:]
# Limit to # of parts given by precision
if precision:
parts = parts[:precision]
numfmt = ("%d", "%d"), ("%4d", "%2d")
fmt = "%1.1s" if short else " %s"
sep = " " if short else ", "
result = sep.join((numfmt[bool(short)][bool(idx)] + fmt) % (val, key[:-1] if val == 1 else key)
for idx, (key, val) in enumerate(parts)
if val #or (short and precision)
) + direction
if not time1:
result = "never" if time2 else "N/A"
if precision and short:
return result.rjust(1 + precision*4 + (4 if time2 else 0))
else:
return result | [
"def",
"human_duration",
"(",
"time1",
",",
"time2",
"=",
"None",
",",
"precision",
"=",
"0",
",",
"short",
"=",
"False",
")",
":",
"if",
"time2",
"is",
"None",
":",
"time2",
"=",
"time",
".",
"time",
"(",
")",
"duration",
"=",
"(",
"time1",
"or",
... | Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).
@param short: Use abbreviations, and right-justify the result to always the same length.
@return: Formatted duration. | [
"Return",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"time",
"delta",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L76-L124 |
pyroscope/pyrobase | src/pyrobase/fmt.py | to_unicode | def to_unicode(text):
""" Return a decoded unicode string.
False values are returned untouched.
"""
if not text or isinstance(text, unicode if PY2 else str):
return text
try:
# Try UTF-8 first
return text.decode("UTF-8")
except UnicodeError:
try:
# Then Windows Latin-1
return text.decode("CP1252")
except UnicodeError:
# Give up, return byte string in the hope things work out
return text | python | def to_unicode(text):
""" Return a decoded unicode string.
False values are returned untouched.
"""
if not text or isinstance(text, unicode if PY2 else str):
return text
try:
# Try UTF-8 first
return text.decode("UTF-8")
except UnicodeError:
try:
# Then Windows Latin-1
return text.decode("CP1252")
except UnicodeError:
# Give up, return byte string in the hope things work out
return text | [
"def",
"to_unicode",
"(",
"text",
")",
":",
"if",
"not",
"text",
"or",
"isinstance",
"(",
"text",
",",
"unicode",
"if",
"PY2",
"else",
"str",
")",
":",
"return",
"text",
"try",
":",
"# Try UTF-8 first",
"return",
"text",
".",
"decode",
"(",
"\"UTF-8\"",
... | Return a decoded unicode string.
False values are returned untouched. | [
"Return",
"a",
"decoded",
"unicode",
"string",
".",
"False",
"values",
"are",
"returned",
"untouched",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L127-L143 |
pyroscope/pyrobase | src/pyrobase/fmt.py | to_utf8 | def to_utf8(text):
""" Enforce UTF8 encoding.
"""
# return empty/false stuff unaltered
if not text:
if isinstance(text, string_types):
text = ""
return text
try:
# Is it a unicode string, or pure ascii?
return text.encode("utf8")
except UnicodeDecodeError:
try:
# Is it a utf8 byte string?
if text.startswith(codecs.BOM_UTF8):
text = text[len(codecs.BOM_UTF8):]
return text.decode("utf8").encode("utf8")
except UnicodeDecodeError:
# Check BOM
if text.startswith(codecs.BOM_UTF16_LE):
encoding = "utf-16le"
text = text[len(codecs.BOM_UTF16_LE):]
elif text.startswith(codecs.BOM_UTF16_BE):
encoding = "utf-16be"
text = text[len(codecs.BOM_UTF16_BE):]
else:
# Assume CP-1252
encoding = "cp1252"
try:
return text.decode(encoding).encode("utf8")
except UnicodeDecodeError as exc:
for line in text.splitlines():
try:
line.decode(encoding).encode("utf8")
except UnicodeDecodeError:
log.warn("Cannot transcode the following into UTF8 cause of %s: %r" % (exc, line))
break
return text | python | def to_utf8(text):
""" Enforce UTF8 encoding.
"""
# return empty/false stuff unaltered
if not text:
if isinstance(text, string_types):
text = ""
return text
try:
# Is it a unicode string, or pure ascii?
return text.encode("utf8")
except UnicodeDecodeError:
try:
# Is it a utf8 byte string?
if text.startswith(codecs.BOM_UTF8):
text = text[len(codecs.BOM_UTF8):]
return text.decode("utf8").encode("utf8")
except UnicodeDecodeError:
# Check BOM
if text.startswith(codecs.BOM_UTF16_LE):
encoding = "utf-16le"
text = text[len(codecs.BOM_UTF16_LE):]
elif text.startswith(codecs.BOM_UTF16_BE):
encoding = "utf-16be"
text = text[len(codecs.BOM_UTF16_BE):]
else:
# Assume CP-1252
encoding = "cp1252"
try:
return text.decode(encoding).encode("utf8")
except UnicodeDecodeError as exc:
for line in text.splitlines():
try:
line.decode(encoding).encode("utf8")
except UnicodeDecodeError:
log.warn("Cannot transcode the following into UTF8 cause of %s: %r" % (exc, line))
break
return text | [
"def",
"to_utf8",
"(",
"text",
")",
":",
"# return empty/false stuff unaltered",
"if",
"not",
"text",
":",
"if",
"isinstance",
"(",
"text",
",",
"string_types",
")",
":",
"text",
"=",
"\"\"",
"return",
"text",
"try",
":",
"# Is it a unicode string, or pure ascii?"... | Enforce UTF8 encoding. | [
"Enforce",
"UTF8",
"encoding",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/fmt.py#L146-L185 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_program | def p_program(self, p):
"""program : source_elements"""
p[0] = self.asttypes.ES5Program(p[1])
p[0].setpos(p) | python | def p_program(self, p):
"""program : source_elements"""
p[0] = self.asttypes.ES5Program(p[1])
p[0].setpos(p) | [
"def",
"p_program",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"ES5Program",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | program : source_elements | [
"program",
":",
"source_elements"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L150-L153 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_source_element_list | def p_source_element_list(self, p):
"""source_element_list : source_element
| source_element_list source_element
"""
if len(p) == 2: # single source element
p[0] = [p[1]]
else:
p[1].append(p[2])
p[0] = p[1] | python | def p_source_element_list(self, p):
"""source_element_list : source_element
| source_element_list source_element
"""
if len(p) == 2: # single source element
p[0] = [p[1]]
else:
p[1].append(p[2])
p[0] = p[1] | [
"def",
"p_source_element_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"# single source element",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
... | source_element_list : source_element
| source_element_list source_element | [
"source_element_list",
":",
"source_element",
"|",
"source_element_list",
"source_element"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L161-L169 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_block | def p_block(self, p):
"""block : LBRACE source_elements RBRACE"""
p[0] = self.asttypes.Block(p[2])
p[0].setpos(p) | python | def p_block(self, p):
"""block : LBRACE source_elements RBRACE"""
p[0] = self.asttypes.Block(p[2])
p[0].setpos(p) | [
"def",
"p_block",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Block",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | block : LBRACE source_elements RBRACE | [
"block",
":",
"LBRACE",
"source_elements",
"RBRACE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L199-L202 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_boolean_literal | def p_boolean_literal(self, p):
"""boolean_literal : TRUE
| FALSE
"""
p[0] = self.asttypes.Boolean(p[1])
p[0].setpos(p) | python | def p_boolean_literal(self, p):
"""boolean_literal : TRUE
| FALSE
"""
p[0] = self.asttypes.Boolean(p[1])
p[0].setpos(p) | [
"def",
"p_boolean_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Boolean",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | boolean_literal : TRUE
| FALSE | [
"boolean_literal",
":",
"TRUE",
"|",
"FALSE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L213-L218 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_null_literal | def p_null_literal(self, p):
"""null_literal : NULL"""
p[0] = self.asttypes.Null(p[1])
p[0].setpos(p) | python | def p_null_literal(self, p):
"""null_literal : NULL"""
p[0] = self.asttypes.Null(p[1])
p[0].setpos(p) | [
"def",
"p_null_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Null",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | null_literal : NULL | [
"null_literal",
":",
"NULL"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L220-L223 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_numeric_literal | def p_numeric_literal(self, p):
"""numeric_literal : NUMBER"""
p[0] = self.asttypes.Number(p[1])
p[0].setpos(p) | python | def p_numeric_literal(self, p):
"""numeric_literal : NUMBER"""
p[0] = self.asttypes.Number(p[1])
p[0].setpos(p) | [
"def",
"p_numeric_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Number",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | numeric_literal : NUMBER | [
"numeric_literal",
":",
"NUMBER"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L225-L228 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_string_literal | def p_string_literal(self, p):
"""string_literal : STRING"""
p[0] = self.asttypes.String(p[1])
p[0].setpos(p) | python | def p_string_literal(self, p):
"""string_literal : STRING"""
p[0] = self.asttypes.String(p[1])
p[0].setpos(p) | [
"def",
"p_string_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"String",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | string_literal : STRING | [
"string_literal",
":",
"STRING"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L230-L233 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_regex_literal | def p_regex_literal(self, p):
"""regex_literal : REGEX"""
p[0] = self.asttypes.Regex(p[1])
p[0].setpos(p) | python | def p_regex_literal(self, p):
"""regex_literal : REGEX"""
p[0] = self.asttypes.Regex(p[1])
p[0].setpos(p) | [
"def",
"p_regex_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Regex",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | regex_literal : REGEX | [
"regex_literal",
":",
"REGEX"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L235-L238 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_identifier | def p_identifier(self, p):
"""identifier : ID"""
p[0] = self.asttypes.Identifier(p[1])
p[0].setpos(p) | python | def p_identifier(self, p):
"""identifier : ID"""
p[0] = self.asttypes.Identifier(p[1])
p[0].setpos(p) | [
"def",
"p_identifier",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Identifier",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | identifier : ID | [
"identifier",
":",
"ID"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L240-L243 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_reserved_word | def p_reserved_word(self, p):
"""reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
| ELSE
| FINALLY
| FOR
| FUNCTION
| IF
| IN
| INSTANCEOF
| NEW
| RETURN
| SWITCH
| THIS
| THROW
| TRY
| TYPEOF
| VAR
| VOID
| WHILE
| WITH
| NULL
| TRUE
| FALSE
| CLASS
| CONST
| ENUM
| EXPORT
| EXTENDS
| IMPORT
| SUPER
"""
p[0] = self.asttypes.Identifier(p[1])
p[0].setpos(p) | python | def p_reserved_word(self, p):
"""reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
| ELSE
| FINALLY
| FOR
| FUNCTION
| IF
| IN
| INSTANCEOF
| NEW
| RETURN
| SWITCH
| THIS
| THROW
| TRY
| TYPEOF
| VAR
| VOID
| WHILE
| WITH
| NULL
| TRUE
| FALSE
| CLASS
| CONST
| ENUM
| EXPORT
| EXTENDS
| IMPORT
| SUPER
"""
p[0] = self.asttypes.Identifier(p[1])
p[0].setpos(p) | [
"def",
"p_reserved_word",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Identifier",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | reserved_word : BREAK
| CASE
| CATCH
| CONTINUE
| DEBUGGER
| DEFAULT
| DELETE
| DO
| ELSE
| FINALLY
| FOR
| FUNCTION
| IF
| IN
| INSTANCEOF
| NEW
| RETURN
| SWITCH
| THIS
| THROW
| TRY
| TYPEOF
| VAR
| VOID
| WHILE
| WITH
| NULL
| TRUE
| FALSE
| CLASS
| CONST
| ENUM
| EXPORT
| EXTENDS
| IMPORT
| SUPER | [
"reserved_word",
":",
"BREAK",
"|",
"CASE",
"|",
"CATCH",
"|",
"CONTINUE",
"|",
"DEBUGGER",
"|",
"DEFAULT",
"|",
"DELETE",
"|",
"DO",
"|",
"ELSE",
"|",
"FINALLY",
"|",
"FOR",
"|",
"FUNCTION",
"|",
"IF",
"|",
"IN",
"|",
"INSTANCEOF",
"|",
"NEW",
"|",
... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L247-L286 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_primary_expr_no_brace_2 | def p_primary_expr_no_brace_2(self, p):
"""primary_expr_no_brace : THIS"""
p[0] = self.asttypes.This()
p[0].setpos(p) | python | def p_primary_expr_no_brace_2(self, p):
"""primary_expr_no_brace : THIS"""
p[0] = self.asttypes.This()
p[0].setpos(p) | [
"def",
"p_primary_expr_no_brace_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"This",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | primary_expr_no_brace : THIS | [
"primary_expr_no_brace",
":",
"THIS"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L307-L310 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_primary_expr_no_brace_4 | def p_primary_expr_no_brace_4(self, p):
"""primary_expr_no_brace : LPAREN expr RPAREN"""
if isinstance(p[2], self.asttypes.GroupingOp):
# this reduces the grouping operator to one.
p[0] = p[2]
else:
p[0] = self.asttypes.GroupingOp(expr=p[2])
p[0].setpos(p) | python | def p_primary_expr_no_brace_4(self, p):
"""primary_expr_no_brace : LPAREN expr RPAREN"""
if isinstance(p[2], self.asttypes.GroupingOp):
# this reduces the grouping operator to one.
p[0] = p[2]
else:
p[0] = self.asttypes.GroupingOp(expr=p[2])
p[0].setpos(p) | [
"def",
"p_primary_expr_no_brace_4",
"(",
"self",
",",
"p",
")",
":",
"if",
"isinstance",
"(",
"p",
"[",
"2",
"]",
",",
"self",
".",
"asttypes",
".",
"GroupingOp",
")",
":",
"# this reduces the grouping operator to one.",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
... | primary_expr_no_brace : LPAREN expr RPAREN | [
"primary_expr_no_brace",
":",
"LPAREN",
"expr",
"RPAREN"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L318-L325 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_array_literal_1 | def p_array_literal_1(self, p):
"""array_literal : LBRACKET elision_opt RBRACKET"""
p[0] = self.asttypes.Array(items=p[2])
p[0].setpos(p) | python | def p_array_literal_1(self, p):
"""array_literal : LBRACKET elision_opt RBRACKET"""
p[0] = self.asttypes.Array(items=p[2])
p[0].setpos(p) | [
"def",
"p_array_literal_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Array",
"(",
"items",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | array_literal : LBRACKET elision_opt RBRACKET | [
"array_literal",
":",
"LBRACKET",
"elision_opt",
"RBRACKET"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L327-L330 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_array_literal_2 | def p_array_literal_2(self, p):
"""array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET
"""
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = self.asttypes.Array(items=items)
p[0].setpos(p) | python | def p_array_literal_2(self, p):
"""array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET
"""
items = p[2]
if len(p) == 6:
items.extend(p[4])
p[0] = self.asttypes.Array(items=items)
p[0].setpos(p) | [
"def",
"p_array_literal_2",
"(",
"self",
",",
"p",
")",
":",
"items",
"=",
"p",
"[",
"2",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"6",
":",
"items",
".",
"extend",
"(",
"p",
"[",
"4",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes... | array_literal : LBRACKET element_list RBRACKET
| LBRACKET element_list COMMA elision_opt RBRACKET | [
"array_literal",
":",
"LBRACKET",
"element_list",
"RBRACKET",
"|",
"LBRACKET",
"element_list",
"COMMA",
"elision_opt",
"RBRACKET"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L332-L340 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_element_list | def p_element_list(self, p):
"""element_list : elision_opt assignment_expr
| element_list COMMA elision_opt assignment_expr
"""
if len(p) == 3:
p[0] = p[1] + [p[2]]
else:
p[1].extend(p[3])
p[1].append(p[4])
p[0] = p[1] | python | def p_element_list(self, p):
"""element_list : elision_opt assignment_expr
| element_list COMMA elision_opt assignment_expr
"""
if len(p) == 3:
p[0] = p[1] + [p[2]]
else:
p[1].extend(p[3])
p[1].append(p[4])
p[0] = p[1] | [
"def",
"p_element_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"extend",
"(",
... | element_list : elision_opt assignment_expr
| element_list COMMA elision_opt assignment_expr | [
"element_list",
":",
"elision_opt",
"assignment_expr",
"|",
"element_list",
"COMMA",
"elision_opt",
"assignment_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L342-L351 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_elision | def p_elision(self, p):
"""elision : COMMA
| elision COMMA
"""
if len(p) == 2:
p[0] = [self.asttypes.Elision(1)]
p[0][0].setpos(p)
else:
# increment the Elision value.
p[1][-1].value += 1
p[0] = p[1]
# TODO there should be a cleaner API for the lexer and their
# token types for ensuring that the mappings are available.
p[0][0]._token_map = {(',' * p[0][0].value): [
p[0][0].findpos(p, 0)]}
return | python | def p_elision(self, p):
"""elision : COMMA
| elision COMMA
"""
if len(p) == 2:
p[0] = [self.asttypes.Elision(1)]
p[0][0].setpos(p)
else:
# increment the Elision value.
p[1][-1].value += 1
p[0] = p[1]
# TODO there should be a cleaner API for the lexer and their
# token types for ensuring that the mappings are available.
p[0][0]._token_map = {(',' * p[0][0].value): [
p[0][0].findpos(p, 0)]}
return | [
"def",
"p_elision",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"self",
".",
"asttypes",
".",
"Elision",
"(",
"1",
")",
"]",
"p",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"setpos",
... | elision : COMMA
| elision COMMA | [
"elision",
":",
"COMMA",
"|",
"elision",
"COMMA"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L361-L376 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_object_literal | def p_object_literal(self, p):
"""object_literal : LBRACE RBRACE
| LBRACE property_list RBRACE
| LBRACE property_list COMMA RBRACE
"""
if len(p) == 3:
p[0] = self.asttypes.Object()
else:
p[0] = self.asttypes.Object(properties=p[2])
p[0].setpos(p) | python | def p_object_literal(self, p):
"""object_literal : LBRACE RBRACE
| LBRACE property_list RBRACE
| LBRACE property_list COMMA RBRACE
"""
if len(p) == 3:
p[0] = self.asttypes.Object()
else:
p[0] = self.asttypes.Object(properties=p[2])
p[0].setpos(p) | [
"def",
"p_object_literal",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Object",
"(",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
... | object_literal : LBRACE RBRACE
| LBRACE property_list RBRACE
| LBRACE property_list COMMA RBRACE | [
"object_literal",
":",
"LBRACE",
"RBRACE",
"|",
"LBRACE",
"property_list",
"RBRACE",
"|",
"LBRACE",
"property_list",
"COMMA",
"RBRACE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L378-L387 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_property_list | def p_property_list(self, p):
"""property_list : property_assignment
| property_list COMMA property_assignment
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | python | def p_property_list(self, p):
"""property_list : property_assignment
| property_list COMMA property_assignment
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | [
"def",
"p_property_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3",
"]",
")",
... | property_list : property_assignment
| property_list COMMA property_assignment | [
"property_list",
":",
"property_assignment",
"|",
"property_list",
"COMMA",
"property_assignment"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L389-L397 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_property_assignment | def p_property_assignment(self, p):
"""property_assignment \
: property_name COLON assignment_expr
| GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE
| SETPROP property_name LPAREN property_set_parameter_list RPAREN\
LBRACE function_body RBRACE
"""
if len(p) == 4:
p[0] = self.asttypes.Assign(left=p[1], op=p[2], right=p[3])
p[0].setpos(p, 2)
elif len(p) == 8:
p[0] = self.asttypes.GetPropAssign(prop_name=p[2], elements=p[6])
p[0].setpos(p)
else:
p[0] = self.asttypes.SetPropAssign(
prop_name=p[2], parameter=p[4], elements=p[7])
p[0].setpos(p) | python | def p_property_assignment(self, p):
"""property_assignment \
: property_name COLON assignment_expr
| GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE
| SETPROP property_name LPAREN property_set_parameter_list RPAREN\
LBRACE function_body RBRACE
"""
if len(p) == 4:
p[0] = self.asttypes.Assign(left=p[1], op=p[2], right=p[3])
p[0].setpos(p, 2)
elif len(p) == 8:
p[0] = self.asttypes.GetPropAssign(prop_name=p[2], elements=p[6])
p[0].setpos(p)
else:
p[0] = self.asttypes.SetPropAssign(
prop_name=p[2], parameter=p[4], elements=p[7])
p[0].setpos(p) | [
"def",
"p_property_assignment",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Assign",
"(",
"left",
"=",
"p",
"[",
"1",
"]",
",",
"op",
"=",
"p",
"[",
"2... | property_assignment \
: property_name COLON assignment_expr
| GETPROP property_name LPAREN RPAREN LBRACE function_body RBRACE
| SETPROP property_name LPAREN property_set_parameter_list RPAREN\
LBRACE function_body RBRACE | [
"property_assignment",
"\\",
":",
"property_name",
"COLON",
"assignment_expr",
"|",
"GETPROP",
"property_name",
"LPAREN",
"RPAREN",
"LBRACE",
"function_body",
"RBRACE",
"|",
"SETPROP",
"property_name",
"LPAREN",
"property_set_parameter_list",
"RPAREN",
"\\",
"LBRACE",
"fu... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L400-L416 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_identifier_name_string | def p_identifier_name_string(self, p):
"""identifier_name_string : identifier_name
"""
p[0] = asttypes.PropIdentifier(p[1].value)
# manually clone the position attributes.
for k in ('_token_map', 'lexpos', 'lineno', 'colno'):
setattr(p[0], k, getattr(p[1], k)) | python | def p_identifier_name_string(self, p):
"""identifier_name_string : identifier_name
"""
p[0] = asttypes.PropIdentifier(p[1].value)
# manually clone the position attributes.
for k in ('_token_map', 'lexpos', 'lineno', 'colno'):
setattr(p[0], k, getattr(p[1], k)) | [
"def",
"p_identifier_name_string",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"asttypes",
".",
"PropIdentifier",
"(",
"p",
"[",
"1",
"]",
".",
"value",
")",
"# manually clone the position attributes.",
"for",
"k",
"in",
"(",
"'_token_map'",
... | identifier_name_string : identifier_name | [
"identifier_name_string",
":",
"identifier_name"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L423-L429 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_member_expr | def p_member_expr(self, p):
"""member_expr : primary_expr
| function_expr
| member_expr LBRACKET expr RBRACKET
| member_expr PERIOD identifier_name_string
| NEW member_expr arguments
"""
if len(p) == 2:
p[0] = p[1]
return
if p[1] == 'new':
p[0] = self.asttypes.NewExpr(p[2], p[3])
p[0].setpos(p)
elif p[2] == '.':
p[0] = self.asttypes.DotAccessor(p[1], p[3])
p[0].setpos(p, 2)
else:
p[0] = self.asttypes.BracketAccessor(p[1], p[3])
p[0].setpos(p, 2) | python | def p_member_expr(self, p):
"""member_expr : primary_expr
| function_expr
| member_expr LBRACKET expr RBRACKET
| member_expr PERIOD identifier_name_string
| NEW member_expr arguments
"""
if len(p) == 2:
p[0] = p[1]
return
if p[1] == 'new':
p[0] = self.asttypes.NewExpr(p[2], p[3])
p[0].setpos(p)
elif p[2] == '.':
p[0] = self.asttypes.DotAccessor(p[1], p[3])
p[0].setpos(p, 2)
else:
p[0] = self.asttypes.BracketAccessor(p[1], p[3])
p[0].setpos(p, 2) | [
"def",
"p_member_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"return",
"if",
"p",
"[",
"1",
"]",
"==",
"'new'",
":",
"p",
"[",
"0",
"]",
"=",
"self",
"... | member_expr : primary_expr
| function_expr
| member_expr LBRACKET expr RBRACKET
| member_expr PERIOD identifier_name_string
| NEW member_expr arguments | [
"member_expr",
":",
"primary_expr",
"|",
"function_expr",
"|",
"member_expr",
"LBRACKET",
"expr",
"RBRACKET",
"|",
"member_expr",
"PERIOD",
"identifier_name_string",
"|",
"NEW",
"member_expr",
"arguments"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L448-L467 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_new_expr | def p_new_expr(self, p):
"""new_expr : member_expr
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | python | def p_new_expr(self, p):
"""new_expr : member_expr
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | [
"def",
"p_new_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"NewExpr",
"(",
"p",
"[",
... | new_expr : member_expr
| NEW new_expr | [
"new_expr",
":",
"member_expr",
"|",
"NEW",
"new_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L490-L498 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_new_expr_nobf | def p_new_expr_nobf(self, p):
"""new_expr_nobf : member_expr_nobf
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | python | def p_new_expr_nobf(self, p):
"""new_expr_nobf : member_expr_nobf
| NEW new_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.NewExpr(p[2])
p[0].setpos(p) | [
"def",
"p_new_expr_nobf",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"NewExpr",
"(",
"p",
"... | new_expr_nobf : member_expr_nobf
| NEW new_expr | [
"new_expr_nobf",
":",
"member_expr_nobf",
"|",
"NEW",
"new_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L500-L508 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_call_expr | def p_call_expr(self, p):
"""call_expr : member_expr arguments
| call_expr arguments
| call_expr LBRACKET expr RBRACKET
| call_expr PERIOD identifier_name_string
"""
if len(p) == 3:
p[0] = self.asttypes.FunctionCall(p[1], p[2])
p[0].setpos(p) # require yacc_tracking
elif len(p) == 4:
p[0] = self.asttypes.DotAccessor(p[1], p[3])
p[0].setpos(p, 2)
else:
p[0] = self.asttypes.BracketAccessor(p[1], p[3])
p[0].setpos(p, 2) | python | def p_call_expr(self, p):
"""call_expr : member_expr arguments
| call_expr arguments
| call_expr LBRACKET expr RBRACKET
| call_expr PERIOD identifier_name_string
"""
if len(p) == 3:
p[0] = self.asttypes.FunctionCall(p[1], p[2])
p[0].setpos(p) # require yacc_tracking
elif len(p) == 4:
p[0] = self.asttypes.DotAccessor(p[1], p[3])
p[0].setpos(p, 2)
else:
p[0] = self.asttypes.BracketAccessor(p[1], p[3])
p[0].setpos(p, 2) | [
"def",
"p_call_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"FunctionCall",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0"... | call_expr : member_expr arguments
| call_expr arguments
| call_expr LBRACKET expr RBRACKET
| call_expr PERIOD identifier_name_string | [
"call_expr",
":",
"member_expr",
"arguments",
"|",
"call_expr",
"arguments",
"|",
"call_expr",
"LBRACKET",
"expr",
"RBRACKET",
"|",
"call_expr",
"PERIOD",
"identifier_name_string"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L510-L524 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_arguments | def p_arguments(self, p):
"""arguments : LPAREN RPAREN
| LPAREN argument_list RPAREN
"""
if len(p) == 4:
p[0] = self.asttypes.Arguments(p[2])
else:
p[0] = self.asttypes.Arguments([])
p[0].setpos(p) | python | def p_arguments(self, p):
"""arguments : LPAREN RPAREN
| LPAREN argument_list RPAREN
"""
if len(p) == 4:
p[0] = self.asttypes.Arguments(p[2])
else:
p[0] = self.asttypes.Arguments([])
p[0].setpos(p) | [
"def",
"p_arguments",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Arguments",
"(",
"p",
"[",
"2",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"se... | arguments : LPAREN RPAREN
| LPAREN argument_list RPAREN | [
"arguments",
":",
"LPAREN",
"RPAREN",
"|",
"LPAREN",
"argument_list",
"RPAREN"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L542-L550 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_argument_list | def p_argument_list(self, p):
"""argument_list : assignment_expr
| argument_list COMMA assignment_expr
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | python | def p_argument_list(self, p):
"""argument_list : assignment_expr
| argument_list COMMA assignment_expr
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | [
"def",
"p_argument_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3",
"]",
")",
... | argument_list : assignment_expr
| argument_list COMMA assignment_expr | [
"argument_list",
":",
"assignment_expr",
"|",
"argument_list",
"COMMA",
"assignment_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L552-L560 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_postfix_expr | def p_postfix_expr(self, p):
"""postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.PostfixExpr(op=p[2], value=p[1])
p[0].setpos(p, 2) | python | def p_postfix_expr(self, p):
"""postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.PostfixExpr(op=p[2], value=p[1])
p[0].setpos(p, 2) | [
"def",
"p_postfix_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"PostfixExpr",
"(",
"op",... | postfix_expr : left_hand_side_expr
| left_hand_side_expr PLUSPLUS
| left_hand_side_expr MINUSMINUS | [
"postfix_expr",
":",
"left_hand_side_expr",
"|",
"left_hand_side_expr",
"PLUSPLUS",
"|",
"left_hand_side_expr",
"MINUSMINUS"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L575-L584 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_unary_expr_common | def p_unary_expr_common(self, p):
"""unary_expr_common : DELETE unary_expr
| VOID unary_expr
| TYPEOF unary_expr
| PLUSPLUS unary_expr
| MINUSMINUS unary_expr
| PLUS unary_expr
| MINUS unary_expr
| BNOT unary_expr
| NOT unary_expr
"""
p[0] = self.asttypes.UnaryExpr(p[1], p[2])
p[0].setpos(p) | python | def p_unary_expr_common(self, p):
"""unary_expr_common : DELETE unary_expr
| VOID unary_expr
| TYPEOF unary_expr
| PLUSPLUS unary_expr
| MINUSMINUS unary_expr
| PLUS unary_expr
| MINUS unary_expr
| BNOT unary_expr
| NOT unary_expr
"""
p[0] = self.asttypes.UnaryExpr(p[1], p[2])
p[0].setpos(p) | [
"def",
"p_unary_expr_common",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"UnaryExpr",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | unary_expr_common : DELETE unary_expr
| VOID unary_expr
| TYPEOF unary_expr
| PLUSPLUS unary_expr
| MINUSMINUS unary_expr
| PLUS unary_expr
| MINUS unary_expr
| BNOT unary_expr
| NOT unary_expr | [
"unary_expr_common",
":",
"DELETE",
"unary_expr",
"|",
"VOID",
"unary_expr",
"|",
"TYPEOF",
"unary_expr",
"|",
"PLUSPLUS",
"unary_expr",
"|",
"MINUSMINUS",
"unary_expr",
"|",
"PLUS",
"unary_expr",
"|",
"MINUS",
"unary_expr",
"|",
"BNOT",
"unary_expr",
"|",
"NOT",
... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L610-L622 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_multiplicative_expr | def p_multiplicative_expr(self, p):
"""multiplicative_expr : unary_expr
| multiplicative_expr MULT unary_expr
| multiplicative_expr DIV unary_expr
| multiplicative_expr MOD unary_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.BinOp(op=p[2], left=p[1], right=p[3])
p[0].setpos(p, 2) | python | def p_multiplicative_expr(self, p):
"""multiplicative_expr : unary_expr
| multiplicative_expr MULT unary_expr
| multiplicative_expr DIV unary_expr
| multiplicative_expr MOD unary_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.BinOp(op=p[2], left=p[1], right=p[3])
p[0].setpos(p, 2) | [
"def",
"p_multiplicative_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"BinOp",
"(",
"op"... | multiplicative_expr : unary_expr
| multiplicative_expr MULT unary_expr
| multiplicative_expr DIV unary_expr
| multiplicative_expr MOD unary_expr | [
"multiplicative_expr",
":",
"unary_expr",
"|",
"multiplicative_expr",
"MULT",
"unary_expr",
"|",
"multiplicative_expr",
"DIV",
"unary_expr",
"|",
"multiplicative_expr",
"MOD",
"unary_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L625-L635 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_conditional_expr | def p_conditional_expr(self, p):
"""
conditional_expr \
: logical_or_expr
| logical_or_expr CONDOP assignment_expr COLON assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Conditional(
predicate=p[1], consequent=p[3], alternative=p[5])
p[0].setpos(p, 2) | python | def p_conditional_expr(self, p):
"""
conditional_expr \
: logical_or_expr
| logical_or_expr CONDOP assignment_expr COLON assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Conditional(
predicate=p[1], consequent=p[3], alternative=p[5])
p[0].setpos(p, 2) | [
"def",
"p_conditional_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Conditional",
"(",
"... | conditional_expr \
: logical_or_expr
| logical_or_expr CONDOP assignment_expr COLON assignment_expr | [
"conditional_expr",
"\\",
":",
"logical_or_expr",
"|",
"logical_or_expr",
"CONDOP",
"assignment_expr",
"COLON",
"assignment_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L947-L958 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_assignment_expr_noin | def p_assignment_expr_noin(self, p):
"""
assignment_expr_noin \
: conditional_expr_noin
| left_hand_side_expr assignment_operator assignment_expr_noin
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Assign(left=p[1], op=p[2], right=p[3])
p[0].setpos(p, 2) | python | def p_assignment_expr_noin(self, p):
"""
assignment_expr_noin \
: conditional_expr_noin
| left_hand_side_expr assignment_operator assignment_expr_noin
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Assign(left=p[1], op=p[2], right=p[3])
p[0].setpos(p, 2) | [
"def",
"p_assignment_expr_noin",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Assign",
"(",
"l... | assignment_expr_noin \
: conditional_expr_noin
| left_hand_side_expr assignment_operator assignment_expr_noin | [
"assignment_expr_noin",
"\\",
":",
"conditional_expr_noin",
"|",
"left_hand_side_expr",
"assignment_operator",
"assignment_expr_noin"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1000-L1010 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_expr | def p_expr(self, p):
"""expr : assignment_expr
| expr COMMA assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Comma(left=p[1], right=p[3])
p[0].setpos(p, 2) | python | def p_expr(self, p):
"""expr : assignment_expr
| expr COMMA assignment_expr
"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = self.asttypes.Comma(left=p[1], right=p[3])
p[0].setpos(p, 2) | [
"def",
"p_expr",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Comma",
"(",
"left",
"=",
"p... | expr : assignment_expr
| expr COMMA assignment_expr | [
"expr",
":",
"assignment_expr",
"|",
"expr",
"COMMA",
"assignment_expr"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1041-L1049 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_variable_statement | def p_variable_statement(self, p):
"""variable_statement : VAR variable_declaration_list SEMI
| VAR variable_declaration_list AUTOSEMI
"""
p[0] = self.asttypes.VarStatement(p[2])
p[0].setpos(p) | python | def p_variable_statement(self, p):
"""variable_statement : VAR variable_declaration_list SEMI
| VAR variable_declaration_list AUTOSEMI
"""
p[0] = self.asttypes.VarStatement(p[2])
p[0].setpos(p) | [
"def",
"p_variable_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"VarStatement",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | variable_statement : VAR variable_declaration_list SEMI
| VAR variable_declaration_list AUTOSEMI | [
"variable_statement",
":",
"VAR",
"variable_declaration_list",
"SEMI",
"|",
"VAR",
"variable_declaration_list",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1072-L1077 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_variable_declaration_list | def p_variable_declaration_list(self, p):
"""
variable_declaration_list \
: variable_declaration
| variable_declaration_list COMMA variable_declaration
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | python | def p_variable_declaration_list(self, p):
"""
variable_declaration_list \
: variable_declaration
| variable_declaration_list COMMA variable_declaration
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | [
"def",
"p_variable_declaration_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3",
... | variable_declaration_list \
: variable_declaration
| variable_declaration_list COMMA variable_declaration | [
"variable_declaration_list",
"\\",
":",
"variable_declaration",
"|",
"variable_declaration_list",
"COMMA",
"variable_declaration"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1079-L1089 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_variable_declaration_list_noin | def p_variable_declaration_list_noin(self, p):
"""
variable_declaration_list_noin \
: variable_declaration_noin
| variable_declaration_list_noin COMMA variable_declaration_noin
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | python | def p_variable_declaration_list_noin(self, p):
"""
variable_declaration_list_noin \
: variable_declaration_noin
| variable_declaration_list_noin COMMA variable_declaration_noin
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | [
"def",
"p_variable_declaration_list_noin",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3... | variable_declaration_list_noin \
: variable_declaration_noin
| variable_declaration_list_noin COMMA variable_declaration_noin | [
"variable_declaration_list_noin",
"\\",
":",
"variable_declaration_noin",
"|",
"variable_declaration_list_noin",
"COMMA",
"variable_declaration_noin"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1091-L1101 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_variable_declaration | def p_variable_declaration(self, p):
"""variable_declaration : identifier
| identifier initializer
"""
if len(p) == 2:
p[0] = self.asttypes.VarDecl(p[1])
p[0].setpos(p) # require yacc_tracking
else:
p[0] = self.asttypes.VarDecl(p[1], p[2])
p[0].setpos(p, additional=(('=', 2),)) | python | def p_variable_declaration(self, p):
"""variable_declaration : identifier
| identifier initializer
"""
if len(p) == 2:
p[0] = self.asttypes.VarDecl(p[1])
p[0].setpos(p) # require yacc_tracking
else:
p[0] = self.asttypes.VarDecl(p[1], p[2])
p[0].setpos(p, additional=(('=', 2),)) | [
"def",
"p_variable_declaration",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"VarDecl",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
... | variable_declaration : identifier
| identifier initializer | [
"variable_declaration",
":",
"identifier",
"|",
"identifier",
"initializer"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1103-L1112 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_variable_declaration_noin | def p_variable_declaration_noin(self, p):
"""variable_declaration_noin : identifier
| identifier initializer_noin
"""
if len(p) == 2:
p[0] = self.asttypes.VarDecl(p[1])
p[0].setpos(p) # require yacc_tracking
else:
p[0] = self.asttypes.VarDecl(p[1], p[2])
p[0].setpos(p, additional=(('=', 2),)) | python | def p_variable_declaration_noin(self, p):
"""variable_declaration_noin : identifier
| identifier initializer_noin
"""
if len(p) == 2:
p[0] = self.asttypes.VarDecl(p[1])
p[0].setpos(p) # require yacc_tracking
else:
p[0] = self.asttypes.VarDecl(p[1], p[2])
p[0].setpos(p, additional=(('=', 2),)) | [
"def",
"p_variable_declaration_noin",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"VarDecl",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpo... | variable_declaration_noin : identifier
| identifier initializer_noin | [
"variable_declaration_noin",
":",
"identifier",
"|",
"identifier",
"initializer_noin"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1114-L1123 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_empty_statement | def p_empty_statement(self, p):
"""empty_statement : SEMI"""
p[0] = self.asttypes.EmptyStatement(p[1])
p[0].setpos(p) | python | def p_empty_statement(self, p):
"""empty_statement : SEMI"""
p[0] = self.asttypes.EmptyStatement(p[1])
p[0].setpos(p) | [
"def",
"p_empty_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"EmptyStatement",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | empty_statement : SEMI | [
"empty_statement",
":",
"SEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1134-L1137 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_expr_statement | def p_expr_statement(self, p):
"""expr_statement : expr_nobf SEMI
| expr_nobf AUTOSEMI
"""
# In 12.4, expression statements cannot start with either the
# 'function' keyword or '{'. However, the lexing and production
# of the FuncExpr nodes can be done through further rules have
# been done, so flag this as an exception, but must be raised
# like so due to avoid the SyntaxError being flagged by ply and
# which would result in an infinite loop in this case.
if isinstance(p[1], self.asttypes.FuncExpr):
_, line, col = p[1].getpos('(', 0)
raise ProductionError(ECMASyntaxError(
'Function statement requires a name at %s:%s' % (line, col)))
# The most bare 'block' rule is defined as part of 'statement'
# and there are no other bare rules that would result in the
# production of such like for 'function_expr'.
p[0] = self.asttypes.ExprStatement(p[1])
p[0].setpos(p) | python | def p_expr_statement(self, p):
"""expr_statement : expr_nobf SEMI
| expr_nobf AUTOSEMI
"""
# In 12.4, expression statements cannot start with either the
# 'function' keyword or '{'. However, the lexing and production
# of the FuncExpr nodes can be done through further rules have
# been done, so flag this as an exception, but must be raised
# like so due to avoid the SyntaxError being flagged by ply and
# which would result in an infinite loop in this case.
if isinstance(p[1], self.asttypes.FuncExpr):
_, line, col = p[1].getpos('(', 0)
raise ProductionError(ECMASyntaxError(
'Function statement requires a name at %s:%s' % (line, col)))
# The most bare 'block' rule is defined as part of 'statement'
# and there are no other bare rules that would result in the
# production of such like for 'function_expr'.
p[0] = self.asttypes.ExprStatement(p[1])
p[0].setpos(p) | [
"def",
"p_expr_statement",
"(",
"self",
",",
"p",
")",
":",
"# In 12.4, expression statements cannot start with either the",
"# 'function' keyword or '{'. However, the lexing and production",
"# of the FuncExpr nodes can be done through further rules have",
"# been done, so flag this as an ex... | expr_statement : expr_nobf SEMI
| expr_nobf AUTOSEMI | [
"expr_statement",
":",
"expr_nobf",
"SEMI",
"|",
"expr_nobf",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1140-L1161 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_if_statement_1 | def p_if_statement_1(self, p):
"""if_statement : IF LPAREN expr RPAREN statement"""
p[0] = self.asttypes.If(predicate=p[3], consequent=p[5])
p[0].setpos(p) | python | def p_if_statement_1(self, p):
"""if_statement : IF LPAREN expr RPAREN statement"""
p[0] = self.asttypes.If(predicate=p[3], consequent=p[5])
p[0].setpos(p) | [
"def",
"p_if_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"If",
"(",
"predicate",
"=",
"p",
"[",
"3",
"]",
",",
"consequent",
"=",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
".",
"s... | if_statement : IF LPAREN expr RPAREN statement | [
"if_statement",
":",
"IF",
"LPAREN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1164-L1167 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_if_statement_2 | def p_if_statement_2(self, p):
"""if_statement : IF LPAREN expr RPAREN statement ELSE statement"""
p[0] = self.asttypes.If(
predicate=p[3], consequent=p[5], alternative=p[7])
p[0].setpos(p) | python | def p_if_statement_2(self, p):
"""if_statement : IF LPAREN expr RPAREN statement ELSE statement"""
p[0] = self.asttypes.If(
predicate=p[3], consequent=p[5], alternative=p[7])
p[0].setpos(p) | [
"def",
"p_if_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"If",
"(",
"predicate",
"=",
"p",
"[",
"3",
"]",
",",
"consequent",
"=",
"p",
"[",
"5",
"]",
",",
"alternative",
"=",
"p",
"[",
... | if_statement : IF LPAREN expr RPAREN statement ELSE statement | [
"if_statement",
":",
"IF",
"LPAREN",
"expr",
"RPAREN",
"statement",
"ELSE",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1169-L1173 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_1 | def p_iteration_statement_1(self, p):
"""
iteration_statement \
: DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI
"""
p[0] = self.asttypes.DoWhile(predicate=p[5], statement=p[2])
p[0].setpos(p) | python | def p_iteration_statement_1(self, p):
"""
iteration_statement \
: DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI
"""
p[0] = self.asttypes.DoWhile(predicate=p[5], statement=p[2])
p[0].setpos(p) | [
"def",
"p_iteration_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"DoWhile",
"(",
"predicate",
"=",
"p",
"[",
"5",
"]",
",",
"statement",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
... | iteration_statement \
: DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI | [
"iteration_statement",
"\\",
":",
"DO",
"statement",
"WHILE",
"LPAREN",
"expr",
"RPAREN",
"SEMI",
"|",
"DO",
"statement",
"WHILE",
"LPAREN",
"expr",
"RPAREN",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1176-L1183 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_2 | def p_iteration_statement_2(self, p):
"""iteration_statement : WHILE LPAREN expr RPAREN statement"""
p[0] = self.asttypes.While(predicate=p[3], statement=p[5])
p[0].setpos(p) | python | def p_iteration_statement_2(self, p):
"""iteration_statement : WHILE LPAREN expr RPAREN statement"""
p[0] = self.asttypes.While(predicate=p[3], statement=p[5])
p[0].setpos(p) | [
"def",
"p_iteration_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"While",
"(",
"predicate",
"=",
"p",
"[",
"3",
"]",
",",
"statement",
"=",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
... | iteration_statement : WHILE LPAREN expr RPAREN statement | [
"iteration_statement",
":",
"WHILE",
"LPAREN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1185-L1188 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_3 | def p_iteration_statement_3(self, p):
"""
iteration_statement \
: FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \
statement
| FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\
expr_opt RPAREN statement
"""
def wrap(node, key):
if node is None:
# work around bug with yacc tracking of empty elements
# by using the previous token, and increment the
# positions
node = self.asttypes.EmptyStatement(';')
node.setpos(p, key - 1)
node.lexpos += 1
node.colno += 1
else:
node = self.asttypes.ExprStatement(expr=node)
node.setpos(p, key)
return node
if len(p) == 10:
p[0] = self.asttypes.For(
init=wrap(p[3], 3), cond=wrap(p[5], 5),
count=p[7], statement=p[9])
else:
init = self.asttypes.VarStatement(p[4])
init.setpos(p, 3)
p[0] = self.asttypes.For(
init=init, cond=wrap(p[6], 6), count=p[8], statement=p[10])
p[0].setpos(p) | python | def p_iteration_statement_3(self, p):
"""
iteration_statement \
: FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \
statement
| FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\
expr_opt RPAREN statement
"""
def wrap(node, key):
if node is None:
# work around bug with yacc tracking of empty elements
# by using the previous token, and increment the
# positions
node = self.asttypes.EmptyStatement(';')
node.setpos(p, key - 1)
node.lexpos += 1
node.colno += 1
else:
node = self.asttypes.ExprStatement(expr=node)
node.setpos(p, key)
return node
if len(p) == 10:
p[0] = self.asttypes.For(
init=wrap(p[3], 3), cond=wrap(p[5], 5),
count=p[7], statement=p[9])
else:
init = self.asttypes.VarStatement(p[4])
init.setpos(p, 3)
p[0] = self.asttypes.For(
init=init, cond=wrap(p[6], 6), count=p[8], statement=p[10])
p[0].setpos(p) | [
"def",
"p_iteration_statement_3",
"(",
"self",
",",
"p",
")",
":",
"def",
"wrap",
"(",
"node",
",",
"key",
")",
":",
"if",
"node",
"is",
"None",
":",
"# work around bug with yacc tracking of empty elements",
"# by using the previous token, and increment the",
"# positio... | iteration_statement \
: FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \
statement
| FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\
expr_opt RPAREN statement | [
"iteration_statement",
"\\",
":",
"FOR",
"LPAREN",
"expr_noin_opt",
"SEMI",
"expr_opt",
"SEMI",
"expr_opt",
"RPAREN",
"\\",
"statement",
"|",
"FOR",
"LPAREN",
"VAR",
"variable_declaration_list_noin",
"SEMI",
"expr_opt",
"SEMI",
"\\",
"expr_opt",
"RPAREN",
"statement"
... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1190-L1221 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_4 | def p_iteration_statement_4(self, p):
"""
iteration_statement \
: FOR LPAREN left_hand_side_expr IN expr RPAREN statement
"""
p[0] = self.asttypes.ForIn(item=p[3], iterable=p[5], statement=p[7])
p[0].setpos(p) | python | def p_iteration_statement_4(self, p):
"""
iteration_statement \
: FOR LPAREN left_hand_side_expr IN expr RPAREN statement
"""
p[0] = self.asttypes.ForIn(item=p[3], iterable=p[5], statement=p[7])
p[0].setpos(p) | [
"def",
"p_iteration_statement_4",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"ForIn",
"(",
"item",
"=",
"p",
"[",
"3",
"]",
",",
"iterable",
"=",
"p",
"[",
"5",
"]",
",",
"statement",
"=",
"p",
"[",
... | iteration_statement \
: FOR LPAREN left_hand_side_expr IN expr RPAREN statement | [
"iteration_statement",
"\\",
":",
"FOR",
"LPAREN",
"left_hand_side_expr",
"IN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1223-L1229 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_5 | def p_iteration_statement_5(self, p):
"""
iteration_statement : \
FOR LPAREN VAR identifier IN expr RPAREN statement
"""
vardecl = self.asttypes.VarDeclNoIn(identifier=p[4])
vardecl.setpos(p, 3)
p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[6], statement=p[8])
p[0].setpos(p) | python | def p_iteration_statement_5(self, p):
"""
iteration_statement : \
FOR LPAREN VAR identifier IN expr RPAREN statement
"""
vardecl = self.asttypes.VarDeclNoIn(identifier=p[4])
vardecl.setpos(p, 3)
p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[6], statement=p[8])
p[0].setpos(p) | [
"def",
"p_iteration_statement_5",
"(",
"self",
",",
"p",
")",
":",
"vardecl",
"=",
"self",
".",
"asttypes",
".",
"VarDeclNoIn",
"(",
"identifier",
"=",
"p",
"[",
"4",
"]",
")",
"vardecl",
".",
"setpos",
"(",
"p",
",",
"3",
")",
"p",
"[",
"0",
"]",
... | iteration_statement : \
FOR LPAREN VAR identifier IN expr RPAREN statement | [
"iteration_statement",
":",
"\\",
"FOR",
"LPAREN",
"VAR",
"identifier",
"IN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1231-L1239 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_iteration_statement_6 | def p_iteration_statement_6(self, p):
"""
iteration_statement \
: FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement
"""
vardecl = self.asttypes.VarDeclNoIn(
identifier=p[4], initializer=p[5])
vardecl.setpos(p, 3)
p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[7], statement=p[9])
p[0].setpos(p) | python | def p_iteration_statement_6(self, p):
"""
iteration_statement \
: FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement
"""
vardecl = self.asttypes.VarDeclNoIn(
identifier=p[4], initializer=p[5])
vardecl.setpos(p, 3)
p[0] = self.asttypes.ForIn(item=vardecl, iterable=p[7], statement=p[9])
p[0].setpos(p) | [
"def",
"p_iteration_statement_6",
"(",
"self",
",",
"p",
")",
":",
"vardecl",
"=",
"self",
".",
"asttypes",
".",
"VarDeclNoIn",
"(",
"identifier",
"=",
"p",
"[",
"4",
"]",
",",
"initializer",
"=",
"p",
"[",
"5",
"]",
")",
"vardecl",
".",
"setpos",
"(... | iteration_statement \
: FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement | [
"iteration_statement",
"\\",
":",
"FOR",
"LPAREN",
"VAR",
"identifier",
"initializer_noin",
"IN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1241-L1250 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_continue_statement_1 | def p_continue_statement_1(self, p):
"""continue_statement : CONTINUE SEMI
| CONTINUE AUTOSEMI
"""
p[0] = self.asttypes.Continue()
p[0].setpos(p) | python | def p_continue_statement_1(self, p):
"""continue_statement : CONTINUE SEMI
| CONTINUE AUTOSEMI
"""
p[0] = self.asttypes.Continue()
p[0].setpos(p) | [
"def",
"p_continue_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Continue",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | continue_statement : CONTINUE SEMI
| CONTINUE AUTOSEMI | [
"continue_statement",
":",
"CONTINUE",
"SEMI",
"|",
"CONTINUE",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1265-L1270 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_continue_statement_2 | def p_continue_statement_2(self, p):
"""continue_statement : CONTINUE identifier SEMI
| CONTINUE identifier AUTOSEMI
"""
p[0] = self.asttypes.Continue(p[2])
p[0].setpos(p) | python | def p_continue_statement_2(self, p):
"""continue_statement : CONTINUE identifier SEMI
| CONTINUE identifier AUTOSEMI
"""
p[0] = self.asttypes.Continue(p[2])
p[0].setpos(p) | [
"def",
"p_continue_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Continue",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | continue_statement : CONTINUE identifier SEMI
| CONTINUE identifier AUTOSEMI | [
"continue_statement",
":",
"CONTINUE",
"identifier",
"SEMI",
"|",
"CONTINUE",
"identifier",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1272-L1277 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_break_statement_1 | def p_break_statement_1(self, p):
"""break_statement : BREAK SEMI
| BREAK AUTOSEMI
"""
p[0] = self.asttypes.Break()
p[0].setpos(p) | python | def p_break_statement_1(self, p):
"""break_statement : BREAK SEMI
| BREAK AUTOSEMI
"""
p[0] = self.asttypes.Break()
p[0].setpos(p) | [
"def",
"p_break_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Break",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | break_statement : BREAK SEMI
| BREAK AUTOSEMI | [
"break_statement",
":",
"BREAK",
"SEMI",
"|",
"BREAK",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1280-L1285 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_break_statement_2 | def p_break_statement_2(self, p):
"""break_statement : BREAK identifier SEMI
| BREAK identifier AUTOSEMI
"""
p[0] = self.asttypes.Break(p[2])
p[0].setpos(p) | python | def p_break_statement_2(self, p):
"""break_statement : BREAK identifier SEMI
| BREAK identifier AUTOSEMI
"""
p[0] = self.asttypes.Break(p[2])
p[0].setpos(p) | [
"def",
"p_break_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Break",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | break_statement : BREAK identifier SEMI
| BREAK identifier AUTOSEMI | [
"break_statement",
":",
"BREAK",
"identifier",
"SEMI",
"|",
"BREAK",
"identifier",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1287-L1292 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_return_statement_1 | def p_return_statement_1(self, p):
"""return_statement : RETURN SEMI
| RETURN AUTOSEMI
"""
p[0] = self.asttypes.Return()
p[0].setpos(p) | python | def p_return_statement_1(self, p):
"""return_statement : RETURN SEMI
| RETURN AUTOSEMI
"""
p[0] = self.asttypes.Return()
p[0].setpos(p) | [
"def",
"p_return_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Return",
"(",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | return_statement : RETURN SEMI
| RETURN AUTOSEMI | [
"return_statement",
":",
"RETURN",
"SEMI",
"|",
"RETURN",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1295-L1300 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_return_statement_2 | def p_return_statement_2(self, p):
"""return_statement : RETURN expr SEMI
| RETURN expr AUTOSEMI
"""
p[0] = self.asttypes.Return(expr=p[2])
p[0].setpos(p) | python | def p_return_statement_2(self, p):
"""return_statement : RETURN expr SEMI
| RETURN expr AUTOSEMI
"""
p[0] = self.asttypes.Return(expr=p[2])
p[0].setpos(p) | [
"def",
"p_return_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Return",
"(",
"expr",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | return_statement : RETURN expr SEMI
| RETURN expr AUTOSEMI | [
"return_statement",
":",
"RETURN",
"expr",
"SEMI",
"|",
"RETURN",
"expr",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1302-L1307 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_with_statement | def p_with_statement(self, p):
"""with_statement : WITH LPAREN expr RPAREN statement"""
p[0] = self.asttypes.With(expr=p[3], statement=p[5])
p[0].setpos(p) | python | def p_with_statement(self, p):
"""with_statement : WITH LPAREN expr RPAREN statement"""
p[0] = self.asttypes.With(expr=p[3], statement=p[5])
p[0].setpos(p) | [
"def",
"p_with_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"With",
"(",
"expr",
"=",
"p",
"[",
"3",
"]",
",",
"statement",
"=",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpo... | with_statement : WITH LPAREN expr RPAREN statement | [
"with_statement",
":",
"WITH",
"LPAREN",
"expr",
"RPAREN",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1310-L1313 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_switch_statement | def p_switch_statement(self, p):
"""switch_statement : SWITCH LPAREN expr RPAREN case_block"""
# this uses a completely different type that corrects a
# subtly wrong interpretation of this construct.
# see: https://github.com/rspivak/slimit/issues/94
p[0] = self.asttypes.Switch(expr=p[3], case_block=p[5])
p[0].setpos(p)
return | python | def p_switch_statement(self, p):
"""switch_statement : SWITCH LPAREN expr RPAREN case_block"""
# this uses a completely different type that corrects a
# subtly wrong interpretation of this construct.
# see: https://github.com/rspivak/slimit/issues/94
p[0] = self.asttypes.Switch(expr=p[3], case_block=p[5])
p[0].setpos(p)
return | [
"def",
"p_switch_statement",
"(",
"self",
",",
"p",
")",
":",
"# this uses a completely different type that corrects a",
"# subtly wrong interpretation of this construct.",
"# see: https://github.com/rspivak/slimit/issues/94",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
"... | switch_statement : SWITCH LPAREN expr RPAREN case_block | [
"switch_statement",
":",
"SWITCH",
"LPAREN",
"expr",
"RPAREN",
"case_block"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1316-L1323 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_case_block | def p_case_block(self, p):
"""
case_block \
: LBRACE case_clauses_opt RBRACE
| LBRACE case_clauses_opt default_clause case_clauses_opt RBRACE
"""
statements = []
for s in p[2:-1]:
if isinstance(s, list):
for i in s:
statements.append(i)
elif isinstance(s, self.asttypes.Default):
statements.append(s)
p[0] = self.asttypes.CaseBlock(statements)
p[0].setpos(p) | python | def p_case_block(self, p):
"""
case_block \
: LBRACE case_clauses_opt RBRACE
| LBRACE case_clauses_opt default_clause case_clauses_opt RBRACE
"""
statements = []
for s in p[2:-1]:
if isinstance(s, list):
for i in s:
statements.append(i)
elif isinstance(s, self.asttypes.Default):
statements.append(s)
p[0] = self.asttypes.CaseBlock(statements)
p[0].setpos(p) | [
"def",
"p_case_block",
"(",
"self",
",",
"p",
")",
":",
"statements",
"=",
"[",
"]",
"for",
"s",
"in",
"p",
"[",
"2",
":",
"-",
"1",
"]",
":",
"if",
"isinstance",
"(",
"s",
",",
"list",
")",
":",
"for",
"i",
"in",
"s",
":",
"statements",
".",... | case_block \
: LBRACE case_clauses_opt RBRACE
| LBRACE case_clauses_opt default_clause case_clauses_opt RBRACE | [
"case_block",
"\\",
":",
"LBRACE",
"case_clauses_opt",
"RBRACE",
"|",
"LBRACE",
"case_clauses_opt",
"default_clause",
"case_clauses_opt",
"RBRACE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1325-L1339 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_case_clauses | def p_case_clauses(self, p):
"""case_clauses : case_clause
| case_clauses case_clause
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[2])
p[0] = p[1] | python | def p_case_clauses(self, p):
"""case_clauses : case_clause
| case_clauses case_clause
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[2])
p[0] = p[1] | [
"def",
"p_case_clauses",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"2",
"]",
")",
... | case_clauses : case_clause
| case_clauses case_clause | [
"case_clauses",
":",
"case_clause",
"|",
"case_clauses",
"case_clause"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1347-L1355 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_case_clause | def p_case_clause(self, p):
"""case_clause : CASE expr COLON source_elements"""
p[0] = self.asttypes.Case(expr=p[2], elements=p[4])
p[0].setpos(p) | python | def p_case_clause(self, p):
"""case_clause : CASE expr COLON source_elements"""
p[0] = self.asttypes.Case(expr=p[2], elements=p[4])
p[0].setpos(p) | [
"def",
"p_case_clause",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Case",
"(",
"expr",
"=",
"p",
"[",
"2",
"]",
",",
"elements",
"=",
"p",
"[",
"4",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
... | case_clause : CASE expr COLON source_elements | [
"case_clause",
":",
"CASE",
"expr",
"COLON",
"source_elements"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1357-L1360 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_default_clause | def p_default_clause(self, p):
"""default_clause : DEFAULT COLON source_elements"""
p[0] = self.asttypes.Default(elements=p[3])
p[0].setpos(p) | python | def p_default_clause(self, p):
"""default_clause : DEFAULT COLON source_elements"""
p[0] = self.asttypes.Default(elements=p[3])
p[0].setpos(p) | [
"def",
"p_default_clause",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Default",
"(",
"elements",
"=",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | default_clause : DEFAULT COLON source_elements | [
"default_clause",
":",
"DEFAULT",
"COLON",
"source_elements"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1362-L1365 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_labelled_statement | def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = self.asttypes.Label(identifier=p[1], statement=p[3])
p[0].setpos(p, 2) | python | def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = self.asttypes.Label(identifier=p[1], statement=p[3])
p[0].setpos(p, 2) | [
"def",
"p_labelled_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Label",
"(",
"identifier",
"=",
"p",
"[",
"1",
"]",
",",
"statement",
"=",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
".... | labelled_statement : identifier COLON statement | [
"labelled_statement",
":",
"identifier",
"COLON",
"statement"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1368-L1371 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_throw_statement | def p_throw_statement(self, p):
"""throw_statement : THROW expr SEMI
| THROW expr AUTOSEMI
"""
p[0] = self.asttypes.Throw(expr=p[2])
p[0].setpos(p) | python | def p_throw_statement(self, p):
"""throw_statement : THROW expr SEMI
| THROW expr AUTOSEMI
"""
p[0] = self.asttypes.Throw(expr=p[2])
p[0].setpos(p) | [
"def",
"p_throw_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Throw",
"(",
"expr",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | throw_statement : THROW expr SEMI
| THROW expr AUTOSEMI | [
"throw_statement",
":",
"THROW",
"expr",
"SEMI",
"|",
"THROW",
"expr",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1374-L1379 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_try_statement_1 | def p_try_statement_1(self, p):
"""try_statement : TRY block catch"""
p[0] = self.asttypes.Try(statements=p[2], catch=p[3])
p[0].setpos(p) | python | def p_try_statement_1(self, p):
"""try_statement : TRY block catch"""
p[0] = self.asttypes.Try(statements=p[2], catch=p[3])
p[0].setpos(p) | [
"def",
"p_try_statement_1",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Try",
"(",
"statements",
"=",
"p",
"[",
"2",
"]",
",",
"catch",
"=",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
".",
"set... | try_statement : TRY block catch | [
"try_statement",
":",
"TRY",
"block",
"catch"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1382-L1385 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_try_statement_2 | def p_try_statement_2(self, p):
"""try_statement : TRY block finally"""
p[0] = self.asttypes.Try(statements=p[2], fin=p[3])
p[0].setpos(p) | python | def p_try_statement_2(self, p):
"""try_statement : TRY block finally"""
p[0] = self.asttypes.Try(statements=p[2], fin=p[3])
p[0].setpos(p) | [
"def",
"p_try_statement_2",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Try",
"(",
"statements",
"=",
"p",
"[",
"2",
"]",
",",
"fin",
"=",
"p",
"[",
"3",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpo... | try_statement : TRY block finally | [
"try_statement",
":",
"TRY",
"block",
"finally"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1387-L1390 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_try_statement_3 | def p_try_statement_3(self, p):
"""try_statement : TRY block catch finally"""
p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4])
p[0].setpos(p) | python | def p_try_statement_3(self, p):
"""try_statement : TRY block catch finally"""
p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4])
p[0].setpos(p) | [
"def",
"p_try_statement_3",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Try",
"(",
"statements",
"=",
"p",
"[",
"2",
"]",
",",
"catch",
"=",
"p",
"[",
"3",
"]",
",",
"fin",
"=",
"p",
"[",
"4",
"]... | try_statement : TRY block catch finally | [
"try_statement",
":",
"TRY",
"block",
"catch",
"finally"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1392-L1395 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_catch | def p_catch(self, p):
"""catch : CATCH LPAREN identifier RPAREN block"""
p[0] = self.asttypes.Catch(identifier=p[3], elements=p[5])
p[0].setpos(p) | python | def p_catch(self, p):
"""catch : CATCH LPAREN identifier RPAREN block"""
p[0] = self.asttypes.Catch(identifier=p[3], elements=p[5])
p[0].setpos(p) | [
"def",
"p_catch",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Catch",
"(",
"identifier",
"=",
"p",
"[",
"3",
"]",
",",
"elements",
"=",
"p",
"[",
"5",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",... | catch : CATCH LPAREN identifier RPAREN block | [
"catch",
":",
"CATCH",
"LPAREN",
"identifier",
"RPAREN",
"block"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1397-L1400 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_finally | def p_finally(self, p):
"""finally : FINALLY block"""
p[0] = self.asttypes.Finally(elements=p[2])
p[0].setpos(p) | python | def p_finally(self, p):
"""finally : FINALLY block"""
p[0] = self.asttypes.Finally(elements=p[2])
p[0].setpos(p) | [
"def",
"p_finally",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Finally",
"(",
"elements",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | finally : FINALLY block | [
"finally",
":",
"FINALLY",
"block"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1402-L1405 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_debugger_statement | def p_debugger_statement(self, p):
"""debugger_statement : DEBUGGER SEMI
| DEBUGGER AUTOSEMI
"""
p[0] = self.asttypes.Debugger(p[1])
p[0].setpos(p) | python | def p_debugger_statement(self, p):
"""debugger_statement : DEBUGGER SEMI
| DEBUGGER AUTOSEMI
"""
p[0] = self.asttypes.Debugger(p[1])
p[0].setpos(p) | [
"def",
"p_debugger_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Debugger",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | debugger_statement : DEBUGGER SEMI
| DEBUGGER AUTOSEMI | [
"debugger_statement",
":",
"DEBUGGER",
"SEMI",
"|",
"DEBUGGER",
"AUTOSEMI"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1408-L1413 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_function_declaration | def p_function_declaration(self, p):
"""
function_declaration \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \
function_body RBRACE
"""
if len(p) == 8:
p[0] = self.asttypes.FuncDecl(
identifier=p[2], parameters=None, elements=p[6])
else:
p[0] = self.asttypes.FuncDecl(
identifier=p[2], parameters=p[4], elements=p[7])
p[0].setpos(p) | python | def p_function_declaration(self, p):
"""
function_declaration \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \
function_body RBRACE
"""
if len(p) == 8:
p[0] = self.asttypes.FuncDecl(
identifier=p[2], parameters=None, elements=p[6])
else:
p[0] = self.asttypes.FuncDecl(
identifier=p[2], parameters=p[4], elements=p[7])
p[0].setpos(p) | [
"def",
"p_function_declaration",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"8",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"FuncDecl",
"(",
"identifier",
"=",
"p",
"[",
"2",
"]",
",",
"parameters",
"=",
... | function_declaration \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \
function_body RBRACE | [
"function_declaration",
"\\",
":",
"FUNCTION",
"identifier",
"LPAREN",
"RPAREN",
"LBRACE",
"function_body",
"RBRACE",
"|",
"FUNCTION",
"identifier",
"LPAREN",
"formal_parameter_list",
"RPAREN",
"LBRACE",
"\\",
"function_body",
"RBRACE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1416-L1429 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_function_expr_2 | def p_function_expr_2(self, p):
"""
function_expr \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN \
LBRACE function_body RBRACE
"""
if len(p) == 8:
p[0] = self.asttypes.FuncExpr(
identifier=p[2], parameters=None, elements=p[6])
else:
p[0] = self.asttypes.FuncExpr(
identifier=p[2], parameters=p[4], elements=p[7])
p[0].setpos(p) | python | def p_function_expr_2(self, p):
"""
function_expr \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN \
LBRACE function_body RBRACE
"""
if len(p) == 8:
p[0] = self.asttypes.FuncExpr(
identifier=p[2], parameters=None, elements=p[6])
else:
p[0] = self.asttypes.FuncExpr(
identifier=p[2], parameters=p[4], elements=p[7])
p[0].setpos(p) | [
"def",
"p_function_expr_2",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"8",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"FuncExpr",
"(",
"identifier",
"=",
"p",
"[",
"2",
"]",
",",
"parameters",
"=",
"Non... | function_expr \
: FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE
| FUNCTION identifier LPAREN formal_parameter_list RPAREN \
LBRACE function_body RBRACE | [
"function_expr",
"\\",
":",
"FUNCTION",
"identifier",
"LPAREN",
"RPAREN",
"LBRACE",
"function_body",
"RBRACE",
"|",
"FUNCTION",
"identifier",
"LPAREN",
"formal_parameter_list",
"RPAREN",
"\\",
"LBRACE",
"function_body",
"RBRACE"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1446-L1459 |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | Parser.p_formal_parameter_list | def p_formal_parameter_list(self, p):
"""formal_parameter_list : identifier
| formal_parameter_list COMMA identifier
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | python | def p_formal_parameter_list(self, p):
"""formal_parameter_list : identifier
| formal_parameter_list COMMA identifier
"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | [
"def",
"p_formal_parameter_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"3",
"]",... | formal_parameter_list : identifier
| formal_parameter_list COMMA identifier | [
"formal_parameter_list",
":",
"identifier",
"|",
"formal_parameter_list",
"COMMA",
"identifier"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L1461-L1469 |
limix/limix-core | limix_core/mean/meanKronSum.py | MeanKronSum.Y | def Y(self, value):
""" set phenotype """
self._N = value.shape[0]
self._P = value.shape[1]
self._Y = value
# missing data
self._Iok = ~sp.isnan(value)
self._veIok = vec(self._Iok)[:, 0]
self._miss = (~self._Iok).any()
# notify and clear_cached
self.clear_cache('pheno')
self._notify()
self._notify('pheno') | python | def Y(self, value):
""" set phenotype """
self._N = value.shape[0]
self._P = value.shape[1]
self._Y = value
# missing data
self._Iok = ~sp.isnan(value)
self._veIok = vec(self._Iok)[:, 0]
self._miss = (~self._Iok).any()
# notify and clear_cached
self.clear_cache('pheno')
self._notify()
self._notify('pheno') | [
"def",
"Y",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_N",
"=",
"value",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"_P",
"=",
"value",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"_Y",
"=",
"value",
"# missing data",
"self",
".",
"_Iok",... | set phenotype | [
"set",
"phenotype"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/meanKronSum.py#L169-L181 |
limix/limix-core | limix_core/mean/meanKronSum.py | MeanKronSum.setDesigns | def setDesigns(self, F, A):
""" set fixed effect designs """
F = to_list(F)
A = to_list(A)
assert len(A) == len(F), 'MeanKronSum: A and F must have same length!'
n_terms = len(F)
n_covs = 0
k = 0
l = 0
for ti in range(n_terms):
assert F[ti].shape[0] == self._N, 'MeanKronSum: Dimension mismatch'
assert A[ti].shape[1] == self._P, 'MeanKronSum: Dimension mismatch'
n_covs += F[ti].shape[1] * A[ti].shape[0]
k += F[ti].shape[1]
l += A[ti].shape[0]
self._n_terms = n_terms
self._n_covs = n_covs
self._k = k
self._l = l
self._F = F
self._A = A
self._b = sp.zeros((n_covs, 1))
self.clear_cache('predict_in_sample', 'Yres', 'designs')
self._notify('designs')
self._notify() | python | def setDesigns(self, F, A):
""" set fixed effect designs """
F = to_list(F)
A = to_list(A)
assert len(A) == len(F), 'MeanKronSum: A and F must have same length!'
n_terms = len(F)
n_covs = 0
k = 0
l = 0
for ti in range(n_terms):
assert F[ti].shape[0] == self._N, 'MeanKronSum: Dimension mismatch'
assert A[ti].shape[1] == self._P, 'MeanKronSum: Dimension mismatch'
n_covs += F[ti].shape[1] * A[ti].shape[0]
k += F[ti].shape[1]
l += A[ti].shape[0]
self._n_terms = n_terms
self._n_covs = n_covs
self._k = k
self._l = l
self._F = F
self._A = A
self._b = sp.zeros((n_covs, 1))
self.clear_cache('predict_in_sample', 'Yres', 'designs')
self._notify('designs')
self._notify() | [
"def",
"setDesigns",
"(",
"self",
",",
"F",
",",
"A",
")",
":",
"F",
"=",
"to_list",
"(",
"F",
")",
"A",
"=",
"to_list",
"(",
"A",
")",
"assert",
"len",
"(",
"A",
")",
"==",
"len",
"(",
"F",
")",
",",
"'MeanKronSum: A and F must have same length!'",
... | set fixed effect designs | [
"set",
"fixed",
"effect",
"designs"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/meanKronSum.py#L187-L211 |
limix/limix-core | limix_core/mean/meanKronSum.py | MeanKronSum.Fstar | def Fstar(self, value):
""" set fixed effect design for predictions """
if value is None:
self._use_to_predict = False
else:
assert value.shape[1] == self._K, 'Dimension mismatch'
self._use_to_predict = True
self._Fstar = value
self.clear_cache('predict') | python | def Fstar(self, value):
""" set fixed effect design for predictions """
if value is None:
self._use_to_predict = False
else:
assert value.shape[1] == self._K, 'Dimension mismatch'
self._use_to_predict = True
self._Fstar = value
self.clear_cache('predict') | [
"def",
"Fstar",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"_use_to_predict",
"=",
"False",
"else",
":",
"assert",
"value",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"_K",
",",
"'Dimension mismatch'",
"s... | set fixed effect design for predictions | [
"set",
"fixed",
"effect",
"design",
"for",
"predictions"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/meanKronSum.py#L214-L222 |
limix/limix-core | limix_core/util/preprocess.py | standardize | def standardize(Y,in_place=False):
"""
standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations?
"""
if in_place:
YY = Y
else:
YY = Y.copy()
for i in range(YY.shape[1]):
Iok = ~SP.isnan(YY[:,i])
Ym = YY[Iok,i].mean()
YY[:,i]-=Ym
Ys = YY[Iok,i].std()
YY[:,i]/=Ys
return YY | python | def standardize(Y,in_place=False):
"""
standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations?
"""
if in_place:
YY = Y
else:
YY = Y.copy()
for i in range(YY.shape[1]):
Iok = ~SP.isnan(YY[:,i])
Ym = YY[Iok,i].mean()
YY[:,i]-=Ym
Ys = YY[Iok,i].std()
YY[:,i]/=Ys
return YY | [
"def",
"standardize",
"(",
"Y",
",",
"in_place",
"=",
"False",
")",
":",
"if",
"in_place",
":",
"YY",
"=",
"Y",
"else",
":",
"YY",
"=",
"Y",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"YY",
".",
"shape",
"[",
"1",
"]",
")",
":",
... | standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations? | [
"standardize",
"Y",
"in",
"a",
"way",
"that",
"is",
"robust",
"to",
"missing",
"values",
"in_place",
":",
"create",
"a",
"copy",
"or",
"carry",
"out",
"inplace",
"opreations?"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L5-L20 |
limix/limix-core | limix_core/util/preprocess.py | covar_rescaling_factor | def covar_rescaling_factor(C):
"""
Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1
"""
n = C.shape[0]
P = sp.eye(n) - sp.ones((n,n))/float(n)
trPCP = sp.trace(sp.dot(P,sp.dot(C,P)))
r = (n-1) / trPCP
return r | python | def covar_rescaling_factor(C):
"""
Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1
"""
n = C.shape[0]
P = sp.eye(n) - sp.ones((n,n))/float(n)
trPCP = sp.trace(sp.dot(P,sp.dot(C,P)))
r = (n-1) / trPCP
return r | [
"def",
"covar_rescaling_factor",
"(",
"C",
")",
":",
"n",
"=",
"C",
".",
"shape",
"[",
"0",
"]",
"P",
"=",
"sp",
".",
"eye",
"(",
"n",
")",
"-",
"sp",
".",
"ones",
"(",
"(",
"n",
",",
"n",
")",
")",
"/",
"float",
"(",
"n",
")",
"trPCP",
"... | Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1 | [
"Returns",
"the",
"rescaling",
"factor",
"for",
"the",
"Gower",
"normalizion",
"on",
"covariance",
"matrix",
"C",
"the",
"rescaled",
"covariance",
"matrix",
"has",
"sample",
"variance",
"of",
"1"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L22-L31 |
limix/limix-core | limix_core/util/preprocess.py | covar_rescaling_factor_efficient | def covar_rescaling_factor_efficient(C):
"""
Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1
"""
n = C.shape[0]
P = sp.eye(n) - sp.ones((n,n))/float(n)
CP = C - C.mean(0)[:, sp.newaxis]
trPCP = sp.sum(P * CP)
r = (n-1) / trPCP
return r | python | def covar_rescaling_factor_efficient(C):
"""
Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1
"""
n = C.shape[0]
P = sp.eye(n) - sp.ones((n,n))/float(n)
CP = C - C.mean(0)[:, sp.newaxis]
trPCP = sp.sum(P * CP)
r = (n-1) / trPCP
return r | [
"def",
"covar_rescaling_factor_efficient",
"(",
"C",
")",
":",
"n",
"=",
"C",
".",
"shape",
"[",
"0",
"]",
"P",
"=",
"sp",
".",
"eye",
"(",
"n",
")",
"-",
"sp",
".",
"ones",
"(",
"(",
"n",
",",
"n",
")",
")",
"/",
"float",
"(",
"n",
")",
"C... | Returns the rescaling factor for the Gower normalizion on covariance matrix C
the rescaled covariance matrix has sample variance of 1 | [
"Returns",
"the",
"rescaling",
"factor",
"for",
"the",
"Gower",
"normalizion",
"on",
"covariance",
"matrix",
"C",
"the",
"rescaled",
"covariance",
"matrix",
"has",
"sample",
"variance",
"of",
"1"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/preprocess.py#L33-L43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.