file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_ivim.py | """
Testing the Intravoxel incoherent motion module
The values of the various parameters used in the tests are inspired by
the study of the IVIM model applied to MR images of the brain by
Federau, Christian, et al. [1].
References
----------
.. [1] Federau, Christian, et al. "Quantitative measurement
of brain perfusion with intravoxel incoherent motion
MR imaging." Radiology 265.3 (2012): 874-881.
"""
import warnings
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_raises, assert_array_less, run_module_suite,
assert_, assert_equal)
from dipy.testing import assert_greater_equal
import pytest
from dipy.reconst.ivim import ivim_prediction, IvimModel
from dipy.core.gradients import gradient_table, generate_bvecs
from dipy.sims.voxel import multi_tensor
from dipy.utils.optpkg import optional_package
cvxpy, have_cvxpy, _ = optional_package("cvxpy")
needs_cvxpy = pytest.mark.skipif(not have_cvxpy, reason="REQUIRES CVXPY")
def setup_module():
global gtab, ivim_fit_single, ivim_model_trr, data_single, params_trr, \
data_multi, ivim_params_trr, D_star, D, f, S0, gtab_with_multiple_b0, \
noisy_single, mevals, gtab_no_b0, ivim_fit_multi, ivim_model_VP, \
f_VP, D_star_VP, D_VP, params_VP
# Let us generate some data for testing.
bvals = np.array([0., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals, bvecs.T, b0_threshold=0)
S0, f, D_star, D = 1000.0, 0.132, 0.00885, 0.000921
# params for a single voxel
params_trr = np.array([S0, f, D_star, D])
mevals = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal = multi_tensor(gtab, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
data_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
data_multi[0, 0, 0] = data_multi[0, 1, 0] = data_multi[
1, 0, 0] = data_multi[1, 1, 0] = data_single
ivim_params_trr = np.zeros((2, 2, 1, 4))
ivim_params_trr[0, 0, 0] = ivim_params_trr[0, 1, 0] = params_trr
ivim_params_trr[1, 0, 0] = ivim_params_trr[1, 1, 0] = params_trr
ivim_model_trr = IvimModel(gtab, fit_method='trr')
ivim_model_one_stage = IvimModel(gtab, fit_method='trr')
ivim_fit_single = ivim_model_trr.fit(data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
ivim_model_one_stage.fit(data_single)
ivim_model_one_stage.fit(data_multi)
bvals_no_b0 = np.array([5., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
_ = generate_bvecs(N) # bvecs_no_b0
gtab_no_b0 = gradient_table(bvals_no_b0, bvecs.T, b0_threshold=0)
bvals_with_multiple_b0 = np.array([0., 0., 0., 0., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_multiple_b0.T,
b0_threshold=0)
noisy_single = np.array([4243.71728516, 4317.81298828, 4244.35693359,
4439.36816406, 4420.06201172, 4152.30078125,
4114.34912109, 4104.59375, 4151.61914062,
4003.58374023, 4013.68408203, 3906.39428711,
3909.06079102, 3495.27197266, 3402.57006836,
3163.10180664, 2896.04003906, 2663.7253418,
2614.87695312, 2316.55371094, 2267.7722168])
noisy_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
noisy_multi[0, 1, 0] = noisy_multi[
1, 0, 0] = noisy_multi[1, 1, 0] = noisy_single
noisy_multi[0, 0, 0] = data_single
ivim_model_VP = IvimModel(gtab, fit_method='VarPro')
f_VP, D_star_VP, D_VP = 0.13, 0.0088, 0.000921
# params for a single voxel
params_VP = np.array([f, D_star, D])
ivim_params_VP = np.zeros((2, 2, 1, 3))
ivim_params_VP[0, 0, 0] = ivim_params_VP[0, 1, 0] = params_VP
ivim_params_VP[1, 0, 0] = ivim_params_VP[1, 1, 0] = params_VP
| def single_exponential(S0, D, bvals):
return S0 * np.exp(-bvals * D)
def test_single_voxel_fit():
"""
Test the implementation of the fitting for a single voxel.
Here, we will use the multi_tensor function to generate a
bi-exponential signal. The multi_tensor generates a multi
tensor signal and expects eigenvalues of each tensor in mevals.
Our basic test requires a scalar signal isotropic signal and
hence we set the same eigenvalue in all three directions to
generate the required signal.
The bvals, f, D_star and D are inspired from the paper by
Federau, Christian, et al. We use the function "generate_bvecs"
to simulate bvectors corresponding to the bvalues.
In the two stage fitting routine, initially we fit the signal
values for bvals less than the specified split_b using the
TensorModel and get an intial guess for f and D. Then, using
these parameters we fit the entire data for all bvalues.
"""
est_signal = ivim_prediction(ivim_fit_single.model_params, gtab)
assert_array_equal(est_signal.shape, data_single.shape)
assert_array_almost_equal(ivim_fit_single.model_params, params_trr)
assert_array_almost_equal(est_signal, data_single)
# Test predict function for single voxel
p = ivim_fit_single.predict(gtab)
assert_array_equal(p.shape, data_single.shape)
assert_array_almost_equal(p, data_single)
def test_multivoxel():
"""Test fitting with multivoxel data.
We generate a multivoxel signal to test the fitting for multivoxel data.
This is to ensure that the fitting routine takes care of signals packed as
1D, 2D or 3D arrays.
"""
ivim_fit_multi = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit_multi.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit_multi.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi)
def test_ivim_errors():
"""
Test if errors raised in the module are working correctly.
Scipy introduced bounded least squares fitting in the version 0.17
and is not supported by the older versions. Initializing an IvimModel
with bounds for older Scipy versions should raise an error.
"""
ivim_model_trr = IvimModel(gtab, bounds=([0., 0., 0., 0.],
[np.inf, 1., 1., 1.]),
fit_method='trr')
ivim_fit = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi)
def test_mask():
"""
Test whether setting incorrect mask raises and error
"""
mask_correct = data_multi[..., 0] > 0.2
mask_not_correct = np.array([[False, True, False], [True, False]],
dtype=np.bool)
ivim_fit = ivim_model_trr.fit(data_multi, mask_correct)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(est_signal, data_multi)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_raises(ValueError, ivim_model_trr.fit, data_multi,
mask=mask_not_correct)
def test_with_higher_S0():
"""
Test whether fitting works for S0 > 1.
"""
# params for a single voxel
S0_2 = 1000.
params2 = np.array([S0_2, f, D_star, D])
mevals2 = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal2 = multi_tensor(gtab, mevals2, snr=None, S0=S0_2,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single2 = signal2[0]
ivim_fit = ivim_model_trr.fit(data_single2)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, data_single2.shape)
assert_array_almost_equal(est_signal, data_single2)
assert_array_almost_equal(ivim_fit.model_params, params2)
def test_b0_threshold_greater_than0():
"""
Added test case for default b0_threshold set to 50.
Checks if error is thrown correctly.
"""
bvals_b0t = np.array([50., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals_b0t)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals_b0t, bvecs.T)
with assert_raises(ValueError) as vae:
_ = IvimModel(gtab, fit_method='trr')
b0_s = "The IVIM model requires a measurement at b==0. As of "
assert b0_s in vae.exception
def test_bounds_x0():
"""
Test to check if setting bounds for signal where initial value is
higher than subsequent values works.
These values are from the IVIM dataset which can be obtained by using
the `read_ivim` function from dipy.data.fetcher. These are values from
the voxel [160, 98, 33] which can be obtained by :
.. code-block:: python
from dipy.data.fetcher import read_ivim
img, gtab = read_ivim()
data = load_nifti_data(img)
signal = data[160, 98, 33, :]
"""
x0_test = np.array([1., 0.13, 0.001, 0.0001])
test_signal = ivim_prediction(x0_test, gtab)
ivim_fit = ivim_model_trr.fit(test_signal)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, test_signal.shape)
def test_predict():
"""
Test the model prediction API.
The predict method is already used in previous tests for estimation of the
signal. But here, we will test is separately.
"""
assert_array_almost_equal(ivim_fit_single.predict(gtab),
data_single)
assert_array_almost_equal(ivim_model_trr.predict
(ivim_fit_single.model_params, gtab),
data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_almost_equal(ivim_fit_multi.predict(gtab),
data_multi)
def test_fit_object():
"""
Test the method of IvimFit class
"""
assert_raises(IndexError, ivim_fit_single.__getitem__, (-.1, 0, 0))
# Check if the S0 called is matching
assert_array_almost_equal(
ivim_fit_single.__getitem__(0).model_params, 1000.)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
# Should raise a TypeError if the arguments are not passed as tuple
assert_raises(TypeError, ivim_fit_multi.__getitem__, -.1, 0)
# Should return IndexError if invalid indices are passed
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0, 2))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (-100, 0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, [-100, 0])
assert_raises(IndexError, ivim_fit_multi.__getitem__, (1, 0, 0, 3, 4))
# Check if the get item returns the S0 value for voxel (1,0,0)
assert_array_almost_equal(
ivim_fit_multi.__getitem__((1, 0, 0)).model_params[0],
data_multi[1, 0, 0][0])
def test_shape():
"""
Test if `shape` in `IvimFit` class gives the correct output.
"""
assert_array_equal(ivim_fit_single.shape, ())
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_equal(ivim_fit_multi.shape, (2, 2, 1))
def test_multiple_b0():
# Generate a signal with multiple b0
# This gives an isotropic signal.
signal = multi_tensor(gtab_with_multiple_b0, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
ivim_model_multiple_b0 = IvimModel(gtab_with_multiple_b0, fit_method='trr')
ivim_model_multiple_b0.fit(data_single)
# Test if all signals are positive
def test_no_b0():
assert_raises(ValueError, IvimModel, gtab_no_b0)
def test_noisy_fit():
"""
Test fitting for noisy signals. This tests whether the threshold condition
applies correctly and returns the linear fitting parameters.
For older scipy versions, the returned value of `f` from a linear fit is
around 135 and D and D_star values are equal. Hence doing a test based on
Scipy version.
"""
model_one_stage = IvimModel(gtab, fit_method='trr')
with warnings.catch_warnings(record=True) as w:
fit_one_stage = model_one_stage.fit(noisy_single)
assert_equal(len(w), 3)
for l_w in w:
assert_(issubclass(l_w.category, UserWarning))
assert_("" in str(w[0].message))
assert_("x0 obtained from linear fitting is not feasibile" in
str(w[0].message))
assert_("x0 is unfeasible" in str(w[1].message))
assert_("Bounds are violated for leastsq fitting" in str(w[2].message))
assert_array_less(fit_one_stage.model_params, [10000., 0.3, .01, 0.001])
def test_S0():
"""
Test if the `IvimFit` class returns the correct S0
"""
assert_array_almost_equal(ivim_fit_single.S0_predicted, S0)
assert_array_almost_equal(ivim_fit_multi.S0_predicted,
ivim_params_trr[..., 0])
def test_perfusion_fraction():
"""
Test if the `IvimFit` class returns the correct f
"""
assert_array_almost_equal(ivim_fit_single.perfusion_fraction, f)
assert_array_almost_equal(
ivim_fit_multi.perfusion_fraction, ivim_params_trr[..., 1])
def test_D_star():
"""
Test if the `IvimFit` class returns the correct D_star
"""
assert_array_almost_equal(ivim_fit_single.D_star, D_star)
assert_array_almost_equal(ivim_fit_multi.D_star, ivim_params_trr[..., 2])
def test_D():
"""
Test if the `IvimFit` class returns the correct D
"""
assert_array_almost_equal(ivim_fit_single.D, D)
assert_array_almost_equal(ivim_fit_multi.D, ivim_params_trr[..., 3])
def test_estimate_linear_fit():
"""
Test the linear estimates considering a single exponential fit.
"""
data_single_exponential_D = single_exponential(S0, D, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D,
split_b=500.,
less_than=False),
(S0, D))
data_single_exponential_D_star = single_exponential(S0, D_star, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D_star,
split_b=100.,
less_than=True),
(S0, D_star))
def test_estimate_f_D_star():
"""
Test if the `estimate_f_D_star` returns the correct parameters after a
non-linear fit.
"""
params_f_D = f + 0.001, D + 0.0001
assert_array_almost_equal(ivim_model_trr.estimate_f_D_star(params_f_D,
data_single, S0,
D),
(f, D_star))
def test_fit_one_stage():
"""
Test to check the results for the one_stage linear fit.
"""
model = IvimModel(gtab, two_stage=False)
fit = model.fit(data_single)
linear_fit_params = [9.88834140e+02, 1.19707191e-01, 7.91176970e-03,
9.30095210e-04]
linear_fit_signal = [988.83414044, 971.77122546, 955.46786293,
939.87125905, 924.93258982, 896.85182201,
870.90346447, 846.81187693, 824.34108781,
803.28900104, 783.48245048, 764.77297789,
747.03322866, 669.54798887, 605.03328304,
549.00852235, 499.21077611, 454.40299244,
413.83192296, 376.98072773, 343.45531017]
assert_array_almost_equal(fit.model_params, linear_fit_params)
assert_array_almost_equal(fit.predict(gtab), linear_fit_signal)
def test_leastsq_failing():
"""
Test for cases where leastsq fitting fails and the results from a linear
fit is returned.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit_single = ivim_model_trr.fit(noisy_single)
assert_greater_equal(len(w), 3)
u_warn = [l_w for l_w in w if issubclass(l_w.category, UserWarning)]
assert_greater_equal(len(u_warn), 3)
message = ["x0 obtained from linear fitting is not feasibile",
"x0 is unfeasible",
"Bounds are violated for leastsq fitting"]
assert_greater_equal(len([lw for lw in u_warn for m in message
if m in str(lw.message)]), 3)
# Test for the S0 and D values
assert_array_almost_equal(fit_single.S0_predicted, 4356.268901117833)
assert_array_almost_equal(fit_single.D, 6.936684e-04)
def test_leastsq_error():
"""
Test error handling of the `_leastsq` method works when unfeasible x0 is
passed. If an unfeasible x0 value is passed using which leastsq fails, the
x0 value is returned as it is.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit = ivim_model_trr._leastsq(data_single, [-1, -1, -1, -1])
assert_greater_equal(len(w), 1)
assert_(issubclass(w[-1].category, UserWarning))
assert_("" in str(w[-1].message))
assert_("x0 is unfeasible" in str(w[-1].message))
assert_array_almost_equal(fit, [-1, -1, -1, -1])
@needs_cvxpy
def test_perfusion_fraction_vp():
"""
Test if the `IvimFit` class returns the correct f
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.perfusion_fraction, f_VP,
decimal=2)
@needs_cvxpy
def test_D_star_vp():
"""
Test if the `IvimFit` class returns the correct D_star
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D_star, D_star_VP, decimal=4)
@needs_cvxpy
def test_D_vp():
"""
Test if the `IvimFit` class returns the correct D
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D, D_VP, decimal=4)
if __name__ == '__main__':
run_module_suite() | random_line_split | |
test_ivim.py | """
Testing the Intravoxel incoherent motion module
The values of the various parameters used in the tests are inspired by
the study of the IVIM model applied to MR images of the brain by
Federau, Christian, et al. [1].
References
----------
.. [1] Federau, Christian, et al. "Quantitative measurement
of brain perfusion with intravoxel incoherent motion
MR imaging." Radiology 265.3 (2012): 874-881.
"""
import warnings
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_raises, assert_array_less, run_module_suite,
assert_, assert_equal)
from dipy.testing import assert_greater_equal
import pytest
from dipy.reconst.ivim import ivim_prediction, IvimModel
from dipy.core.gradients import gradient_table, generate_bvecs
from dipy.sims.voxel import multi_tensor
from dipy.utils.optpkg import optional_package
cvxpy, have_cvxpy, _ = optional_package("cvxpy")
needs_cvxpy = pytest.mark.skipif(not have_cvxpy, reason="REQUIRES CVXPY")
def setup_module():
global gtab, ivim_fit_single, ivim_model_trr, data_single, params_trr, \
data_multi, ivim_params_trr, D_star, D, f, S0, gtab_with_multiple_b0, \
noisy_single, mevals, gtab_no_b0, ivim_fit_multi, ivim_model_VP, \
f_VP, D_star_VP, D_VP, params_VP
# Let us generate some data for testing.
bvals = np.array([0., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals, bvecs.T, b0_threshold=0)
S0, f, D_star, D = 1000.0, 0.132, 0.00885, 0.000921
# params for a single voxel
params_trr = np.array([S0, f, D_star, D])
mevals = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal = multi_tensor(gtab, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
data_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
data_multi[0, 0, 0] = data_multi[0, 1, 0] = data_multi[
1, 0, 0] = data_multi[1, 1, 0] = data_single
ivim_params_trr = np.zeros((2, 2, 1, 4))
ivim_params_trr[0, 0, 0] = ivim_params_trr[0, 1, 0] = params_trr
ivim_params_trr[1, 0, 0] = ivim_params_trr[1, 1, 0] = params_trr
ivim_model_trr = IvimModel(gtab, fit_method='trr')
ivim_model_one_stage = IvimModel(gtab, fit_method='trr')
ivim_fit_single = ivim_model_trr.fit(data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
ivim_model_one_stage.fit(data_single)
ivim_model_one_stage.fit(data_multi)
bvals_no_b0 = np.array([5., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
_ = generate_bvecs(N) # bvecs_no_b0
gtab_no_b0 = gradient_table(bvals_no_b0, bvecs.T, b0_threshold=0)
bvals_with_multiple_b0 = np.array([0., 0., 0., 0., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_multiple_b0.T,
b0_threshold=0)
noisy_single = np.array([4243.71728516, 4317.81298828, 4244.35693359,
4439.36816406, 4420.06201172, 4152.30078125,
4114.34912109, 4104.59375, 4151.61914062,
4003.58374023, 4013.68408203, 3906.39428711,
3909.06079102, 3495.27197266, 3402.57006836,
3163.10180664, 2896.04003906, 2663.7253418,
2614.87695312, 2316.55371094, 2267.7722168])
noisy_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
noisy_multi[0, 1, 0] = noisy_multi[
1, 0, 0] = noisy_multi[1, 1, 0] = noisy_single
noisy_multi[0, 0, 0] = data_single
ivim_model_VP = IvimModel(gtab, fit_method='VarPro')
f_VP, D_star_VP, D_VP = 0.13, 0.0088, 0.000921
# params for a single voxel
params_VP = np.array([f, D_star, D])
ivim_params_VP = np.zeros((2, 2, 1, 3))
ivim_params_VP[0, 0, 0] = ivim_params_VP[0, 1, 0] = params_VP
ivim_params_VP[1, 0, 0] = ivim_params_VP[1, 1, 0] = params_VP
def single_exponential(S0, D, bvals):
return S0 * np.exp(-bvals * D)
def test_single_voxel_fit():
"""
Test the implementation of the fitting for a single voxel.
Here, we will use the multi_tensor function to generate a
bi-exponential signal. The multi_tensor generates a multi
tensor signal and expects eigenvalues of each tensor in mevals.
Our basic test requires a scalar signal isotropic signal and
hence we set the same eigenvalue in all three directions to
generate the required signal.
The bvals, f, D_star and D are inspired from the paper by
Federau, Christian, et al. We use the function "generate_bvecs"
to simulate bvectors corresponding to the bvalues.
In the two stage fitting routine, initially we fit the signal
values for bvals less than the specified split_b using the
TensorModel and get an intial guess for f and D. Then, using
these parameters we fit the entire data for all bvalues.
"""
est_signal = ivim_prediction(ivim_fit_single.model_params, gtab)
assert_array_equal(est_signal.shape, data_single.shape)
assert_array_almost_equal(ivim_fit_single.model_params, params_trr)
assert_array_almost_equal(est_signal, data_single)
# Test predict function for single voxel
p = ivim_fit_single.predict(gtab)
assert_array_equal(p.shape, data_single.shape)
assert_array_almost_equal(p, data_single)
def test_multivoxel():
"""Test fitting with multivoxel data.
We generate a multivoxel signal to test the fitting for multivoxel data.
This is to ensure that the fitting routine takes care of signals packed as
1D, 2D or 3D arrays.
"""
ivim_fit_multi = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit_multi.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit_multi.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi)
def test_ivim_errors():
|
def test_mask():
"""
Test whether setting incorrect mask raises and error
"""
mask_correct = data_multi[..., 0] > 0.2
mask_not_correct = np.array([[False, True, False], [True, False]],
dtype=np.bool)
ivim_fit = ivim_model_trr.fit(data_multi, mask_correct)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(est_signal, data_multi)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_raises(ValueError, ivim_model_trr.fit, data_multi,
mask=mask_not_correct)
def test_with_higher_S0():
"""
Test whether fitting works for S0 > 1.
"""
# params for a single voxel
S0_2 = 1000.
params2 = np.array([S0_2, f, D_star, D])
mevals2 = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal2 = multi_tensor(gtab, mevals2, snr=None, S0=S0_2,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single2 = signal2[0]
ivim_fit = ivim_model_trr.fit(data_single2)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, data_single2.shape)
assert_array_almost_equal(est_signal, data_single2)
assert_array_almost_equal(ivim_fit.model_params, params2)
def test_b0_threshold_greater_than0():
"""
Added test case for default b0_threshold set to 50.
Checks if error is thrown correctly.
"""
bvals_b0t = np.array([50., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals_b0t)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals_b0t, bvecs.T)
with assert_raises(ValueError) as vae:
_ = IvimModel(gtab, fit_method='trr')
b0_s = "The IVIM model requires a measurement at b==0. As of "
assert b0_s in vae.exception
def test_bounds_x0():
"""
Test to check if setting bounds for signal where initial value is
higher than subsequent values works.
These values are from the IVIM dataset which can be obtained by using
the `read_ivim` function from dipy.data.fetcher. These are values from
the voxel [160, 98, 33] which can be obtained by :
.. code-block:: python
from dipy.data.fetcher import read_ivim
img, gtab = read_ivim()
data = load_nifti_data(img)
signal = data[160, 98, 33, :]
"""
x0_test = np.array([1., 0.13, 0.001, 0.0001])
test_signal = ivim_prediction(x0_test, gtab)
ivim_fit = ivim_model_trr.fit(test_signal)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, test_signal.shape)
def test_predict():
"""
Test the model prediction API.
The predict method is already used in previous tests for estimation of the
signal. But here, we will test is separately.
"""
assert_array_almost_equal(ivim_fit_single.predict(gtab),
data_single)
assert_array_almost_equal(ivim_model_trr.predict
(ivim_fit_single.model_params, gtab),
data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_almost_equal(ivim_fit_multi.predict(gtab),
data_multi)
def test_fit_object():
"""
Test the method of IvimFit class
"""
assert_raises(IndexError, ivim_fit_single.__getitem__, (-.1, 0, 0))
# Check if the S0 called is matching
assert_array_almost_equal(
ivim_fit_single.__getitem__(0).model_params, 1000.)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
# Should raise a TypeError if the arguments are not passed as tuple
assert_raises(TypeError, ivim_fit_multi.__getitem__, -.1, 0)
# Should return IndexError if invalid indices are passed
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0, 2))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (-100, 0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, [-100, 0])
assert_raises(IndexError, ivim_fit_multi.__getitem__, (1, 0, 0, 3, 4))
# Check if the get item returns the S0 value for voxel (1,0,0)
assert_array_almost_equal(
ivim_fit_multi.__getitem__((1, 0, 0)).model_params[0],
data_multi[1, 0, 0][0])
def test_shape():
"""
Test if `shape` in `IvimFit` class gives the correct output.
"""
assert_array_equal(ivim_fit_single.shape, ())
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_equal(ivim_fit_multi.shape, (2, 2, 1))
def test_multiple_b0():
# Generate a signal with multiple b0
# This gives an isotropic signal.
signal = multi_tensor(gtab_with_multiple_b0, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
ivim_model_multiple_b0 = IvimModel(gtab_with_multiple_b0, fit_method='trr')
ivim_model_multiple_b0.fit(data_single)
# Test if all signals are positive
def test_no_b0():
assert_raises(ValueError, IvimModel, gtab_no_b0)
def test_noisy_fit():
"""
Test fitting for noisy signals. This tests whether the threshold condition
applies correctly and returns the linear fitting parameters.
For older scipy versions, the returned value of `f` from a linear fit is
around 135 and D and D_star values are equal. Hence doing a test based on
Scipy version.
"""
model_one_stage = IvimModel(gtab, fit_method='trr')
with warnings.catch_warnings(record=True) as w:
fit_one_stage = model_one_stage.fit(noisy_single)
assert_equal(len(w), 3)
for l_w in w:
assert_(issubclass(l_w.category, UserWarning))
assert_("" in str(w[0].message))
assert_("x0 obtained from linear fitting is not feasibile" in
str(w[0].message))
assert_("x0 is unfeasible" in str(w[1].message))
assert_("Bounds are violated for leastsq fitting" in str(w[2].message))
assert_array_less(fit_one_stage.model_params, [10000., 0.3, .01, 0.001])
def test_S0():
"""
Test if the `IvimFit` class returns the correct S0
"""
assert_array_almost_equal(ivim_fit_single.S0_predicted, S0)
assert_array_almost_equal(ivim_fit_multi.S0_predicted,
ivim_params_trr[..., 0])
def test_perfusion_fraction():
"""
Test if the `IvimFit` class returns the correct f
"""
assert_array_almost_equal(ivim_fit_single.perfusion_fraction, f)
assert_array_almost_equal(
ivim_fit_multi.perfusion_fraction, ivim_params_trr[..., 1])
def test_D_star():
"""
Test if the `IvimFit` class returns the correct D_star
"""
assert_array_almost_equal(ivim_fit_single.D_star, D_star)
assert_array_almost_equal(ivim_fit_multi.D_star, ivim_params_trr[..., 2])
def test_D():
"""
Test if the `IvimFit` class returns the correct D
"""
assert_array_almost_equal(ivim_fit_single.D, D)
assert_array_almost_equal(ivim_fit_multi.D, ivim_params_trr[..., 3])
def test_estimate_linear_fit():
"""
Test the linear estimates considering a single exponential fit.
"""
data_single_exponential_D = single_exponential(S0, D, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D,
split_b=500.,
less_than=False),
(S0, D))
data_single_exponential_D_star = single_exponential(S0, D_star, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D_star,
split_b=100.,
less_than=True),
(S0, D_star))
def test_estimate_f_D_star():
"""
Test if the `estimate_f_D_star` returns the correct parameters after a
non-linear fit.
"""
params_f_D = f + 0.001, D + 0.0001
assert_array_almost_equal(ivim_model_trr.estimate_f_D_star(params_f_D,
data_single, S0,
D),
(f, D_star))
def test_fit_one_stage():
"""
Test to check the results for the one_stage linear fit.
"""
model = IvimModel(gtab, two_stage=False)
fit = model.fit(data_single)
linear_fit_params = [9.88834140e+02, 1.19707191e-01, 7.91176970e-03,
9.30095210e-04]
linear_fit_signal = [988.83414044, 971.77122546, 955.46786293,
939.87125905, 924.93258982, 896.85182201,
870.90346447, 846.81187693, 824.34108781,
803.28900104, 783.48245048, 764.77297789,
747.03322866, 669.54798887, 605.03328304,
549.00852235, 499.21077611, 454.40299244,
413.83192296, 376.98072773, 343.45531017]
assert_array_almost_equal(fit.model_params, linear_fit_params)
assert_array_almost_equal(fit.predict(gtab), linear_fit_signal)
def test_leastsq_failing():
"""
Test for cases where leastsq fitting fails and the results from a linear
fit is returned.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit_single = ivim_model_trr.fit(noisy_single)
assert_greater_equal(len(w), 3)
u_warn = [l_w for l_w in w if issubclass(l_w.category, UserWarning)]
assert_greater_equal(len(u_warn), 3)
message = ["x0 obtained from linear fitting is not feasibile",
"x0 is unfeasible",
"Bounds are violated for leastsq fitting"]
assert_greater_equal(len([lw for lw in u_warn for m in message
if m in str(lw.message)]), 3)
# Test for the S0 and D values
assert_array_almost_equal(fit_single.S0_predicted, 4356.268901117833)
assert_array_almost_equal(fit_single.D, 6.936684e-04)
def test_leastsq_error():
"""
Test error handling of the `_leastsq` method works when unfeasible x0 is
passed. If an unfeasible x0 value is passed using which leastsq fails, the
x0 value is returned as it is.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit = ivim_model_trr._leastsq(data_single, [-1, -1, -1, -1])
assert_greater_equal(len(w), 1)
assert_(issubclass(w[-1].category, UserWarning))
assert_("" in str(w[-1].message))
assert_("x0 is unfeasible" in str(w[-1].message))
assert_array_almost_equal(fit, [-1, -1, -1, -1])
@needs_cvxpy
def test_perfusion_fraction_vp():
"""
Test if the `IvimFit` class returns the correct f
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.perfusion_fraction, f_VP,
decimal=2)
@needs_cvxpy
def test_D_star_vp():
"""
Test if the `IvimFit` class returns the correct D_star
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D_star, D_star_VP, decimal=4)
@needs_cvxpy
def test_D_vp():
"""
Test if the `IvimFit` class returns the correct D
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D, D_VP, decimal=4)
if __name__ == '__main__':
run_module_suite()
| """
Test if errors raised in the module are working correctly.
Scipy introduced bounded least squares fitting in the version 0.17
and is not supported by the older versions. Initializing an IvimModel
with bounds for older Scipy versions should raise an error.
"""
ivim_model_trr = IvimModel(gtab, bounds=([0., 0., 0., 0.],
[np.inf, 1., 1., 1.]),
fit_method='trr')
ivim_fit = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi) | identifier_body |
test_ivim.py | """
Testing the Intravoxel incoherent motion module
The values of the various parameters used in the tests are inspired by
the study of the IVIM model applied to MR images of the brain by
Federau, Christian, et al. [1].
References
----------
.. [1] Federau, Christian, et al. "Quantitative measurement
of brain perfusion with intravoxel incoherent motion
MR imaging." Radiology 265.3 (2012): 874-881.
"""
import warnings
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_raises, assert_array_less, run_module_suite,
assert_, assert_equal)
from dipy.testing import assert_greater_equal
import pytest
from dipy.reconst.ivim import ivim_prediction, IvimModel
from dipy.core.gradients import gradient_table, generate_bvecs
from dipy.sims.voxel import multi_tensor
from dipy.utils.optpkg import optional_package
cvxpy, have_cvxpy, _ = optional_package("cvxpy")
needs_cvxpy = pytest.mark.skipif(not have_cvxpy, reason="REQUIRES CVXPY")
def setup_module():
global gtab, ivim_fit_single, ivim_model_trr, data_single, params_trr, \
data_multi, ivim_params_trr, D_star, D, f, S0, gtab_with_multiple_b0, \
noisy_single, mevals, gtab_no_b0, ivim_fit_multi, ivim_model_VP, \
f_VP, D_star_VP, D_VP, params_VP
# Let us generate some data for testing.
bvals = np.array([0., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals, bvecs.T, b0_threshold=0)
S0, f, D_star, D = 1000.0, 0.132, 0.00885, 0.000921
# params for a single voxel
params_trr = np.array([S0, f, D_star, D])
mevals = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal = multi_tensor(gtab, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
data_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
data_multi[0, 0, 0] = data_multi[0, 1, 0] = data_multi[
1, 0, 0] = data_multi[1, 1, 0] = data_single
ivim_params_trr = np.zeros((2, 2, 1, 4))
ivim_params_trr[0, 0, 0] = ivim_params_trr[0, 1, 0] = params_trr
ivim_params_trr[1, 0, 0] = ivim_params_trr[1, 1, 0] = params_trr
ivim_model_trr = IvimModel(gtab, fit_method='trr')
ivim_model_one_stage = IvimModel(gtab, fit_method='trr')
ivim_fit_single = ivim_model_trr.fit(data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
ivim_model_one_stage.fit(data_single)
ivim_model_one_stage.fit(data_multi)
bvals_no_b0 = np.array([5., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
_ = generate_bvecs(N) # bvecs_no_b0
gtab_no_b0 = gradient_table(bvals_no_b0, bvecs.T, b0_threshold=0)
bvals_with_multiple_b0 = np.array([0., 0., 0., 0., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300.,
400., 500., 600., 700., 800., 900.,
1000.])
bvecs_with_multiple_b0 = generate_bvecs(N)
gtab_with_multiple_b0 = gradient_table(bvals_with_multiple_b0,
bvecs_with_multiple_b0.T,
b0_threshold=0)
noisy_single = np.array([4243.71728516, 4317.81298828, 4244.35693359,
4439.36816406, 4420.06201172, 4152.30078125,
4114.34912109, 4104.59375, 4151.61914062,
4003.58374023, 4013.68408203, 3906.39428711,
3909.06079102, 3495.27197266, 3402.57006836,
3163.10180664, 2896.04003906, 2663.7253418,
2614.87695312, 2316.55371094, 2267.7722168])
noisy_multi = np.zeros((2, 2, 1, len(gtab.bvals)))
noisy_multi[0, 1, 0] = noisy_multi[
1, 0, 0] = noisy_multi[1, 1, 0] = noisy_single
noisy_multi[0, 0, 0] = data_single
ivim_model_VP = IvimModel(gtab, fit_method='VarPro')
f_VP, D_star_VP, D_VP = 0.13, 0.0088, 0.000921
# params for a single voxel
params_VP = np.array([f, D_star, D])
ivim_params_VP = np.zeros((2, 2, 1, 3))
ivim_params_VP[0, 0, 0] = ivim_params_VP[0, 1, 0] = params_VP
ivim_params_VP[1, 0, 0] = ivim_params_VP[1, 1, 0] = params_VP
def single_exponential(S0, D, bvals):
return S0 * np.exp(-bvals * D)
def | ():
"""
Test the implementation of the fitting for a single voxel.
Here, we will use the multi_tensor function to generate a
bi-exponential signal. The multi_tensor generates a multi
tensor signal and expects eigenvalues of each tensor in mevals.
Our basic test requires a scalar signal isotropic signal and
hence we set the same eigenvalue in all three directions to
generate the required signal.
The bvals, f, D_star and D are inspired from the paper by
Federau, Christian, et al. We use the function "generate_bvecs"
to simulate bvectors corresponding to the bvalues.
In the two stage fitting routine, initially we fit the signal
values for bvals less than the specified split_b using the
TensorModel and get an intial guess for f and D. Then, using
these parameters we fit the entire data for all bvalues.
"""
est_signal = ivim_prediction(ivim_fit_single.model_params, gtab)
assert_array_equal(est_signal.shape, data_single.shape)
assert_array_almost_equal(ivim_fit_single.model_params, params_trr)
assert_array_almost_equal(est_signal, data_single)
# Test predict function for single voxel
p = ivim_fit_single.predict(gtab)
assert_array_equal(p.shape, data_single.shape)
assert_array_almost_equal(p, data_single)
def test_multivoxel():
"""Test fitting with multivoxel data.
We generate a multivoxel signal to test the fitting for multivoxel data.
This is to ensure that the fitting routine takes care of signals packed as
1D, 2D or 3D arrays.
"""
ivim_fit_multi = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit_multi.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit_multi.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi)
def test_ivim_errors():
"""
Test if errors raised in the module are working correctly.
Scipy introduced bounded least squares fitting in the version 0.17
and is not supported by the older versions. Initializing an IvimModel
with bounds for older Scipy versions should raise an error.
"""
ivim_model_trr = IvimModel(gtab, bounds=([0., 0., 0., 0.],
[np.inf, 1., 1., 1.]),
fit_method='trr')
ivim_fit = ivim_model_trr.fit(data_multi)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_array_almost_equal(est_signal, data_multi)
def test_mask():
"""
Test whether setting incorrect mask raises and error
"""
mask_correct = data_multi[..., 0] > 0.2
mask_not_correct = np.array([[False, True, False], [True, False]],
dtype=np.bool)
ivim_fit = ivim_model_trr.fit(data_multi, mask_correct)
est_signal = ivim_fit.predict(gtab, S0=1.)
assert_array_equal(est_signal.shape, data_multi.shape)
assert_array_almost_equal(est_signal, data_multi)
assert_array_almost_equal(ivim_fit.model_params, ivim_params_trr)
assert_raises(ValueError, ivim_model_trr.fit, data_multi,
mask=mask_not_correct)
def test_with_higher_S0():
"""
Test whether fitting works for S0 > 1.
"""
# params for a single voxel
S0_2 = 1000.
params2 = np.array([S0_2, f, D_star, D])
mevals2 = np.array(([D_star, D_star, D_star], [D, D, D]))
# This gives an isotropic signal.
signal2 = multi_tensor(gtab, mevals2, snr=None, S0=S0_2,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single2 = signal2[0]
ivim_fit = ivim_model_trr.fit(data_single2)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, data_single2.shape)
assert_array_almost_equal(est_signal, data_single2)
assert_array_almost_equal(ivim_fit.model_params, params2)
def test_b0_threshold_greater_than0():
"""
Added test case for default b0_threshold set to 50.
Checks if error is thrown correctly.
"""
bvals_b0t = np.array([50., 10., 20., 30., 40., 60., 80., 100.,
120., 140., 160., 180., 200., 300., 400.,
500., 600., 700., 800., 900., 1000.])
N = len(bvals_b0t)
bvecs = generate_bvecs(N)
gtab = gradient_table(bvals_b0t, bvecs.T)
with assert_raises(ValueError) as vae:
_ = IvimModel(gtab, fit_method='trr')
b0_s = "The IVIM model requires a measurement at b==0. As of "
assert b0_s in vae.exception
def test_bounds_x0():
"""
Test to check if setting bounds for signal where initial value is
higher than subsequent values works.
These values are from the IVIM dataset which can be obtained by using
the `read_ivim` function from dipy.data.fetcher. These are values from
the voxel [160, 98, 33] which can be obtained by :
.. code-block:: python
from dipy.data.fetcher import read_ivim
img, gtab = read_ivim()
data = load_nifti_data(img)
signal = data[160, 98, 33, :]
"""
x0_test = np.array([1., 0.13, 0.001, 0.0001])
test_signal = ivim_prediction(x0_test, gtab)
ivim_fit = ivim_model_trr.fit(test_signal)
est_signal = ivim_fit.predict(gtab)
assert_array_equal(est_signal.shape, test_signal.shape)
def test_predict():
"""
Test the model prediction API.
The predict method is already used in previous tests for estimation of the
signal. But here, we will test is separately.
"""
assert_array_almost_equal(ivim_fit_single.predict(gtab),
data_single)
assert_array_almost_equal(ivim_model_trr.predict
(ivim_fit_single.model_params, gtab),
data_single)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_almost_equal(ivim_fit_multi.predict(gtab),
data_multi)
def test_fit_object():
"""
Test the method of IvimFit class
"""
assert_raises(IndexError, ivim_fit_single.__getitem__, (-.1, 0, 0))
# Check if the S0 called is matching
assert_array_almost_equal(
ivim_fit_single.__getitem__(0).model_params, 1000.)
ivim_fit_multi = ivim_model_trr.fit(data_multi)
# Should raise a TypeError if the arguments are not passed as tuple
assert_raises(TypeError, ivim_fit_multi.__getitem__, -.1, 0)
# Should return IndexError if invalid indices are passed
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (100, -0, 2))
assert_raises(IndexError, ivim_fit_multi.__getitem__, (-100, 0))
assert_raises(IndexError, ivim_fit_multi.__getitem__, [-100, 0])
assert_raises(IndexError, ivim_fit_multi.__getitem__, (1, 0, 0, 3, 4))
# Check if the get item returns the S0 value for voxel (1,0,0)
assert_array_almost_equal(
ivim_fit_multi.__getitem__((1, 0, 0)).model_params[0],
data_multi[1, 0, 0][0])
def test_shape():
"""
Test if `shape` in `IvimFit` class gives the correct output.
"""
assert_array_equal(ivim_fit_single.shape, ())
ivim_fit_multi = ivim_model_trr.fit(data_multi)
assert_array_equal(ivim_fit_multi.shape, (2, 2, 1))
def test_multiple_b0():
# Generate a signal with multiple b0
# This gives an isotropic signal.
signal = multi_tensor(gtab_with_multiple_b0, mevals, snr=None, S0=S0,
fractions=[f * 100, 100 * (1 - f)])
# Single voxel data
data_single = signal[0]
ivim_model_multiple_b0 = IvimModel(gtab_with_multiple_b0, fit_method='trr')
ivim_model_multiple_b0.fit(data_single)
# Test if all signals are positive
def test_no_b0():
assert_raises(ValueError, IvimModel, gtab_no_b0)
def test_noisy_fit():
"""
Test fitting for noisy signals. This tests whether the threshold condition
applies correctly and returns the linear fitting parameters.
For older scipy versions, the returned value of `f` from a linear fit is
around 135 and D and D_star values are equal. Hence doing a test based on
Scipy version.
"""
model_one_stage = IvimModel(gtab, fit_method='trr')
with warnings.catch_warnings(record=True) as w:
fit_one_stage = model_one_stage.fit(noisy_single)
assert_equal(len(w), 3)
for l_w in w:
assert_(issubclass(l_w.category, UserWarning))
assert_("" in str(w[0].message))
assert_("x0 obtained from linear fitting is not feasibile" in
str(w[0].message))
assert_("x0 is unfeasible" in str(w[1].message))
assert_("Bounds are violated for leastsq fitting" in str(w[2].message))
assert_array_less(fit_one_stage.model_params, [10000., 0.3, .01, 0.001])
def test_S0():
"""
Test if the `IvimFit` class returns the correct S0
"""
assert_array_almost_equal(ivim_fit_single.S0_predicted, S0)
assert_array_almost_equal(ivim_fit_multi.S0_predicted,
ivim_params_trr[..., 0])
def test_perfusion_fraction():
"""
Test if the `IvimFit` class returns the correct f
"""
assert_array_almost_equal(ivim_fit_single.perfusion_fraction, f)
assert_array_almost_equal(
ivim_fit_multi.perfusion_fraction, ivim_params_trr[..., 1])
def test_D_star():
"""
Test if the `IvimFit` class returns the correct D_star
"""
assert_array_almost_equal(ivim_fit_single.D_star, D_star)
assert_array_almost_equal(ivim_fit_multi.D_star, ivim_params_trr[..., 2])
def test_D():
"""
Test if the `IvimFit` class returns the correct D
"""
assert_array_almost_equal(ivim_fit_single.D, D)
assert_array_almost_equal(ivim_fit_multi.D, ivim_params_trr[..., 3])
def test_estimate_linear_fit():
"""
Test the linear estimates considering a single exponential fit.
"""
data_single_exponential_D = single_exponential(S0, D, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D,
split_b=500.,
less_than=False),
(S0, D))
data_single_exponential_D_star = single_exponential(S0, D_star, gtab.bvals)
assert_array_almost_equal(ivim_model_trr.estimate_linear_fit(
data_single_exponential_D_star,
split_b=100.,
less_than=True),
(S0, D_star))
def test_estimate_f_D_star():
"""
Test if the `estimate_f_D_star` returns the correct parameters after a
non-linear fit.
"""
params_f_D = f + 0.001, D + 0.0001
assert_array_almost_equal(ivim_model_trr.estimate_f_D_star(params_f_D,
data_single, S0,
D),
(f, D_star))
def test_fit_one_stage():
"""
Test to check the results for the one_stage linear fit.
"""
model = IvimModel(gtab, two_stage=False)
fit = model.fit(data_single)
linear_fit_params = [9.88834140e+02, 1.19707191e-01, 7.91176970e-03,
9.30095210e-04]
linear_fit_signal = [988.83414044, 971.77122546, 955.46786293,
939.87125905, 924.93258982, 896.85182201,
870.90346447, 846.81187693, 824.34108781,
803.28900104, 783.48245048, 764.77297789,
747.03322866, 669.54798887, 605.03328304,
549.00852235, 499.21077611, 454.40299244,
413.83192296, 376.98072773, 343.45531017]
assert_array_almost_equal(fit.model_params, linear_fit_params)
assert_array_almost_equal(fit.predict(gtab), linear_fit_signal)
def test_leastsq_failing():
"""
Test for cases where leastsq fitting fails and the results from a linear
fit is returned.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit_single = ivim_model_trr.fit(noisy_single)
assert_greater_equal(len(w), 3)
u_warn = [l_w for l_w in w if issubclass(l_w.category, UserWarning)]
assert_greater_equal(len(u_warn), 3)
message = ["x0 obtained from linear fitting is not feasibile",
"x0 is unfeasible",
"Bounds are violated for leastsq fitting"]
assert_greater_equal(len([lw for lw in u_warn for m in message
if m in str(lw.message)]), 3)
# Test for the S0 and D values
assert_array_almost_equal(fit_single.S0_predicted, 4356.268901117833)
assert_array_almost_equal(fit_single.D, 6.936684e-04)
def test_leastsq_error():
"""
Test error handling of the `_leastsq` method works when unfeasible x0 is
passed. If an unfeasible x0 value is passed using which leastsq fails, the
x0 value is returned as it is.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", category=UserWarning)
fit = ivim_model_trr._leastsq(data_single, [-1, -1, -1, -1])
assert_greater_equal(len(w), 1)
assert_(issubclass(w[-1].category, UserWarning))
assert_("" in str(w[-1].message))
assert_("x0 is unfeasible" in str(w[-1].message))
assert_array_almost_equal(fit, [-1, -1, -1, -1])
@needs_cvxpy
def test_perfusion_fraction_vp():
"""
Test if the `IvimFit` class returns the correct f
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.perfusion_fraction, f_VP,
decimal=2)
@needs_cvxpy
def test_D_star_vp():
"""
Test if the `IvimFit` class returns the correct D_star
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D_star, D_star_VP, decimal=4)
@needs_cvxpy
def test_D_vp():
"""
Test if the `IvimFit` class returns the correct D
"""
ivim_fit_VP = ivim_model_VP.fit(data_single)
assert_array_almost_equal(ivim_fit_VP.D, D_VP, decimal=4)
if __name__ == '__main__':
run_module_suite()
| test_single_voxel_fit | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describing the error. This message comes from fleet directly whenever fleet
/// provides a message.
pub message: Option<String>,
}
impl FleetError {
/// Constructs a new `FleetError` from a `hyper::error::HttpError`. Not intended for public
/// use.
pub fn from_hyper_error(error: &HttpError) -> FleetError {
FleetError {
code: None,
message: Some(error.description().to_string()),
}
}
/// Constructs a new `FleetError` from a `hyper::client::Response`. Not intended for public
/// use.
pub fn from_hyper_response(response: &mut Response) -> FleetError {
FleetError {
code: Some(response.status.to_u16()),
message: extract_message(response),
}
}
}
impl fmt::Display for FleetError {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
}
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(response) {
Ok(json) => {
match json.find_path(&["error", "message"]) {
Some(message_json) => match message_json.as_string() {
Some(message) => {
if message.len() == 0 {
Some("Error in JSON response from Fleet was empty".to_string())
} else {
Some(message.to_string())
}
},
None => Some("Error in JSON response from Fleet was empty".to_string()),
},
None => Some("Error parsing JSON response from Fleet".to_string()),
}
},
Err(error) => Some(error.description().to_string()),
}
}
| fmt | identifier_name |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describing the error. This message comes from fleet directly whenever fleet
/// provides a message.
pub message: Option<String>,
}
impl FleetError {
/// Constructs a new `FleetError` from a `hyper::error::HttpError`. Not intended for public
/// use.
pub fn from_hyper_error(error: &HttpError) -> FleetError {
FleetError {
code: None,
message: Some(error.description().to_string()),
}
}
/// Constructs a new `FleetError` from a `hyper::client::Response`. Not intended for public
/// use.
pub fn from_hyper_response(response: &mut Response) -> FleetError {
FleetError {
code: Some(response.status.to_u16()),
message: extract_message(response),
}
}
}
impl fmt::Display for FleetError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(response) {
Ok(json) => {
match json.find_path(&["error", "message"]) {
Some(message_json) => match message_json.as_string() {
Some(message) => {
if message.len() == 0 {
Some("Error in JSON response from Fleet was empty".to_string())
} else {
Some(message.to_string())
}
},
None => Some("Error in JSON response from Fleet was empty".to_string()),
},
None => Some("Error parsing JSON response from Fleet".to_string()),
}
},
Err(error) => Some(error.description().to_string()),
}
}
| {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
} | identifier_body |
error.rs | use std::error::Error;
use std::fmt;
use hyper::client::Response;
use hyper::error::HttpError;
use rustc_serialize::json::Json;
/// An error returned by `Client` when an API call fails.
pub struct FleetError {
/// An HTTP status code returned by the fleet API.
pub code: Option<u16>,
/// A message describing the error. This message comes from fleet directly whenever fleet
/// provides a message.
pub message: Option<String>,
}
impl FleetError {
/// Constructs a new `FleetError` from a `hyper::error::HttpError`. Not intended for public
/// use.
pub fn from_hyper_error(error: &HttpError) -> FleetError {
FleetError { | }
/// Constructs a new `FleetError` from a `hyper::client::Response`. Not intended for public
/// use.
pub fn from_hyper_response(response: &mut Response) -> FleetError {
FleetError {
code: Some(response.status.to_u16()),
message: extract_message(response),
}
}
}
impl fmt::Display for FleetError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: {}",
self.code.unwrap_or(0),
self.message.clone().unwrap_or("Unknown error".to_string()),
)
}
}
fn extract_message(response: &mut Response) -> Option<String> {
match Json::from_reader(response) {
Ok(json) => {
match json.find_path(&["error", "message"]) {
Some(message_json) => match message_json.as_string() {
Some(message) => {
if message.len() == 0 {
Some("Error in JSON response from Fleet was empty".to_string())
} else {
Some(message.to_string())
}
},
None => Some("Error in JSON response from Fleet was empty".to_string()),
},
None => Some("Error parsing JSON response from Fleet".to_string()),
}
},
Err(error) => Some(error.description().to_string()),
}
} | code: None,
message: Some(error.description().to_string()),
} | random_line_split |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_value(initial_value)
def set_index (self, initial_index):
if initial_index is None:
self.index = len (self.items) / 2
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
"""
Set index to the smallest value such that items[index] >= v.
If there is no such item, set index to the maximum value.
"""
self.set_index(0) # side effect!
cv = self.current()
more = True
while cv < v and more:
cv, more = next(self) # side effect!
def __next__ (self):
new_index = self.index + 1
if new_index < len (self.items):
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def prev (self):
new_index = self.index - 1
if new_index >= 0:
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def current (self):
return self.items[self.index]
def | (self):
return self.items[:] # copy of items
| get_seq | identifier_name |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
|
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_value(initial_value)
def set_index (self, initial_index):
if initial_index is None:
self.index = len (self.items) / 2
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
"""
Set index to the smallest value such that items[index] >= v.
If there is no such item, set index to the maximum value.
"""
self.set_index(0) # side effect!
cv = self.current()
more = True
while cv < v and more:
cv, more = next(self) # side effect!
def __next__ (self):
new_index = self.index + 1
if new_index < len (self.items):
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def prev (self):
new_index = self.index - 1
if new_index >= 0:
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def current (self):
return self.items[self.index]
def get_seq (self):
return self.items[:] # copy of items | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals | random_line_split |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
|
def set_index (self, initial_index):
if initial_index is None:
self.index = len (self.items) / 2
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
"""
Set index to the smallest value such that items[index] >= v.
If there is no such item, set index to the maximum value.
"""
self.set_index(0) # side effect!
cv = self.current()
more = True
while cv < v and more:
cv, more = next(self) # side effect!
def __next__ (self):
new_index = self.index + 1
if new_index < len (self.items):
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def prev (self):
new_index = self.index - 1
if new_index >= 0:
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def current (self):
return self.items[self.index]
def get_seq (self):
return self.items[:] # copy of items
| assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_value(initial_value) | identifier_body |
seq_with_cursor.py | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_value(initial_value)
def set_index (self, initial_index):
if initial_index is None:
|
elif initial_index >= 0 and initial_index < len (self.items):
self.index = initial_index
else:
raise ValueError
def set_index_by_value(self, v):
"""
Set index to the smallest value such that items[index] >= v.
If there is no such item, set index to the maximum value.
"""
self.set_index(0) # side effect!
cv = self.current()
more = True
while cv < v and more:
cv, more = next(self) # side effect!
def __next__ (self):
new_index = self.index + 1
if new_index < len (self.items):
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def prev (self):
new_index = self.index - 1
if new_index >= 0:
self.index = new_index
return self.items[new_index], True
else:
return self.items[self.index], False
def current (self):
return self.items[self.index]
def get_seq (self):
return self.items[:] # copy of items
| self.index = len (self.items) / 2 | conditional_block |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equal %d" % (len(actual), len(expected))
assert sorted(actual, key=keyfunc) == sorted(expected, key=keyfunc)
def keyfunc(tpl):
left, right = tpl
return edist(left, right)
def test_empty_mst_list():
""" the (E)MST solution to an empty list is an empty list """
assert solve([]) == [], __doc__
def test_non_list():
""" this function should reject non-lists (invalid inputs) by raising
a TypeError """
with pytest.raises(TypeError):
solve(True)
def test_list_of_one():
""" the (E)MST solution to a list of one is an empty list """ | """ the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1), Point(1, 3)
actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def test_triangle():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Point(6, 0)]
actual = solve(graph)
compare_solutions(actual, [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))])
for result in actual:
left, right = result
if left == Point(0, 0) or left == Point(6, 0):
assert right == Point(3, 0), \
"expected right (%s) to == %s (left is %s)" % (right, Point(3, 0), left)
else:
assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0)) | assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two(): | random_line_split |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equal %d" % (len(actual), len(expected))
assert sorted(actual, key=keyfunc) == sorted(expected, key=keyfunc)
def keyfunc(tpl):
left, right = tpl
return edist(left, right)
def test_empty_mst_list():
""" the (E)MST solution to an empty list is an empty list """
assert solve([]) == [], __doc__
def test_non_list():
""" this function should reject non-lists (invalid inputs) by raising
a TypeError """
with pytest.raises(TypeError):
solve(True)
def test_list_of_one():
""" the (E)MST solution to a list of one is an empty list """
assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two():
""" the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1), Point(1, 3)
actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def | ():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Point(6, 0)]
actual = solve(graph)
compare_solutions(actual, [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))])
for result in actual:
left, right = result
if left == Point(0, 0) or left == Point(6, 0):
assert right == Point(3, 0), \
"expected right (%s) to == %s (left is %s)" % (right, Point(3, 0), left)
else:
assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0))
| test_triangle | identifier_name |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equal %d" % (len(actual), len(expected))
assert sorted(actual, key=keyfunc) == sorted(expected, key=keyfunc)
def keyfunc(tpl):
left, right = tpl
return edist(left, right)
def test_empty_mst_list():
""" the (E)MST solution to an empty list is an empty list """
assert solve([]) == [], __doc__
def test_non_list():
|
def test_list_of_one():
""" the (E)MST solution to a list of one is an empty list """
assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two():
""" the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1), Point(1, 3)
actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def test_triangle():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Point(6, 0)]
actual = solve(graph)
compare_solutions(actual, [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))])
for result in actual:
left, right = result
if left == Point(0, 0) or left == Point(6, 0):
assert right == Point(3, 0), \
"expected right (%s) to == %s (left is %s)" % (right, Point(3, 0), left)
else:
assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0))
| """ this function should reject non-lists (invalid inputs) by raising
a TypeError """
with pytest.raises(TypeError):
solve(True) | identifier_body |
test_euclidean_mst.py | """ Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equal %d" % (len(actual), len(expected))
assert sorted(actual, key=keyfunc) == sorted(expected, key=keyfunc)
def keyfunc(tpl):
left, right = tpl
return edist(left, right)
def test_empty_mst_list():
""" the (E)MST solution to an empty list is an empty list """
assert solve([]) == [], __doc__
def test_non_list():
""" this function should reject non-lists (invalid inputs) by raising
a TypeError """
with pytest.raises(TypeError):
solve(True)
def test_list_of_one():
""" the (E)MST solution to a list of one is an empty list """
assert solve([Point(0, 0)]) == [], __doc__
def test_list_of_two():
""" the (E)MST solution to a list of two points (i.e. [a, b]) is a list
containing a tuple of points (i.e. [(a, b)]) """
one, two = Point(3, 1), Point(1, 3)
actual = solve([one, two])
compare_solutions(actual, [(one, two)])
def test_triangle():
""" Given a list of points L:
L = [Point(0, 0), Point(3, 0), Point(0, 6)]
The solution is:
[(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))]
"""
graph = [Point(0, 0), Point(3, 0), Point(6, 0)]
actual = solve(graph)
compare_solutions(actual, [(Point(0, 0), Point(3, 0)), (Point(3, 0), Point(6, 0))])
for result in actual:
left, right = result
if left == Point(0, 0) or left == Point(6, 0):
assert right == Point(3, 0), \
"expected right (%s) to == %s (left is %s)" % (right, Point(3, 0), left)
else:
| assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0)) | conditional_block | |
calc.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import numpy
def run(self, Input):
number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"] | self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | random_line_split | |
calc.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import numpy
def run(self, Input):
number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"]
self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
| self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | conditional_block | |
calc.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import numpy
def | (self, Input):
number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"]
self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform)
| run | identifier_name |
calc.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import numpy
def run(self, Input):
| number_of_steps = 16
self.time = numpy.zeros(number_of_steps)
uniform = Input["uniform"]
self.out = numpy.zeros(number_of_steps)
for i in range(len(self.time)):
self.time[i] = 0.25*i
time = self.time[i]
self.out[i] = math.sin(time+uniform) | identifier_body | |
Modal.d.ts | import * as React from 'react';
import { Sizes, TransitionCallbacks } from 'react-bootstrap';
import * as ModalBody from './ModalBody';
import * as ModalHeader from './ModalHeader';
import * as ModalTitle from './ModalTitle';
import * as ModalDialog from './ModalDialog';
import * as ModalFooter from './ModalFooter';
declare namespace Modal {
interface ModalProps extends TransitionCallbacks, React.HTMLProps<Modal> {
// Required
onHide: Function;
// Optional
animation?: boolean;
autoFocus?: boolean;
backdrop?: boolean | string;
backdropClassName?: string;
backdropStyle?: any;
backdropTransitionTimeout?: number;
bsSize?: Sizes;
container?: any; // TODO: Add more specific type
containerClassName?: string;
dialogClassName?: string;
dialogComponent?: any; // TODO: Add more specific type
dialogTransitionTimeout?: number;
enforceFocus?: boolean;
keyboard?: boolean;
onBackdropClick?: (node: HTMLElement) => any;
onEscapeKeyUp?: (node: HTMLElement) => any;
onShow?: (node: HTMLElement) => any;
show?: boolean;
transition?: React.ReactElement<any>;
}
}
declare class Modal extends React.Component<Modal.ModalProps> {
static Body: typeof ModalBody;
static Header: typeof ModalHeader;
static Title: typeof ModalTitle; | }
export = Modal; | static Footer: typeof ModalFooter;
static Dialog: typeof ModalDialog; | random_line_split |
Modal.d.ts | import * as React from 'react';
import { Sizes, TransitionCallbacks } from 'react-bootstrap';
import * as ModalBody from './ModalBody';
import * as ModalHeader from './ModalHeader';
import * as ModalTitle from './ModalTitle';
import * as ModalDialog from './ModalDialog';
import * as ModalFooter from './ModalFooter';
declare namespace Modal {
interface ModalProps extends TransitionCallbacks, React.HTMLProps<Modal> {
// Required
onHide: Function;
// Optional
animation?: boolean;
autoFocus?: boolean;
backdrop?: boolean | string;
backdropClassName?: string;
backdropStyle?: any;
backdropTransitionTimeout?: number;
bsSize?: Sizes;
container?: any; // TODO: Add more specific type
containerClassName?: string;
dialogClassName?: string;
dialogComponent?: any; // TODO: Add more specific type
dialogTransitionTimeout?: number;
enforceFocus?: boolean;
keyboard?: boolean;
onBackdropClick?: (node: HTMLElement) => any;
onEscapeKeyUp?: (node: HTMLElement) => any;
onShow?: (node: HTMLElement) => any;
show?: boolean;
transition?: React.ReactElement<any>;
}
}
declare class | extends React.Component<Modal.ModalProps> {
static Body: typeof ModalBody;
static Header: typeof ModalHeader;
static Title: typeof ModalTitle;
static Footer: typeof ModalFooter;
static Dialog: typeof ModalDialog;
}
export = Modal;
| Modal | identifier_name |
main.js | var knwl = new Knwl();
var demo = {};
demo.resultBoxes = {};
demo.input = null;
demo.resultsDiv = null;
demo.setup = function() {
var resultsDiv = document.getElementById('results');
demo.resultsDiv = resultsDiv;
for (var el in demo.resultBoxes) {
if (demo.resultsDiv.contains(demo.resultBoxes[el])) {
demo.resultsDiv.removeChild(demo.resultBoxes[el]);
}
}
demo.resultBoxes = {};
demo.input = document.getElementById('input');
for (var key in knwl.plugins) {
var resultBox = document.createElement('div');
resultBox.setAttribute('class', 'resultBox');
resultBox.innerHTML += '<p class = "title">' + key + '</p>';
demo.resultBoxes[key] = resultBox;
resultsDiv.appendChild(resultBox);
}
};
demo.startParse = function() {
demo.parse();
};
demo.parse = function() {
demo.setup();
knwl.init(demo.input.value);
for (var parser in knwl.plugins) {
var data = knwl.get(parser);
for (var ii = 0; ii < data.length; ii++) {
var resultDiv = document.createElement('div');
resultDiv.setAttribute('class', 'result');
for (var key in data[ii]) {
if (key !== 'found') { | if (key !== 'preview') {
p.innerHTML = key + ': <span class = "val">' + data[ii][key] + '</span>';
} else {
p.innerHTML = data[ii][key];
p.setAttribute('class', 'preview');
}
resultDiv.appendChild(p);
}
}
demo.resultBoxes[parser].appendChild(resultDiv);
}
if (data.length === 0) {
demo.resultsDiv.removeChild(demo.resultBoxes[parser]);
}
}
};
window.onload = function() {
demo.setup();
if (localStorage.getItem('knwlDemoText') !== '')
demo.input.value = localStorage.getItem('knwlDemoText');
demo.input.onkeydown = function() {
setTimeout(function() {
localStorage.setItem('knwlDemoText', demo.input.value);
},10);
};
};
console.info('This is a demo of knwl.js using a few of the plugins available by default. Website: http://loadfive.com/os/knwl');
console.info('Feel free to use this demo to test your own Knwl.js parser plugins. Just add them to the header of index.html, and the demo will recognize them automatically.'); | var p = document.createElement('p'); | random_line_split |
main.js | var knwl = new Knwl();
var demo = {};
demo.resultBoxes = {};
demo.input = null;
demo.resultsDiv = null;
demo.setup = function() {
var resultsDiv = document.getElementById('results');
demo.resultsDiv = resultsDiv;
for (var el in demo.resultBoxes) {
if (demo.resultsDiv.contains(demo.resultBoxes[el])) {
demo.resultsDiv.removeChild(demo.resultBoxes[el]);
}
}
demo.resultBoxes = {};
demo.input = document.getElementById('input');
for (var key in knwl.plugins) {
var resultBox = document.createElement('div');
resultBox.setAttribute('class', 'resultBox');
resultBox.innerHTML += '<p class = "title">' + key + '</p>';
demo.resultBoxes[key] = resultBox;
resultsDiv.appendChild(resultBox);
}
};
demo.startParse = function() {
demo.parse();
};
demo.parse = function() {
demo.setup();
knwl.init(demo.input.value);
for (var parser in knwl.plugins) {
var data = knwl.get(parser);
for (var ii = 0; ii < data.length; ii++) {
var resultDiv = document.createElement('div');
resultDiv.setAttribute('class', 'result');
for (var key in data[ii]) {
if (key !== 'found') {
var p = document.createElement('p');
if (key !== 'preview') {
p.innerHTML = key + ': <span class = "val">' + data[ii][key] + '</span>';
} else |
resultDiv.appendChild(p);
}
}
demo.resultBoxes[parser].appendChild(resultDiv);
}
if (data.length === 0) {
demo.resultsDiv.removeChild(demo.resultBoxes[parser]);
}
}
};
window.onload = function() {
demo.setup();
if (localStorage.getItem('knwlDemoText') !== '')
demo.input.value = localStorage.getItem('knwlDemoText');
demo.input.onkeydown = function() {
setTimeout(function() {
localStorage.setItem('knwlDemoText', demo.input.value);
},10);
};
};
console.info('This is a demo of knwl.js using a few of the plugins available by default. Website: http://loadfive.com/os/knwl');
console.info('Feel free to use this demo to test your own Knwl.js parser plugins. Just add them to the header of index.html, and the demo will recognize them automatically.');
| {
p.innerHTML = data[ii][key];
p.setAttribute('class', 'preview');
} | conditional_block |
workbench.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/browser/style';
import { localize } from 'vs/nls';
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { RunOnceScheduler, runWhenIdle, timeout } from 'vs/base/common/async';
import { getZoomLevel, isFirefox, isSafari, isChrome, getPixelRatio } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { Registry } from 'vs/platform/registry/common/platform';
import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IEditorInputFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions';
import { Position, Parts, IWorkbenchLayoutService, positionToString } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService, WillSaveStateReason, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
import { NotificationsTelemetry } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class Workbench extends Layout {
private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>());
readonly onBeforeShutdown = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
readonly onWillShutdown = this._onWillShutdown.event;
private readonly _onDidShutdown = this._register(new Emitter<void>());
readonly onDidShutdown = this._onDidShutdown.event;
constructor(
parent: HTMLElement,
private readonly serviceCollection: ServiceCollection,
logService: ILogService
) {
super(parent);
// Perf: measure workbench startup time
mark('code/willStartWorkbench');
this.registerErrorHandler(logService);
}
private registerErrorHandler(logService: ILogService): void {
// Listen on unhandled rejection events
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
onUnexpectedError(event.reason);
// Prevent the printing of this event to the console
event.preventDefault();
});
// Install handler for unexpected errors
setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService));
// Inform user about loading issues from the loader
interface AnnotatedLoadingError extends Error {
phase: 'loading';
moduleId: string;
neededBy: string[];
}
interface AnnotatedFactoryError extends Error {
phase: 'factory';
moduleId: string;
}
interface AnnotatedValidationError extends Error {
phase: 'configuration';
}
type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError;
(<any>window).require.config({
onError: (err: AnnotatedError) => {
if (err.phase === 'loading') {
onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
}
console.error(err);
}
});
}
private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 };
private handleUnexpectedError(error: unknown, logService: ILogService): void {
const message = toErrorMessage(error, true);
if (!message) {
return;
}
const now = Date.now();
if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) {
return; // Return if error message identical to previous and shorter than 1 second
}
this.previousUnexpectedError.time = now;
this.previousUnexpectedError.message = message;
// Log it
logService.error(message);
}
startup(): IInstantiationService {
try {
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
// Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigurationService);
const hostService = accessor.get(IHostService);
// Layout
this.initLayout(accessor);
// Registries
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
// Context Keys
this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
// Register Listeners
this.registerListeners(lifecycleService, storageService, configurationService, hostService);
// Render Workbench
this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
// Workbench Layout
this.createWorkbenchLayout();
// Layout
this.layout();
// Restore
this.restore(lifecycleService);
});
return instantiationService;
} catch (error) {
onUnexpectedError(error);
throw error; // rethrow because this is a critical issue we cannot handle properly here
}
}
private initServices(serviceCollection: ServiceCollection): IInstantiationService {
// Layout Service
serviceCollection.set(IWorkbenchLayoutService, this);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// native and web or `workbench.sandbox.main.ts` if the service
// is native only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// All Contributed Services
const contributedServices = getSingletonServiceDescriptors();
for (let [id, descriptor] of contributedServices) {
serviceCollection.set(id, descriptor);
}
const instantiationService = new InstantiationService(serviceCollection, true);
// Wrap up
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
// TODO@Sandeep debt around cyclic dependencies
const configurationService = accessor.get(IConfigurationService) as any;
if (typeof configurationService.acquireInstantiationService === 'function') {
setTimeout(() => {
configurationService.acquireInstantiationService(instantiationService);
}, 0);
}
// Signal to lifecycle that services are set
lifecycleService.phase = LifecyclePhase.Ready;
});
return instantiationService;
}
private registerListeners(lifecycleService: ILifecycleService, storageService: IStorageService, configurationService: IConfigurationService, hostService: IHostService): void {
// Configuration changes
this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService)));
// Font Info
if (isNative) {
this._register(storageService.onWillSaveState(e => {
if (e.reason === WillSaveStateReason.SHUTDOWN) {
this.storeFontInfo(storageService);
}
}));
} else {
this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService)));
}
// Lifecycle
this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event)));
this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
this._register(lifecycleService.onDidShutdown(() => {
this._onDidShutdown.fire();
this.dispose();
}));
// In some environments we do not get enough time to persist state on shutdown.
// In other cases, VSCode might crash, so we periodically save state to reduce
// the chance of loosing any state.
// The window loosing focus is a good indication that the user has stopped working
// in that window so we pick that at a time to collect state.
this._register(hostService.onDidChangeFocus(focus => {
if (!focus) {
storageService.flush();
}
}));
}
private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined;
private setFontAliasing(configurationService: IConfigurationService) {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
this.container.classList.remove(...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));
// Add specific
if (fontAliasingValues.some(option => option === aliasing)) {
this.container.classList.add(`monaco-font-aliasing-${aliasing}`);
}
}
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
const storedFontInfoRaw = storageService.get('editorFontInfo', StorageScope.GLOBAL);
if (storedFontInfoRaw) |
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel(), getPixelRatio()));
}
private storeFontInfo(storageService: IStorageService): void {
const serializedFontInfo = serializeFontInfo();
if (serializedFontInfo) {
storageService.store('editorFontInfo', JSON.stringify(serializedFontInfo), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
}
private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void {
// ARIA
setARIAContainer(this.container);
// State specific classes
const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';
const workbenchClasses = coalesce([
'monaco-workbench',
platformClass,
isWeb ? 'web' : undefined,
isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined,
...this.getLayoutClasses()
]);
this.container.classList.add(...workbenchClasses);
document.body.classList.add(platformClass); // used by our fonts
if (isWeb) {
document.body.classList.add('web');
}
// Apply font aliasing
this.setFontAliasing(configurationService);
// Warm up font cache information before building up too many dom elements
this.restoreFontInfo(storageService, configurationService);
// Create Parts
[
{ id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] },
{ id: Parts.BANNER_PART, role: 'banner', classes: ['banner'] },
{ id: Parts.ACTIVITYBAR_PART, role: 'none', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, // Use role 'none' for some parts to make screen readers less chatty #114892
{ id: Parts.SIDEBAR_PART, role: 'none', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } },
{ id: Parts.PANEL_PART, role: 'none', classes: ['panel', positionToString(this.state.panel.position)] },
{ id: Parts.STATUSBAR_PART, role: 'status', classes: ['statusbar'] }
].forEach(({ id, role, classes, options }) => {
const partContainer = this.createPart(id, role, classes);
this.getPart(id).create(partContainer, options);
});
// Notification Handlers
this.createNotificationsHandlers(instantiationService, notificationService);
// Add Workbench to DOM
this.parent.appendChild(this.container);
}
private createPart(id: string, role: string, classes: string[]): HTMLElement {
const part = document.createElement(role === 'status' ? 'footer' /* Use footer element for status bar #98376 */ : 'div');
part.classList.add('part', ...classes);
part.id = id;
part.setAttribute('role', role);
if (role === 'status') {
part.setAttribute('aria-live', 'off');
}
return part;
}
private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void {
// Instantiate Notification components
const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model));
const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model));
this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model));
const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model);
this._register(instantiationService.createInstance(NotificationsTelemetry));
// Visibility
this._register(notificationsCenter.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
notificationsToasts.update(notificationsCenter.isVisible);
}));
this._register(notificationsToasts.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
}));
// Register Commands
registerNotificationCommands(notificationsCenter, notificationsToasts, notificationService.model);
// Register with Layout
this.registerNotifications({
onDidChangeNotificationsVisibility: Event.map(Event.any(notificationsToasts.onDidChangeVisibility, notificationsCenter.onDidChangeVisibility), () => notificationsToasts.isVisible || notificationsCenter.isVisible)
});
}
private restore(lifecycleService: ILifecycleService): void {
// Ask each part to restore
try {
this.restoreParts();
} catch (error) {
onUnexpectedError(error);
}
// Transition into restored phase after layout has restored
// but do not wait indefinitly on this to account for slow
// editors restoring. Since the workbench is fully functional
// even when the visible editors have not resolved, we still
// want contributions on the `Restored` phase to work before
// slow editors have resolved. But we also do not want fast
// editors to resolve slow when too many contributions get
// instantiated, so we find a middle ground solution via
// `Promise.race`
this.whenReady.finally(() =>
Promise.race([
this.whenRestored,
timeout(2000)
]).finally(() => {
// Set lifecycle phase to `Restored`
lifecycleService.phase = LifecyclePhase.Restored;
// Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec)
const eventuallyPhaseScheduler = this._register(new RunOnceScheduler(() => {
this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500));
}, 2500));
eventuallyPhaseScheduler.schedule();
// Update perf marks only when the layout is fully
// restored. We want the time it takes to restore
// editors to be included in these numbers
function markDidStartWorkbench() {
mark('code/didStartWorkbench');
performance.measure('perf: workbench create & restore', 'code/didLoadWorkbenchMain', 'code/didStartWorkbench');
}
if (this.isRestored()) {
markDidStartWorkbench();
} else {
this.whenRestored.finally(() => markDidStartWorkbench());
}
})
);
}
}
| {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
} | conditional_block |
workbench.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/browser/style';
import { localize } from 'vs/nls';
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { RunOnceScheduler, runWhenIdle, timeout } from 'vs/base/common/async';
import { getZoomLevel, isFirefox, isSafari, isChrome, getPixelRatio } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { Registry } from 'vs/platform/registry/common/platform';
import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IEditorInputFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions';
import { Position, Parts, IWorkbenchLayoutService, positionToString } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService, WillSaveStateReason, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
import { NotificationsTelemetry } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class Workbench extends Layout {
private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>());
readonly onBeforeShutdown = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
readonly onWillShutdown = this._onWillShutdown.event;
private readonly _onDidShutdown = this._register(new Emitter<void>());
readonly onDidShutdown = this._onDidShutdown.event;
constructor(
parent: HTMLElement,
private readonly serviceCollection: ServiceCollection,
logService: ILogService
) {
super(parent);
// Perf: measure workbench startup time
mark('code/willStartWorkbench');
this.registerErrorHandler(logService);
}
private registerErrorHandler(logService: ILogService): void {
// Listen on unhandled rejection events
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
onUnexpectedError(event.reason);
// Prevent the printing of this event to the console
event.preventDefault();
});
// Install handler for unexpected errors
setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService));
// Inform user about loading issues from the loader
interface AnnotatedLoadingError extends Error {
phase: 'loading';
moduleId: string;
neededBy: string[];
}
interface AnnotatedFactoryError extends Error {
phase: 'factory';
moduleId: string;
}
interface AnnotatedValidationError extends Error {
phase: 'configuration';
}
type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError;
(<any>window).require.config({
onError: (err: AnnotatedError) => {
if (err.phase === 'loading') {
onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
}
console.error(err);
}
});
}
private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 };
private handleUnexpectedError(error: unknown, logService: ILogService): void {
const message = toErrorMessage(error, true);
if (!message) {
return;
}
const now = Date.now();
if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) {
return; // Return if error message identical to previous and shorter than 1 second
}
this.previousUnexpectedError.time = now;
this.previousUnexpectedError.message = message;
// Log it
logService.error(message);
}
startup(): IInstantiationService {
try { | // Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigurationService);
const hostService = accessor.get(IHostService);
// Layout
this.initLayout(accessor);
// Registries
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
// Context Keys
this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
// Register Listeners
this.registerListeners(lifecycleService, storageService, configurationService, hostService);
// Render Workbench
this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
// Workbench Layout
this.createWorkbenchLayout();
// Layout
this.layout();
// Restore
this.restore(lifecycleService);
});
return instantiationService;
} catch (error) {
onUnexpectedError(error);
throw error; // rethrow because this is a critical issue we cannot handle properly here
}
}
private initServices(serviceCollection: ServiceCollection): IInstantiationService {
// Layout Service
serviceCollection.set(IWorkbenchLayoutService, this);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// native and web or `workbench.sandbox.main.ts` if the service
// is native only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// All Contributed Services
const contributedServices = getSingletonServiceDescriptors();
for (let [id, descriptor] of contributedServices) {
serviceCollection.set(id, descriptor);
}
const instantiationService = new InstantiationService(serviceCollection, true);
// Wrap up
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
// TODO@Sandeep debt around cyclic dependencies
const configurationService = accessor.get(IConfigurationService) as any;
if (typeof configurationService.acquireInstantiationService === 'function') {
setTimeout(() => {
configurationService.acquireInstantiationService(instantiationService);
}, 0);
}
// Signal to lifecycle that services are set
lifecycleService.phase = LifecyclePhase.Ready;
});
return instantiationService;
}
private registerListeners(lifecycleService: ILifecycleService, storageService: IStorageService, configurationService: IConfigurationService, hostService: IHostService): void {
// Configuration changes
this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService)));
// Font Info
if (isNative) {
this._register(storageService.onWillSaveState(e => {
if (e.reason === WillSaveStateReason.SHUTDOWN) {
this.storeFontInfo(storageService);
}
}));
} else {
this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService)));
}
// Lifecycle
this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event)));
this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
this._register(lifecycleService.onDidShutdown(() => {
this._onDidShutdown.fire();
this.dispose();
}));
// In some environments we do not get enough time to persist state on shutdown.
// In other cases, VSCode might crash, so we periodically save state to reduce
// the chance of loosing any state.
// The window loosing focus is a good indication that the user has stopped working
// in that window so we pick that at a time to collect state.
this._register(hostService.onDidChangeFocus(focus => {
if (!focus) {
storageService.flush();
}
}));
}
private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined;
private setFontAliasing(configurationService: IConfigurationService) {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
this.container.classList.remove(...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));
// Add specific
if (fontAliasingValues.some(option => option === aliasing)) {
this.container.classList.add(`monaco-font-aliasing-${aliasing}`);
}
}
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
const storedFontInfoRaw = storageService.get('editorFontInfo', StorageScope.GLOBAL);
if (storedFontInfoRaw) {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
}
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel(), getPixelRatio()));
}
private storeFontInfo(storageService: IStorageService): void {
const serializedFontInfo = serializeFontInfo();
if (serializedFontInfo) {
storageService.store('editorFontInfo', JSON.stringify(serializedFontInfo), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
}
private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void {
// ARIA
setARIAContainer(this.container);
// State specific classes
const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';
const workbenchClasses = coalesce([
'monaco-workbench',
platformClass,
isWeb ? 'web' : undefined,
isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined,
...this.getLayoutClasses()
]);
this.container.classList.add(...workbenchClasses);
document.body.classList.add(platformClass); // used by our fonts
if (isWeb) {
document.body.classList.add('web');
}
// Apply font aliasing
this.setFontAliasing(configurationService);
// Warm up font cache information before building up too many dom elements
this.restoreFontInfo(storageService, configurationService);
// Create Parts
[
{ id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] },
{ id: Parts.BANNER_PART, role: 'banner', classes: ['banner'] },
{ id: Parts.ACTIVITYBAR_PART, role: 'none', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, // Use role 'none' for some parts to make screen readers less chatty #114892
{ id: Parts.SIDEBAR_PART, role: 'none', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } },
{ id: Parts.PANEL_PART, role: 'none', classes: ['panel', positionToString(this.state.panel.position)] },
{ id: Parts.STATUSBAR_PART, role: 'status', classes: ['statusbar'] }
].forEach(({ id, role, classes, options }) => {
const partContainer = this.createPart(id, role, classes);
this.getPart(id).create(partContainer, options);
});
// Notification Handlers
this.createNotificationsHandlers(instantiationService, notificationService);
// Add Workbench to DOM
this.parent.appendChild(this.container);
}
private createPart(id: string, role: string, classes: string[]): HTMLElement {
const part = document.createElement(role === 'status' ? 'footer' /* Use footer element for status bar #98376 */ : 'div');
part.classList.add('part', ...classes);
part.id = id;
part.setAttribute('role', role);
if (role === 'status') {
part.setAttribute('aria-live', 'off');
}
return part;
}
private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void {
// Instantiate Notification components
const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model));
const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model));
this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model));
const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model);
this._register(instantiationService.createInstance(NotificationsTelemetry));
// Visibility
this._register(notificationsCenter.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
notificationsToasts.update(notificationsCenter.isVisible);
}));
this._register(notificationsToasts.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
}));
// Register Commands
registerNotificationCommands(notificationsCenter, notificationsToasts, notificationService.model);
// Register with Layout
this.registerNotifications({
onDidChangeNotificationsVisibility: Event.map(Event.any(notificationsToasts.onDidChangeVisibility, notificationsCenter.onDidChangeVisibility), () => notificationsToasts.isVisible || notificationsCenter.isVisible)
});
}
private restore(lifecycleService: ILifecycleService): void {
// Ask each part to restore
try {
this.restoreParts();
} catch (error) {
onUnexpectedError(error);
}
// Transition into restored phase after layout has restored
// but do not wait indefinitly on this to account for slow
// editors restoring. Since the workbench is fully functional
// even when the visible editors have not resolved, we still
// want contributions on the `Restored` phase to work before
// slow editors have resolved. But we also do not want fast
// editors to resolve slow when too many contributions get
// instantiated, so we find a middle ground solution via
// `Promise.race`
this.whenReady.finally(() =>
Promise.race([
this.whenRestored,
timeout(2000)
]).finally(() => {
// Set lifecycle phase to `Restored`
lifecycleService.phase = LifecyclePhase.Restored;
// Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec)
const eventuallyPhaseScheduler = this._register(new RunOnceScheduler(() => {
this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500));
}, 2500));
eventuallyPhaseScheduler.schedule();
// Update perf marks only when the layout is fully
// restored. We want the time it takes to restore
// editors to be included in these numbers
function markDidStartWorkbench() {
mark('code/didStartWorkbench');
performance.measure('perf: workbench create & restore', 'code/didLoadWorkbenchMain', 'code/didStartWorkbench');
}
if (this.isRestored()) {
markDidStartWorkbench();
} else {
this.whenRestored.finally(() => markDidStartWorkbench());
}
})
);
}
} |
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
| random_line_split |
workbench.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/browser/style';
import { localize } from 'vs/nls';
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { RunOnceScheduler, runWhenIdle, timeout } from 'vs/base/common/async';
import { getZoomLevel, isFirefox, isSafari, isChrome, getPixelRatio } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { Registry } from 'vs/platform/registry/common/platform';
import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IEditorInputFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions';
import { Position, Parts, IWorkbenchLayoutService, positionToString } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService, WillSaveStateReason, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
import { NotificationsTelemetry } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class Workbench extends Layout {
private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>());
readonly onBeforeShutdown = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
readonly onWillShutdown = this._onWillShutdown.event;
private readonly _onDidShutdown = this._register(new Emitter<void>());
readonly onDidShutdown = this._onDidShutdown.event;
constructor(
parent: HTMLElement,
private readonly serviceCollection: ServiceCollection,
logService: ILogService
) {
super(parent);
// Perf: measure workbench startup time
mark('code/willStartWorkbench');
this.registerErrorHandler(logService);
}
private registerErrorHandler(logService: ILogService): void {
// Listen on unhandled rejection events
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
onUnexpectedError(event.reason);
// Prevent the printing of this event to the console
event.preventDefault();
});
// Install handler for unexpected errors
setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService));
// Inform user about loading issues from the loader
interface AnnotatedLoadingError extends Error {
phase: 'loading';
moduleId: string;
neededBy: string[];
}
interface AnnotatedFactoryError extends Error {
phase: 'factory';
moduleId: string;
}
interface AnnotatedValidationError extends Error {
phase: 'configuration';
}
type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError;
(<any>window).require.config({
onError: (err: AnnotatedError) => {
if (err.phase === 'loading') {
onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
}
console.error(err);
}
});
}
private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 };
private handleUnexpectedError(error: unknown, logService: ILogService): void {
const message = toErrorMessage(error, true);
if (!message) {
return;
}
const now = Date.now();
if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) {
return; // Return if error message identical to previous and shorter than 1 second
}
this.previousUnexpectedError.time = now;
this.previousUnexpectedError.message = message;
// Log it
logService.error(message);
}
startup(): IInstantiationService {
try {
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
// Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigurationService);
const hostService = accessor.get(IHostService);
// Layout
this.initLayout(accessor);
// Registries
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
// Context Keys
this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
// Register Listeners
this.registerListeners(lifecycleService, storageService, configurationService, hostService);
// Render Workbench
this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
// Workbench Layout
this.createWorkbenchLayout();
// Layout
this.layout();
// Restore
this.restore(lifecycleService);
});
return instantiationService;
} catch (error) {
onUnexpectedError(error);
throw error; // rethrow because this is a critical issue we cannot handle properly here
}
}
private initServices(serviceCollection: ServiceCollection): IInstantiationService {
// Layout Service
serviceCollection.set(IWorkbenchLayoutService, this);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// native and web or `workbench.sandbox.main.ts` if the service
// is native only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// All Contributed Services
const contributedServices = getSingletonServiceDescriptors();
for (let [id, descriptor] of contributedServices) {
serviceCollection.set(id, descriptor);
}
const instantiationService = new InstantiationService(serviceCollection, true);
// Wrap up
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
// TODO@Sandeep debt around cyclic dependencies
const configurationService = accessor.get(IConfigurationService) as any;
if (typeof configurationService.acquireInstantiationService === 'function') {
setTimeout(() => {
configurationService.acquireInstantiationService(instantiationService);
}, 0);
}
// Signal to lifecycle that services are set
lifecycleService.phase = LifecyclePhase.Ready;
});
return instantiationService;
}
private registerListeners(lifecycleService: ILifecycleService, storageService: IStorageService, configurationService: IConfigurationService, hostService: IHostService): void {
// Configuration changes
this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService)));
// Font Info
if (isNative) {
this._register(storageService.onWillSaveState(e => {
if (e.reason === WillSaveStateReason.SHUTDOWN) {
this.storeFontInfo(storageService);
}
}));
} else {
this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService)));
}
// Lifecycle
this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event)));
this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
this._register(lifecycleService.onDidShutdown(() => {
this._onDidShutdown.fire();
this.dispose();
}));
// In some environments we do not get enough time to persist state on shutdown.
// In other cases, VSCode might crash, so we periodically save state to reduce
// the chance of loosing any state.
// The window loosing focus is a good indication that the user has stopped working
// in that window so we pick that at a time to collect state.
this._register(hostService.onDidChangeFocus(focus => {
if (!focus) {
storageService.flush();
}
}));
}
private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined;
private setFontAliasing(configurationService: IConfigurationService) |
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
const storedFontInfoRaw = storageService.get('editorFontInfo', StorageScope.GLOBAL);
if (storedFontInfoRaw) {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
}
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel(), getPixelRatio()));
}
private storeFontInfo(storageService: IStorageService): void {
const serializedFontInfo = serializeFontInfo();
if (serializedFontInfo) {
storageService.store('editorFontInfo', JSON.stringify(serializedFontInfo), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
}
private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void {
// ARIA
setARIAContainer(this.container);
// State specific classes
const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';
const workbenchClasses = coalesce([
'monaco-workbench',
platformClass,
isWeb ? 'web' : undefined,
isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined,
...this.getLayoutClasses()
]);
this.container.classList.add(...workbenchClasses);
document.body.classList.add(platformClass); // used by our fonts
if (isWeb) {
document.body.classList.add('web');
}
// Apply font aliasing
this.setFontAliasing(configurationService);
// Warm up font cache information before building up too many dom elements
this.restoreFontInfo(storageService, configurationService);
// Create Parts
[
{ id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] },
{ id: Parts.BANNER_PART, role: 'banner', classes: ['banner'] },
{ id: Parts.ACTIVITYBAR_PART, role: 'none', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, // Use role 'none' for some parts to make screen readers less chatty #114892
{ id: Parts.SIDEBAR_PART, role: 'none', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } },
{ id: Parts.PANEL_PART, role: 'none', classes: ['panel', positionToString(this.state.panel.position)] },
{ id: Parts.STATUSBAR_PART, role: 'status', classes: ['statusbar'] }
].forEach(({ id, role, classes, options }) => {
const partContainer = this.createPart(id, role, classes);
this.getPart(id).create(partContainer, options);
});
// Notification Handlers
this.createNotificationsHandlers(instantiationService, notificationService);
// Add Workbench to DOM
this.parent.appendChild(this.container);
}
private createPart(id: string, role: string, classes: string[]): HTMLElement {
const part = document.createElement(role === 'status' ? 'footer' /* Use footer element for status bar #98376 */ : 'div');
part.classList.add('part', ...classes);
part.id = id;
part.setAttribute('role', role);
if (role === 'status') {
part.setAttribute('aria-live', 'off');
}
return part;
}
private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void {
// Instantiate Notification components
const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model));
const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model));
this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model));
const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model);
this._register(instantiationService.createInstance(NotificationsTelemetry));
// Visibility
this._register(notificationsCenter.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
notificationsToasts.update(notificationsCenter.isVisible);
}));
this._register(notificationsToasts.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
}));
// Register Commands
registerNotificationCommands(notificationsCenter, notificationsToasts, notificationService.model);
// Register with Layout
this.registerNotifications({
onDidChangeNotificationsVisibility: Event.map(Event.any(notificationsToasts.onDidChangeVisibility, notificationsCenter.onDidChangeVisibility), () => notificationsToasts.isVisible || notificationsCenter.isVisible)
});
}
private restore(lifecycleService: ILifecycleService): void {
// Ask each part to restore
try {
this.restoreParts();
} catch (error) {
onUnexpectedError(error);
}
// Transition into restored phase after layout has restored
// but do not wait indefinitly on this to account for slow
// editors restoring. Since the workbench is fully functional
// even when the visible editors have not resolved, we still
// want contributions on the `Restored` phase to work before
// slow editors have resolved. But we also do not want fast
// editors to resolve slow when too many contributions get
// instantiated, so we find a middle ground solution via
// `Promise.race`
this.whenReady.finally(() =>
Promise.race([
this.whenRestored,
timeout(2000)
]).finally(() => {
// Set lifecycle phase to `Restored`
lifecycleService.phase = LifecyclePhase.Restored;
// Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec)
const eventuallyPhaseScheduler = this._register(new RunOnceScheduler(() => {
this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500));
}, 2500));
eventuallyPhaseScheduler.schedule();
// Update perf marks only when the layout is fully
// restored. We want the time it takes to restore
// editors to be included in these numbers
function markDidStartWorkbench() {
mark('code/didStartWorkbench');
performance.measure('perf: workbench create & restore', 'code/didLoadWorkbenchMain', 'code/didStartWorkbench');
}
if (this.isRestored()) {
markDidStartWorkbench();
} else {
this.whenRestored.finally(() => markDidStartWorkbench());
}
})
);
}
}
| {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
this.container.classList.remove(...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));
// Add specific
if (fontAliasingValues.some(option => option === aliasing)) {
this.container.classList.add(`monaco-font-aliasing-${aliasing}`);
}
} | identifier_body |
workbench.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/workbench/browser/style';
import { localize } from 'vs/nls';
import { Event, Emitter, setGlobalLeakWarningThreshold } from 'vs/base/common/event';
import { RunOnceScheduler, runWhenIdle, timeout } from 'vs/base/common/async';
import { getZoomLevel, isFirefox, isSafari, isChrome, getPixelRatio } from 'vs/base/browser/browser';
import { mark } from 'vs/base/common/performance';
import { onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { Registry } from 'vs/platform/registry/common/platform';
import { isWindows, isLinux, isWeb, isNative, isMacintosh } from 'vs/base/common/platform';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { IEditorInputFactoryRegistry, EditorExtensions } from 'vs/workbench/common/editor';
import { getSingletonServiceDescriptors } from 'vs/platform/instantiation/common/extensions';
import { Position, Parts, IWorkbenchLayoutService, positionToString } from 'vs/workbench/services/layout/browser/layoutService';
import { IStorageService, WillSaveStateReason, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { LifecyclePhase, ILifecycleService, WillShutdownEvent, BeforeShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { NotificationService } from 'vs/workbench/services/notification/common/notificationService';
import { NotificationsCenter } from 'vs/workbench/browser/parts/notifications/notificationsCenter';
import { NotificationsAlerts } from 'vs/workbench/browser/parts/notifications/notificationsAlerts';
import { NotificationsStatus } from 'vs/workbench/browser/parts/notifications/notificationsStatus';
import { NotificationsTelemetry } from 'vs/workbench/browser/parts/notifications/notificationsTelemetry';
import { registerNotificationCommands } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { NotificationsToasts } from 'vs/workbench/browser/parts/notifications/notificationsToasts';
import { setARIAContainer } from 'vs/base/browser/ui/aria/aria';
import { readFontInfo, restoreFontInfo, serializeFontInfo } from 'vs/editor/browser/config/configuration';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { ILogService } from 'vs/platform/log/common/log';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { WorkbenchContextKeysHandler } from 'vs/workbench/browser/contextkeys';
import { coalesce } from 'vs/base/common/arrays';
import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService';
import { Layout } from 'vs/workbench/browser/layout';
import { IHostService } from 'vs/workbench/services/host/browser/host';
export class Workbench extends Layout {
private readonly _onBeforeShutdown = this._register(new Emitter<BeforeShutdownEvent>());
readonly onBeforeShutdown = this._onBeforeShutdown.event;
private readonly _onWillShutdown = this._register(new Emitter<WillShutdownEvent>());
readonly onWillShutdown = this._onWillShutdown.event;
private readonly _onDidShutdown = this._register(new Emitter<void>());
readonly onDidShutdown = this._onDidShutdown.event;
constructor(
parent: HTMLElement,
private readonly serviceCollection: ServiceCollection,
logService: ILogService
) {
super(parent);
// Perf: measure workbench startup time
mark('code/willStartWorkbench');
this.registerErrorHandler(logService);
}
private registerErrorHandler(logService: ILogService): void {
// Listen on unhandled rejection events
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent
onUnexpectedError(event.reason);
// Prevent the printing of this event to the console
event.preventDefault();
});
// Install handler for unexpected errors
setUnexpectedErrorHandler(error => this.handleUnexpectedError(error, logService));
// Inform user about loading issues from the loader
interface AnnotatedLoadingError extends Error {
phase: 'loading';
moduleId: string;
neededBy: string[];
}
interface AnnotatedFactoryError extends Error {
phase: 'factory';
moduleId: string;
}
interface AnnotatedValidationError extends Error {
phase: 'configuration';
}
type AnnotatedError = AnnotatedLoadingError | AnnotatedFactoryError | AnnotatedValidationError;
(<any>window).require.config({
onError: (err: AnnotatedError) => {
if (err.phase === 'loading') {
onUnexpectedError(new Error(localize('loaderErrorNative', "Failed to load a required file. Please restart the application to try again. Details: {0}", JSON.stringify(err))));
}
console.error(err);
}
});
}
private previousUnexpectedError: { message: string | undefined, time: number } = { message: undefined, time: 0 };
private handleUnexpectedError(error: unknown, logService: ILogService): void {
const message = toErrorMessage(error, true);
if (!message) {
return;
}
const now = Date.now();
if (message === this.previousUnexpectedError.message && now - this.previousUnexpectedError.time <= 1000) {
return; // Return if error message identical to previous and shorter than 1 second
}
this.previousUnexpectedError.time = now;
this.previousUnexpectedError.message = message;
// Log it
logService.error(message);
}
startup(): IInstantiationService {
try {
// Configure emitter leak warning threshold
setGlobalLeakWarningThreshold(175);
// Services
const instantiationService = this.initServices(this.serviceCollection);
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
const storageService = accessor.get(IStorageService);
const configurationService = accessor.get(IConfigurationService);
const hostService = accessor.get(IHostService);
// Layout
this.initLayout(accessor);
// Registries
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).start(accessor);
Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).start(accessor);
// Context Keys
this._register(instantiationService.createInstance(WorkbenchContextKeysHandler));
// Register Listeners
this.registerListeners(lifecycleService, storageService, configurationService, hostService);
// Render Workbench
this.renderWorkbench(instantiationService, accessor.get(INotificationService) as NotificationService, storageService, configurationService);
// Workbench Layout
this.createWorkbenchLayout();
// Layout
this.layout();
// Restore
this.restore(lifecycleService);
});
return instantiationService;
} catch (error) {
onUnexpectedError(error);
throw error; // rethrow because this is a critical issue we cannot handle properly here
}
}
private initServices(serviceCollection: ServiceCollection): IInstantiationService {
// Layout Service
serviceCollection.set(IWorkbenchLayoutService, this);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// native and web or `workbench.sandbox.main.ts` if the service
// is native only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// All Contributed Services
const contributedServices = getSingletonServiceDescriptors();
for (let [id, descriptor] of contributedServices) {
serviceCollection.set(id, descriptor);
}
const instantiationService = new InstantiationService(serviceCollection, true);
// Wrap up
instantiationService.invokeFunction(accessor => {
const lifecycleService = accessor.get(ILifecycleService);
// TODO@Sandeep debt around cyclic dependencies
const configurationService = accessor.get(IConfigurationService) as any;
if (typeof configurationService.acquireInstantiationService === 'function') {
setTimeout(() => {
configurationService.acquireInstantiationService(instantiationService);
}, 0);
}
// Signal to lifecycle that services are set
lifecycleService.phase = LifecyclePhase.Ready;
});
return instantiationService;
}
private registerListeners(lifecycleService: ILifecycleService, storageService: IStorageService, configurationService: IConfigurationService, hostService: IHostService): void {
// Configuration changes
this._register(configurationService.onDidChangeConfiguration(() => this.setFontAliasing(configurationService)));
// Font Info
if (isNative) {
this._register(storageService.onWillSaveState(e => {
if (e.reason === WillSaveStateReason.SHUTDOWN) {
this.storeFontInfo(storageService);
}
}));
} else {
this._register(lifecycleService.onWillShutdown(() => this.storeFontInfo(storageService)));
}
// Lifecycle
this._register(lifecycleService.onBeforeShutdown(event => this._onBeforeShutdown.fire(event)));
this._register(lifecycleService.onWillShutdown(event => this._onWillShutdown.fire(event)));
this._register(lifecycleService.onDidShutdown(() => {
this._onDidShutdown.fire();
this.dispose();
}));
// In some environments we do not get enough time to persist state on shutdown.
// In other cases, VSCode might crash, so we periodically save state to reduce
// the chance of loosing any state.
// The window loosing focus is a good indication that the user has stopped working
// in that window so we pick that at a time to collect state.
this._register(hostService.onDidChangeFocus(focus => {
if (!focus) {
storageService.flush();
}
}));
}
private fontAliasing: 'default' | 'antialiased' | 'none' | 'auto' | undefined;
private setFontAliasing(configurationService: IConfigurationService) {
if (!isMacintosh) {
return; // macOS only
}
const aliasing = configurationService.getValue<'default' | 'antialiased' | 'none' | 'auto'>('workbench.fontAliasing');
if (this.fontAliasing === aliasing) {
return;
}
this.fontAliasing = aliasing;
// Remove all
const fontAliasingValues: (typeof aliasing)[] = ['antialiased', 'none', 'auto'];
this.container.classList.remove(...fontAliasingValues.map(value => `monaco-font-aliasing-${value}`));
// Add specific
if (fontAliasingValues.some(option => option === aliasing)) {
this.container.classList.add(`monaco-font-aliasing-${aliasing}`);
}
}
private restoreFontInfo(storageService: IStorageService, configurationService: IConfigurationService): void {
const storedFontInfoRaw = storageService.get('editorFontInfo', StorageScope.GLOBAL);
if (storedFontInfoRaw) {
try {
const storedFontInfo = JSON.parse(storedFontInfoRaw);
if (Array.isArray(storedFontInfo)) {
restoreFontInfo(storedFontInfo);
}
} catch (err) {
/* ignore */
}
}
readFontInfo(BareFontInfo.createFromRawSettings(configurationService.getValue('editor'), getZoomLevel(), getPixelRatio()));
}
private | (storageService: IStorageService): void {
const serializedFontInfo = serializeFontInfo();
if (serializedFontInfo) {
storageService.store('editorFontInfo', JSON.stringify(serializedFontInfo), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
}
private renderWorkbench(instantiationService: IInstantiationService, notificationService: NotificationService, storageService: IStorageService, configurationService: IConfigurationService): void {
// ARIA
setARIAContainer(this.container);
// State specific classes
const platformClass = isWindows ? 'windows' : isLinux ? 'linux' : 'mac';
const workbenchClasses = coalesce([
'monaco-workbench',
platformClass,
isWeb ? 'web' : undefined,
isChrome ? 'chromium' : isFirefox ? 'firefox' : isSafari ? 'safari' : undefined,
...this.getLayoutClasses()
]);
this.container.classList.add(...workbenchClasses);
document.body.classList.add(platformClass); // used by our fonts
if (isWeb) {
document.body.classList.add('web');
}
// Apply font aliasing
this.setFontAliasing(configurationService);
// Warm up font cache information before building up too many dom elements
this.restoreFontInfo(storageService, configurationService);
// Create Parts
[
{ id: Parts.TITLEBAR_PART, role: 'contentinfo', classes: ['titlebar'] },
{ id: Parts.BANNER_PART, role: 'banner', classes: ['banner'] },
{ id: Parts.ACTIVITYBAR_PART, role: 'none', classes: ['activitybar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] }, // Use role 'none' for some parts to make screen readers less chatty #114892
{ id: Parts.SIDEBAR_PART, role: 'none', classes: ['sidebar', this.state.sideBar.position === Position.LEFT ? 'left' : 'right'] },
{ id: Parts.EDITOR_PART, role: 'main', classes: ['editor'], options: { restorePreviousState: this.state.editor.restoreEditors } },
{ id: Parts.PANEL_PART, role: 'none', classes: ['panel', positionToString(this.state.panel.position)] },
{ id: Parts.STATUSBAR_PART, role: 'status', classes: ['statusbar'] }
].forEach(({ id, role, classes, options }) => {
const partContainer = this.createPart(id, role, classes);
this.getPart(id).create(partContainer, options);
});
// Notification Handlers
this.createNotificationsHandlers(instantiationService, notificationService);
// Add Workbench to DOM
this.parent.appendChild(this.container);
}
private createPart(id: string, role: string, classes: string[]): HTMLElement {
const part = document.createElement(role === 'status' ? 'footer' /* Use footer element for status bar #98376 */ : 'div');
part.classList.add('part', ...classes);
part.id = id;
part.setAttribute('role', role);
if (role === 'status') {
part.setAttribute('aria-live', 'off');
}
return part;
}
private createNotificationsHandlers(instantiationService: IInstantiationService, notificationService: NotificationService): void {
// Instantiate Notification components
const notificationsCenter = this._register(instantiationService.createInstance(NotificationsCenter, this.container, notificationService.model));
const notificationsToasts = this._register(instantiationService.createInstance(NotificationsToasts, this.container, notificationService.model));
this._register(instantiationService.createInstance(NotificationsAlerts, notificationService.model));
const notificationsStatus = instantiationService.createInstance(NotificationsStatus, notificationService.model);
this._register(instantiationService.createInstance(NotificationsTelemetry));
// Visibility
this._register(notificationsCenter.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
notificationsToasts.update(notificationsCenter.isVisible);
}));
this._register(notificationsToasts.onDidChangeVisibility(() => {
notificationsStatus.update(notificationsCenter.isVisible, notificationsToasts.isVisible);
}));
// Register Commands
registerNotificationCommands(notificationsCenter, notificationsToasts, notificationService.model);
// Register with Layout
this.registerNotifications({
onDidChangeNotificationsVisibility: Event.map(Event.any(notificationsToasts.onDidChangeVisibility, notificationsCenter.onDidChangeVisibility), () => notificationsToasts.isVisible || notificationsCenter.isVisible)
});
}
private restore(lifecycleService: ILifecycleService): void {
// Ask each part to restore
try {
this.restoreParts();
} catch (error) {
onUnexpectedError(error);
}
// Transition into restored phase after layout has restored
// but do not wait indefinitly on this to account for slow
// editors restoring. Since the workbench is fully functional
// even when the visible editors have not resolved, we still
// want contributions on the `Restored` phase to work before
// slow editors have resolved. But we also do not want fast
// editors to resolve slow when too many contributions get
// instantiated, so we find a middle ground solution via
// `Promise.race`
this.whenReady.finally(() =>
Promise.race([
this.whenRestored,
timeout(2000)
]).finally(() => {
// Set lifecycle phase to `Restored`
lifecycleService.phase = LifecyclePhase.Restored;
// Set lifecycle phase to `Eventually` after a short delay and when idle (min 2.5sec, max 5sec)
const eventuallyPhaseScheduler = this._register(new RunOnceScheduler(() => {
this._register(runWhenIdle(() => lifecycleService.phase = LifecyclePhase.Eventually, 2500));
}, 2500));
eventuallyPhaseScheduler.schedule();
// Update perf marks only when the layout is fully
// restored. We want the time it takes to restore
// editors to be included in these numbers
function markDidStartWorkbench() {
mark('code/didStartWorkbench');
performance.measure('perf: workbench create & restore', 'code/didLoadWorkbenchMain', 'code/didStartWorkbench');
}
if (this.isRestored()) {
markDidStartWorkbench();
} else {
this.whenRestored.finally(() => markDidStartWorkbench());
}
})
);
}
}
| storeFontInfo | identifier_name |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import os
import sys
from optparse import OptionParser
from django.core import management
import syspath_override
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.pootle/pootle.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.sample'
def init_settings(settings_filepath, template_filename):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from. | os.makedirs(dirname)
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def parse_args(args):
"""Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if index is None:
return (args, None, [])
return (args[:index], args[index], args[(index + 1):])
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(os.path.abspath(
os.path.expanduser(config_path),
)
)
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print u"Configuration file does not exist at %r or " \
u"%r environment variable has not been set.\n" \
u"Use '%s init' to initialize the configuration file." % \
(config_path, settings_envvar, runner_name)
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
sys_args = sys.argv
runner_name = os.path.basename(sys_args[0])
(args, command, command_args) = parse_args(sys_args[1:])
if not (command or args):
# XXX: Should we display a more verbose help/usage message?
print "Usage: %s [--config=/path/to/settings.conf] [command] " \
"[options]" % runner_name
sys.exit(2)
if command == 'init':
noinput = '--noinput' in command_args
if noinput:
command_args.remove('--noinput')
# Determine which config file to write
try:
import re
config_path = command_args[0]
# Remove possible initial dashes
config_path = re.sub('^-+', '', config_path)
except IndexError:
config_path = default_settings_path
config_path = os.path.expanduser(config_path)
if os.path.exists(config_path):
resp = None
if noinput:
resp = 'n'
while resp not in ('Y', 'n'):
resp = raw_input('File already exists at %r, overwrite? [nY] ' \
% config_path)
if resp == 'n':
print "File already exists, not overwriting."
return
try:
init_settings(config_path, settings_template)
except (IOError, OSError) as e:
raise e.__class__, 'Unable to write default settings file to %r' \
% config_path
print "Configuration file created at %r" % config_path
return
parser = OptionParser()
parser.add_option('--config', metavar='CONFIG',
default=default_settings_path,
help=u'Use the specified configuration file.')
parser.add_option('-v', '--version', action='store_true',
default=False,
help=u'Display version information and exit.')
(opts, opt_args) = parser.parse_args(args)
if opts.version:
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version
print "Pootle %s" % __version__.sver
print "Translate Toolkit %s" % tt_version.sver
print "Django %s" % get_version()
return
configure_app(project=project, config_path=opts.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
management.execute_from_command_line([runner_name, command] + command_args)
sys.exit(0)
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='pootle',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main() | """
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname): | random_line_split |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import os
import sys
from optparse import OptionParser
from django.core import management
import syspath_override
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.pootle/pootle.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.sample'
def init_settings(settings_filepath, template_filename):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
"""
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def parse_args(args):
|
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(os.path.abspath(
os.path.expanduser(config_path),
)
)
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print u"Configuration file does not exist at %r or " \
u"%r environment variable has not been set.\n" \
u"Use '%s init' to initialize the configuration file." % \
(config_path, settings_envvar, runner_name)
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
sys_args = sys.argv
runner_name = os.path.basename(sys_args[0])
(args, command, command_args) = parse_args(sys_args[1:])
if not (command or args):
# XXX: Should we display a more verbose help/usage message?
print "Usage: %s [--config=/path/to/settings.conf] [command] " \
"[options]" % runner_name
sys.exit(2)
if command == 'init':
noinput = '--noinput' in command_args
if noinput:
command_args.remove('--noinput')
# Determine which config file to write
try:
import re
config_path = command_args[0]
# Remove possible initial dashes
config_path = re.sub('^-+', '', config_path)
except IndexError:
config_path = default_settings_path
config_path = os.path.expanduser(config_path)
if os.path.exists(config_path):
resp = None
if noinput:
resp = 'n'
while resp not in ('Y', 'n'):
resp = raw_input('File already exists at %r, overwrite? [nY] ' \
% config_path)
if resp == 'n':
print "File already exists, not overwriting."
return
try:
init_settings(config_path, settings_template)
except (IOError, OSError) as e:
raise e.__class__, 'Unable to write default settings file to %r' \
% config_path
print "Configuration file created at %r" % config_path
return
parser = OptionParser()
parser.add_option('--config', metavar='CONFIG',
default=default_settings_path,
help=u'Use the specified configuration file.')
parser.add_option('-v', '--version', action='store_true',
default=False,
help=u'Display version information and exit.')
(opts, opt_args) = parser.parse_args(args)
if opts.version:
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version
print "Pootle %s" % __version__.sver
print "Translate Toolkit %s" % tt_version.sver
print "Django %s" % get_version()
return
configure_app(project=project, config_path=opts.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
management.execute_from_command_line([runner_name, command] + command_args)
sys.exit(0)
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='pootle',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| """Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if index is None:
return (args, None, [])
return (args[:index], args[index], args[(index + 1):]) | identifier_body |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import os
import sys
from optparse import OptionParser
from django.core import management
import syspath_override
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.pootle/pootle.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.sample'
def init_settings(settings_filepath, template_filename):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
"""
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def | (args):
"""Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if index is None:
return (args, None, [])
return (args[:index], args[index], args[(index + 1):])
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(os.path.abspath(
os.path.expanduser(config_path),
)
)
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print u"Configuration file does not exist at %r or " \
u"%r environment variable has not been set.\n" \
u"Use '%s init' to initialize the configuration file." % \
(config_path, settings_envvar, runner_name)
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
sys_args = sys.argv
runner_name = os.path.basename(sys_args[0])
(args, command, command_args) = parse_args(sys_args[1:])
if not (command or args):
# XXX: Should we display a more verbose help/usage message?
print "Usage: %s [--config=/path/to/settings.conf] [command] " \
"[options]" % runner_name
sys.exit(2)
if command == 'init':
noinput = '--noinput' in command_args
if noinput:
command_args.remove('--noinput')
# Determine which config file to write
try:
import re
config_path = command_args[0]
# Remove possible initial dashes
config_path = re.sub('^-+', '', config_path)
except IndexError:
config_path = default_settings_path
config_path = os.path.expanduser(config_path)
if os.path.exists(config_path):
resp = None
if noinput:
resp = 'n'
while resp not in ('Y', 'n'):
resp = raw_input('File already exists at %r, overwrite? [nY] ' \
% config_path)
if resp == 'n':
print "File already exists, not overwriting."
return
try:
init_settings(config_path, settings_template)
except (IOError, OSError) as e:
raise e.__class__, 'Unable to write default settings file to %r' \
% config_path
print "Configuration file created at %r" % config_path
return
parser = OptionParser()
parser.add_option('--config', metavar='CONFIG',
default=default_settings_path,
help=u'Use the specified configuration file.')
parser.add_option('-v', '--version', action='store_true',
default=False,
help=u'Display version information and exit.')
(opts, opt_args) = parser.parse_args(args)
if opts.version:
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version
print "Pootle %s" % __version__.sver
print "Translate Toolkit %s" % tt_version.sver
print "Django %s" % get_version()
return
configure_app(project=project, config_path=opts.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
management.execute_from_command_line([runner_name, command] + command_args)
sys.exit(0)
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='pootle',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| parse_args | identifier_name |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import os
import sys
from optparse import OptionParser
from django.core import management
import syspath_override
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.pootle/pootle.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.sample'
def init_settings(settings_filepath, template_filename):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
"""
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
|
fp = open(settings_filepath, 'w')
import base64
output = open(template_filename).read()
output = output % {
'default_key': base64.b64encode(os.urandom(KEY_LENGTH)),
}
fp.write(output)
fp.close()
def parse_args(args):
"""Parses the given arguments.
:param args: List of command-line arguments as got from sys.argv.
:return: 3-element tuple: (args, command, command_args)
"""
index = None
for i, arg in enumerate(args):
if not arg.startswith('-'):
index = i
break
if index is None:
return (args, None, [])
return (args[:index], args[index], args[(index + 1):])
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(os.path.abspath(
os.path.expanduser(config_path),
)
)
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print u"Configuration file does not exist at %r or " \
u"%r environment variable has not been set.\n" \
u"Use '%s init' to initialize the configuration file." % \
(config_path, settings_envvar, runner_name)
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
sys_args = sys.argv
runner_name = os.path.basename(sys_args[0])
(args, command, command_args) = parse_args(sys_args[1:])
if not (command or args):
# XXX: Should we display a more verbose help/usage message?
print "Usage: %s [--config=/path/to/settings.conf] [command] " \
"[options]" % runner_name
sys.exit(2)
if command == 'init':
noinput = '--noinput' in command_args
if noinput:
command_args.remove('--noinput')
# Determine which config file to write
try:
import re
config_path = command_args[0]
# Remove possible initial dashes
config_path = re.sub('^-+', '', config_path)
except IndexError:
config_path = default_settings_path
config_path = os.path.expanduser(config_path)
if os.path.exists(config_path):
resp = None
if noinput:
resp = 'n'
while resp not in ('Y', 'n'):
resp = raw_input('File already exists at %r, overwrite? [nY] ' \
% config_path)
if resp == 'n':
print "File already exists, not overwriting."
return
try:
init_settings(config_path, settings_template)
except (IOError, OSError) as e:
raise e.__class__, 'Unable to write default settings file to %r' \
% config_path
print "Configuration file created at %r" % config_path
return
parser = OptionParser()
parser.add_option('--config', metavar='CONFIG',
default=default_settings_path,
help=u'Use the specified configuration file.')
parser.add_option('-v', '--version', action='store_true',
default=False,
help=u'Display version information and exit.')
(opts, opt_args) = parser.parse_args(args)
if opts.version:
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version
print "Pootle %s" % __version__.sver
print "Translate Toolkit %s" % tt_version.sver
print "Django %s" % get_version()
return
configure_app(project=project, config_path=opts.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
management.execute_from_command_line([runner_name, command] + command_args)
sys.exit(0)
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='pootle',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| os.makedirs(dirname) | conditional_block |
MenuList.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _List = _interopRequireDefault(require("../List"));
var _getScrollbarSize = _interopRequireDefault(require("../utils/getScrollbarSize"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return;
}
wrappedOnce = true;
} // Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return;
}
}
}
/**
* A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton.
* It's exposed to help customization of the [`Menu`](/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
(0, _useEnhancedEffect.default)(() => {
if (autoFocus) |
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${(0, _getScrollbarSize.default)((0, _ownerDocument.default)(containerElement))}px`;
listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = (0, _ownerDocument.default)(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = (0, _useForkRef.default)(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["Material-UI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return /*#__PURE__*/React.cloneElement(child, newChildProps);
}
return child;
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_List.default, (0, _extends2.default)({
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1
}, other, {
children: items
}));
});
process.env.NODE_ENV !== "production" ? MenuList.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order.
* @default false
*/
autoFocus: _propTypes.default.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`.
* @default false
*/
autoFocusItem: _propTypes.default.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: _propTypes.default.node,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable: _propTypes.default.bool,
/**
* If `true`, the menu items will not wrap focus.
* @default false
*/
disableListWrap: _propTypes.default.bool,
/**
* @ignore
*/
onKeyDown: _propTypes.default.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
* @default 'selectedMenu'
*/
variant: _propTypes.default.oneOf(['menu', 'selectedMenu'])
} : void 0;
var _default = MenuList;
exports.default = _default; | {
listRef.current.focus();
} | conditional_block |
MenuList.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _List = _interopRequireDefault(require("../List"));
var _getScrollbarSize = _interopRequireDefault(require("../utils/getScrollbarSize"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function nextItem(list, item, disableListWrap) |
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return;
}
wrappedOnce = true;
} // Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return;
}
}
}
/**
* A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton.
* It's exposed to help customization of the [`Menu`](/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
(0, _useEnhancedEffect.default)(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${(0, _getScrollbarSize.default)((0, _ownerDocument.default)(containerElement))}px`;
listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = (0, _ownerDocument.default)(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = (0, _useForkRef.default)(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["Material-UI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return /*#__PURE__*/React.cloneElement(child, newChildProps);
}
return child;
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_List.default, (0, _extends2.default)({
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1
}, other, {
children: items
}));
});
process.env.NODE_ENV !== "production" ? MenuList.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order.
* @default false
*/
autoFocus: _propTypes.default.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`.
* @default false
*/
autoFocusItem: _propTypes.default.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: _propTypes.default.node,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable: _propTypes.default.bool,
/**
* If `true`, the menu items will not wrap focus.
* @default false
*/
disableListWrap: _propTypes.default.bool,
/**
* @ignore
*/
onKeyDown: _propTypes.default.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
* @default 'selectedMenu'
*/
variant: _propTypes.default.oneOf(['menu', 'selectedMenu'])
} : void 0;
var _default = MenuList;
exports.default = _default; | {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
} | identifier_body |
MenuList.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _List = _interopRequireDefault(require("../List"));
var _getScrollbarSize = _interopRequireDefault(require("../utils/getScrollbarSize"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function | (obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return;
}
wrappedOnce = true;
} // Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return;
}
}
}
/**
* A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton.
* It's exposed to help customization of the [`Menu`](/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
(0, _useEnhancedEffect.default)(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${(0, _getScrollbarSize.default)((0, _ownerDocument.default)(containerElement))}px`;
listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = (0, _ownerDocument.default)(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = (0, _useForkRef.default)(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["Material-UI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return /*#__PURE__*/React.cloneElement(child, newChildProps);
}
return child;
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_List.default, (0, _extends2.default)({
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1
}, other, {
children: items
}));
});
process.env.NODE_ENV !== "production" ? MenuList.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order.
* @default false
*/
autoFocus: _propTypes.default.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`.
* @default false
*/
autoFocusItem: _propTypes.default.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: _propTypes.default.node,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable: _propTypes.default.bool,
/**
* If `true`, the menu items will not wrap focus.
* @default false
*/
disableListWrap: _propTypes.default.bool,
/**
* @ignore
*/
onKeyDown: _propTypes.default.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
* @default 'selectedMenu'
*/
variant: _propTypes.default.oneOf(['menu', 'selectedMenu'])
} : void 0;
var _default = MenuList;
exports.default = _default; | _interopRequireWildcard | identifier_name |
MenuList.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _reactIs = require("react-is");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _List = _interopRequireDefault(require("../List"));
var _getScrollbarSize = _interopRequireDefault(require("../utils/getScrollbarSize"));
var _useForkRef = _interopRequireDefault(require("../utils/useForkRef"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["actions", "autoFocus", "autoFocusItem", "children", "className", "disabledItemsFocusable", "disableListWrap", "onKeyDown", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.indexOf(textCriteria.keys.join('')) === 0;
}
function moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return;
}
wrappedOnce = true;
} // Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return;
}
}
}
/**
* A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton.
* It's exposed to help customization of the [`Menu`](/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null
});
(0, _useEnhancedEffect.default)(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
React.useImperativeHandle(actions, () => ({
adjustStyleForScrollbar: (containerElement, theme) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${(0, _getScrollbarSize.default)((0, _ownerDocument.default)(containerElement))}px`;
listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
}
}), []);
const handleKeyDown = event => {
const list = listRef.current;
const key = event.key;
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = (0, _ownerDocument.default)(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = (0, _useForkRef.default)(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return;
}
if (process.env.NODE_ENV !== 'production') {
if ((0, _reactIs.isFragment)(child)) {
console.error(["Material-UI: The Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
} |
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return /*#__PURE__*/React.cloneElement(child, newChildProps);
}
return child;
});
return /*#__PURE__*/(0, _jsxRuntime.jsx)(_List.default, (0, _extends2.default)({
role: "menu",
ref: handleRef,
className: className,
onKeyDown: handleKeyDown,
tabIndex: autoFocus ? 0 : -1
}, other, {
children: items
}));
});
process.env.NODE_ENV !== "production" ? MenuList.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order.
* @default false
*/
autoFocus: _propTypes.default.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`.
* @default false
*/
autoFocusItem: _propTypes.default.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: _propTypes.default.node,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable: _propTypes.default.bool,
/**
* If `true`, the menu items will not wrap focus.
* @default false
*/
disableListWrap: _propTypes.default.bool,
/**
* @ignore
*/
onKeyDown: _propTypes.default.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
* @default 'selectedMenu'
*/
variant: _propTypes.default.oneOf(['menu', 'selectedMenu'])
} : void 0;
var _default = MenuList;
exports.default = _default; | } | random_line_split |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path
def main():
actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', 'wraps gmap'),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def check_index(dbfile):
dbfile = get_abs_path(dbfile)
dbdir, filename = op.split(dbfile)
if not dbdir:
dbdir = "."
dbname = filename.rsplit(".", 1)[0]
safile = op.join(dbdir, "{0}/{0}.genomecomp".format(dbname))
if dbname == filename:
dbname = filename + ".db"
if need_update(dbfile, safile):
cmd = "gmap_build -D {0} -d {1} {2}".format(dbdir, dbname, filename)
sh(cmd)
else:
logging.error("`{0}` exists. `gmap_build` already run.".format(safile))
return dbdir, dbname
def | (args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile)
def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile
def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fasta import join
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--join", default=False, action="store_true",
help="Join sequences with padded 50Ns")
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--snp", default=False, action="store_true",
help="Call SNPs after GSNAP")
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[0:2]
if opts.join:
dbfile = join([dbfile, "--gapsize=50", "--newid=chr1"])
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = prefix + ".log"
gsnapfile = prefix + ".gsnap"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1"
cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip"
try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.snp:
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
nativefile = pf + ".unique.native"
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile
if __name__ == '__main__':
main()
| index | identifier_name |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path
def main():
actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', 'wraps gmap'),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def check_index(dbfile):
dbfile = get_abs_path(dbfile)
dbdir, filename = op.split(dbfile)
if not dbdir:
dbdir = "."
dbname = filename.rsplit(".", 1)[0]
safile = op.join(dbdir, "{0}/{0}.genomecomp".format(dbname))
if dbname == filename:
dbname = filename + ".db"
if need_update(dbfile, safile):
cmd = "gmap_build -D {0} -d {1} {2}".format(dbdir, dbname, filename)
sh(cmd)
else:
logging.error("`{0}` exists. `gmap_build` already run.".format(safile))
return dbdir, dbname
def index(args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile)
def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
|
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile
def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fasta import join
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--join", default=False, action="store_true",
help="Join sequences with padded 50Ns")
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--snp", default=False, action="store_true",
help="Call SNPs after GSNAP")
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[0:2]
if opts.join:
dbfile = join([dbfile, "--gapsize=50", "--newid=chr1"])
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = prefix + ".log"
gsnapfile = prefix + ".gsnap"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1"
cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip"
try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.snp:
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
nativefile = pf + ".unique.native"
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile
if __name__ == '__main__':
main()
| sys.exit(not p.print_help()) | conditional_block |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path
def main():
actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', 'wraps gmap'),
)
p = ActionDispatcher(actions)
p.dispatch(globals())
def check_index(dbfile):
dbfile = get_abs_path(dbfile)
dbdir, filename = op.split(dbfile)
if not dbdir:
dbdir = "."
dbname = filename.rsplit(".", 1)[0]
safile = op.join(dbdir, "{0}/{0}.genomecomp".format(dbname))
if dbname == filename:
dbname = filename + ".db"
if need_update(dbfile, safile):
cmd = "gmap_build -D {0} -d {1} {2}".format(dbdir, dbname, filename)
sh(cmd)
else:
logging.error("`{0}` exists. `gmap_build` already run.".format(safile))
return dbdir, dbname
def index(args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile)
def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile
def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fasta import join
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--join", default=False, action="store_true",
help="Join sequences with padded 50Ns")
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--snp", default=False, action="store_true",
help="Call SNPs after GSNAP")
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[0:2]
if opts.join:
dbfile = join([dbfile, "--gapsize=50", "--newid=chr1"])
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = prefix + ".log"
gsnapfile = prefix + ".gsnap"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1" | try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.snp:
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
nativefile = pf + ".unique.native"
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile
if __name__ == '__main__':
main() | cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip" | random_line_split |
gmap.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path
def main():
|
def check_index(dbfile):
dbfile = get_abs_path(dbfile)
dbdir, filename = op.split(dbfile)
if not dbdir:
dbdir = "."
dbname = filename.rsplit(".", 1)[0]
safile = op.join(dbdir, "{0}/{0}.genomecomp".format(dbname))
if dbname == filename:
dbname = filename + ".db"
if need_update(dbfile, safile):
cmd = "gmap_build -D {0} -d {1} {2}".format(dbdir, dbname, filename)
sh(cmd)
else:
logging.error("`{0}` exists. `gmap_build` already run.".format(safile))
return dbdir, dbname
def index(args):
"""
%prog index database.fasta
`
Wrapper for `gmap_build`. Same interface.
"""
p = OptionParser(index.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
dbfile, = args
check_index(dbfile)
def gmap(args):
"""
%prog gmap database.fasta fastafile
Wrapper for `gmap`.
"""
p = OptionParser(gmap.__doc__)
p.add_option("--cross", default=False, action="store_true",
help="Cross-species alignment")
p.add_option("--npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, fastafile = args
assert op.exists(dbfile) and op.exists(fastafile)
prefix = get_prefix(fastafile, dbfile)
logfile = prefix + ".log"
gmapfile = prefix + ".gmap.gff3"
if not need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}".format(opts.cpus)
cmd += " --npaths {0}".format(opts.npaths)
if opts.cross:
cmd += " --cross-species"
cmd += " " + fastafile
sh(cmd, outfile=gmapfile, errfile=logfile)
return gmapfile, logfile
def align(args):
"""
%prog align database.fasta read1.fq read2.fq
Wrapper for `gsnap` single-end or paired-end, depending on the number of
args.
"""
from jcvi.formats.fasta import join
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.add_option("--join", default=False, action="store_true",
help="Join sequences with padded 50Ns")
p.add_option("--rnaseq", default=False, action="store_true",
help="Input is RNA-seq reads, turn splicing on")
p.add_option("--snp", default=False, action="store_true",
help="Call SNPs after GSNAP")
p.set_home("eddyyeh")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) == 2:
logging.debug("Single-end alignment")
elif len(args) == 3:
logging.debug("Paired-end alignment")
else:
sys.exit(not p.print_help())
dbfile, readfile = args[0:2]
if opts.join:
dbfile = join([dbfile, "--gapsize=50", "--newid=chr1"])
assert op.exists(dbfile) and op.exists(readfile)
prefix = get_prefix(readfile, dbfile)
logfile = prefix + ".log"
gsnapfile = prefix + ".gsnap"
if not need_update((dbfile, readfile), gsnapfile):
logging.error("`{0}` exists. `gsnap` already run.".format(gsnapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gsnap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -B 5 -m 0.1 -i 2 -n 3" # memory, mismatch, indel penalty, nhits
if opts.rnaseq:
cmd += " -N 1"
cmd += " -t {0}".format(opts.cpus)
cmd += " --gmap-mode none --nofails"
if readfile.endswith(".gz"):
cmd += " --gunzip"
try:
offset = "sanger" if guessoffset([readfile]) == 33 else "illumina"
cmd += " --quality-protocol {0}".format(offset)
except AssertionError:
pass
cmd += " " + " ".join(args[1:])
sh(cmd, outfile=gsnapfile, errfile=logfile)
if opts.snp:
EYHOME = opts.eddyyeh_home
pf = gsnapfile.rsplit(".", 1)[0]
nativefile = pf + ".unique.native"
if need_update(gsnapfile, nativefile):
cmd = op.join(EYHOME, "convert2native.pl")
cmd += " --gsnap {0} -o {1}".format(gsnapfile, nativefile)
cmd += " -proc {0}".format(opts.cpus)
sh(cmd)
return gsnapfile, logfile
if __name__ == '__main__':
main()
| actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', 'wraps gmap'),
)
p = ActionDispatcher(actions)
p.dispatch(globals()) | identifier_body |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}
impl MysqlMiddleware {
pub fn new(db_name: &str, user: &str, pass: &str) -> MysqlMiddleware {
let options = MyOpts {
user: Some(user.into()),
pass: Some(pass.into()),
db_name: Some(db_name.into()),
..Default::default()
};
let pool = MyPool::new(options).unwrap();
MysqlMiddleware {
pool: Arc::new(pool),
}
} | }
impl Key for MysqlMiddleware { type Value = Arc<MyPool>; }
impl Middleware for MysqlMiddleware {
fn invoke<'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}
}
pub trait MysqlRequestExtensions {
fn db_connection(&self) -> Arc<MyPool>;
}
impl<'a, 'b, 'c> MysqlRequestExtensions for Request<'a, 'b, 'c> {
fn db_connection(&self) -> Arc<MyPool> {
self.extensions().get::<MysqlMiddleware>().unwrap().clone()
}
} | random_line_split | |
middleware.rs | use std::default::Default;
use std::sync::Arc;
use mysql::conn::MyOpts;
use mysql::conn::pool::MyPool;
use mysql::value::from_value;
use nickel::{Request, Response, Middleware, Continue, MiddlewareResult};
use typemap::Key;
use plugin::{Pluggable, Extensible};
pub struct MysqlMiddleware {
pub pool: Arc<MyPool>,
}
impl MysqlMiddleware {
pub fn new(db_name: &str, user: &str, pass: &str) -> MysqlMiddleware {
let options = MyOpts {
user: Some(user.into()),
pass: Some(pass.into()),
db_name: Some(db_name.into()),
..Default::default()
};
let pool = MyPool::new(options).unwrap();
MysqlMiddleware {
pool: Arc::new(pool),
}
}
}
impl Key for MysqlMiddleware { type Value = Arc<MyPool>; }
impl Middleware for MysqlMiddleware {
fn | <'res>(&self, request: &mut Request, response: Response<'res>) -> MiddlewareResult<'res> {
request.extensions_mut().insert::<MysqlMiddleware>(self.pool.clone());
Ok(Continue(response))
}
}
pub trait MysqlRequestExtensions {
fn db_connection(&self) -> Arc<MyPool>;
}
impl<'a, 'b, 'c> MysqlRequestExtensions for Request<'a, 'b, 'c> {
fn db_connection(&self) -> Arc<MyPool> {
self.extensions().get::<MysqlMiddleware>().unwrap().clone()
}
}
| invoke | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relais.reset()?,
}
Ok(())
}
pub fn random(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.test_random()?,
false => relais.reset()?,
}
Ok(())}
pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> |
pub fn set(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>, num: u64) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.set(num)?,
false => relais.clear(num)?,
}
Ok(())
}
| {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
} | identifier_body |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relais.reset()?,
}
Ok(())
}
pub fn | (button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.test_random()?,
false => relais.reset()?,
}
Ok(())}
pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
}
pub fn set(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>, num: u64) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.set(num)?,
false => relais.clear(num)?,
}
Ok(())
}
| random | identifier_name |
relais_controller.rs | use errors::*;
use gtk;
use gtk::prelude::*;
use shift_register::*;
use std::sync::{Arc, Mutex};
pub fn all(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.all()?,
false => relais.reset()?,
}
Ok(())
}
pub fn random(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.test_random()?,
false => relais.reset()?,
}
Ok(())}
| let mut relais = relais.lock().unwrap();
match button.get_active() {
true => {
for i in 1..10 {
relais.set(i);
::std::thread::sleep(::std::time::Duration::from_millis(100));
}
},
false => relais.reset()?,
}
Ok(())
}
pub fn set(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>, num: u64) -> Result<()> {
let mut relais = relais.lock().unwrap();
match button.get_active() {
true => relais.set(num)?,
false => relais.clear(num)?,
}
Ok(())
} | pub fn one_after_one(button: >k::ToggleButton, relais: &Arc<Mutex<ShiftRegister>>) -> Result<()> { | random_line_split |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array |
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::<f32>(0.0, dims);
// d(pressure)/dt field
let mut p_dot = p.clone();
// Laplacian (Del^2) convolution kernel.
let laplacian_values = [0.0f32, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0];
let laplacian_kernel = Array::new(&laplacian_values, Dim4::new(&[3, 3, 1, 1])) / (dx * dx);
// Create a window to show the waves.
let mut win = Window::new(1000, 1000, "Waves".to_string());
// Hann windowed pulse.
let pulse_time = 100.0f64;
let centre_freq = 0.05;
// Number of samples in pulse.
let pulse_n = (pulse_time/dt).floor() as u64;
let i = range::<f32>(Dim4::new(&[pulse_n, 1, 1, 1]), 0);
let t = i.clone() * dt;
let hamming_window = cos(&(i * (2.0 * PI / pulse_n as f64))) * -0.46 + 0.54;
let wave = sin(&(&t * centre_freq * 2.0 * PI));
let pulse = wave * hamming_window;
// Iteration count.
let mut it = 0;
while !win.is_closed() {
// Convole with laplacian to get spacial second derivative.
let lap_p = convolve2(&p, &laplacian_kernel, ConvMode::DEFAULT, ConvDomain::SPATIAL);
// Calculate the updated pressure and d(pressure)/dt fields.
p_dot += lap_p * (c * dt);
p += &p_dot * dt;
if it < pulse_n {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
}
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
}
| {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
} | identifier_body |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn | (a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::<f32>(0.0, dims);
// d(pressure)/dt field
let mut p_dot = p.clone();
// Laplacian (Del^2) convolution kernel.
let laplacian_values = [0.0f32, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0];
let laplacian_kernel = Array::new(&laplacian_values, Dim4::new(&[3, 3, 1, 1])) / (dx * dx);
// Create a window to show the waves.
let mut win = Window::new(1000, 1000, "Waves".to_string());
// Hann windowed pulse.
let pulse_time = 100.0f64;
let centre_freq = 0.05;
// Number of samples in pulse.
let pulse_n = (pulse_time/dt).floor() as u64;
let i = range::<f32>(Dim4::new(&[pulse_n, 1, 1, 1]), 0);
let t = i.clone() * dt;
let hamming_window = cos(&(i * (2.0 * PI / pulse_n as f64))) * -0.46 + 0.54;
let wave = sin(&(&t * centre_freq * 2.0 * PI));
let pulse = wave * hamming_window;
// Iteration count.
let mut it = 0;
while !win.is_closed() {
// Convole with laplacian to get spacial second derivative.
let lap_p = convolve2(&p, &laplacian_kernel, ConvMode::DEFAULT, ConvDomain::SPATIAL);
// Calculate the updated pressure and d(pressure)/dt fields.
p_dot += lap_p * (c * dt);
p += &p_dot * dt;
if it < pulse_n {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
}
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
}
| normalise | identifier_name |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info();
acoustic_wave_simulation();
}
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::<f32>(0.0, dims);
// d(pressure)/dt field
let mut p_dot = p.clone();
// Laplacian (Del^2) convolution kernel.
let laplacian_values = [0.0f32, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0];
let laplacian_kernel = Array::new(&laplacian_values, Dim4::new(&[3, 3, 1, 1])) / (dx * dx);
// Create a window to show the waves.
let mut win = Window::new(1000, 1000, "Waves".to_string());
// Hann windowed pulse.
let pulse_time = 100.0f64;
let centre_freq = 0.05;
// Number of samples in pulse.
let pulse_n = (pulse_time/dt).floor() as u64;
let i = range::<f32>(Dim4::new(&[pulse_n, 1, 1, 1]), 0);
let t = i.clone() * dt;
let hamming_window = cos(&(i * (2.0 * PI / pulse_n as f64))) * -0.46 + 0.54;
let wave = sin(&(&t * centre_freq * 2.0 * PI));
let pulse = wave * hamming_window;
// Iteration count.
let mut it = 0;
while !win.is_closed() {
// Convole with laplacian to get spacial second derivative.
let lap_p = convolve2(&p, &laplacian_kernel, ConvMode::DEFAULT, ConvDomain::SPATIAL);
// Calculate the updated pressure and d(pressure)/dt fields.
p_dot += lap_p * (c * dt);
p += &p_dot * dt;
if it < pulse_n |
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
}
| {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
} | conditional_block |
acoustic_wave.rs | extern crate arrayfire as af;
use af::*;
use std::f64::consts::*;
fn main() {
set_device(0);
info(); |
fn normalise(a: &Array) -> Array {
(a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32
}
fn acoustic_wave_simulation() {
// Speed of sound
let c = 0.1;
// Distance step
let dx = 0.5;
// Time step
let dt = 1.0;
// Grid size.
let nx = 1500;
let ny = 1500;
// Grid dimensions.
let dims = Dim4::new(&[nx, ny, 1, 1]);
// Pressure field
let mut p = constant::<f32>(0.0, dims);
// d(pressure)/dt field
let mut p_dot = p.clone();
// Laplacian (Del^2) convolution kernel.
let laplacian_values = [0.0f32, 1.0, 0.0,
1.0, -4.0, 1.0,
0.0, 1.0, 0.0];
let laplacian_kernel = Array::new(&laplacian_values, Dim4::new(&[3, 3, 1, 1])) / (dx * dx);
// Create a window to show the waves.
let mut win = Window::new(1000, 1000, "Waves".to_string());
// Hann windowed pulse.
let pulse_time = 100.0f64;
let centre_freq = 0.05;
// Number of samples in pulse.
let pulse_n = (pulse_time/dt).floor() as u64;
let i = range::<f32>(Dim4::new(&[pulse_n, 1, 1, 1]), 0);
let t = i.clone() * dt;
let hamming_window = cos(&(i * (2.0 * PI / pulse_n as f64))) * -0.46 + 0.54;
let wave = sin(&(&t * centre_freq * 2.0 * PI));
let pulse = wave * hamming_window;
// Iteration count.
let mut it = 0;
while !win.is_closed() {
// Convole with laplacian to get spacial second derivative.
let lap_p = convolve2(&p, &laplacian_kernel, ConvMode::DEFAULT, ConvDomain::SPATIAL);
// Calculate the updated pressure and d(pressure)/dt fields.
p_dot += lap_p * (c * dt);
p += &p_dot * dt;
if it < pulse_n {
// Location of the source.
let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)];
// Set the pressure there.
p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]));
}
// Draw the image.
win.set_colormap(af::ColorMap::BLUE);
win.draw_image(&normalise(&p), None);
it += 1;
}
} |
acoustic_wave_simulation();
} | random_line_split |
evictions.component.ts | import {
Component, OnInit, Input, OnDestroy, ViewChild, Inject, AfterViewInit, ChangeDetectorRef,
HostListener, Output, EventEmitter
} from '@angular/core';
import { Router, ActivatedRoute, ParamMap, RouterLink } from '@angular/router';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { DOCUMENT, DecimalPipe } from '@angular/common';
import { Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { ToastsManager, ToastOptions } from 'ng2-toastr';
import { environment } from '../../../../environments/environment';
import { RankingLocation } from '../../ranking-location';
import { RankingService } from '../../ranking.service';
import { ScrollService } from '../../../services/scroll.service';
import { LoadingService } from '../../../services/loading.service';
import { PlatformService } from '../../../services/platform.service';
import { AnalyticsService } from '../../../services/analytics.service';
import { RankingUiComponent } from '../../ranking-ui/ranking-ui.component';
import { RankingListComponent } from '../../ranking-list/ranking-list.component';
import { RankingPanelComponent } from '../../ranking-panel/ranking-panel.component';
@Component({
selector: 'app-evictions',
templateUrl: './evictions.component.html',
styleUrls: ['./evictions.component.scss']
})
export class EvictionsComponent implements OnInit, AfterViewInit, OnDestroy {
/** string representing the region */
@Input()
set region(regionValue) {
if (!regionValue) { return; }
if (regionValue !== this.store.region) {
this.debug('set region', regionValue, this.store.region);
this.store.region = regionValue;
this.updateEvictionList();
}
}
get region() { return this.store.region; }
/** ID representing the selected area type */
@Input()
set areaType(newType) {
if (!newType) { return; }
if ((!this.store.areaType || newType.value !== this.store.areaType.value) && newType) {
this.debug('set areaType', newType, this.store.areaType);
this.store.areaType = newType;
this.updateEvictionList();
this.trackAreaChange();
}
}
get areaType() { return this.store.areaType; }
/** object key representing the data property to sort by */
@Input()
set dataProperty(newProp) {
if (!newProp) { return; }
if ((!this.store.dataProperty || newProp.value !== this.store.dataProperty.value) && newProp) {
this.debug('set dataProp', newProp, this.store.dataProperty);
this.store.dataProperty = newProp;
this.updateEvictionList();
this.trackRankByChange();
}
}
get dataProperty() { return this.store.dataProperty; }
/** the index of the selected location for the data panel */
@Input()
set selectedIndex(value: number) {
const panelOpened = this.store.selectedIndex === null;
this.store.selectedIndex = value;
// location exists in the current list, set active and scroll to it
if (value !== null && value < this.topCount) { this.scrollToIndex(value); }
// if the panel is newly opened, focus
if (panelOpened) { this.focusPanel(); }
this.updateTweet();
}
get selectedIndex(): number { return this.store.selectedIndex; }
/** Reference to the ranking list component */
@ViewChild(RankingListComponent) rankingList: RankingListComponent;
/** Reference to the ranking panel component */
@ViewChild(RankingPanelComponent) rankingPanel: RankingPanelComponent;
/** tracks if the data has been loaded and parsed */
isDataReady = false;
/** A shortened version of `listData`, containing only the first `topCount` items */
truncatedList: Array<RankingLocation>;
/** Stores the maximum value in the truncated List */
dataMax = 1;
/** list of data for the current UI selections */
listData: Array<RankingLocation>; // Array of locations to show the rank list for
/** state for UI panel on mobile / tablet */
showUiPanel = false;
/** Boolean of whether to show scroll to top button */
showScrollButton = false;
/** number of items to show in the list */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex: null
};
/** returns if all of the required params are set to be able to fetch data */
get canRetrieveData(): boolean {
return this.canNavigate && this.isDataReady;
}
private get canNavigate(): boolean {
return this.region && this.areaType && this.dataProperty &&
this.areaType.hasOwnProperty('value') &&
this.dataProperty.hasOwnProperty('value');
}
private destroy: Subject<any> = new Subject();
private _debug = true;
constructor(
public rankings: RankingService,
public loader: LoadingService,
public platform: PlatformService,
private route: ActivatedRoute,
private router: Router,
private scroll: ScrollService,
private translate: TranslateService,
private analytics: AnalyticsService,
private translatePipe: TranslatePipe,
private decimal: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private toast: ToastsManager,
@Inject(DOCUMENT) private document: any
) {
this.store.areaType = this.rankings.areaTypes[0];
this.store.dataProperty = this.rankings.sortProps[0];
this.toast.onClickToast().subscribe(t => this.toast.dismissToast(t));
this.debug('init');
}
/** subscribe to when the rankings data is ready, show loading */
ngOnInit() {
this.rankings.isReady.takeUntil(this.destroy)
.subscribe((ready) => {
this.isDataReady = ready;
if (ready) {
this.updateEvictionList();
this.loader.end('evictions');
}
});
this.translate.onLangChange.subscribe((l) => {
this.currentLang = l.lang;
this.updateQueryParam('lang', l.lang);
this.updateTweet();
});
// set kiosk mode if kiosk url
this.kiosk = this.platform.nativeWindow.location.hostname.includes('kiosk');
}
/** load data once the view has been initialized */
ngAfterViewInit() {
this.loader.start('evictions');
this.rankings.loadEvictionsData();
// list takes a bit to render, so setup page scroll in a timeout instead
setTimeout(() => { this.setupPageScroll(); }, 500);
}
/** clear any subscriptions on destroy */
ngOnDestroy() {
this.rankings.setReady(false);
this.destroy.next();
this.destroy.complete();
}
/** Move to previous or next location with arrows, hide panel with escape */
@HostListener('keydown', ['$event']) onKeypress(e) {
if (this.selectedIndex === null) { return; }
if ((e.keyCode === 37 || e.keyCode === 39)) {
// left or right
const newValue = (e.keyCode === 37) ? this.selectedIndex - 1 : this.selectedIndex + 1;
this.setCurrentLocation(Math.min(Math.max(0, newValue), this.topCount));
}
if (e.keyCode === 27) {
// escape
this.onClose();
e.preventDefault();
}
}
/** Updates one of the query parameters and updates the route */
updateQueryParam(paramName: string, value: any) {
if (!this.canNavigate) { return; }
if (paramName === 'r' || paramName === 'a' || paramName === 'd') {
this.selectedIndex = null;
}
const params = this.getQueryParams();
params[paramName] = value;
this.router.navigate([ '/', 'evictions' ], { queryParams: params });
}
/** Update the route when the region changes */
onRegionChange(newRegion: string) {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
}
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
onDataPropertyChange(dataProp: { name: string, value: string }) {
if (this.dataProperty && dataProp.value === this.dataProperty.value) { return; }
this.updateQueryParam('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.showUnavailableToast();
return;
}
const value = (locationIndex || locationIndex === 0) ? locationIndex : null;
this.updateQueryParam('l', value);
}
/**
* Scrolls to the searched location if it exists in the list
* or switches to the corresponding area type for the location and activates
* the location
* @param location
*/
onSearchSelectLocation(e: { selection: RankingLocation, queryTerm: string } | null) {
let location: RankingLocation = null;
if (e.selection) { location = e.selection; }
if (location === null) { return this.setCurrentLocation(null); }
this.showUiPanel = false;
let listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
if (listIndex > -1) {
this.setCurrentLocation(listIndex);
} else {
// location doesn't exist in the list, update to full list and find the location
this.region = 'United States';
this.areaType = this.rankings.areaTypes.filter(t => t.value === location.areaType)[0];
this.updateEvictionList();
listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
this.setCurrentLocation(listIndex);
}
this.scrollToIndex(Math.min(99, listIndex));
this.trackSearchSelection(location, e.queryTerm);
}
/** handles the click on a specific location */
onClickLocation(index: number) {
this.setCurrentLocation(index);
this.trackLocationSelection(this.listData[index]);
}
/** Switch the selected location to the next one in the list */
onGoToNext() {
if (this.selectedIndex < this.listData.length - 1) {
this.setCurrentLocation(this.selectedIndex + 1);
}
}
/** Switch the selected location to the previous one in the list */
onGoToPrevious() {
if (this.selectedIndex > 0) |
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
onPanelLocationClick(rank: number) {
this.scrollToIndex(rank - 1);
}
/** Updates Twitter text for city rankings based on selections */
updateTweet() {
if (!this.canNavigate || !this.listData) { return ''; }
this.tweet = this.isDefaultSelection() ? this.getDefaultTweet() :
(this.isLocationSelected() ? this.getLocationTweet() : this.getRegionTweet());
this.debug('updated tweet - ', this.tweet);
}
scrollToTop() {
this.scroll.scrollTo(this.rankingList.el.nativeElement);
// set focus to an element at the top of the page for keyboard nav
const focusableEl = this.rankingList.el.nativeElement.querySelector('app-ranking-list button');
setTimeout(() => {
if (focusableEl.length) {
focusableEl[0].focus();
focusableEl[0].blur();
}
}, this.scroll.defaultDuration);
}
private isLocationInvalid(locationIndex: number) {
return locationIndex !== null && (
this.listData[locationIndex][this.dataProperty.value] < 0 ||
this.listData[locationIndex]['evictions'] < 0
);
}
/** Get location selected data for analytics tracking */
private getSelectedData(location: RankingLocation): any {
return {
locationSelected: location.displayName,
locatonSelectedLevel: this.rankings.areaTypes[location.areaType].langKey,
};
}
/** Gets the selected filters for analytics tracking */
private getSelectedFilters() {
return {
area: this.areaType.langKey,
rankBy: this.dataProperty.langKey,
region: this.region
};
}
private trackAreaChange() {
this.analytics.trackEvent('rankingsAreaSelection', this.getSelectedFilters());
}
private trackRankByChange() {
this.analytics.trackEvent('rankingsRankBySelection', this.getSelectedFilters());
}
/** Track when a location is selected */
private trackLocationSelection(location: RankingLocation, method = 'list') {
const selectedEvent: any = this.getSelectedData(location);
selectedEvent.locationFindingMethod = method;
this.analytics.trackEvent('locationSelection', selectedEvent);
}
/** Track when an option in search is selected. */
private trackSearchSelection(location: RankingLocation, term: string) {
this.trackLocationSelection(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), locationFindingMethod: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffset = 0;
this.scroll.verticalOffset$
.map(offset => offset > 600)
.distinctUntilChanged()
.subscribe(showButton => {
this.debug('show scroll to top button:', showButton);
this.showScrollButton = showButton;
});
}
/** Shows a toast message indicating the data is not available */
private showUnavailableToast() {
this.toast.error(
this.translatePipe.transform('RANKINGS.LOCATION_DATA_UNAVAILABLE'),
null,
{messageClass: 'ranking-error'}
);
}
/** gets the query parameters for the current view */
private getQueryParams() {
// this.selectedIndex
const params = {
r: this.region,
a: this.areaType.value,
d: this.dataProperty.value
};
if (this.translate.currentLang !== 'en') {
params['lang'] = this.translate.currentLang;
}
if (this.selectedIndex || this.selectedIndex === 0) {
params['l'] = this.selectedIndex;
}
return params;
}
/**
* Set default tweet parameters with the US and no location selected, has the
* following parameters:
* - areaType: selected area type
* - action: string representing if it was an eviction or filing
* - amount: the average of the top 10 if showing rates, otherwise the total of the top 10
* - year: year for the data
* - link: link to the view
*/
private getDefaultTweet(): string {
// action text
let action = this.isPropJudgments() ?
'RANKINGS.SHARE_JUDGMENT_PLURAL' : 'RANKINGS.SHARE_FILING_PLURAL';
action = this.translatePipe.transform(action);
// add together top 10 for amount
let amount = this.listData.slice(0, 10).reduce((a, b) => {
return a + b[this.dataProperty.value];
}, 0);
// format number based on if it's a rate or not
amount = this.isRateValue() ?
this.cappedRateValue(amount / 10) : this.decimal.transform(amount);
// add average text if the number is an average rate
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_AVERAGE', { amount }) : amount;
return this.translatePipe.transform('RANKINGS.SHARE_DEFAULT', {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
action,
amount,
year: this.rankings.year,
link: this.platform.currentUrl()
});
}
/**
* Creates the tweet string based on the selected location
*/
private getLocationTweet() {
const location = this.listData[this.selectedIndex];
// if there is no location, exit early
if (!location) { return; }
let amount = this.isRateValue() ?
this.cappedRateValue(location[this.dataProperty.value]) :
this.decimal.transform(location[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const category = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_RATE') :
this.translatePipe.transform('RANKINGS.SHARE_TOTAL');
const ranking =
`${this.selectedIndex + 1}${this.rankings.ordinalSuffix(
this.selectedIndex + 1, this.isRateValue()
)}`;
// Needs to be split because of gender in Spanish
const translationKey = this.isRateValue() ?
'RANKINGS.SHARE_SELECTION_RATE' : 'RANKINGS.SHARE_SELECTION_TOTAL';
return this.translatePipe.transform(translationKey, {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
region: this.region,
year: this.rankings.year,
amount,
area: location.name,
action,
ranking,
category,
link: this.platform.currentUrl()
});
}
/**
* Creates a tweet for when there is a region selected, but no location
*/
private getRegionTweet() {
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const state = this.rankings.stateData.find(s => s.name === this.region);
if (state[this.dataProperty.value] < 0) {
return this.getFallbackTweet();
}
let amount = this.isRateValue() ?
this.cappedRateValue(state[this.dataProperty.value]) :
this.decimal.transform(state[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const areaType = this.translatePipe.transform(this.areaType.langKey).toLowerCase();
const hadAmount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_HAD_RATE', { areaType }) :
this.translatePipe.transform('RANKINGS.SHARE_HAD_COUNT', { areaType });
const topArea = this.listData.length > 0 ?
this.translatePipe.transform(
'RANKINGS.SHARE_REGION_TOP_AREA', { topArea: this.listData[0].name, hadAmount }
) : '';
// Translate region amount (since possible that it's unavailable)
const regionParams = {
year: this.rankings.year, region: this.region, amount, action
};
const regionAmount = (amount || state[this.dataProperty.value] === 0) ?
this.translatePipe.transform('RANKINGS.SHARE_REGION_AMOUNT', regionParams) :
this.translatePipe.transform('RANKINGS.SHARE_REGION_UNAVAILABLE', regionParams);
return this.translatePipe.transform('RANKINGS.SHARE_REGION_NO_SELECTION', {
regionAmount, topArea, link: this.platform.currentUrl()
});
}
/**
* Creates fallback tweet for states where data is unavailable
*/
private getFallbackTweet() {
return this.translatePipe.transform('RANKINGS.SHARE_FALLBACK', {
link: this.platform.currentUrl()
});
}
/** Sets the focus on the first button in the rankings panel */
private focusPanel() {
if (!this.rankingPanel || !this.rankingPanel.el) { return; }
// use a timeout, the buttons are not immediately available
setTimeout(() => {
const buttons = this.rankingPanel.el.nativeElement.getElementsByTagName('button');
if (buttons.length) {
buttons[0].focus();
}
}, 500);
}
/** Scrolls to an item in the list and optionally sets focus */
private scrollToIndex(index: number, focus = false) {
if (!this.rankingList || !this.rankingList.el) { return; }
// set focus back to the list item
const listItems = this.rankingList.el.nativeElement.getElementsByTagName('button');
if (listItems.length > index) {
// timeout to allow item to expand first
if (focus) { listItems[index].focus(); }
}
setTimeout(() => { this.scroll.scrollTo(listItems[index]); }, 100);
}
/** Returns true if the data property is eviction judgements */
private isPropJudgments(): boolean {
return this.dataProperty.value.startsWith('e');
}
/** Returns true if all of the user selections are at their default values */
private isDefaultSelection(): boolean {
return this.region === 'United States' &&
!this.selectedIndex && this.selectedIndex !== 0;
}
/** Returns true if a location is selected */
private isLocationSelected(): boolean {
return (this.selectedIndex !== null && this.selectedIndex !== undefined);
}
/** Returns true if the data property is a rate instead of a count */
private isRateValue(): boolean {
return this.dataProperty.value.endsWith('Rate');
}
/** Returns the formatted rate number, with >100 instead of values over */
private cappedRateValue(val: number): string {
return val > 100 ? '>100' : this.decimal.transform(val, '1.1-2');
}
/**
* Update the list data based on the selected UI properties
*/
private updateEvictionList() {
if (this.canRetrieveData) {
this.listData = this.rankings.getFilteredEvictions(
this.region, this.areaType.value, this.dataProperty.value
);
this.truncatedList = this.listData.slice(0, this.topCount);
// TODO: find highest value including CIs, remove 1.1
this.dataMax = Math.max.apply(
Math, this.truncatedList.map(l => {
return !isNaN(l[this.dataProperty.value]) ? l[this.dataProperty.value] : 0;
})
) * 1.1;
this.updateTweet();
this.changeDetectorRef.detectChanges();
} else {
console.warn('data is not ready yet');
}
}
private debug(...args) {
// tslint:disable-next-line
environment.production || !this._debug ? null : console.debug.apply(console, [ 'evictions: ', ...args]);
}
}
| {
this.setCurrentLocation(this.selectedIndex - 1);
} | conditional_block |
evictions.component.ts | import {
Component, OnInit, Input, OnDestroy, ViewChild, Inject, AfterViewInit, ChangeDetectorRef,
HostListener, Output, EventEmitter
} from '@angular/core';
import { Router, ActivatedRoute, ParamMap, RouterLink } from '@angular/router';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { DOCUMENT, DecimalPipe } from '@angular/common';
import { Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { ToastsManager, ToastOptions } from 'ng2-toastr';
import { environment } from '../../../../environments/environment';
import { RankingLocation } from '../../ranking-location';
import { RankingService } from '../../ranking.service';
import { ScrollService } from '../../../services/scroll.service';
import { LoadingService } from '../../../services/loading.service';
import { PlatformService } from '../../../services/platform.service';
import { AnalyticsService } from '../../../services/analytics.service';
import { RankingUiComponent } from '../../ranking-ui/ranking-ui.component';
import { RankingListComponent } from '../../ranking-list/ranking-list.component';
import { RankingPanelComponent } from '../../ranking-panel/ranking-panel.component';
@Component({
selector: 'app-evictions',
templateUrl: './evictions.component.html',
styleUrls: ['./evictions.component.scss']
})
export class EvictionsComponent implements OnInit, AfterViewInit, OnDestroy {
/** string representing the region */
@Input()
set region(regionValue) {
if (!regionValue) { return; }
if (regionValue !== this.store.region) {
this.debug('set region', regionValue, this.store.region);
this.store.region = regionValue;
this.updateEvictionList();
}
}
get region() { return this.store.region; }
/** ID representing the selected area type */
@Input()
set areaType(newType) {
if (!newType) { return; }
if ((!this.store.areaType || newType.value !== this.store.areaType.value) && newType) {
this.debug('set areaType', newType, this.store.areaType);
this.store.areaType = newType;
this.updateEvictionList();
this.trackAreaChange();
}
}
get areaType() { return this.store.areaType; }
/** object key representing the data property to sort by */
@Input()
set dataProperty(newProp) {
if (!newProp) { return; }
if ((!this.store.dataProperty || newProp.value !== this.store.dataProperty.value) && newProp) {
this.debug('set dataProp', newProp, this.store.dataProperty);
this.store.dataProperty = newProp;
this.updateEvictionList();
this.trackRankByChange();
}
}
get dataProperty() { return this.store.dataProperty; }
/** the index of the selected location for the data panel */
@Input()
set selectedIndex(value: number) {
const panelOpened = this.store.selectedIndex === null;
this.store.selectedIndex = value;
// location exists in the current list, set active and scroll to it
if (value !== null && value < this.topCount) { this.scrollToIndex(value); }
// if the panel is newly opened, focus
if (panelOpened) { this.focusPanel(); }
this.updateTweet();
}
get selectedIndex(): number { return this.store.selectedIndex; }
/** Reference to the ranking list component */
@ViewChild(RankingListComponent) rankingList: RankingListComponent;
/** Reference to the ranking panel component */
@ViewChild(RankingPanelComponent) rankingPanel: RankingPanelComponent;
/** tracks if the data has been loaded and parsed */
isDataReady = false;
/** A shortened version of `listData`, containing only the first `topCount` items */
truncatedList: Array<RankingLocation>;
/** Stores the maximum value in the truncated List */
dataMax = 1;
/** list of data for the current UI selections */
listData: Array<RankingLocation>; // Array of locations to show the rank list for
/** state for UI panel on mobile / tablet */
showUiPanel = false;
/** Boolean of whether to show scroll to top button */
showScrollButton = false;
/** number of items to show in the list */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex: null
};
/** returns if all of the required params are set to be able to fetch data */
get canRetrieveData(): boolean {
return this.canNavigate && this.isDataReady;
}
private get canNavigate(): boolean {
return this.region && this.areaType && this.dataProperty &&
this.areaType.hasOwnProperty('value') &&
this.dataProperty.hasOwnProperty('value');
}
private destroy: Subject<any> = new Subject();
private _debug = true;
constructor(
public rankings: RankingService,
public loader: LoadingService,
public platform: PlatformService,
private route: ActivatedRoute,
private router: Router,
private scroll: ScrollService,
private translate: TranslateService,
private analytics: AnalyticsService,
private translatePipe: TranslatePipe,
private decimal: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private toast: ToastsManager,
@Inject(DOCUMENT) private document: any
) {
this.store.areaType = this.rankings.areaTypes[0];
this.store.dataProperty = this.rankings.sortProps[0];
this.toast.onClickToast().subscribe(t => this.toast.dismissToast(t));
this.debug('init');
}
/** subscribe to when the rankings data is ready, show loading */
ngOnInit() {
this.rankings.isReady.takeUntil(this.destroy)
.subscribe((ready) => {
this.isDataReady = ready;
if (ready) {
this.updateEvictionList();
this.loader.end('evictions');
}
});
this.translate.onLangChange.subscribe((l) => {
this.currentLang = l.lang;
this.updateQueryParam('lang', l.lang);
this.updateTweet();
});
// set kiosk mode if kiosk url
this.kiosk = this.platform.nativeWindow.location.hostname.includes('kiosk');
}
/** load data once the view has been initialized */
ngAfterViewInit() {
this.loader.start('evictions');
this.rankings.loadEvictionsData();
// list takes a bit to render, so setup page scroll in a timeout instead
setTimeout(() => { this.setupPageScroll(); }, 500);
}
/** clear any subscriptions on destroy */
ngOnDestroy() {
this.rankings.setReady(false);
this.destroy.next();
this.destroy.complete();
}
/** Move to previous or next location with arrows, hide panel with escape */
@HostListener('keydown', ['$event']) onKeypress(e) {
if (this.selectedIndex === null) { return; }
if ((e.keyCode === 37 || e.keyCode === 39)) {
// left or right
const newValue = (e.keyCode === 37) ? this.selectedIndex - 1 : this.selectedIndex + 1;
this.setCurrentLocation(Math.min(Math.max(0, newValue), this.topCount));
}
if (e.keyCode === 27) {
// escape
this.onClose();
e.preventDefault();
}
}
/** Updates one of the query parameters and updates the route */
updateQueryParam(paramName: string, value: any) {
if (!this.canNavigate) { return; }
if (paramName === 'r' || paramName === 'a' || paramName === 'd') {
this.selectedIndex = null;
}
const params = this.getQueryParams();
params[paramName] = value;
this.router.navigate([ '/', 'evictions' ], { queryParams: params });
}
/** Update the route when the region changes */
onRegionChange(newRegion: string) {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
}
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
onDataPropertyChange(dataProp: { name: string, value: string }) {
if (this.dataProperty && dataProp.value === this.dataProperty.value) { return; }
this.updateQueryParam('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.showUnavailableToast();
return;
}
const value = (locationIndex || locationIndex === 0) ? locationIndex : null;
this.updateQueryParam('l', value);
}
/**
* Scrolls to the searched location if it exists in the list
* or switches to the corresponding area type for the location and activates
* the location
* @param location
*/
onSearchSelectLocation(e: { selection: RankingLocation, queryTerm: string } | null) {
let location: RankingLocation = null;
if (e.selection) { location = e.selection; }
if (location === null) { return this.setCurrentLocation(null); }
this.showUiPanel = false;
let listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
if (listIndex > -1) {
this.setCurrentLocation(listIndex);
} else {
// location doesn't exist in the list, update to full list and find the location
this.region = 'United States';
this.areaType = this.rankings.areaTypes.filter(t => t.value === location.areaType)[0];
this.updateEvictionList();
listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
this.setCurrentLocation(listIndex);
}
this.scrollToIndex(Math.min(99, listIndex));
this.trackSearchSelection(location, e.queryTerm);
}
/** handles the click on a specific location */
onClickLocation(index: number) {
this.setCurrentLocation(index);
this.trackLocationSelection(this.listData[index]);
}
/** Switch the selected location to the next one in the list */
onGoToNext() {
if (this.selectedIndex < this.listData.length - 1) {
this.setCurrentLocation(this.selectedIndex + 1);
}
}
/** Switch the selected location to the previous one in the list */
onGoToPrevious() {
if (this.selectedIndex > 0) {
this.setCurrentLocation(this.selectedIndex - 1);
}
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
onPanelLocationClick(rank: number) {
this.scrollToIndex(rank - 1);
}
/** Updates Twitter text for city rankings based on selections */
updateTweet() {
if (!this.canNavigate || !this.listData) { return ''; }
this.tweet = this.isDefaultSelection() ? this.getDefaultTweet() :
(this.isLocationSelected() ? this.getLocationTweet() : this.getRegionTweet());
this.debug('updated tweet - ', this.tweet);
}
scrollToTop() {
this.scroll.scrollTo(this.rankingList.el.nativeElement);
// set focus to an element at the top of the page for keyboard nav
const focusableEl = this.rankingList.el.nativeElement.querySelector('app-ranking-list button');
setTimeout(() => {
if (focusableEl.length) {
focusableEl[0].focus();
focusableEl[0].blur();
}
}, this.scroll.defaultDuration);
}
private isLocationInvalid(locationIndex: number) {
return locationIndex !== null && (
this.listData[locationIndex][this.dataProperty.value] < 0 ||
this.listData[locationIndex]['evictions'] < 0
);
}
/** Get location selected data for analytics tracking */
private getSelectedData(location: RankingLocation): any {
return {
locationSelected: location.displayName,
locatonSelectedLevel: this.rankings.areaTypes[location.areaType].langKey,
};
}
/** Gets the selected filters for analytics tracking */
private getSelectedFilters() {
return {
area: this.areaType.langKey,
rankBy: this.dataProperty.langKey,
region: this.region
};
}
private trackAreaChange() {
this.analytics.trackEvent('rankingsAreaSelection', this.getSelectedFilters());
}
private trackRankByChange() {
this.analytics.trackEvent('rankingsRankBySelection', this.getSelectedFilters());
}
/** Track when a location is selected */
private trackLocationSelection(location: RankingLocation, method = 'list') {
const selectedEvent: any = this.getSelectedData(location);
selectedEvent.locationFindingMethod = method;
this.analytics.trackEvent('locationSelection', selectedEvent);
}
/** Track when an option in search is selected. */
private trackSearchSelection(location: RankingLocation, term: string) {
this.trackLocationSelection(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), locationFindingMethod: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffset = 0;
this.scroll.verticalOffset$
.map(offset => offset > 600)
.distinctUntilChanged()
.subscribe(showButton => {
this.debug('show scroll to top button:', showButton);
this.showScrollButton = showButton;
});
}
/** Shows a toast message indicating the data is not available */
private showUnavailableToast() {
this.toast.error(
this.translatePipe.transform('RANKINGS.LOCATION_DATA_UNAVAILABLE'),
null,
{messageClass: 'ranking-error'}
);
}
/** gets the query parameters for the current view */
private getQueryParams() {
// this.selectedIndex
const params = {
r: this.region,
a: this.areaType.value,
d: this.dataProperty.value
};
if (this.translate.currentLang !== 'en') {
params['lang'] = this.translate.currentLang;
}
if (this.selectedIndex || this.selectedIndex === 0) {
params['l'] = this.selectedIndex;
}
return params;
}
/**
* Set default tweet parameters with the US and no location selected, has the
* following parameters:
* - areaType: selected area type
* - action: string representing if it was an eviction or filing
* - amount: the average of the top 10 if showing rates, otherwise the total of the top 10
* - year: year for the data
* - link: link to the view
*/
private getDefaultTweet(): string {
// action text
let action = this.isPropJudgments() ?
'RANKINGS.SHARE_JUDGMENT_PLURAL' : 'RANKINGS.SHARE_FILING_PLURAL';
action = this.translatePipe.transform(action);
// add together top 10 for amount
let amount = this.listData.slice(0, 10).reduce((a, b) => {
return a + b[this.dataProperty.value];
}, 0);
// format number based on if it's a rate or not
amount = this.isRateValue() ?
this.cappedRateValue(amount / 10) : this.decimal.transform(amount);
// add average text if the number is an average rate
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_AVERAGE', { amount }) : amount;
return this.translatePipe.transform('RANKINGS.SHARE_DEFAULT', {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
action,
amount,
year: this.rankings.year,
link: this.platform.currentUrl()
});
}
/**
* Creates the tweet string based on the selected location
*/
private getLocationTweet() {
const location = this.listData[this.selectedIndex];
// if there is no location, exit early
if (!location) { return; }
let amount = this.isRateValue() ?
this.cappedRateValue(location[this.dataProperty.value]) :
this.decimal.transform(location[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const category = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_RATE') :
this.translatePipe.transform('RANKINGS.SHARE_TOTAL');
const ranking =
`${this.selectedIndex + 1}${this.rankings.ordinalSuffix(
this.selectedIndex + 1, this.isRateValue()
)}`;
// Needs to be split because of gender in Spanish
const translationKey = this.isRateValue() ?
'RANKINGS.SHARE_SELECTION_RATE' : 'RANKINGS.SHARE_SELECTION_TOTAL';
return this.translatePipe.transform(translationKey, {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
region: this.region,
year: this.rankings.year,
amount,
area: location.name,
action,
ranking,
category,
link: this.platform.currentUrl()
});
}
/**
* Creates a tweet for when there is a region selected, but no location
*/
private getRegionTweet() {
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const state = this.rankings.stateData.find(s => s.name === this.region);
if (state[this.dataProperty.value] < 0) {
return this.getFallbackTweet();
}
let amount = this.isRateValue() ?
this.cappedRateValue(state[this.dataProperty.value]) :
this.decimal.transform(state[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const areaType = this.translatePipe.transform(this.areaType.langKey).toLowerCase();
const hadAmount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_HAD_RATE', { areaType }) :
this.translatePipe.transform('RANKINGS.SHARE_HAD_COUNT', { areaType });
const topArea = this.listData.length > 0 ?
this.translatePipe.transform(
'RANKINGS.SHARE_REGION_TOP_AREA', { topArea: this.listData[0].name, hadAmount }
) : '';
// Translate region amount (since possible that it's unavailable)
const regionParams = {
year: this.rankings.year, region: this.region, amount, action
};
const regionAmount = (amount || state[this.dataProperty.value] === 0) ?
this.translatePipe.transform('RANKINGS.SHARE_REGION_AMOUNT', regionParams) :
this.translatePipe.transform('RANKINGS.SHARE_REGION_UNAVAILABLE', regionParams);
return this.translatePipe.transform('RANKINGS.SHARE_REGION_NO_SELECTION', {
regionAmount, topArea, link: this.platform.currentUrl()
});
}
/**
* Creates fallback tweet for states where data is unavailable
*/
private getFallbackTweet() {
return this.translatePipe.transform('RANKINGS.SHARE_FALLBACK', {
link: this.platform.currentUrl()
});
}
/** Sets the focus on the first button in the rankings panel */
private focusPanel() {
if (!this.rankingPanel || !this.rankingPanel.el) { return; }
// use a timeout, the buttons are not immediately available
setTimeout(() => {
const buttons = this.rankingPanel.el.nativeElement.getElementsByTagName('button');
if (buttons.length) {
buttons[0].focus();
}
}, 500);
}
/** Scrolls to an item in the list and optionally sets focus */
private scrollToIndex(index: number, focus = false) {
if (!this.rankingList || !this.rankingList.el) { return; }
// set focus back to the list item
const listItems = this.rankingList.el.nativeElement.getElementsByTagName('button');
if (listItems.length > index) {
// timeout to allow item to expand first
if (focus) { listItems[index].focus(); }
}
setTimeout(() => { this.scroll.scrollTo(listItems[index]); }, 100);
}
/** Returns true if the data property is eviction judgements */
private isPropJudgments(): boolean {
return this.dataProperty.value.startsWith('e');
}
/** Returns true if all of the user selections are at their default values */
private isDefaultSelection(): boolean {
return this.region === 'United States' &&
!this.selectedIndex && this.selectedIndex !== 0;
}
/** Returns true if a location is selected */
private isLocationSelected(): boolean {
return (this.selectedIndex !== null && this.selectedIndex !== undefined);
}
/** Returns true if the data property is a rate instead of a count */
private isRateValue(): boolean {
return this.dataProperty.value.endsWith('Rate');
}
/** Returns the formatted rate number, with >100 instead of values over */
private cappedRateValue(val: number): string {
return val > 100 ? '>100' : this.decimal.transform(val, '1.1-2');
}
/**
* Update the list data based on the selected UI properties
*/
private updateEvictionList() {
if (this.canRetrieveData) {
this.listData = this.rankings.getFilteredEvictions(
this.region, this.areaType.value, this.dataProperty.value
);
this.truncatedList = this.listData.slice(0, this.topCount);
// TODO: find highest value including CIs, remove 1.1
this.dataMax = Math.max.apply(
Math, this.truncatedList.map(l => {
return !isNaN(l[this.dataProperty.value]) ? l[this.dataProperty.value] : 0;
})
) * 1.1;
this.updateTweet();
this.changeDetectorRef.detectChanges(); | } else {
console.warn('data is not ready yet');
}
}
private debug(...args) {
// tslint:disable-next-line
environment.production || !this._debug ? null : console.debug.apply(console, [ 'evictions: ', ...args]);
}
} | random_line_split | |
evictions.component.ts | import {
Component, OnInit, Input, OnDestroy, ViewChild, Inject, AfterViewInit, ChangeDetectorRef,
HostListener, Output, EventEmitter
} from '@angular/core';
import { Router, ActivatedRoute, ParamMap, RouterLink } from '@angular/router';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { DOCUMENT, DecimalPipe } from '@angular/common';
import { Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { ToastsManager, ToastOptions } from 'ng2-toastr';
import { environment } from '../../../../environments/environment';
import { RankingLocation } from '../../ranking-location';
import { RankingService } from '../../ranking.service';
import { ScrollService } from '../../../services/scroll.service';
import { LoadingService } from '../../../services/loading.service';
import { PlatformService } from '../../../services/platform.service';
import { AnalyticsService } from '../../../services/analytics.service';
import { RankingUiComponent } from '../../ranking-ui/ranking-ui.component';
import { RankingListComponent } from '../../ranking-list/ranking-list.component';
import { RankingPanelComponent } from '../../ranking-panel/ranking-panel.component';
@Component({
selector: 'app-evictions',
templateUrl: './evictions.component.html',
styleUrls: ['./evictions.component.scss']
})
export class EvictionsComponent implements OnInit, AfterViewInit, OnDestroy {
/** string representing the region */
@Input()
set region(regionValue) {
if (!regionValue) { return; }
if (regionValue !== this.store.region) {
this.debug('set region', regionValue, this.store.region);
this.store.region = regionValue;
this.updateEvictionList();
}
}
get region() { return this.store.region; }
/** ID representing the selected area type */
@Input()
set areaType(newType) {
if (!newType) { return; }
if ((!this.store.areaType || newType.value !== this.store.areaType.value) && newType) {
this.debug('set areaType', newType, this.store.areaType);
this.store.areaType = newType;
this.updateEvictionList();
this.trackAreaChange();
}
}
get areaType() { return this.store.areaType; }
/** object key representing the data property to sort by */
@Input()
set dataProperty(newProp) {
if (!newProp) { return; }
if ((!this.store.dataProperty || newProp.value !== this.store.dataProperty.value) && newProp) {
this.debug('set dataProp', newProp, this.store.dataProperty);
this.store.dataProperty = newProp;
this.updateEvictionList();
this.trackRankByChange();
}
}
get dataProperty() { return this.store.dataProperty; }
/** the index of the selected location for the data panel */
@Input()
set selectedIndex(value: number) {
const panelOpened = this.store.selectedIndex === null;
this.store.selectedIndex = value;
// location exists in the current list, set active and scroll to it
if (value !== null && value < this.topCount) { this.scrollToIndex(value); }
// if the panel is newly opened, focus
if (panelOpened) { this.focusPanel(); }
this.updateTweet();
}
get selectedIndex(): number { return this.store.selectedIndex; }
/** Reference to the ranking list component */
@ViewChild(RankingListComponent) rankingList: RankingListComponent;
/** Reference to the ranking panel component */
@ViewChild(RankingPanelComponent) rankingPanel: RankingPanelComponent;
/** tracks if the data has been loaded and parsed */
isDataReady = false;
/** A shortened version of `listData`, containing only the first `topCount` items */
truncatedList: Array<RankingLocation>;
/** Stores the maximum value in the truncated List */
dataMax = 1;
/** list of data for the current UI selections */
listData: Array<RankingLocation>; // Array of locations to show the rank list for
/** state for UI panel on mobile / tablet */
showUiPanel = false;
/** Boolean of whether to show scroll to top button */
showScrollButton = false;
/** number of items to show in the list */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex: null
};
/** returns if all of the required params are set to be able to fetch data */
get canRetrieveData(): boolean {
return this.canNavigate && this.isDataReady;
}
private get canNavigate(): boolean {
return this.region && this.areaType && this.dataProperty &&
this.areaType.hasOwnProperty('value') &&
this.dataProperty.hasOwnProperty('value');
}
private destroy: Subject<any> = new Subject();
private _debug = true;
constructor(
public rankings: RankingService,
public loader: LoadingService,
public platform: PlatformService,
private route: ActivatedRoute,
private router: Router,
private scroll: ScrollService,
private translate: TranslateService,
private analytics: AnalyticsService,
private translatePipe: TranslatePipe,
private decimal: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private toast: ToastsManager,
@Inject(DOCUMENT) private document: any
) {
this.store.areaType = this.rankings.areaTypes[0];
this.store.dataProperty = this.rankings.sortProps[0];
this.toast.onClickToast().subscribe(t => this.toast.dismissToast(t));
this.debug('init');
}
/** subscribe to when the rankings data is ready, show loading */
ngOnInit() {
this.rankings.isReady.takeUntil(this.destroy)
.subscribe((ready) => {
this.isDataReady = ready;
if (ready) {
this.updateEvictionList();
this.loader.end('evictions');
}
});
this.translate.onLangChange.subscribe((l) => {
this.currentLang = l.lang;
this.updateQueryParam('lang', l.lang);
this.updateTweet();
});
// set kiosk mode if kiosk url
this.kiosk = this.platform.nativeWindow.location.hostname.includes('kiosk');
}
/** load data once the view has been initialized */
ngAfterViewInit() {
this.loader.start('evictions');
this.rankings.loadEvictionsData();
// list takes a bit to render, so setup page scroll in a timeout instead
setTimeout(() => { this.setupPageScroll(); }, 500);
}
/** clear any subscriptions on destroy */
ngOnDestroy() {
this.rankings.setReady(false);
this.destroy.next();
this.destroy.complete();
}
/** Move to previous or next location with arrows, hide panel with escape */
@HostListener('keydown', ['$event']) onKeypress(e) {
if (this.selectedIndex === null) { return; }
if ((e.keyCode === 37 || e.keyCode === 39)) {
// left or right
const newValue = (e.keyCode === 37) ? this.selectedIndex - 1 : this.selectedIndex + 1;
this.setCurrentLocation(Math.min(Math.max(0, newValue), this.topCount));
}
if (e.keyCode === 27) {
// escape
this.onClose();
e.preventDefault();
}
}
/** Updates one of the query parameters and updates the route */
updateQueryParam(paramName: string, value: any) {
if (!this.canNavigate) { return; }
if (paramName === 'r' || paramName === 'a' || paramName === 'd') {
this.selectedIndex = null;
}
const params = this.getQueryParams();
params[paramName] = value;
this.router.navigate([ '/', 'evictions' ], { queryParams: params });
}
/** Update the route when the region changes */
onRegionChange(newRegion: string) {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
}
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
onDataPropertyChange(dataProp: { name: string, value: string }) {
if (this.dataProperty && dataProp.value === this.dataProperty.value) { return; }
this.updateQueryParam('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.showUnavailableToast();
return;
}
const value = (locationIndex || locationIndex === 0) ? locationIndex : null;
this.updateQueryParam('l', value);
}
/**
* Scrolls to the searched location if it exists in the list
* or switches to the corresponding area type for the location and activates
* the location
* @param location
*/
onSearchSelectLocation(e: { selection: RankingLocation, queryTerm: string } | null) {
let location: RankingLocation = null;
if (e.selection) { location = e.selection; }
if (location === null) { return this.setCurrentLocation(null); }
this.showUiPanel = false;
let listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
if (listIndex > -1) {
this.setCurrentLocation(listIndex);
} else {
// location doesn't exist in the list, update to full list and find the location
this.region = 'United States';
this.areaType = this.rankings.areaTypes.filter(t => t.value === location.areaType)[0];
this.updateEvictionList();
listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
this.setCurrentLocation(listIndex);
}
this.scrollToIndex(Math.min(99, listIndex));
this.trackSearchSelection(location, e.queryTerm);
}
/** handles the click on a specific location */
onClickLocation(index: number) {
this.setCurrentLocation(index);
this.trackLocationSelection(this.listData[index]);
}
/** Switch the selected location to the next one in the list */
onGoToNext() {
if (this.selectedIndex < this.listData.length - 1) {
this.setCurrentLocation(this.selectedIndex + 1);
}
}
/** Switch the selected location to the previous one in the list */
onGoToPrevious() {
if (this.selectedIndex > 0) {
this.setCurrentLocation(this.selectedIndex - 1);
}
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
onPanelLocationClick(rank: number) {
this.scrollToIndex(rank - 1);
}
/** Updates Twitter text for city rankings based on selections */
updateTweet() {
if (!this.canNavigate || !this.listData) { return ''; }
this.tweet = this.isDefaultSelection() ? this.getDefaultTweet() :
(this.isLocationSelected() ? this.getLocationTweet() : this.getRegionTweet());
this.debug('updated tweet - ', this.tweet);
}
scrollToTop() {
this.scroll.scrollTo(this.rankingList.el.nativeElement);
// set focus to an element at the top of the page for keyboard nav
const focusableEl = this.rankingList.el.nativeElement.querySelector('app-ranking-list button');
setTimeout(() => {
if (focusableEl.length) {
focusableEl[0].focus();
focusableEl[0].blur();
}
}, this.scroll.defaultDuration);
}
private isLocationInvalid(locationIndex: number) {
return locationIndex !== null && (
this.listData[locationIndex][this.dataProperty.value] < 0 ||
this.listData[locationIndex]['evictions'] < 0
);
}
/** Get location selected data for analytics tracking */
private getSelectedData(location: RankingLocation): any {
return {
locationSelected: location.displayName,
locatonSelectedLevel: this.rankings.areaTypes[location.areaType].langKey,
};
}
/** Gets the selected filters for analytics tracking */
private getSelectedFilters() {
return {
area: this.areaType.langKey,
rankBy: this.dataProperty.langKey,
region: this.region
};
}
private trackAreaChange() {
this.analytics.trackEvent('rankingsAreaSelection', this.getSelectedFilters());
}
private trackRankByChange() {
this.analytics.trackEvent('rankingsRankBySelection', this.getSelectedFilters());
}
/** Track when a location is selected */
private trackLocationSelection(location: RankingLocation, method = 'list') {
const selectedEvent: any = this.getSelectedData(location);
selectedEvent.locationFindingMethod = method;
this.analytics.trackEvent('locationSelection', selectedEvent);
}
/** Track when an option in search is selected. */
private trackSearchSelection(location: RankingLocation, term: string) {
this.trackLocationSelection(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), locationFindingMethod: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffset = 0;
this.scroll.verticalOffset$
.map(offset => offset > 600)
.distinctUntilChanged()
.subscribe(showButton => {
this.debug('show scroll to top button:', showButton);
this.showScrollButton = showButton;
});
}
/** Shows a toast message indicating the data is not available */
private showUnavailableToast() {
this.toast.error(
this.translatePipe.transform('RANKINGS.LOCATION_DATA_UNAVAILABLE'),
null,
{messageClass: 'ranking-error'}
);
}
/** gets the query parameters for the current view */
private getQueryParams() {
// this.selectedIndex
const params = {
r: this.region,
a: this.areaType.value,
d: this.dataProperty.value
};
if (this.translate.currentLang !== 'en') {
params['lang'] = this.translate.currentLang;
}
if (this.selectedIndex || this.selectedIndex === 0) {
params['l'] = this.selectedIndex;
}
return params;
}
/**
* Set default tweet parameters with the US and no location selected, has the
* following parameters:
* - areaType: selected area type
* - action: string representing if it was an eviction or filing
* - amount: the average of the top 10 if showing rates, otherwise the total of the top 10
* - year: year for the data
* - link: link to the view
*/
private getDefaultTweet(): string {
// action text
let action = this.isPropJudgments() ?
'RANKINGS.SHARE_JUDGMENT_PLURAL' : 'RANKINGS.SHARE_FILING_PLURAL';
action = this.translatePipe.transform(action);
// add together top 10 for amount
let amount = this.listData.slice(0, 10).reduce((a, b) => {
return a + b[this.dataProperty.value];
}, 0);
// format number based on if it's a rate or not
amount = this.isRateValue() ?
this.cappedRateValue(amount / 10) : this.decimal.transform(amount);
// add average text if the number is an average rate
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_AVERAGE', { amount }) : amount;
return this.translatePipe.transform('RANKINGS.SHARE_DEFAULT', {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
action,
amount,
year: this.rankings.year,
link: this.platform.currentUrl()
});
}
/**
* Creates the tweet string based on the selected location
*/
private getLocationTweet() {
const location = this.listData[this.selectedIndex];
// if there is no location, exit early
if (!location) { return; }
let amount = this.isRateValue() ?
this.cappedRateValue(location[this.dataProperty.value]) :
this.decimal.transform(location[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const category = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_RATE') :
this.translatePipe.transform('RANKINGS.SHARE_TOTAL');
const ranking =
`${this.selectedIndex + 1}${this.rankings.ordinalSuffix(
this.selectedIndex + 1, this.isRateValue()
)}`;
// Needs to be split because of gender in Spanish
const translationKey = this.isRateValue() ?
'RANKINGS.SHARE_SELECTION_RATE' : 'RANKINGS.SHARE_SELECTION_TOTAL';
return this.translatePipe.transform(translationKey, {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
region: this.region,
year: this.rankings.year,
amount,
area: location.name,
action,
ranking,
category,
link: this.platform.currentUrl()
});
}
/**
* Creates a tweet for when there is a region selected, but no location
*/
private | () {
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const state = this.rankings.stateData.find(s => s.name === this.region);
if (state[this.dataProperty.value] < 0) {
return this.getFallbackTweet();
}
let amount = this.isRateValue() ?
this.cappedRateValue(state[this.dataProperty.value]) :
this.decimal.transform(state[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const areaType = this.translatePipe.transform(this.areaType.langKey).toLowerCase();
const hadAmount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_HAD_RATE', { areaType }) :
this.translatePipe.transform('RANKINGS.SHARE_HAD_COUNT', { areaType });
const topArea = this.listData.length > 0 ?
this.translatePipe.transform(
'RANKINGS.SHARE_REGION_TOP_AREA', { topArea: this.listData[0].name, hadAmount }
) : '';
// Translate region amount (since possible that it's unavailable)
const regionParams = {
year: this.rankings.year, region: this.region, amount, action
};
const regionAmount = (amount || state[this.dataProperty.value] === 0) ?
this.translatePipe.transform('RANKINGS.SHARE_REGION_AMOUNT', regionParams) :
this.translatePipe.transform('RANKINGS.SHARE_REGION_UNAVAILABLE', regionParams);
return this.translatePipe.transform('RANKINGS.SHARE_REGION_NO_SELECTION', {
regionAmount, topArea, link: this.platform.currentUrl()
});
}
/**
* Creates fallback tweet for states where data is unavailable
*/
private getFallbackTweet() {
return this.translatePipe.transform('RANKINGS.SHARE_FALLBACK', {
link: this.platform.currentUrl()
});
}
/** Sets the focus on the first button in the rankings panel */
private focusPanel() {
if (!this.rankingPanel || !this.rankingPanel.el) { return; }
// use a timeout, the buttons are not immediately available
setTimeout(() => {
const buttons = this.rankingPanel.el.nativeElement.getElementsByTagName('button');
if (buttons.length) {
buttons[0].focus();
}
}, 500);
}
/** Scrolls to an item in the list and optionally sets focus */
private scrollToIndex(index: number, focus = false) {
if (!this.rankingList || !this.rankingList.el) { return; }
// set focus back to the list item
const listItems = this.rankingList.el.nativeElement.getElementsByTagName('button');
if (listItems.length > index) {
// timeout to allow item to expand first
if (focus) { listItems[index].focus(); }
}
setTimeout(() => { this.scroll.scrollTo(listItems[index]); }, 100);
}
/** Returns true if the data property is eviction judgements */
private isPropJudgments(): boolean {
return this.dataProperty.value.startsWith('e');
}
/** Returns true if all of the user selections are at their default values */
private isDefaultSelection(): boolean {
return this.region === 'United States' &&
!this.selectedIndex && this.selectedIndex !== 0;
}
/** Returns true if a location is selected */
private isLocationSelected(): boolean {
return (this.selectedIndex !== null && this.selectedIndex !== undefined);
}
/** Returns true if the data property is a rate instead of a count */
private isRateValue(): boolean {
return this.dataProperty.value.endsWith('Rate');
}
/** Returns the formatted rate number, with >100 instead of values over */
private cappedRateValue(val: number): string {
return val > 100 ? '>100' : this.decimal.transform(val, '1.1-2');
}
/**
* Update the list data based on the selected UI properties
*/
private updateEvictionList() {
if (this.canRetrieveData) {
this.listData = this.rankings.getFilteredEvictions(
this.region, this.areaType.value, this.dataProperty.value
);
this.truncatedList = this.listData.slice(0, this.topCount);
// TODO: find highest value including CIs, remove 1.1
this.dataMax = Math.max.apply(
Math, this.truncatedList.map(l => {
return !isNaN(l[this.dataProperty.value]) ? l[this.dataProperty.value] : 0;
})
) * 1.1;
this.updateTweet();
this.changeDetectorRef.detectChanges();
} else {
console.warn('data is not ready yet');
}
}
private debug(...args) {
// tslint:disable-next-line
environment.production || !this._debug ? null : console.debug.apply(console, [ 'evictions: ', ...args]);
}
}
| getRegionTweet | identifier_name |
evictions.component.ts | import {
Component, OnInit, Input, OnDestroy, ViewChild, Inject, AfterViewInit, ChangeDetectorRef,
HostListener, Output, EventEmitter
} from '@angular/core';
import { Router, ActivatedRoute, ParamMap, RouterLink } from '@angular/router';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { DOCUMENT, DecimalPipe } from '@angular/common';
import { Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { ToastsManager, ToastOptions } from 'ng2-toastr';
import { environment } from '../../../../environments/environment';
import { RankingLocation } from '../../ranking-location';
import { RankingService } from '../../ranking.service';
import { ScrollService } from '../../../services/scroll.service';
import { LoadingService } from '../../../services/loading.service';
import { PlatformService } from '../../../services/platform.service';
import { AnalyticsService } from '../../../services/analytics.service';
import { RankingUiComponent } from '../../ranking-ui/ranking-ui.component';
import { RankingListComponent } from '../../ranking-list/ranking-list.component';
import { RankingPanelComponent } from '../../ranking-panel/ranking-panel.component';
@Component({
selector: 'app-evictions',
templateUrl: './evictions.component.html',
styleUrls: ['./evictions.component.scss']
})
export class EvictionsComponent implements OnInit, AfterViewInit, OnDestroy {
/** string representing the region */
@Input()
set region(regionValue) {
if (!regionValue) { return; }
if (regionValue !== this.store.region) {
this.debug('set region', regionValue, this.store.region);
this.store.region = regionValue;
this.updateEvictionList();
}
}
get region() { return this.store.region; }
/** ID representing the selected area type */
@Input()
set areaType(newType) {
if (!newType) { return; }
if ((!this.store.areaType || newType.value !== this.store.areaType.value) && newType) {
this.debug('set areaType', newType, this.store.areaType);
this.store.areaType = newType;
this.updateEvictionList();
this.trackAreaChange();
}
}
get areaType() { return this.store.areaType; }
/** object key representing the data property to sort by */
@Input()
set dataProperty(newProp) {
if (!newProp) { return; }
if ((!this.store.dataProperty || newProp.value !== this.store.dataProperty.value) && newProp) {
this.debug('set dataProp', newProp, this.store.dataProperty);
this.store.dataProperty = newProp;
this.updateEvictionList();
this.trackRankByChange();
}
}
get dataProperty() { return this.store.dataProperty; }
/** the index of the selected location for the data panel */
@Input()
set selectedIndex(value: number) {
const panelOpened = this.store.selectedIndex === null;
this.store.selectedIndex = value;
// location exists in the current list, set active and scroll to it
if (value !== null && value < this.topCount) { this.scrollToIndex(value); }
// if the panel is newly opened, focus
if (panelOpened) { this.focusPanel(); }
this.updateTweet();
}
get selectedIndex(): number { return this.store.selectedIndex; }
/** Reference to the ranking list component */
@ViewChild(RankingListComponent) rankingList: RankingListComponent;
/** Reference to the ranking panel component */
@ViewChild(RankingPanelComponent) rankingPanel: RankingPanelComponent;
/** tracks if the data has been loaded and parsed */
isDataReady = false;
/** A shortened version of `listData`, containing only the first `topCount` items */
truncatedList: Array<RankingLocation>;
/** Stores the maximum value in the truncated List */
dataMax = 1;
/** list of data for the current UI selections */
listData: Array<RankingLocation>; // Array of locations to show the rank list for
/** state for UI panel on mobile / tablet */
showUiPanel = false;
/** Boolean of whether to show scroll to top button */
showScrollButton = false;
/** number of items to show in the list */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex: null
};
/** returns if all of the required params are set to be able to fetch data */
get canRetrieveData(): boolean {
return this.canNavigate && this.isDataReady;
}
private get canNavigate(): boolean {
return this.region && this.areaType && this.dataProperty &&
this.areaType.hasOwnProperty('value') &&
this.dataProperty.hasOwnProperty('value');
}
private destroy: Subject<any> = new Subject();
private _debug = true;
constructor(
public rankings: RankingService,
public loader: LoadingService,
public platform: PlatformService,
private route: ActivatedRoute,
private router: Router,
private scroll: ScrollService,
private translate: TranslateService,
private analytics: AnalyticsService,
private translatePipe: TranslatePipe,
private decimal: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private toast: ToastsManager,
@Inject(DOCUMENT) private document: any
) {
this.store.areaType = this.rankings.areaTypes[0];
this.store.dataProperty = this.rankings.sortProps[0];
this.toast.onClickToast().subscribe(t => this.toast.dismissToast(t));
this.debug('init');
}
/** subscribe to when the rankings data is ready, show loading */
ngOnInit() {
this.rankings.isReady.takeUntil(this.destroy)
.subscribe((ready) => {
this.isDataReady = ready;
if (ready) {
this.updateEvictionList();
this.loader.end('evictions');
}
});
this.translate.onLangChange.subscribe((l) => {
this.currentLang = l.lang;
this.updateQueryParam('lang', l.lang);
this.updateTweet();
});
// set kiosk mode if kiosk url
this.kiosk = this.platform.nativeWindow.location.hostname.includes('kiosk');
}
/** load data once the view has been initialized */
ngAfterViewInit() {
this.loader.start('evictions');
this.rankings.loadEvictionsData();
// list takes a bit to render, so setup page scroll in a timeout instead
setTimeout(() => { this.setupPageScroll(); }, 500);
}
/** clear any subscriptions on destroy */
ngOnDestroy() {
this.rankings.setReady(false);
this.destroy.next();
this.destroy.complete();
}
/** Move to previous or next location with arrows, hide panel with escape */
@HostListener('keydown', ['$event']) onKeypress(e) {
if (this.selectedIndex === null) { return; }
if ((e.keyCode === 37 || e.keyCode === 39)) {
// left or right
const newValue = (e.keyCode === 37) ? this.selectedIndex - 1 : this.selectedIndex + 1;
this.setCurrentLocation(Math.min(Math.max(0, newValue), this.topCount));
}
if (e.keyCode === 27) {
// escape
this.onClose();
e.preventDefault();
}
}
/** Updates one of the query parameters and updates the route */
updateQueryParam(paramName: string, value: any) {
if (!this.canNavigate) { return; }
if (paramName === 'r' || paramName === 'a' || paramName === 'd') {
this.selectedIndex = null;
}
const params = this.getQueryParams();
params[paramName] = value;
this.router.navigate([ '/', 'evictions' ], { queryParams: params });
}
/** Update the route when the region changes */
onRegionChange(newRegion: string) |
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
onDataPropertyChange(dataProp: { name: string, value: string }) {
if (this.dataProperty && dataProp.value === this.dataProperty.value) { return; }
this.updateQueryParam('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.showUnavailableToast();
return;
}
const value = (locationIndex || locationIndex === 0) ? locationIndex : null;
this.updateQueryParam('l', value);
}
/**
* Scrolls to the searched location if it exists in the list
* or switches to the corresponding area type for the location and activates
* the location
* @param location
*/
onSearchSelectLocation(e: { selection: RankingLocation, queryTerm: string } | null) {
let location: RankingLocation = null;
if (e.selection) { location = e.selection; }
if (location === null) { return this.setCurrentLocation(null); }
this.showUiPanel = false;
let listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
if (listIndex > -1) {
this.setCurrentLocation(listIndex);
} else {
// location doesn't exist in the list, update to full list and find the location
this.region = 'United States';
this.areaType = this.rankings.areaTypes.filter(t => t.value === location.areaType)[0];
this.updateEvictionList();
listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
this.setCurrentLocation(listIndex);
}
this.scrollToIndex(Math.min(99, listIndex));
this.trackSearchSelection(location, e.queryTerm);
}
/** handles the click on a specific location */
onClickLocation(index: number) {
this.setCurrentLocation(index);
this.trackLocationSelection(this.listData[index]);
}
/** Switch the selected location to the next one in the list */
onGoToNext() {
if (this.selectedIndex < this.listData.length - 1) {
this.setCurrentLocation(this.selectedIndex + 1);
}
}
/** Switch the selected location to the previous one in the list */
onGoToPrevious() {
if (this.selectedIndex > 0) {
this.setCurrentLocation(this.selectedIndex - 1);
}
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
onPanelLocationClick(rank: number) {
this.scrollToIndex(rank - 1);
}
/** Updates Twitter text for city rankings based on selections */
updateTweet() {
if (!this.canNavigate || !this.listData) { return ''; }
this.tweet = this.isDefaultSelection() ? this.getDefaultTweet() :
(this.isLocationSelected() ? this.getLocationTweet() : this.getRegionTweet());
this.debug('updated tweet - ', this.tweet);
}
scrollToTop() {
this.scroll.scrollTo(this.rankingList.el.nativeElement);
// set focus to an element at the top of the page for keyboard nav
const focusableEl = this.rankingList.el.nativeElement.querySelector('app-ranking-list button');
setTimeout(() => {
if (focusableEl.length) {
focusableEl[0].focus();
focusableEl[0].blur();
}
}, this.scroll.defaultDuration);
}
private isLocationInvalid(locationIndex: number) {
return locationIndex !== null && (
this.listData[locationIndex][this.dataProperty.value] < 0 ||
this.listData[locationIndex]['evictions'] < 0
);
}
/** Get location selected data for analytics tracking */
private getSelectedData(location: RankingLocation): any {
return {
locationSelected: location.displayName,
locatonSelectedLevel: this.rankings.areaTypes[location.areaType].langKey,
};
}
/** Gets the selected filters for analytics tracking */
private getSelectedFilters() {
return {
area: this.areaType.langKey,
rankBy: this.dataProperty.langKey,
region: this.region
};
}
private trackAreaChange() {
this.analytics.trackEvent('rankingsAreaSelection', this.getSelectedFilters());
}
private trackRankByChange() {
this.analytics.trackEvent('rankingsRankBySelection', this.getSelectedFilters());
}
/** Track when a location is selected */
private trackLocationSelection(location: RankingLocation, method = 'list') {
const selectedEvent: any = this.getSelectedData(location);
selectedEvent.locationFindingMethod = method;
this.analytics.trackEvent('locationSelection', selectedEvent);
}
/** Track when an option in search is selected. */
private trackSearchSelection(location: RankingLocation, term: string) {
this.trackLocationSelection(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), locationFindingMethod: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffset = 0;
this.scroll.verticalOffset$
.map(offset => offset > 600)
.distinctUntilChanged()
.subscribe(showButton => {
this.debug('show scroll to top button:', showButton);
this.showScrollButton = showButton;
});
}
/** Shows a toast message indicating the data is not available */
private showUnavailableToast() {
this.toast.error(
this.translatePipe.transform('RANKINGS.LOCATION_DATA_UNAVAILABLE'),
null,
{messageClass: 'ranking-error'}
);
}
/** gets the query parameters for the current view */
private getQueryParams() {
// this.selectedIndex
const params = {
r: this.region,
a: this.areaType.value,
d: this.dataProperty.value
};
if (this.translate.currentLang !== 'en') {
params['lang'] = this.translate.currentLang;
}
if (this.selectedIndex || this.selectedIndex === 0) {
params['l'] = this.selectedIndex;
}
return params;
}
/**
* Set default tweet parameters with the US and no location selected, has the
* following parameters:
* - areaType: selected area type
* - action: string representing if it was an eviction or filing
* - amount: the average of the top 10 if showing rates, otherwise the total of the top 10
* - year: year for the data
* - link: link to the view
*/
private getDefaultTweet(): string {
// action text
let action = this.isPropJudgments() ?
'RANKINGS.SHARE_JUDGMENT_PLURAL' : 'RANKINGS.SHARE_FILING_PLURAL';
action = this.translatePipe.transform(action);
// add together top 10 for amount
let amount = this.listData.slice(0, 10).reduce((a, b) => {
return a + b[this.dataProperty.value];
}, 0);
// format number based on if it's a rate or not
amount = this.isRateValue() ?
this.cappedRateValue(amount / 10) : this.decimal.transform(amount);
// add average text if the number is an average rate
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_AVERAGE', { amount }) : amount;
return this.translatePipe.transform('RANKINGS.SHARE_DEFAULT', {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
action,
amount,
year: this.rankings.year,
link: this.platform.currentUrl()
});
}
/**
* Creates the tweet string based on the selected location
*/
private getLocationTweet() {
const location = this.listData[this.selectedIndex];
// if there is no location, exit early
if (!location) { return; }
let amount = this.isRateValue() ?
this.cappedRateValue(location[this.dataProperty.value]) :
this.decimal.transform(location[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const category = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_RATE') :
this.translatePipe.transform('RANKINGS.SHARE_TOTAL');
const ranking =
`${this.selectedIndex + 1}${this.rankings.ordinalSuffix(
this.selectedIndex + 1, this.isRateValue()
)}`;
// Needs to be split because of gender in Spanish
const translationKey = this.isRateValue() ?
'RANKINGS.SHARE_SELECTION_RATE' : 'RANKINGS.SHARE_SELECTION_TOTAL';
return this.translatePipe.transform(translationKey, {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
region: this.region,
year: this.rankings.year,
amount,
area: location.name,
action,
ranking,
category,
link: this.platform.currentUrl()
});
}
/**
* Creates a tweet for when there is a region selected, but no location
*/
private getRegionTweet() {
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_JUDGMENT') :
this.translatePipe.transform('RANKINGS.SHARE_PASSIVE_FILING');
const state = this.rankings.stateData.find(s => s.name === this.region);
if (state[this.dataProperty.value] < 0) {
return this.getFallbackTweet();
}
let amount = this.isRateValue() ?
this.cappedRateValue(state[this.dataProperty.value]) :
this.decimal.transform(state[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const areaType = this.translatePipe.transform(this.areaType.langKey).toLowerCase();
const hadAmount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_HAD_RATE', { areaType }) :
this.translatePipe.transform('RANKINGS.SHARE_HAD_COUNT', { areaType });
const topArea = this.listData.length > 0 ?
this.translatePipe.transform(
'RANKINGS.SHARE_REGION_TOP_AREA', { topArea: this.listData[0].name, hadAmount }
) : '';
// Translate region amount (since possible that it's unavailable)
const regionParams = {
year: this.rankings.year, region: this.region, amount, action
};
const regionAmount = (amount || state[this.dataProperty.value] === 0) ?
this.translatePipe.transform('RANKINGS.SHARE_REGION_AMOUNT', regionParams) :
this.translatePipe.transform('RANKINGS.SHARE_REGION_UNAVAILABLE', regionParams);
return this.translatePipe.transform('RANKINGS.SHARE_REGION_NO_SELECTION', {
regionAmount, topArea, link: this.platform.currentUrl()
});
}
/**
* Creates fallback tweet for states where data is unavailable
*/
private getFallbackTweet() {
return this.translatePipe.transform('RANKINGS.SHARE_FALLBACK', {
link: this.platform.currentUrl()
});
}
/** Sets the focus on the first button in the rankings panel */
private focusPanel() {
if (!this.rankingPanel || !this.rankingPanel.el) { return; }
// use a timeout, the buttons are not immediately available
setTimeout(() => {
const buttons = this.rankingPanel.el.nativeElement.getElementsByTagName('button');
if (buttons.length) {
buttons[0].focus();
}
}, 500);
}
/** Scrolls to an item in the list and optionally sets focus */
private scrollToIndex(index: number, focus = false) {
if (!this.rankingList || !this.rankingList.el) { return; }
// set focus back to the list item
const listItems = this.rankingList.el.nativeElement.getElementsByTagName('button');
if (listItems.length > index) {
// timeout to allow item to expand first
if (focus) { listItems[index].focus(); }
}
setTimeout(() => { this.scroll.scrollTo(listItems[index]); }, 100);
}
/** Returns true if the data property is eviction judgements */
private isPropJudgments(): boolean {
return this.dataProperty.value.startsWith('e');
}
/** Returns true if all of the user selections are at their default values */
private isDefaultSelection(): boolean {
return this.region === 'United States' &&
!this.selectedIndex && this.selectedIndex !== 0;
}
/** Returns true if a location is selected */
private isLocationSelected(): boolean {
return (this.selectedIndex !== null && this.selectedIndex !== undefined);
}
/** Returns true if the data property is a rate instead of a count */
private isRateValue(): boolean {
return this.dataProperty.value.endsWith('Rate');
}
/** Returns the formatted rate number, with >100 instead of values over */
private cappedRateValue(val: number): string {
return val > 100 ? '>100' : this.decimal.transform(val, '1.1-2');
}
/**
* Update the list data based on the selected UI properties
*/
private updateEvictionList() {
if (this.canRetrieveData) {
this.listData = this.rankings.getFilteredEvictions(
this.region, this.areaType.value, this.dataProperty.value
);
this.truncatedList = this.listData.slice(0, this.topCount);
// TODO: find highest value including CIs, remove 1.1
this.dataMax = Math.max.apply(
Math, this.truncatedList.map(l => {
return !isNaN(l[this.dataProperty.value]) ? l[this.dataProperty.value] : 0;
})
) * 1.1;
this.updateTweet();
this.changeDetectorRef.detectChanges();
} else {
console.warn('data is not ready yet');
}
}
private debug(...args) {
// tslint:disable-next-line
environment.production || !this._debug ? null : console.debug.apply(console, [ 'evictions: ', ...args]);
}
}
| {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
} | identifier_body |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSource, Legend, LegendItem,
PreText, Slider, TextInput)
from bokeh.plotting import figure
xs = sy.Symbol('x') | expr = sy.exp(-xs)*sy.sin(xs)
def taylor(fx, xs, order, x_range=(0, 1), n=200):
x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, ty
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source)
p.background_fill_color = "lightgrey"
legend = Legend(location="top_right")
legend.items = [
LegendItem(label=value(f"{expr}"), renderers=[line_f]),
LegendItem(label=value(f"taylor({expr})"), renderers=[line_t]),
]
p.add_layout(legend)
def update():
try:
expr = sy.sympify(text.value, dict(x=xs))
except Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
legend.items[0].label = value(f"{expr}")
legend.items[1].label = value(f"taylor({expr})")
source.data = dict(x=x, fy=fy, ty=ty)
slider = Slider(start=1, end=20, value=1, step=1, title="Order")
slider.on_change('value', lambda attr, old, new: update())
text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', lambda attr, old, new: update())
errbox = PreText()
update()
inputs = column(text, slider, errbox, width=400)
curdoc().add_root(column(inputs, p)) | random_line_split | |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSource, Legend, LegendItem,
PreText, Slider, TextInput)
from bokeh.plotting import figure
xs = sy.Symbol('x')
expr = sy.exp(-xs)*sy.sin(xs)
def taylor(fx, xs, order, x_range=(0, 1), n=200):
x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
|
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, ty
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source)
p.background_fill_color = "lightgrey"
legend = Legend(location="top_right")
legend.items = [
LegendItem(label=value(f"{expr}"), renderers=[line_f]),
LegendItem(label=value(f"taylor({expr})"), renderers=[line_t]),
]
p.add_layout(legend)
def update():
try:
expr = sy.sympify(text.value, dict(x=xs))
except Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
legend.items[0].label = value(f"{expr}")
legend.items[1].label = value(f"taylor({expr})")
source.data = dict(x=x, fy=fy, ty=ty)
slider = Slider(start=1, end=20, value=1, step=1, title="Order")
slider.on_change('value', lambda attr, old, new: update())
text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', lambda attr, old, new: update())
errbox = PreText()
update()
inputs = column(text, slider, errbox, width=400)
curdoc().add_root(column(inputs, p))
| ty = np.zeros_like(x)
ty.fill(float(tx)) | conditional_block |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSource, Legend, LegendItem,
PreText, Slider, TextInput)
from bokeh.plotting import figure
xs = sy.Symbol('x')
expr = sy.exp(-xs)*sy.sin(xs)
def taylor(fx, xs, order, x_range=(0, 1), n=200):
|
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source)
p.background_fill_color = "lightgrey"
legend = Legend(location="top_right")
legend.items = [
LegendItem(label=value(f"{expr}"), renderers=[line_f]),
LegendItem(label=value(f"taylor({expr})"), renderers=[line_t]),
]
p.add_layout(legend)
def update():
try:
expr = sy.sympify(text.value, dict(x=xs))
except Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
legend.items[0].label = value(f"{expr}")
legend.items[1].label = value(f"taylor({expr})")
source.data = dict(x=x, fy=fy, ty=ty)
slider = Slider(start=1, end=20, value=1, step=1, title="Order")
slider.on_change('value', lambda attr, old, new: update())
text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', lambda attr, old, new: update())
errbox = PreText()
update()
inputs = column(text, slider, errbox, width=400)
curdoc().add_root(column(inputs, p))
| x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, ty | identifier_body |
taylor.py | ''' A taylor series visualization graph. This example demonstrates
the ability of Bokeh for inputted expressions to reflect on a chart.
'''
import numpy as np
import sympy as sy
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import (ColumnDataSource, Legend, LegendItem,
PreText, Slider, TextInput)
from bokeh.plotting import figure
xs = sy.Symbol('x')
expr = sy.exp(-xs)*sy.sin(xs)
def taylor(fx, xs, order, x_range=(0, 1), n=200):
x0, x1 = x_range
x = np.linspace(float(x0), float(x1), n)
fy = sy.lambdify(xs, fx, modules=['numpy'])(x)
tx = fx.series(xs, n=order).removeO()
if tx.is_Number:
ty = np.zeros_like(x)
ty.fill(float(tx))
else:
ty = sy.lambdify(xs, tx, modules=['numpy'])(x)
return x, fy, ty
source = ColumnDataSource(data=dict(x=[], fy=[], ty=[]))
p = figure(x_range=(-7,7), y_range=(-100, 200), width=800, height=400)
line_f = p.line(x="x", y="fy", line_color="navy", line_width=2, source=source)
line_t = p.line(x="x", y="ty", line_color="firebrick", line_width=2, source=source)
p.background_fill_color = "lightgrey"
legend = Legend(location="top_right")
legend.items = [
LegendItem(label=value(f"{expr}"), renderers=[line_f]),
LegendItem(label=value(f"taylor({expr})"), renderers=[line_t]),
]
p.add_layout(legend)
def | ():
try:
expr = sy.sympify(text.value, dict(x=xs))
except Exception as exception:
errbox.text = str(exception)
else:
errbox.text = ""
x, fy, ty = taylor(expr, xs, slider.value, (-2*sy.pi, 2*sy.pi), 200)
p.title.text = "Taylor (n=%d) expansion comparison for: %s" % (slider.value, expr)
legend.items[0].label = value(f"{expr}")
legend.items[1].label = value(f"taylor({expr})")
source.data = dict(x=x, fy=fy, ty=ty)
slider = Slider(start=1, end=20, value=1, step=1, title="Order")
slider.on_change('value', lambda attr, old, new: update())
text = TextInput(value=str(expr), title="Expression:")
text.on_change('value', lambda attr, old, new: update())
errbox = PreText()
update()
inputs = column(text, slider, errbox, width=400)
curdoc().add_root(column(inputs, p))
| update | identifier_name |
test-shift.js |
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
//var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
var e = connection.exchange();
var q = connection.queue('node-123ack-queue');
q.bind(e, 'ackmessage.*');
q.subscribe({ ack: true }, function (json) {
recvCount++;
puts('Got message ' + JSON.stringify(json));
if (recvCount == 1) {
puts('Got message 1.. waiting');
assert.equal('A', json.name);
setTimeout(function () {
puts('shift!');
q.shift();
}, 1000);
} else if (recvCount == 2) {
puts('got message 2');
assert.equal('B', json.name);
puts('closing connection');
connection.end();
} else {
throw new Error('Too many message!');
}
})
.addCallback(function () {
puts("publishing 2 json messages");
e.publish('ackmessage.json1', { name: 'A' });
e.publish('ackmessage.json2', { name: 'B' });
});
});
process.addListener('exit', function () {
assert.equal(2, recvCount);
}); | require('./harness'); | random_line_split | |
test-shift.js | require('./harness');
var recvCount = 0;
var body = "hello world";
connection.addListener('ready', function () {
puts("connected to " + connection.serverProperties.product);
//var e = connection.exchange('node-ack-fanout', {type: 'fanout'});
var e = connection.exchange();
var q = connection.queue('node-123ack-queue');
q.bind(e, 'ackmessage.*');
q.subscribe({ ack: true }, function (json) {
recvCount++;
puts('Got message ' + JSON.stringify(json));
if (recvCount == 1) {
puts('Got message 1.. waiting');
assert.equal('A', json.name);
setTimeout(function () {
puts('shift!');
q.shift();
}, 1000);
} else if (recvCount == 2) | else {
throw new Error('Too many message!');
}
})
.addCallback(function () {
puts("publishing 2 json messages");
e.publish('ackmessage.json1', { name: 'A' });
e.publish('ackmessage.json2', { name: 'B' });
});
});
process.addListener('exit', function () {
assert.equal(2, recvCount);
});
| {
puts('got message 2');
assert.equal('B', json.name);
puts('closing connection');
connection.end();
} | conditional_block |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.conf')
if os.path.exists(auth_conf):
cf = ConfigParser.ConfigParser()
cf.read(auth_conf)
self.user = cf.get("auth", "user")
self.passwd = cf.get("auth", "passwd")
else:
self.user = ''
self.passwd = ''
def get_session(self):
s = requests.Session()
s.auth = (self.user, self.passwd)
r = s.get(self.auth_url)
if r.status_code != 200:
print("authentication failed. status_code: " + r.status_code)
return requests.Session()
else:
print("authentication succeed")
return s
class Repo:
"""GitHub Repository"""
def __init__(self):
self.auth_url = 'https://api.github.com'
def get_commits(self, s, owner, repo, nums=30):
url = '/'.join([self.auth_url, 'repos', owner, repo, 'commits'])
commits = s.get(url)
if commits.status_code == 200:
return commits.json()
def get_commit_info(self, s, commit_json):
commit_info = {}
# url for get_commit_diff
commit_info['diff_url'] = commit_json['url']
commit_info['diff'] = self.get_commit_diff(s, commit_info['diff_url'])
commit_info['html_url'] = commit_json['html_url']
commit_info['sha'] = commit_json['sha']
commit = commit_json['commit']
commit_info['url'] = commit['url']
author = {}
author['name'] = commit['author']['name']
author['email'] = commit['author']['email']
commit_info['author'] = author
commit_info['updated'] = commit['author']['date']
commit_info['message'] = commit['message']
return commit_info
def get_commit_diff(self, s, commit_url):
diff_headers = {'Accept': 'application/vnd.github.diff'}
commit_diff = s.get(commit_url, headers=diff_headers)
if commit_diff.status_code == 200:
commit_diff_txt = commit_diff.text
return commit_diff_txt
else:
return ''
def get_repo_info(self, s, owner, repo):
url = '/'.join([self.auth_url, 'repos', owner, repo])
repo_json = s.get(url).json()
repo_info = {}
repo_info['description'] = repo_json['description']
repo_info['full_name'] = repo_json['full_name']
repo_info['html_url'] = repo_json['html_url']
repo_info['updated_at'] = repo_json['updated_at']
repo_info['author'] = self.get_author(s, owner)
return repo_info
def get_author(self, s, owner):
url = '/'.join([self.auth_url, 'users', owner])
author_raw = s.get(url)
if author_raw.status_code != 200:
return None
author_json = author_raw.json()
author_info = {}
author_info['name'] = owner
author_info['email'] = author_json['email']
return author_info
def get_commits_info(self, s, owner, repo):
commits_json = self.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = self.get_commit_info(s, commit_json)
commits_info.append(commit_info)
return commits_info
class GitHubRSS:
"""GitHub RSS"""
def __init__(self):
self.atom = True
def init_fg(self, repo_info):
|
def add_entry(self, fg, commit_info):
fe = fg.add_entry()
fe.title(commit_info['message'])
fe.link(href=commit_info['html_url'])
id_prefix = 'tag:github.com,2008:Grit::Commit/'
entry_id = id_prefix + commit_info['sha']
fe.id(entry_id)
fe.author(commit_info['author'])
fe.published(commit_info['updated'])
fe.updated(commit_info['updated'])
fe.content(commit_info['diff'])
return fg
def gen_atom(self, fg, atom_fn='atom.xml'):
fg.atom_file(atom_fn)
if __name__ == "__main__":
# auth with GitHub username and password
user = raw_input('Enter your GitHub username: ')
passwd = getpass.getpass()
g_commit = GitHubCommit(user, passwd)
s = requests.Session()
s.auth = (g_commit.user, g_commit.passwd)
r = s.get(g_commit.auth_url)
if r.status_code == 401:
print("Unauthorized. Wrong username or password!")
sys.exit("Exit for Unauthorized status")
owner = 'billryan'
repo = 'algorithm-exercise'
repo_info = g_commit.get_repo_info(s, owner, repo)
commits_json = g_commit.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = g_commit.get_commit_info(s, commit_json)
commits_info.append(commit_info)
# generate rss
rss = GitHubRSS()
fg_repo = rss.init_fg(repo_info)
for commit_info in commits_info:
rss.add_entry(fg_repo, commit_info)
rss.gen_atom(fg_repo, '/tmp/test/atom_test.xml')
| fg = FeedGenerator()
title = 'Recent commits to ' + repo_info['full_name']
fg.title(title)
fg.link(href=repo_info['html_url'])
fg.updated(repo_info['updated_at'])
fg.id(repo_info['html_url'])
fg.author(repo_info['author'])
return fg | identifier_body |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.conf')
if os.path.exists(auth_conf):
cf = ConfigParser.ConfigParser()
cf.read(auth_conf)
self.user = cf.get("auth", "user")
self.passwd = cf.get("auth", "passwd")
else:
self.user = ''
self.passwd = ''
def | (self):
s = requests.Session()
s.auth = (self.user, self.passwd)
r = s.get(self.auth_url)
if r.status_code != 200:
print("authentication failed. status_code: " + r.status_code)
return requests.Session()
else:
print("authentication succeed")
return s
class Repo:
"""GitHub Repository"""
def __init__(self):
self.auth_url = 'https://api.github.com'
def get_commits(self, s, owner, repo, nums=30):
url = '/'.join([self.auth_url, 'repos', owner, repo, 'commits'])
commits = s.get(url)
if commits.status_code == 200:
return commits.json()
def get_commit_info(self, s, commit_json):
commit_info = {}
# url for get_commit_diff
commit_info['diff_url'] = commit_json['url']
commit_info['diff'] = self.get_commit_diff(s, commit_info['diff_url'])
commit_info['html_url'] = commit_json['html_url']
commit_info['sha'] = commit_json['sha']
commit = commit_json['commit']
commit_info['url'] = commit['url']
author = {}
author['name'] = commit['author']['name']
author['email'] = commit['author']['email']
commit_info['author'] = author
commit_info['updated'] = commit['author']['date']
commit_info['message'] = commit['message']
return commit_info
def get_commit_diff(self, s, commit_url):
diff_headers = {'Accept': 'application/vnd.github.diff'}
commit_diff = s.get(commit_url, headers=diff_headers)
if commit_diff.status_code == 200:
commit_diff_txt = commit_diff.text
return commit_diff_txt
else:
return ''
def get_repo_info(self, s, owner, repo):
url = '/'.join([self.auth_url, 'repos', owner, repo])
repo_json = s.get(url).json()
repo_info = {}
repo_info['description'] = repo_json['description']
repo_info['full_name'] = repo_json['full_name']
repo_info['html_url'] = repo_json['html_url']
repo_info['updated_at'] = repo_json['updated_at']
repo_info['author'] = self.get_author(s, owner)
return repo_info
def get_author(self, s, owner):
url = '/'.join([self.auth_url, 'users', owner])
author_raw = s.get(url)
if author_raw.status_code != 200:
return None
author_json = author_raw.json()
author_info = {}
author_info['name'] = owner
author_info['email'] = author_json['email']
return author_info
def get_commits_info(self, s, owner, repo):
commits_json = self.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = self.get_commit_info(s, commit_json)
commits_info.append(commit_info)
return commits_info
class GitHubRSS:
"""GitHub RSS"""
def __init__(self):
self.atom = True
def init_fg(self, repo_info):
fg = FeedGenerator()
title = 'Recent commits to ' + repo_info['full_name']
fg.title(title)
fg.link(href=repo_info['html_url'])
fg.updated(repo_info['updated_at'])
fg.id(repo_info['html_url'])
fg.author(repo_info['author'])
return fg
def add_entry(self, fg, commit_info):
fe = fg.add_entry()
fe.title(commit_info['message'])
fe.link(href=commit_info['html_url'])
id_prefix = 'tag:github.com,2008:Grit::Commit/'
entry_id = id_prefix + commit_info['sha']
fe.id(entry_id)
fe.author(commit_info['author'])
fe.published(commit_info['updated'])
fe.updated(commit_info['updated'])
fe.content(commit_info['diff'])
return fg
def gen_atom(self, fg, atom_fn='atom.xml'):
fg.atom_file(atom_fn)
if __name__ == "__main__":
# auth with GitHub username and password
user = raw_input('Enter your GitHub username: ')
passwd = getpass.getpass()
g_commit = GitHubCommit(user, passwd)
s = requests.Session()
s.auth = (g_commit.user, g_commit.passwd)
r = s.get(g_commit.auth_url)
if r.status_code == 401:
print("Unauthorized. Wrong username or password!")
sys.exit("Exit for Unauthorized status")
owner = 'billryan'
repo = 'algorithm-exercise'
repo_info = g_commit.get_repo_info(s, owner, repo)
commits_json = g_commit.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = g_commit.get_commit_info(s, commit_json)
commits_info.append(commit_info)
# generate rss
rss = GitHubRSS()
fg_repo = rss.init_fg(repo_info)
for commit_info in commits_info:
rss.add_entry(fg_repo, commit_info)
rss.gen_atom(fg_repo, '/tmp/test/atom_test.xml')
| get_session | identifier_name |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.conf')
if os.path.exists(auth_conf):
cf = ConfigParser.ConfigParser()
cf.read(auth_conf)
self.user = cf.get("auth", "user")
self.passwd = cf.get("auth", "passwd")
else:
self.user = ''
self.passwd = ''
def get_session(self):
s = requests.Session()
s.auth = (self.user, self.passwd)
r = s.get(self.auth_url)
if r.status_code != 200:
print("authentication failed. status_code: " + r.status_code)
return requests.Session()
else:
print("authentication succeed")
return s
class Repo:
"""GitHub Repository"""
def __init__(self):
self.auth_url = 'https://api.github.com'
def get_commits(self, s, owner, repo, nums=30):
url = '/'.join([self.auth_url, 'repos', owner, repo, 'commits'])
commits = s.get(url)
if commits.status_code == 200:
return commits.json()
def get_commit_info(self, s, commit_json):
commit_info = {}
# url for get_commit_diff
commit_info['diff_url'] = commit_json['url']
commit_info['diff'] = self.get_commit_diff(s, commit_info['diff_url'])
commit_info['html_url'] = commit_json['html_url']
commit_info['sha'] = commit_json['sha']
commit = commit_json['commit']
commit_info['url'] = commit['url']
author = {}
author['name'] = commit['author']['name']
author['email'] = commit['author']['email']
commit_info['author'] = author
commit_info['updated'] = commit['author']['date']
commit_info['message'] = commit['message']
return commit_info
def get_commit_diff(self, s, commit_url):
diff_headers = {'Accept': 'application/vnd.github.diff'}
commit_diff = s.get(commit_url, headers=diff_headers)
if commit_diff.status_code == 200:
commit_diff_txt = commit_diff.text
return commit_diff_txt
else:
return ''
def get_repo_info(self, s, owner, repo):
url = '/'.join([self.auth_url, 'repos', owner, repo])
repo_json = s.get(url).json()
repo_info = {}
repo_info['description'] = repo_json['description']
repo_info['full_name'] = repo_json['full_name']
repo_info['html_url'] = repo_json['html_url']
repo_info['updated_at'] = repo_json['updated_at']
repo_info['author'] = self.get_author(s, owner)
return repo_info
def get_author(self, s, owner):
url = '/'.join([self.auth_url, 'users', owner])
author_raw = s.get(url)
if author_raw.status_code != 200:
return None
author_json = author_raw.json()
author_info = {}
author_info['name'] = owner
author_info['email'] = author_json['email']
return author_info
def get_commits_info(self, s, owner, repo):
commits_json = self.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = self.get_commit_info(s, commit_json)
commits_info.append(commit_info)
return commits_info
class GitHubRSS:
"""GitHub RSS"""
def __init__(self):
self.atom = True
def init_fg(self, repo_info):
fg = FeedGenerator()
title = 'Recent commits to ' + repo_info['full_name']
fg.title(title)
fg.link(href=repo_info['html_url'])
fg.updated(repo_info['updated_at'])
fg.id(repo_info['html_url'])
fg.author(repo_info['author'])
return fg
def add_entry(self, fg, commit_info):
fe = fg.add_entry()
fe.title(commit_info['message'])
fe.link(href=commit_info['html_url'])
id_prefix = 'tag:github.com,2008:Grit::Commit/'
entry_id = id_prefix + commit_info['sha']
fe.id(entry_id)
fe.author(commit_info['author'])
fe.published(commit_info['updated'])
fe.updated(commit_info['updated'])
fe.content(commit_info['diff'])
return fg
def gen_atom(self, fg, atom_fn='atom.xml'):
fg.atom_file(atom_fn)
if __name__ == "__main__":
# auth with GitHub username and password
user = raw_input('Enter your GitHub username: ')
passwd = getpass.getpass()
g_commit = GitHubCommit(user, passwd)
s = requests.Session()
s.auth = (g_commit.user, g_commit.passwd)
r = s.get(g_commit.auth_url)
if r.status_code == 401:
print("Unauthorized. Wrong username or password!")
sys.exit("Exit for Unauthorized status")
owner = 'billryan'
repo = 'algorithm-exercise'
repo_info = g_commit.get_repo_info(s, owner, repo)
commits_json = g_commit.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = g_commit.get_commit_info(s, commit_json)
commits_info.append(commit_info)
# generate rss
rss = GitHubRSS()
fg_repo = rss.init_fg(repo_info)
for commit_info in commits_info:
|
rss.gen_atom(fg_repo, '/tmp/test/atom_test.xml')
| rss.add_entry(fg_repo, commit_info) | conditional_block |
gh.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import getpass
import requests
import ConfigParser
BASE_DIR = os.path.dirname(__file__)
class Auth:
"""GitHub API Auth"""
def __init__(self):
self.auth_url = 'https://api.github.com'
auth_conf = os.path.join(BASE_DIR, 'auth.conf')
if os.path.exists(auth_conf):
cf = ConfigParser.ConfigParser()
cf.read(auth_conf)
self.user = cf.get("auth", "user")
self.passwd = cf.get("auth", "passwd")
else:
self.user = ''
self.passwd = ''
def get_session(self):
s = requests.Session()
s.auth = (self.user, self.passwd)
r = s.get(self.auth_url)
if r.status_code != 200:
print("authentication failed. status_code: " + r.status_code)
return requests.Session()
else:
print("authentication succeed")
return s
class Repo:
"""GitHub Repository"""
def __init__(self):
self.auth_url = 'https://api.github.com'
def get_commits(self, s, owner, repo, nums=30):
url = '/'.join([self.auth_url, 'repos', owner, repo, 'commits'])
commits = s.get(url)
if commits.status_code == 200:
return commits.json()
def get_commit_info(self, s, commit_json):
commit_info = {}
# url for get_commit_diff
commit_info['diff_url'] = commit_json['url']
commit_info['diff'] = self.get_commit_diff(s, commit_info['diff_url'])
commit_info['html_url'] = commit_json['html_url']
commit_info['sha'] = commit_json['sha']
commit = commit_json['commit']
commit_info['url'] = commit['url']
author = {}
author['name'] = commit['author']['name']
author['email'] = commit['author']['email']
commit_info['author'] = author
commit_info['updated'] = commit['author']['date']
commit_info['message'] = commit['message']
return commit_info
| def get_commit_diff(self, s, commit_url):
diff_headers = {'Accept': 'application/vnd.github.diff'}
commit_diff = s.get(commit_url, headers=diff_headers)
if commit_diff.status_code == 200:
commit_diff_txt = commit_diff.text
return commit_diff_txt
else:
return ''
def get_repo_info(self, s, owner, repo):
url = '/'.join([self.auth_url, 'repos', owner, repo])
repo_json = s.get(url).json()
repo_info = {}
repo_info['description'] = repo_json['description']
repo_info['full_name'] = repo_json['full_name']
repo_info['html_url'] = repo_json['html_url']
repo_info['updated_at'] = repo_json['updated_at']
repo_info['author'] = self.get_author(s, owner)
return repo_info
def get_author(self, s, owner):
url = '/'.join([self.auth_url, 'users', owner])
author_raw = s.get(url)
if author_raw.status_code != 200:
return None
author_json = author_raw.json()
author_info = {}
author_info['name'] = owner
author_info['email'] = author_json['email']
return author_info
def get_commits_info(self, s, owner, repo):
commits_json = self.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = self.get_commit_info(s, commit_json)
commits_info.append(commit_info)
return commits_info
class GitHubRSS:
"""GitHub RSS"""
def __init__(self):
self.atom = True
def init_fg(self, repo_info):
fg = FeedGenerator()
title = 'Recent commits to ' + repo_info['full_name']
fg.title(title)
fg.link(href=repo_info['html_url'])
fg.updated(repo_info['updated_at'])
fg.id(repo_info['html_url'])
fg.author(repo_info['author'])
return fg
def add_entry(self, fg, commit_info):
fe = fg.add_entry()
fe.title(commit_info['message'])
fe.link(href=commit_info['html_url'])
id_prefix = 'tag:github.com,2008:Grit::Commit/'
entry_id = id_prefix + commit_info['sha']
fe.id(entry_id)
fe.author(commit_info['author'])
fe.published(commit_info['updated'])
fe.updated(commit_info['updated'])
fe.content(commit_info['diff'])
return fg
def gen_atom(self, fg, atom_fn='atom.xml'):
fg.atom_file(atom_fn)
if __name__ == "__main__":
# auth with GitHub username and password
user = raw_input('Enter your GitHub username: ')
passwd = getpass.getpass()
g_commit = GitHubCommit(user, passwd)
s = requests.Session()
s.auth = (g_commit.user, g_commit.passwd)
r = s.get(g_commit.auth_url)
if r.status_code == 401:
print("Unauthorized. Wrong username or password!")
sys.exit("Exit for Unauthorized status")
owner = 'billryan'
repo = 'algorithm-exercise'
repo_info = g_commit.get_repo_info(s, owner, repo)
commits_json = g_commit.get_commits(s, owner, repo)
commits_info = []
for commit_json in commits_json:
commit_info = g_commit.get_commit_info(s, commit_json)
commits_info.append(commit_info)
# generate rss
rss = GitHubRSS()
fg_repo = rss.init_fg(repo_info)
for commit_info in commits_info:
rss.add_entry(fg_repo, commit_info)
rss.gen_atom(fg_repo, '/tmp/test/atom_test.xml') | random_line_split | |
treeitems.py | import logging
from argos.external import six
from argos.utils.cls import check_class, check_is_a_string
logger = logging.getLogger(__name__)
class BaseTreeItem(object):
""" Base class for storing item data in a tree form. Each tree item represents a row
in the BaseTreeModel (QAbstractItemModel).
The tree items have no notion of which field is stored in which column. This is implemented
in BaseTreeModel._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not contain slashes (/).
"""
check_class(nodeName, six.string_types, allow_none=False)
assert nodeName, "nodeName may not be empty"
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = str(nodeName)
self._parentItem = None
self._model = None
self._childItems = [] # the fetched children
self._nodePath = self._constructNodePath()
def finalize(self):
""" Can be used to cleanup resources. Should be called explicitly.
Finalizes its children before closing itself
"""
for child in self.childItems:
child.finalize()
def __str__(self):
return "<{}: {}>".format(type(self).__name__, self.nodePath)
def __repr__(self):
return ("<{}: {!r}, children:[{}]>".
format(type(self).__name__, self.nodePath,
', '.join([repr(child) for child in self.childItems])))
@property
def model(self):
""" Returns the ConfigTreeModel this item belongs to.
If the model is None (not set), it will use and cache the parent's model.
Therefore make sure that an ancestor node has a reference to the model! Typically by
setting the model property of the invisible root item in the model constructor.
"""
if self._model is None and self.parentItem is not None:
self._model = self.parentItem.model
return self._model
@model.setter
def model(self, value):
""" Sets ConfigTreeModel this item belongs to.
"""
self._model = value
@property
def decoration(self):
""" An optional decoration (e.g. icon).
The default implementation returns None (no decoration).
"""
return None
@property
def font(self):
""" Returns a font for displaying this item's text in the tree.
The default implementation returns None (i.e. uses default font).
"""
return None
@property
def backgroundBrush(self):
""" Returns a brush for drawing the background role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def foregroundBrush(self):
""" Returns a brush for drawing the foreground role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def sizeHint(self):
""" Returns a size hint for displaying the items in the tree
The default implementation returns None (i.e. no hint).
Should return a QSize object or None
"""
return None
@property
def nodeName(self):
""" The node name. Is used to construct the nodePath"""
return self._nodeName
@nodeName.setter
def nodeName(self, nodeName):
""" The node name. Is used to construct the nodePath"""
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = nodeName
self._recursiveSetNodePath(self._constructNodePath())
def _constructNodePath(self):
""" Recursively prepends the parents nodeName to the path until the root node is reached."""
if self.parentItem is None:
return '' # invisible root node; is not included in the path
else:
return self.parentItem.nodePath + '/' + self.nodeName
@property
def nodePath(self):
""" The sequence of nodeNames from the root to this node. Separated by slashes."""
return self._nodePath
def _recursiveSetNodePath(self, nodePath):
""" Sets the nodePath property and updates it for all children.
"""
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
@property
def parentItem(self):
""" The parent item """
return self._parentItem
@parentItem.setter
def parentItem(self, value):
""" The parent item """
self._parentItem = value
self._recursiveSetNodePath(self._constructNodePath())
@property
def childItems(self):
""" List of child items """
#logger.debug("childItems {!r}".format(self))
return self._childItems
def hasChildren(self):
""" Returns True if the item has children.
If it has children the corresponding node in the tree can be expanded.
"""
return len(self.childItems) > 0
def nChildren(self): # TODO: numChildren
""" Returns the number of children
"""
return len(self.childItems)
def | (self, row):
""" Gets the child given its row number
"""
return self.childItems[row]
def childByNodeName(self, nodeName):
""" Gets first (direct) child that has the nodeName.
"""
assert '/' not in nodeName, "nodeName can not contain slashes"
for child in self.childItems:
if child.nodeName == nodeName:
return child
raise IndexError("No child item found having nodeName: {}".format(nodeName))
def findByNodePath(self, nodePath):
""" Recursively searches for the child having the nodePath. Starts at self.
"""
def _auxGetByPath(parts, item):
"Aux function that does the actual recursive search"
#logger.debug("_auxGetByPath item={}, parts={}".format(item, parts))
if len(parts) == 0:
return item
head, tail = parts[0], parts[1:]
if head == '':
# Two consecutive slashes. Just go one level deeper.
return _auxGetByPath(tail, item)
else:
childItem = item.childByNodeName(head)
return _auxGetByPath(tail, childItem)
# The actual body of findByNodePath starts here
check_is_a_string(nodePath)
assert not nodePath.startswith('/'), "nodePath may not start with a slash"
if not nodePath:
raise IndexError("Item not found: {!r}".format(nodePath))
return _auxGetByPath(nodePath.split('/'), self)
def childNumber(self):
""" Gets the index (nr) of this node in its parent's list of children.
"""
# This is O(n) in time. # TODO: store row number in the items?
if self.parentItem is not None:
return self.parentItem.childItems.index(self)
return 0
def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem instead.
param childItem: a BaseTreeItem that will be added
param position: integer position before which the item will be added.
If position is None (default) the item will be appended at the end.
Returns childItem so that calls may be chained.
"""
if position is None:
position = self.nChildren()
assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem)
assert childItem._model is None, "childItem already has a model: {}".format(childItem)
childItem.parentItem = self
childItem.model = self.model
self.childItems.insert(position, childItem)
return childItem
def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
"position should be 0 < {} <= {}".format(position, len(self.childItems))
self.childItems[position].finalize()
self.childItems.pop(position)
def removeAllChildren(self):
""" Removes the all children of this node.
Calls the child items finalize to close their resources before removing them.
"""
for childItem in self.childItems:
childItem.finalize()
self._childItems = []
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
logger.log(level, indent * " " + str(self))
for childItems in self.childItems:
childItems.logBranch(indent + 1, level=level)
class AbstractLazyLoadTreeItem(BaseTreeItem):
""" Abstract base class for a tree item that can do lazy loading of children.
Descendants should override the _fetchAllChildren
"""
def __init__(self, nodeName=''):
""" Constructor
"""
super(AbstractLazyLoadTreeItem, self).__init__(nodeName=nodeName)
self._canFetchChildren = True # children not yet fetched (successfully or unsuccessfully)
def hasChildren(self):
""" Returns True if the item has (fetched or unfetched) children
"""
return self._canFetchChildren or len(self.childItems) > 0
def canFetchChildren(self):
""" Returns True if children can be fetched, and False if they already have been fetched.
Also returns False if they have been fetched and tried.
"""
return self._canFetchChildren
def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childItems = self._fetchAllChildren()
finally:
self._canFetchChildren = False # Set to True, even if tried and failed.
return childItems
def _fetchAllChildren(self):
""" The function that actually fetches the children.
The result must be a list of RepoTreeItems. Their parents must be None,
as that attribute will be set by BaseTreeitem.insertItem()
:rtype: list of BaseRti objects
"""
raise NotImplementedError
def removeAllChildren(self):
""" Removes all children """
try:
super(AbstractLazyLoadTreeItem, self).removeAllChildren()
finally:
self._canFetchChildren = True
| child | identifier_name |
treeitems.py | import logging
from argos.external import six
from argos.utils.cls import check_class, check_is_a_string
logger = logging.getLogger(__name__)
class BaseTreeItem(object):
""" Base class for storing item data in a tree form. Each tree item represents a row
in the BaseTreeModel (QAbstractItemModel).
The tree items have no notion of which field is stored in which column. This is implemented
in BaseTreeModel._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not contain slashes (/).
"""
check_class(nodeName, six.string_types, allow_none=False)
assert nodeName, "nodeName may not be empty"
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = str(nodeName)
self._parentItem = None
self._model = None
self._childItems = [] # the fetched children
self._nodePath = self._constructNodePath()
def finalize(self):
""" Can be used to cleanup resources. Should be called explicitly.
Finalizes its children before closing itself
"""
for child in self.childItems:
child.finalize()
def __str__(self):
return "<{}: {}>".format(type(self).__name__, self.nodePath)
def __repr__(self):
return ("<{}: {!r}, children:[{}]>".
format(type(self).__name__, self.nodePath,
', '.join([repr(child) for child in self.childItems])))
@property
def model(self):
""" Returns the ConfigTreeModel this item belongs to.
If the model is None (not set), it will use and cache the parent's model.
Therefore make sure that an ancestor node has a reference to the model! Typically by
setting the model property of the invisible root item in the model constructor.
"""
if self._model is None and self.parentItem is not None:
self._model = self.parentItem.model
return self._model
@model.setter
def model(self, value):
""" Sets ConfigTreeModel this item belongs to.
"""
self._model = value
@property
def decoration(self):
""" An optional decoration (e.g. icon).
The default implementation returns None (no decoration).
"""
return None
@property
def font(self):
|
@property
def backgroundBrush(self):
""" Returns a brush for drawing the background role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def foregroundBrush(self):
""" Returns a brush for drawing the foreground role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def sizeHint(self):
""" Returns a size hint for displaying the items in the tree
The default implementation returns None (i.e. no hint).
Should return a QSize object or None
"""
return None
@property
def nodeName(self):
""" The node name. Is used to construct the nodePath"""
return self._nodeName
@nodeName.setter
def nodeName(self, nodeName):
""" The node name. Is used to construct the nodePath"""
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = nodeName
self._recursiveSetNodePath(self._constructNodePath())
def _constructNodePath(self):
""" Recursively prepends the parents nodeName to the path until the root node is reached."""
if self.parentItem is None:
return '' # invisible root node; is not included in the path
else:
return self.parentItem.nodePath + '/' + self.nodeName
@property
def nodePath(self):
""" The sequence of nodeNames from the root to this node. Separated by slashes."""
return self._nodePath
def _recursiveSetNodePath(self, nodePath):
""" Sets the nodePath property and updates it for all children.
"""
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
@property
def parentItem(self):
""" The parent item """
return self._parentItem
@parentItem.setter
def parentItem(self, value):
""" The parent item """
self._parentItem = value
self._recursiveSetNodePath(self._constructNodePath())
@property
def childItems(self):
""" List of child items """
#logger.debug("childItems {!r}".format(self))
return self._childItems
def hasChildren(self):
""" Returns True if the item has children.
If it has children the corresponding node in the tree can be expanded.
"""
return len(self.childItems) > 0
def nChildren(self): # TODO: numChildren
""" Returns the number of children
"""
return len(self.childItems)
def child(self, row):
""" Gets the child given its row number
"""
return self.childItems[row]
def childByNodeName(self, nodeName):
""" Gets first (direct) child that has the nodeName.
"""
assert '/' not in nodeName, "nodeName can not contain slashes"
for child in self.childItems:
if child.nodeName == nodeName:
return child
raise IndexError("No child item found having nodeName: {}".format(nodeName))
def findByNodePath(self, nodePath):
""" Recursively searches for the child having the nodePath. Starts at self.
"""
def _auxGetByPath(parts, item):
"Aux function that does the actual recursive search"
#logger.debug("_auxGetByPath item={}, parts={}".format(item, parts))
if len(parts) == 0:
return item
head, tail = parts[0], parts[1:]
if head == '':
# Two consecutive slashes. Just go one level deeper.
return _auxGetByPath(tail, item)
else:
childItem = item.childByNodeName(head)
return _auxGetByPath(tail, childItem)
# The actual body of findByNodePath starts here
check_is_a_string(nodePath)
assert not nodePath.startswith('/'), "nodePath may not start with a slash"
if not nodePath:
raise IndexError("Item not found: {!r}".format(nodePath))
return _auxGetByPath(nodePath.split('/'), self)
def childNumber(self):
""" Gets the index (nr) of this node in its parent's list of children.
"""
# This is O(n) in time. # TODO: store row number in the items?
if self.parentItem is not None:
return self.parentItem.childItems.index(self)
return 0
def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem instead.
param childItem: a BaseTreeItem that will be added
param position: integer position before which the item will be added.
If position is None (default) the item will be appended at the end.
Returns childItem so that calls may be chained.
"""
if position is None:
position = self.nChildren()
assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem)
assert childItem._model is None, "childItem already has a model: {}".format(childItem)
childItem.parentItem = self
childItem.model = self.model
self.childItems.insert(position, childItem)
return childItem
def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
"position should be 0 < {} <= {}".format(position, len(self.childItems))
self.childItems[position].finalize()
self.childItems.pop(position)
def removeAllChildren(self):
""" Removes the all children of this node.
Calls the child items finalize to close their resources before removing them.
"""
for childItem in self.childItems:
childItem.finalize()
self._childItems = []
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
logger.log(level, indent * " " + str(self))
for childItems in self.childItems:
childItems.logBranch(indent + 1, level=level)
class AbstractLazyLoadTreeItem(BaseTreeItem):
""" Abstract base class for a tree item that can do lazy loading of children.
Descendants should override the _fetchAllChildren
"""
def __init__(self, nodeName=''):
""" Constructor
"""
super(AbstractLazyLoadTreeItem, self).__init__(nodeName=nodeName)
self._canFetchChildren = True # children not yet fetched (successfully or unsuccessfully)
def hasChildren(self):
""" Returns True if the item has (fetched or unfetched) children
"""
return self._canFetchChildren or len(self.childItems) > 0
def canFetchChildren(self):
""" Returns True if children can be fetched, and False if they already have been fetched.
Also returns False if they have been fetched and tried.
"""
return self._canFetchChildren
def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childItems = self._fetchAllChildren()
finally:
self._canFetchChildren = False # Set to True, even if tried and failed.
return childItems
def _fetchAllChildren(self):
""" The function that actually fetches the children.
The result must be a list of RepoTreeItems. Their parents must be None,
as that attribute will be set by BaseTreeitem.insertItem()
:rtype: list of BaseRti objects
"""
raise NotImplementedError
def removeAllChildren(self):
""" Removes all children """
try:
super(AbstractLazyLoadTreeItem, self).removeAllChildren()
finally:
self._canFetchChildren = True
| """ Returns a font for displaying this item's text in the tree.
The default implementation returns None (i.e. uses default font).
"""
return None | identifier_body |
treeitems.py | import logging
from argos.external import six
from argos.utils.cls import check_class, check_is_a_string
logger = logging.getLogger(__name__)
class BaseTreeItem(object):
""" Base class for storing item data in a tree form. Each tree item represents a row
in the BaseTreeModel (QAbstractItemModel).
The tree items have no notion of which field is stored in which column. This is implemented
in BaseTreeModel._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not contain slashes (/).
"""
check_class(nodeName, six.string_types, allow_none=False)
assert nodeName, "nodeName may not be empty"
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = str(nodeName)
self._parentItem = None
self._model = None
self._childItems = [] # the fetched children
self._nodePath = self._constructNodePath()
def finalize(self):
""" Can be used to cleanup resources. Should be called explicitly.
Finalizes its children before closing itself
"""
for child in self.childItems:
child.finalize()
def __str__(self):
return "<{}: {}>".format(type(self).__name__, self.nodePath)
def __repr__(self):
return ("<{}: {!r}, children:[{}]>".
format(type(self).__name__, self.nodePath,
', '.join([repr(child) for child in self.childItems])))
@property
def model(self):
""" Returns the ConfigTreeModel this item belongs to.
If the model is None (not set), it will use and cache the parent's model.
Therefore make sure that an ancestor node has a reference to the model! Typically by
setting the model property of the invisible root item in the model constructor.
"""
if self._model is None and self.parentItem is not None:
self._model = self.parentItem.model
return self._model
@model.setter
def model(self, value):
""" Sets ConfigTreeModel this item belongs to.
"""
self._model = value
@property
def decoration(self):
""" An optional decoration (e.g. icon).
The default implementation returns None (no decoration).
"""
return None
@property
def font(self):
""" Returns a font for displaying this item's text in the tree.
The default implementation returns None (i.e. uses default font).
"""
return None
@property
def backgroundBrush(self):
""" Returns a brush for drawing the background role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def foregroundBrush(self):
""" Returns a brush for drawing the foreground role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def sizeHint(self):
""" Returns a size hint for displaying the items in the tree
The default implementation returns None (i.e. no hint).
Should return a QSize object or None
"""
return None
@property
def nodeName(self):
""" The node name. Is used to construct the nodePath"""
return self._nodeName
@nodeName.setter
def nodeName(self, nodeName):
""" The node name. Is used to construct the nodePath"""
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = nodeName
self._recursiveSetNodePath(self._constructNodePath())
def _constructNodePath(self):
""" Recursively prepends the parents nodeName to the path until the root node is reached."""
if self.parentItem is None:
return '' # invisible root node; is not included in the path
else:
return self.parentItem.nodePath + '/' + self.nodeName
@property
def nodePath(self):
""" The sequence of nodeNames from the root to this node. Separated by slashes."""
return self._nodePath
def _recursiveSetNodePath(self, nodePath):
""" Sets the nodePath property and updates it for all children.
"""
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
@property
def parentItem(self):
""" The parent item """
return self._parentItem
@parentItem.setter
def parentItem(self, value):
""" The parent item """
self._parentItem = value
self._recursiveSetNodePath(self._constructNodePath())
@property
def childItems(self):
""" List of child items """
#logger.debug("childItems {!r}".format(self))
return self._childItems
def hasChildren(self):
""" Returns True if the item has children.
If it has children the corresponding node in the tree can be expanded.
"""
return len(self.childItems) > 0
def nChildren(self): # TODO: numChildren
""" Returns the number of children
"""
return len(self.childItems)
def child(self, row):
""" Gets the child given its row number
"""
return self.childItems[row]
def childByNodeName(self, nodeName):
""" Gets first (direct) child that has the nodeName.
"""
assert '/' not in nodeName, "nodeName can not contain slashes"
for child in self.childItems:
if child.nodeName == nodeName:
return child
raise IndexError("No child item found having nodeName: {}".format(nodeName))
def findByNodePath(self, nodePath):
""" Recursively searches for the child having the nodePath. Starts at self.
"""
def _auxGetByPath(parts, item):
"Aux function that does the actual recursive search"
#logger.debug("_auxGetByPath item={}, parts={}".format(item, parts))
if len(parts) == 0:
return item
head, tail = parts[0], parts[1:]
if head == '':
# Two consecutive slashes. Just go one level deeper.
return _auxGetByPath(tail, item)
else:
childItem = item.childByNodeName(head)
return _auxGetByPath(tail, childItem)
# The actual body of findByNodePath starts here
check_is_a_string(nodePath)
assert not nodePath.startswith('/'), "nodePath may not start with a slash"
if not nodePath:
raise IndexError("Item not found: {!r}".format(nodePath))
return _auxGetByPath(nodePath.split('/'), self)
def childNumber(self):
""" Gets the index (nr) of this node in its parent's list of children.
"""
# This is O(n) in time. # TODO: store row number in the items?
if self.parentItem is not None:
return self.parentItem.childItems.index(self)
return 0
def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem instead.
param childItem: a BaseTreeItem that will be added
param position: integer position before which the item will be added.
If position is None (default) the item will be appended at the end.
Returns childItem so that calls may be chained. | """
if position is None:
position = self.nChildren()
assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem)
assert childItem._model is None, "childItem already has a model: {}".format(childItem)
childItem.parentItem = self
childItem.model = self.model
self.childItems.insert(position, childItem)
return childItem
def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
"position should be 0 < {} <= {}".format(position, len(self.childItems))
self.childItems[position].finalize()
self.childItems.pop(position)
def removeAllChildren(self):
""" Removes the all children of this node.
Calls the child items finalize to close their resources before removing them.
"""
for childItem in self.childItems:
childItem.finalize()
self._childItems = []
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
logger.log(level, indent * " " + str(self))
for childItems in self.childItems:
childItems.logBranch(indent + 1, level=level)
class AbstractLazyLoadTreeItem(BaseTreeItem):
""" Abstract base class for a tree item that can do lazy loading of children.
Descendants should override the _fetchAllChildren
"""
def __init__(self, nodeName=''):
""" Constructor
"""
super(AbstractLazyLoadTreeItem, self).__init__(nodeName=nodeName)
self._canFetchChildren = True # children not yet fetched (successfully or unsuccessfully)
def hasChildren(self):
""" Returns True if the item has (fetched or unfetched) children
"""
return self._canFetchChildren or len(self.childItems) > 0
def canFetchChildren(self):
""" Returns True if children can be fetched, and False if they already have been fetched.
Also returns False if they have been fetched and tried.
"""
return self._canFetchChildren
def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childItems = self._fetchAllChildren()
finally:
self._canFetchChildren = False # Set to True, even if tried and failed.
return childItems
def _fetchAllChildren(self):
""" The function that actually fetches the children.
The result must be a list of RepoTreeItems. Their parents must be None,
as that attribute will be set by BaseTreeitem.insertItem()
:rtype: list of BaseRti objects
"""
raise NotImplementedError
def removeAllChildren(self):
""" Removes all children """
try:
super(AbstractLazyLoadTreeItem, self).removeAllChildren()
finally:
self._canFetchChildren = True | random_line_split | |
treeitems.py | import logging
from argos.external import six
from argos.utils.cls import check_class, check_is_a_string
logger = logging.getLogger(__name__)
class BaseTreeItem(object):
""" Base class for storing item data in a tree form. Each tree item represents a row
in the BaseTreeModel (QAbstractItemModel).
The tree items have no notion of which field is stored in which column. This is implemented
in BaseTreeModel._itemValueForColumn
"""
def __init__(self, nodeName):
""" Constructor
:param nodeName: short name describing this node. Is used to construct the nodePath.
Currently we don't check for uniqueness in the children but this may change.
The nodeName may not contain slashes (/).
"""
check_class(nodeName, six.string_types, allow_none=False)
assert nodeName, "nodeName may not be empty"
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = str(nodeName)
self._parentItem = None
self._model = None
self._childItems = [] # the fetched children
self._nodePath = self._constructNodePath()
def finalize(self):
""" Can be used to cleanup resources. Should be called explicitly.
Finalizes its children before closing itself
"""
for child in self.childItems:
child.finalize()
def __str__(self):
return "<{}: {}>".format(type(self).__name__, self.nodePath)
def __repr__(self):
return ("<{}: {!r}, children:[{}]>".
format(type(self).__name__, self.nodePath,
', '.join([repr(child) for child in self.childItems])))
@property
def model(self):
""" Returns the ConfigTreeModel this item belongs to.
If the model is None (not set), it will use and cache the parent's model.
Therefore make sure that an ancestor node has a reference to the model! Typically by
setting the model property of the invisible root item in the model constructor.
"""
if self._model is None and self.parentItem is not None:
self._model = self.parentItem.model
return self._model
@model.setter
def model(self, value):
""" Sets ConfigTreeModel this item belongs to.
"""
self._model = value
@property
def decoration(self):
""" An optional decoration (e.g. icon).
The default implementation returns None (no decoration).
"""
return None
@property
def font(self):
""" Returns a font for displaying this item's text in the tree.
The default implementation returns None (i.e. uses default font).
"""
return None
@property
def backgroundBrush(self):
""" Returns a brush for drawing the background role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def foregroundBrush(self):
""" Returns a brush for drawing the foreground role in the tree.
The default implementation returns None (i.e. uses default brush).
"""
return None
@property
def sizeHint(self):
""" Returns a size hint for displaying the items in the tree
The default implementation returns None (i.e. no hint).
Should return a QSize object or None
"""
return None
@property
def nodeName(self):
""" The node name. Is used to construct the nodePath"""
return self._nodeName
@nodeName.setter
def nodeName(self, nodeName):
""" The node name. Is used to construct the nodePath"""
assert '/' not in nodeName, "nodeName may not contain slashes"
self._nodeName = nodeName
self._recursiveSetNodePath(self._constructNodePath())
def _constructNodePath(self):
""" Recursively prepends the parents nodeName to the path until the root node is reached."""
if self.parentItem is None:
return '' # invisible root node; is not included in the path
else:
return self.parentItem.nodePath + '/' + self.nodeName
@property
def nodePath(self):
""" The sequence of nodeNames from the root to this node. Separated by slashes."""
return self._nodePath
def _recursiveSetNodePath(self, nodePath):
""" Sets the nodePath property and updates it for all children.
"""
self._nodePath = nodePath
for childItem in self.childItems:
childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
@property
def parentItem(self):
""" The parent item """
return self._parentItem
@parentItem.setter
def parentItem(self, value):
""" The parent item """
self._parentItem = value
self._recursiveSetNodePath(self._constructNodePath())
@property
def childItems(self):
""" List of child items """
#logger.debug("childItems {!r}".format(self))
return self._childItems
def hasChildren(self):
""" Returns True if the item has children.
If it has children the corresponding node in the tree can be expanded.
"""
return len(self.childItems) > 0
def nChildren(self): # TODO: numChildren
""" Returns the number of children
"""
return len(self.childItems)
def child(self, row):
""" Gets the child given its row number
"""
return self.childItems[row]
def childByNodeName(self, nodeName):
""" Gets first (direct) child that has the nodeName.
"""
assert '/' not in nodeName, "nodeName can not contain slashes"
for child in self.childItems:
if child.nodeName == nodeName:
return child
raise IndexError("No child item found having nodeName: {}".format(nodeName))
def findByNodePath(self, nodePath):
""" Recursively searches for the child having the nodePath. Starts at self.
"""
def _auxGetByPath(parts, item):
"Aux function that does the actual recursive search"
#logger.debug("_auxGetByPath item={}, parts={}".format(item, parts))
if len(parts) == 0:
return item
head, tail = parts[0], parts[1:]
if head == '':
# Two consecutive slashes. Just go one level deeper.
return _auxGetByPath(tail, item)
else:
childItem = item.childByNodeName(head)
return _auxGetByPath(tail, childItem)
# The actual body of findByNodePath starts here
check_is_a_string(nodePath)
assert not nodePath.startswith('/'), "nodePath may not start with a slash"
if not nodePath:
|
return _auxGetByPath(nodePath.split('/'), self)
def childNumber(self):
""" Gets the index (nr) of this node in its parent's list of children.
"""
# This is O(n) in time. # TODO: store row number in the items?
if self.parentItem is not None:
return self.parentItem.childItems.index(self)
return 0
def insertChild(self, childItem, position=None):
""" Inserts a child item to the current item.
The childItem must not yet have a parent (it will be set by this function).
IMPORTANT: this does not let the model know that items have been added.
Use BaseTreeModel.insertItem instead.
param childItem: a BaseTreeItem that will be added
param position: integer position before which the item will be added.
If position is None (default) the item will be appended at the end.
Returns childItem so that calls may be chained.
"""
if position is None:
position = self.nChildren()
assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem)
assert childItem._model is None, "childItem already has a model: {}".format(childItem)
childItem.parentItem = self
childItem.model = self.model
self.childItems.insert(position, childItem)
return childItem
def removeChild(self, position):
""" Removes the child at the position 'position'
Calls the child item finalize to close its resources before removing it.
"""
assert 0 <= position <= len(self.childItems), \
"position should be 0 < {} <= {}".format(position, len(self.childItems))
self.childItems[position].finalize()
self.childItems.pop(position)
def removeAllChildren(self):
""" Removes the all children of this node.
Calls the child items finalize to close their resources before removing them.
"""
for childItem in self.childItems:
childItem.finalize()
self._childItems = []
def logBranch(self, indent=0, level=logging.DEBUG):
""" Logs the item and all descendants, one line per child
"""
if 0:
print(indent * " " + str(self))
else:
logger.log(level, indent * " " + str(self))
for childItems in self.childItems:
childItems.logBranch(indent + 1, level=level)
class AbstractLazyLoadTreeItem(BaseTreeItem):
""" Abstract base class for a tree item that can do lazy loading of children.
Descendants should override the _fetchAllChildren
"""
def __init__(self, nodeName=''):
""" Constructor
"""
super(AbstractLazyLoadTreeItem, self).__init__(nodeName=nodeName)
self._canFetchChildren = True # children not yet fetched (successfully or unsuccessfully)
def hasChildren(self):
""" Returns True if the item has (fetched or unfetched) children
"""
return self._canFetchChildren or len(self.childItems) > 0
def canFetchChildren(self):
""" Returns True if children can be fetched, and False if they already have been fetched.
Also returns False if they have been fetched and tried.
"""
return self._canFetchChildren
def fetchChildren(self):
""" Fetches children.
The actual work is done by _fetchAllChildren. Descendant classes should typically
override that method instead of this one.
"""
assert self._canFetchChildren, "canFetchChildren must be True"
try:
childItems = self._fetchAllChildren()
finally:
self._canFetchChildren = False # Set to True, even if tried and failed.
return childItems
def _fetchAllChildren(self):
""" The function that actually fetches the children.
The result must be a list of RepoTreeItems. Their parents must be None,
as that attribute will be set by BaseTreeitem.insertItem()
:rtype: list of BaseRti objects
"""
raise NotImplementedError
def removeAllChildren(self):
""" Removes all children """
try:
super(AbstractLazyLoadTreeItem, self).removeAllChildren()
finally:
self._canFetchChildren = True
| raise IndexError("Item not found: {!r}".format(nodePath)) | conditional_block |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.errors import AnsibleError
# FIXME: this object should be created upfront and passed through
# the entire chain of calls to here, as there are other things
# which may want to output display/logs too
from ansible.utils.display import Display
__all__ = ['ConnectionBase']
class ConnectionBase:
'''
A base class for connections to contain common code.
'''
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def _become_method_supported(self, become_method):
''' Checks if the current class supports this privilege escalation method '''
if become_method in self.__class__.become_methods:
|
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
| return True | conditional_block |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.errors import AnsibleError
# FIXME: this object should be created upfront and passed through
# the entire chain of calls to here, as there are other things
# which may want to output display/logs too
from ansible.utils.display import Display
__all__ = ['ConnectionBase']
class ConnectionBase:
'''
A base class for connections to contain common code.
'''
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def | (self, become_method):
''' Checks if the current class supports this privilege escalation method '''
if become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method)
| _become_method_supported | identifier_name |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.errors import AnsibleError
# FIXME: this object should be created upfront and passed through
# the entire chain of calls to here, as there are other things
# which may want to output display/logs too
from ansible.utils.display import Display
__all__ = ['ConnectionBase']
class ConnectionBase:
'''
A base class for connections to contain common code.
'''
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def _become_method_supported(self, become_method):
''' Checks if the current class supports this privilege escalation method '''
if become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method) | # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
| random_line_split |
__init__.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.errors import AnsibleError
# FIXME: this object should be created upfront and passed through
# the entire chain of calls to here, as there are other things
# which may want to output display/logs too
from ansible.utils.display import Display
__all__ = ['ConnectionBase']
class ConnectionBase:
| '''
A base class for connections to contain common code.
'''
has_pipelining = False
become_methods = C.BECOME_METHODS
def __init__(self, connection_info, *args, **kwargs):
self._connection_info = connection_info
self._display = Display(verbosity=connection_info.verbosity)
def _become_method_supported(self, become_method):
''' Checks if the current class supports this privilege escalation method '''
if become_method in self.__class__.become_methods:
return True
raise AnsibleError("Internal Error: this connection module does not support running commands via %s" % become_method) | identifier_body | |
htmltablecaptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLTableCaptionElement {
htmlelement: HTMLElement
}
impl HTMLTableCaptionElement {
fn new_inherited(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLTableCaptionElement |
#[allow(unrooted_must_root)]
pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
HTMLTableCaptionElementBinding::Wrap)
}
}
| {
HTMLTableCaptionElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
} | identifier_body |
htmltablecaptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLTableCaptionElement {
htmlelement: HTMLElement
}
impl HTMLTableCaptionElement {
fn new_inherited(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLTableCaptionElement {
HTMLTableCaptionElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn | (local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document),
document,
HTMLTableCaptionElementBinding::Wrap)
}
}
| new | identifier_name |
htmltablecaptionelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLTableCaptionElement {
htmlelement: HTMLElement
}
impl HTMLTableCaptionElement {
fn new_inherited(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLTableCaptionElement {
HTMLTableCaptionElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)] | document,
HTMLTableCaptionElementBinding::Wrap)
}
} | pub fn new(local_name: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTableCaptionElement> {
Node::reflect_node(box HTMLTableCaptionElement::new_inherited(local_name, prefix, document), | random_line_split |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function | ($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Loadouts.Randomize'))) {
return;
}
vm.disableRandomLoadout = true;
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) {
return store;
}
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
return ((classType === 3) || (classType === classTypeId));
};
var types = ['Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'];
let accountItems = [];
var items = {};
_.each(stores, (store) => {
accountItems = accountItems.concat(_.filter(store.items, (item) => checkClassType(item.classType)));
});
var foundExotic = {};
var fn = (type) => (item) => ((item.type === type) &&
item.equipment &&
(store.level >= item.equipRequiredLevel) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!item.notransfer || (item.notransfer && (item.owner === store.id))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService.applyLoadout(store, {
classType: -1,
name: $translate.instant('Loadouts.Random'),
items: items
}, true);
}
return null;
})
.then(() => {
vm.disableRandomLoadout = false;
})
.catch(() => {
vm.disableRandomLoadout = false;
});
};
}
| dimRandomCtrl | identifier_name |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) | {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Loadouts.Randomize'))) {
return;
}
vm.disableRandomLoadout = true;
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) {
return store;
}
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
return ((classType === 3) || (classType === classTypeId));
};
var types = ['Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'];
let accountItems = [];
var items = {};
_.each(stores, (store) => {
accountItems = accountItems.concat(_.filter(store.items, (item) => checkClassType(item.classType)));
});
var foundExotic = {};
var fn = (type) => (item) => ((item.type === type) &&
item.equipment &&
(store.level >= item.equipRequiredLevel) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!item.notransfer || (item.notransfer && (item.owner === store.id))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService.applyLoadout(store, {
classType: -1,
name: $translate.instant('Loadouts.Random'),
items: items
}, true);
}
return null;
})
.then(() => {
vm.disableRandomLoadout = false;
})
.catch(() => {
vm.disableRandomLoadout = false;
});
};
} | identifier_body | |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Loadouts.Randomize'))) {
return;
}
vm.disableRandomLoadout = true;
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) {
return store;
}
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
return ((classType === 3) || (classType === classTypeId));
};
var types = ['Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'];
let accountItems = [];
var items = {};
_.each(stores, (store) => {
accountItems = accountItems.concat(_.filter(store.items, (item) => checkClassType(item.classType)));
});
var foundExotic = {};
var fn = (type) => (item) => ((item.type === type) &&
item.equipment &&
(store.level >= item.equipRequiredLevel) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!item.notransfer || (item.notransfer && (item.owner === store.id))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService.applyLoadout(store, {
classType: -1,
name: $translate.instant('Loadouts.Random'),
items: items
}, true);
}
return null;
})
.then(() => {
vm.disableRandomLoadout = false;
})
.catch(() => {
vm.disableRandomLoadout = false;
});
}; | } | random_line_split | |
dimRandom.controller.js | import angular from 'angular';
import _ from 'underscore';
angular.module('dimApp')
.controller('dimRandomCtrl', dimRandomCtrl);
function dimRandomCtrl($window, $scope, $q, dimStoreService, dimLoadoutService, $translate) {
var vm = this;
$scope.$on('dim-stores-updated', function() {
vm.showRandomLoadout = true;
});
vm.showRandomLoadout = false;
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return;
}
if (!$window.confirm($translate.instant('Loadouts.Randomize'))) {
return;
}
vm.disableRandomLoadout = true;
$q.when(dimStoreService.getStores())
.then((stores) => {
const store = _.reduce(stores, (memo, store) => {
if (!memo) |
const d1 = new Date(store.lastPlayed);
return (d1 >= memo) ? store : memo;
}, null);
if (store) {
const classTypeId = ({
titan: 0,
hunter: 1,
warlock: 2
})[store.class];
var checkClassType = function(classType) {
return ((classType === 3) || (classType === classTypeId));
};
var types = ['Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'];
let accountItems = [];
var items = {};
_.each(stores, (store) => {
accountItems = accountItems.concat(_.filter(store.items, (item) => checkClassType(item.classType)));
});
var foundExotic = {};
var fn = (type) => (item) => ((item.type === type) &&
item.equipment &&
(store.level >= item.equipRequiredLevel) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!item.notransfer || (item.notransfer && (item.owner === store.id))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService.applyLoadout(store, {
classType: -1,
name: $translate.instant('Loadouts.Random'),
items: items
}, true);
}
return null;
})
.then(() => {
vm.disableRandomLoadout = false;
})
.catch(() => {
vm.disableRandomLoadout = false;
});
};
}
| {
return store;
} | conditional_block |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/run/quagga'
QCONFIG_DIR = 'configs'
ZCONFIG_DIR = 'configs'
class SdnIpHost(Host):
def __init__(self, name, ip, route, *args, **kwargs):
Host.__init__(self, name, ip=ip, *args, **kwargs)
self.route = route
def config(self, **kwargs):
Host.config(self, **kwargs)
debug("configuring route %s" % self.route)
self.cmd('ip route add default via %s' % self.route)
class Router(Host):
def __init__(self, name, quaggaConfFile, zebraConfFile, intfDict, *args, **kwargs):
Host.__init__(self, name, *args, **kwargs)
self.quaggaConfFile = quaggaConfFile
self.zebraConfFile = zebraConfFile
self.intfDict = intfDict
def config(self, **kwargs):
Host.config(self, **kwargs)
self.cmd('sysctl net.ipv4.ip_forward=1')
for intf, attrs in self.intfDict.items():
self.cmd('ip addr flush dev %s' % intf)
# setup mac address to specific interface
if 'mac' in attrs:
self.cmd('ip link set %s down' % intf)
self.cmd('ip link set %s address %s' % (intf, attrs['mac']))
self.cmd('ip link set %s up ' % intf)
# setup address to interfaces
for addr in attrs['ipAddrs']:
self.cmd('ip addr add %s dev %s' % (addr, intf))
self.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bgpd -d -f %s -z %s/zebra%s.api -i %s/bgpd%s.pid' % (self.quaggaConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
def terminate(self):
self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self)
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='0000000000000001', cls=OVSSwitch, failMode="standalone")
# Quagga 1
bgpEth0 = {
'mac': '00:00:00:00:00:01',
'ipAddrs': [ |
bgpIntfs = {
'bgpq1-eth0': bgpEth0
}
bgpq1 = self.addHost("bgpq1", cls=Router,
quaggaConfFile='{}/quagga1.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq1, s1)
# Quagga 2
bgpEth0 = {
'mac': '00:00:00:00:00:02',
'ipAddrs': [
'10.0.2.1/24',
]
}
bgpIntfs = {
'bgpq2-eth0': bgpEth0
}
bgpq2 = self.addHost("bgpq2", cls=Router,
quaggaConfFile='{}/quagga2.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq2, s1)
topos = {'sdnip': SdnIpTopo}
if __name__ == '__main__':
setLogLevel('debug')
topo = SdnIpTopo()
net = Mininet(topo=topo, controller=RemoteController)
net.start()
CLI(net)
net.stop()
info("done\n") | '10.0.1.1/24',
]
} | random_line_split |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/run/quagga'
QCONFIG_DIR = 'configs'
ZCONFIG_DIR = 'configs'
class SdnIpHost(Host):
def __init__(self, name, ip, route, *args, **kwargs):
Host.__init__(self, name, ip=ip, *args, **kwargs)
self.route = route
def config(self, **kwargs):
Host.config(self, **kwargs)
debug("configuring route %s" % self.route)
self.cmd('ip route add default via %s' % self.route)
class Router(Host):
def __init__(self, name, quaggaConfFile, zebraConfFile, intfDict, *args, **kwargs):
Host.__init__(self, name, *args, **kwargs)
self.quaggaConfFile = quaggaConfFile
self.zebraConfFile = zebraConfFile
self.intfDict = intfDict
def config(self, **kwargs):
Host.config(self, **kwargs)
self.cmd('sysctl net.ipv4.ip_forward=1')
for intf, attrs in self.intfDict.items():
self.cmd('ip addr flush dev %s' % intf)
# setup mac address to specific interface
if 'mac' in attrs:
self.cmd('ip link set %s down' % intf)
self.cmd('ip link set %s address %s' % (intf, attrs['mac']))
self.cmd('ip link set %s up ' % intf)
# setup address to interfaces
for addr in attrs['ipAddrs']:
self.cmd('ip addr add %s dev %s' % (addr, intf))
self.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bgpd -d -f %s -z %s/zebra%s.api -i %s/bgpd%s.pid' % (self.quaggaConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
def terminate(self):
|
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='0000000000000001', cls=OVSSwitch, failMode="standalone")
# Quagga 1
bgpEth0 = {
'mac': '00:00:00:00:00:01',
'ipAddrs': [
'10.0.1.1/24',
]
}
bgpIntfs = {
'bgpq1-eth0': bgpEth0
}
bgpq1 = self.addHost("bgpq1", cls=Router,
quaggaConfFile='{}/quagga1.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq1, s1)
# Quagga 2
bgpEth0 = {
'mac': '00:00:00:00:00:02',
'ipAddrs': [
'10.0.2.1/24',
]
}
bgpIntfs = {
'bgpq2-eth0': bgpEth0
}
bgpq2 = self.addHost("bgpq2", cls=Router,
quaggaConfFile='{}/quagga2.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq2, s1)
topos = {'sdnip': SdnIpTopo}
if __name__ == '__main__':
setLogLevel('debug')
topo = SdnIpTopo()
net = Mininet(topo=topo, controller=RemoteController)
net.start()
CLI(net)
net.stop()
info("done\n")
| self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self) | identifier_body |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/run/quagga'
QCONFIG_DIR = 'configs'
ZCONFIG_DIR = 'configs'
class SdnIpHost(Host):
def | (self, name, ip, route, *args, **kwargs):
Host.__init__(self, name, ip=ip, *args, **kwargs)
self.route = route
def config(self, **kwargs):
Host.config(self, **kwargs)
debug("configuring route %s" % self.route)
self.cmd('ip route add default via %s' % self.route)
class Router(Host):
def __init__(self, name, quaggaConfFile, zebraConfFile, intfDict, *args, **kwargs):
Host.__init__(self, name, *args, **kwargs)
self.quaggaConfFile = quaggaConfFile
self.zebraConfFile = zebraConfFile
self.intfDict = intfDict
def config(self, **kwargs):
Host.config(self, **kwargs)
self.cmd('sysctl net.ipv4.ip_forward=1')
for intf, attrs in self.intfDict.items():
self.cmd('ip addr flush dev %s' % intf)
# setup mac address to specific interface
if 'mac' in attrs:
self.cmd('ip link set %s down' % intf)
self.cmd('ip link set %s address %s' % (intf, attrs['mac']))
self.cmd('ip link set %s up ' % intf)
# setup address to interfaces
for addr in attrs['ipAddrs']:
self.cmd('ip addr add %s dev %s' % (addr, intf))
self.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bgpd -d -f %s -z %s/zebra%s.api -i %s/bgpd%s.pid' % (self.quaggaConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
def terminate(self):
self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self)
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='0000000000000001', cls=OVSSwitch, failMode="standalone")
# Quagga 1
bgpEth0 = {
'mac': '00:00:00:00:00:01',
'ipAddrs': [
'10.0.1.1/24',
]
}
bgpIntfs = {
'bgpq1-eth0': bgpEth0
}
bgpq1 = self.addHost("bgpq1", cls=Router,
quaggaConfFile='{}/quagga1.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq1, s1)
# Quagga 2
bgpEth0 = {
'mac': '00:00:00:00:00:02',
'ipAddrs': [
'10.0.2.1/24',
]
}
bgpIntfs = {
'bgpq2-eth0': bgpEth0
}
bgpq2 = self.addHost("bgpq2", cls=Router,
quaggaConfFile='{}/quagga2.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq2, s1)
topos = {'sdnip': SdnIpTopo}
if __name__ == '__main__':
setLogLevel('debug')
topo = SdnIpTopo()
net = Mininet(topo=topo, controller=RemoteController)
net.start()
CLI(net)
net.stop()
info("done\n")
| __init__ | identifier_name |
topo.py | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/run/quagga'
QCONFIG_DIR = 'configs'
ZCONFIG_DIR = 'configs'
class SdnIpHost(Host):
def __init__(self, name, ip, route, *args, **kwargs):
Host.__init__(self, name, ip=ip, *args, **kwargs)
self.route = route
def config(self, **kwargs):
Host.config(self, **kwargs)
debug("configuring route %s" % self.route)
self.cmd('ip route add default via %s' % self.route)
class Router(Host):
def __init__(self, name, quaggaConfFile, zebraConfFile, intfDict, *args, **kwargs):
Host.__init__(self, name, *args, **kwargs)
self.quaggaConfFile = quaggaConfFile
self.zebraConfFile = zebraConfFile
self.intfDict = intfDict
def config(self, **kwargs):
Host.config(self, **kwargs)
self.cmd('sysctl net.ipv4.ip_forward=1')
for intf, attrs in self.intfDict.items():
self.cmd('ip addr flush dev %s' % intf)
# setup mac address to specific interface
if 'mac' in attrs:
|
# setup address to interfaces
for addr in attrs['ipAddrs']:
self.cmd('ip addr add %s dev %s' % (addr, intf))
self.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bgpd -d -f %s -z %s/zebra%s.api -i %s/bgpd%s.pid' % (self.quaggaConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
def terminate(self):
self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self)
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='0000000000000001', cls=OVSSwitch, failMode="standalone")
# Quagga 1
bgpEth0 = {
'mac': '00:00:00:00:00:01',
'ipAddrs': [
'10.0.1.1/24',
]
}
bgpIntfs = {
'bgpq1-eth0': bgpEth0
}
bgpq1 = self.addHost("bgpq1", cls=Router,
quaggaConfFile='{}/quagga1.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq1, s1)
# Quagga 2
bgpEth0 = {
'mac': '00:00:00:00:00:02',
'ipAddrs': [
'10.0.2.1/24',
]
}
bgpIntfs = {
'bgpq2-eth0': bgpEth0
}
bgpq2 = self.addHost("bgpq2", cls=Router,
quaggaConfFile='{}/quagga2.conf'.format(QCONFIG_DIR),
zebraConfFile=zebraConf,
intfDict=bgpIntfs)
self.addLink(bgpq2, s1)
topos = {'sdnip': SdnIpTopo}
if __name__ == '__main__':
setLogLevel('debug')
topo = SdnIpTopo()
net = Mininet(topo=topo, controller=RemoteController)
net.start()
CLI(net)
net.stop()
info("done\n")
| self.cmd('ip link set %s down' % intf)
self.cmd('ip link set %s address %s' % (intf, attrs['mac']))
self.cmd('ip link set %s up ' % intf) | conditional_block |
mapAccumRight.js | import _curry3 from './internal/_curry3.js';
/**
* The `mapAccumRight` function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from right to left, and returning a final value of this
* accumulator together with the new list.
*
* Similar to [`mapAccum`](#mapAccum), except moves through the input list from
* the right to the left.
*
* The iterator function receives two arguments, *acc* and *value*, and should
* return a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.addIndex, R.mapAccum
* @example
*
* const digits = ['1', '2', '3', '4'];
* const appender = (a, b) => [b + a, b + a];
*
* R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']]
* @symb R.mapAccumRight(f, a, [b, c, d]) = [
* f(f(f(a, d)[0], c)[0], b)[0],
* [
* f(a, d)[1],
* f(f(a, d)[0], c)[1], | * ]
*/
var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
var idx = list.length - 1;
var result = [];
var tuple = [acc];
while (idx >= 0) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
}
return [tuple[0], result];
});
export default mapAccumRight; | * f(f(f(a, d)[0], c)[0], b)[1]
* ] | random_line_split |
mapAccumRight.js | import _curry3 from './internal/_curry3.js';
/**
* The `mapAccumRight` function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from right to left, and returning a final value of this
* accumulator together with the new list.
*
* Similar to [`mapAccum`](#mapAccum), except moves through the input list from
* the right to the left.
*
* The iterator function receives two arguments, *acc* and *value*, and should
* return a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.addIndex, R.mapAccum
* @example
*
* const digits = ['1', '2', '3', '4'];
* const appender = (a, b) => [b + a, b + a];
*
* R.mapAccumRight(appender, 5, digits); //=> ['12345', ['12345', '2345', '345', '45']]
* @symb R.mapAccumRight(f, a, [b, c, d]) = [
* f(f(f(a, d)[0], c)[0], b)[0],
* [
* f(a, d)[1],
* f(f(a, d)[0], c)[1],
* f(f(f(a, d)[0], c)[0], b)[1]
* ]
* ]
*/
var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
var idx = list.length - 1;
var result = [];
var tuple = [acc];
while (idx >= 0) |
return [tuple[0], result];
});
export default mapAccumRight;
| {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
} | conditional_block |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/',
'chambers': {
'upper': {'name': 'Senate', 'title': 'Senator'},
'lower': {'name': 'House', 'title': 'Representative'},
},
'terms': [
{'name': '2011-2012', 'sessions': ['2011', '2012'],
'start_year': 2011, 'end_year': 2012},
{'name': '2013-2014', 'sessions': ['2013', '2014'],
'start_year': 2013, 'end_year': 2014},
{'name': '2015-2016', 'sessions': ['2015', '2016'],
'start_year': 2015, 'end_year': 2016},
{'name': '2017-2018', 'sessions': ['2017'],
'start_year': 2017, 'end_year': 2018}
],
'session_details': {
'2011': {'display_name': '2011 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2011%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2011 Session',
},
'2012': {'display_name': '2012 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2012 Session',
},
'2013': {'display_name': '2013 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2013%20Session%20Bill%20Status%20Tables.zip',
# Their dump filename changed, probably just a hiccup.
'_scraped_name': '2013',
# '_scraped_name': '2013 Session',
},
'2014': {'display_name': '2014 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2014%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2014 Session',
},
'2015': {'display_name': '2015 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2015%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2015 Session',
},
'2016': {'display_name': '2016 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2016%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2016 Session',
},
'2017': {'display_name': '2017 Regular Session',
'_scraped_name': '2017 Session',
},
},
'feature_flags': ['subjects', 'influenceexplorer'],
'_ignored_scraped_sessions': ['2013 Session','2017 Session Bill Status Tables Link.txt'],
}
def session_list():
from billy.scrape.utils import url_xpath
zips = url_xpath('http://gencourt.state.nh.us/downloads/',
'//a[contains(@href, "Bill%20Status%20Tables")]/text()')
return [zip.replace(' Bill Status Tables.zip', '') for zip in zips]
def extract_text(doc, data):
| doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content() | identifier_body | |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/',
'chambers': {
'upper': {'name': 'Senate', 'title': 'Senator'},
'lower': {'name': 'House', 'title': 'Representative'},
},
'terms': [
{'name': '2011-2012', 'sessions': ['2011', '2012'],
'start_year': 2011, 'end_year': 2012},
{'name': '2013-2014', 'sessions': ['2013', '2014'],
'start_year': 2013, 'end_year': 2014},
{'name': '2015-2016', 'sessions': ['2015', '2016'],
'start_year': 2015, 'end_year': 2016},
{'name': '2017-2018', 'sessions': ['2017'],
'start_year': 2017, 'end_year': 2018}
],
'session_details': {
'2011': {'display_name': '2011 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2011%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2011 Session',
},
'2012': {'display_name': '2012 Regular Session', | # Their dump filename changed, probably just a hiccup.
'_scraped_name': '2013',
# '_scraped_name': '2013 Session',
},
'2014': {'display_name': '2014 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2014%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2014 Session',
},
'2015': {'display_name': '2015 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2015%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2015 Session',
},
'2016': {'display_name': '2016 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2016%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2016 Session',
},
'2017': {'display_name': '2017 Regular Session',
'_scraped_name': '2017 Session',
},
},
'feature_flags': ['subjects', 'influenceexplorer'],
'_ignored_scraped_sessions': ['2013 Session','2017 Session Bill Status Tables Link.txt'],
}
def session_list():
from billy.scrape.utils import url_xpath
zips = url_xpath('http://gencourt.state.nh.us/downloads/',
'//a[contains(@href, "Bill%20Status%20Tables")]/text()')
return [zip.replace(' Bill Status Tables.zip', '') for zip in zips]
def extract_text(doc, data):
doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content() | 'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2012 Session',
},
'2013': {'display_name': '2013 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2013%20Session%20Bill%20Status%20Tables.zip', | random_line_split |
__init__.py | import lxml.html
from .bills import NHBillScraper
from .legislators import NHLegislatorScraper
from .committees import NHCommitteeScraper
metadata = {
'abbreviation': 'nh',
'name': 'New Hampshire',
'capitol_timezone': 'America/New_York',
'legislature_name': 'New Hampshire General Court',
'legislature_url': 'http://www.gencourt.state.nh.us/',
'chambers': {
'upper': {'name': 'Senate', 'title': 'Senator'},
'lower': {'name': 'House', 'title': 'Representative'},
},
'terms': [
{'name': '2011-2012', 'sessions': ['2011', '2012'],
'start_year': 2011, 'end_year': 2012},
{'name': '2013-2014', 'sessions': ['2013', '2014'],
'start_year': 2013, 'end_year': 2014},
{'name': '2015-2016', 'sessions': ['2015', '2016'],
'start_year': 2015, 'end_year': 2016},
{'name': '2017-2018', 'sessions': ['2017'],
'start_year': 2017, 'end_year': 2018}
],
'session_details': {
'2011': {'display_name': '2011 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2011%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2011 Session',
},
'2012': {'display_name': '2012 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2012%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2012 Session',
},
'2013': {'display_name': '2013 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2013%20Session%20Bill%20Status%20Tables.zip',
# Their dump filename changed, probably just a hiccup.
'_scraped_name': '2013',
# '_scraped_name': '2013 Session',
},
'2014': {'display_name': '2014 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2014%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2014 Session',
},
'2015': {'display_name': '2015 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2015%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2015 Session',
},
'2016': {'display_name': '2016 Regular Session',
'zip_url': 'http://gencourt.state.nh.us/downloads/2016%20Session%20Bill%20Status%20Tables.zip',
'_scraped_name': '2016 Session',
},
'2017': {'display_name': '2017 Regular Session',
'_scraped_name': '2017 Session',
},
},
'feature_flags': ['subjects', 'influenceexplorer'],
'_ignored_scraped_sessions': ['2013 Session','2017 Session Bill Status Tables Link.txt'],
}
def session_list():
from billy.scrape.utils import url_xpath
zips = url_xpath('http://gencourt.state.nh.us/downloads/',
'//a[contains(@href, "Bill%20Status%20Tables")]/text()')
return [zip.replace(' Bill Status Tables.zip', '') for zip in zips]
def | (doc, data):
doc = lxml.html.fromstring(data)
return doc.xpath('//html')[0].text_content()
| extract_text | identifier_name |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
return [
'ssh', sshopts,
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && python ./lock.py %s' % subcmd)
]
def lock_operation(command):
# Copy essential sources always to remote host. This is necessary as
# another test executor might have removed the files meanwhile.
files = [os.path.join(localdir, f) for f in ['lock.py', 'remote.py']]
cmds = [[
'scp',
sshopts,
] + files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)],
lock_cmd(command)]
for cmd in cmds:
assert_subprocess(cmd)
def | ():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def scp_tests():
test_files = [
os.path.abspath(t)
for t in glob.glob(os.path.join(localdir, 'test_*')) +
[os.path.join(localdir, 'remote.py')]
]
cmd = ['scp'
] + test_files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def rm_rf_testfiles():
cmd = [
'ssh',
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && del /S /F /Q * '
'&& for /d %G in ("*") do rmdir "%~G" /Q')
]
exit_code, stdout, stderr = run_subprocess(cmd)
if stdout:
sys.stdout.write(stdout)
if stderr:
sys.stderr.write(stderr)
if exit_code != 0:
pytest.skip(stderr)
@pytest.fixture(scope='session', autouse=True)
def session_scope():
try:
acquire_lock()
scp_agent_exe()
scp_tests()
yield
finally:
release_lock()
rm_rf_testfiles()
| acquire_lock | identifier_name |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
return [
'ssh', sshopts,
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && python ./lock.py %s' % subcmd)
]
def lock_operation(command):
# Copy essential sources always to remote host. This is necessary as
# another test executor might have removed the files meanwhile.
files = [os.path.join(localdir, f) for f in ['lock.py', 'remote.py']]
cmds = [[
'scp',
sshopts,
] + files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)],
lock_cmd(command)]
for cmd in cmds:
assert_subprocess(cmd)
def acquire_lock():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def scp_tests():
|
def rm_rf_testfiles():
cmd = [
'ssh',
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && del /S /F /Q * '
'&& for /d %G in ("*") do rmdir "%~G" /Q')
]
exit_code, stdout, stderr = run_subprocess(cmd)
if stdout:
sys.stdout.write(stdout)
if stderr:
sys.stderr.write(stderr)
if exit_code != 0:
pytest.skip(stderr)
@pytest.fixture(scope='session', autouse=True)
def session_scope():
try:
acquire_lock()
scp_agent_exe()
scp_tests()
yield
finally:
release_lock()
rm_rf_testfiles()
| test_files = [
os.path.abspath(t)
for t in glob.glob(os.path.join(localdir, 'test_*')) +
[os.path.join(localdir, 'remote.py')]
]
cmd = ['scp'
] + test_files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd) | identifier_body |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
return [
'ssh', sshopts,
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && python ./lock.py %s' % subcmd)
]
def lock_operation(command):
# Copy essential sources always to remote host. This is necessary as
# another test executor might have removed the files meanwhile.
files = [os.path.join(localdir, f) for f in ['lock.py', 'remote.py']]
cmds = [[
'scp',
sshopts,
] + files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)],
lock_cmd(command)]
for cmd in cmds:
|
def acquire_lock():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def scp_tests():
test_files = [
os.path.abspath(t)
for t in glob.glob(os.path.join(localdir, 'test_*')) +
[os.path.join(localdir, 'remote.py')]
]
cmd = ['scp'
] + test_files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def rm_rf_testfiles():
cmd = [
'ssh',
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && del /S /F /Q * '
'&& for /d %G in ("*") do rmdir "%~G" /Q')
]
exit_code, stdout, stderr = run_subprocess(cmd)
if stdout:
sys.stdout.write(stdout)
if stderr:
sys.stderr.write(stderr)
if exit_code != 0:
pytest.skip(stderr)
@pytest.fixture(scope='session', autouse=True)
def session_scope():
try:
acquire_lock()
scp_agent_exe()
scp_tests()
yield
finally:
release_lock()
rm_rf_testfiles()
| assert_subprocess(cmd) | conditional_block |
conftest.py | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset: 4 -*-
import glob
import os
import pytest
from remote import (assert_subprocess, remote_ip, remotedir, remoteuser,
run_subprocess, sshopts)
import sys
localdir = os.path.dirname(os.path.abspath(__file__))
def lock_cmd(subcmd):
return [
'ssh', sshopts,
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && python ./lock.py %s' % subcmd)
]
def lock_operation(command):
# Copy essential sources always to remote host. This is necessary as
# another test executor might have removed the files meanwhile.
files = [os.path.join(localdir, f) for f in ['lock.py', 'remote.py']]
cmds = [[
'scp',
sshopts,
] + files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)],
lock_cmd(command)]
for cmd in cmds:
assert_subprocess(cmd)
def acquire_lock():
lock_operation('acquire')
def release_lock():
lock_operation('release')
def scp_agent_exe():
agents_windows_dir = os.path.dirname(localdir)
agent_exe = os.path.join(agents_windows_dir, 'check_mk_agent-64.exe')
cmd = ['scp', agent_exe, '%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def scp_tests():
test_files = [
os.path.abspath(t)
for t in glob.glob(os.path.join(localdir, 'test_*')) +
[os.path.join(localdir, 'remote.py')]
]
cmd = ['scp'
] + test_files + ['%s@%s:%s' % (remoteuser, remote_ip, remotedir)]
assert_subprocess(cmd)
def rm_rf_testfiles():
cmd = [
'ssh',
'%s@%s' % (remoteuser, remote_ip),
('cd %s' % remotedir + ' && del /S /F /Q * '
'&& for /d %G in ("*") do rmdir "%~G" /Q')
]
exit_code, stdout, stderr = run_subprocess(cmd)
if stdout:
sys.stdout.write(stdout)
if stderr:
sys.stderr.write(stderr)
if exit_code != 0:
pytest.skip(stderr)
@pytest.fixture(scope='session', autouse=True)
def session_scope():
try:
acquire_lock() | scp_agent_exe()
scp_tests()
yield
finally:
release_lock()
rm_rf_testfiles() | random_line_split | |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {Node} - The located html element. | if (context !== undefined) {
if (matches(context, element)) {
return context;
}
else {
return context.querySelector(element);
}
}
else {
return document.querySelector(element);
}
}
if (element instanceof Node) {
return element;
}
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @returns {array[HTMLElement]} - The results array to append to.
* @returns {array[HTMLElement]} - The located html element. Will be the results array if one is passed otherwise a new one.
*/
export function all(element: HTMLElement | HTMLElement[] | string, context?: HTMLElement, results?: HTMLElement[]): HTMLElement[] {
if (typeof element === 'string') {
if (results === undefined) {
results = [];
}
if (context !== undefined) {
//Be sure to include the main element if it matches the selector.
if (matches(context, element)) {
results.push(context);
}
//This will add all child elements that match the selector.
nodesToArray(context.querySelectorAll(element), results);
}
else {
nodesToArray(document.querySelectorAll(element), results);
}
}
else if (element instanceof HTMLElement) {
if (results === undefined) {
results = [element];
}
else {
results.push(element);
}
}
else {
if (results === undefined) {
results = element;
}
else {
for (var i = 0; i < element.length; ++i) {
results.push(element[i]);
}
}
}
return results;
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @param cb - Called with each htmlelement that is found
*/
export function iterate(element: HTMLElement | HTMLElement[] | string, context: HTMLElement, cb: ElementIteratorCallback) {
if (typeId.isString(element)) {
if (context) {
if (matches(context, element)) {
cb(context);
}
else {
iterateQuery(context.querySelectorAll(element), cb);
}
}
else {
iterateQuery(document.querySelectorAll(element), cb);
}
}
else if (element instanceof HTMLElement) {
cb(element);
}
else if (Array.isArray(element)) {
for (var i = 0; i < element.length; ++i) {
cb(element[i]);
}
}
};
function alwaysTrue(node) {
return true;
}
//createNodeIterator is tricky, this will make sure it can be called on ie and modern browsers
var createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return document.createNodeIterator(root, whatToShow);
}
try {
//See if the default version works, no error should occur during the following call.
const iter = createNodeIteratorShim(document, NodeFilter.SHOW_ELEMENT);
} catch (_) {
//If we get an error here the default version does not work, so use the shimmed version for ie.
createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return (<any>document).createNodeIterator(root, whatToShow, alwaysTrue, false);
}
}
/**
* Iterate a node collection using createNodeIterator. There is no query for this version
* as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateNodes(node: Node, whatToShow?: number, cb?: NodeIteratorCallback) {
var iter = createNodeIteratorShim(node, whatToShow);
var resultNode;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Iterate an element collection using createNodeIterator with SHOW_ELEMENT as its arg.
* There is no query for this version as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateElementNodes(node: Node, cb?: ElementIteratorCallback) {
var iter = createNodeIteratorShim(node, NodeFilter.SHOW_ELEMENT);
var resultNode: any;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Determine if an element matches the given selector.
* @param {type} element
* @param {type} selector
* @returns {type}
*/
export function matches(element: Element, selector: string) {
return element.matches(selector);
}
function nodesToArray(nodes: NodeListOf<Element>, arr: Element[]) {
for (var i = 0; i < nodes.length; ++i) {
arr.push(nodes[i]);
}
}
function iterateQuery(nodes: NodeListOf<Element>, cb: ElementIteratorCallback) {
for (var i = 0; i < nodes.length; ++i) {
cb(nodes[i]);
}
} | */
export function first(element: Node | string, context?: HTMLElement): Node {
if (typeof element === 'string') { | random_line_split |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {Node} - The located html element.
*/
export function fi | lement: Node | string, context?: HTMLElement): Node {
if (typeof element === 'string') {
if (context !== undefined) {
if (matches(context, element)) {
return context;
}
else {
return context.querySelector(element);
}
}
else {
return document.querySelector(element);
}
}
if (element instanceof Node) {
return element;
}
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @returns {array[HTMLElement]} - The results array to append to.
* @returns {array[HTMLElement]} - The located html element. Will be the results array if one is passed otherwise a new one.
*/
export function all(element: HTMLElement | HTMLElement[] | string, context?: HTMLElement, results?: HTMLElement[]): HTMLElement[] {
if (typeof element === 'string') {
if (results === undefined) {
results = [];
}
if (context !== undefined) {
//Be sure to include the main element if it matches the selector.
if (matches(context, element)) {
results.push(context);
}
//This will add all child elements that match the selector.
nodesToArray(context.querySelectorAll(element), results);
}
else {
nodesToArray(document.querySelectorAll(element), results);
}
}
else if (element instanceof HTMLElement) {
if (results === undefined) {
results = [element];
}
else {
results.push(element);
}
}
else {
if (results === undefined) {
results = element;
}
else {
for (var i = 0; i < element.length; ++i) {
results.push(element[i]);
}
}
}
return results;
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @param cb - Called with each htmlelement that is found
*/
export function iterate(element: HTMLElement | HTMLElement[] | string, context: HTMLElement, cb: ElementIteratorCallback) {
if (typeId.isString(element)) {
if (context) {
if (matches(context, element)) {
cb(context);
}
else {
iterateQuery(context.querySelectorAll(element), cb);
}
}
else {
iterateQuery(document.querySelectorAll(element), cb);
}
}
else if (element instanceof HTMLElement) {
cb(element);
}
else if (Array.isArray(element)) {
for (var i = 0; i < element.length; ++i) {
cb(element[i]);
}
}
};
function alwaysTrue(node) {
return true;
}
//createNodeIterator is tricky, this will make sure it can be called on ie and modern browsers
var createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return document.createNodeIterator(root, whatToShow);
}
try {
//See if the default version works, no error should occur during the following call.
const iter = createNodeIteratorShim(document, NodeFilter.SHOW_ELEMENT);
} catch (_) {
//If we get an error here the default version does not work, so use the shimmed version for ie.
createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return (<any>document).createNodeIterator(root, whatToShow, alwaysTrue, false);
}
}
/**
* Iterate a node collection using createNodeIterator. There is no query for this version
* as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateNodes(node: Node, whatToShow?: number, cb?: NodeIteratorCallback) {
var iter = createNodeIteratorShim(node, whatToShow);
var resultNode;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Iterate an element collection using createNodeIterator with SHOW_ELEMENT as its arg.
* There is no query for this version as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateElementNodes(node: Node, cb?: ElementIteratorCallback) {
var iter = createNodeIteratorShim(node, NodeFilter.SHOW_ELEMENT);
var resultNode: any;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Determine if an element matches the given selector.
* @param {type} element
* @param {type} selector
* @returns {type}
*/
export function matches(element: Element, selector: string) {
return element.matches(selector);
}
function nodesToArray(nodes: NodeListOf<Element>, arr: Element[]) {
for (var i = 0; i < nodes.length; ++i) {
arr.push(nodes[i]);
}
}
function iterateQuery(nodes: NodeListOf<Element>, cb: ElementIteratorCallback) {
for (var i = 0; i < nodes.length; ++i) {
cb(nodes[i]);
}
} | rst(e | identifier_name |
domquery.ts | "use strict";
import * as typeId from './typeidentifiers';
export type NodeIteratorCallback = (node: Node) => void;
export type ElementIteratorCallback = (element: Element) => void;
/**
* Derive the plain javascript element from a passed element
* @param {string|Node} element - the element to detect
* @returns {Node} - The located html element.
*/
export function first(element: Node | string, context?: HTMLElement): Node {
if (typeof element === 'string') {
if (context !== undefined) {
if (matches(context, element)) {
return context;
}
else {
return context.querySelector(element);
}
}
else {
return document.querySelector(element);
}
}
if (element instanceof Node) {
return element;
}
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @returns {array[HTMLElement]} - The results array to append to.
* @returns {array[HTMLElement]} - The located html element. Will be the results array if one is passed otherwise a new one.
*/
export function all(element: HTMLElement | HTMLElement[] | string, context?: HTMLElement, results?: HTMLElement[]): HTMLElement[] {
if (typeof element === 'string') {
if (results === undefined) {
results = [];
}
if (context !== undefined) {
//Be sure to include the main element if it matches the selector.
if (matches(context, element)) {
results.push(context);
}
//This will add all child elements that match the selector.
nodesToArray(context.querySelectorAll(element), results);
}
else {
nodesToArray(document.querySelectorAll(element), results);
}
}
else if (element instanceof HTMLElement) {
if (results === undefined) {
results = [element];
}
else {
results.push(element);
}
}
else {
if (results === undefined) {
results = element;
}
else {
for (var i = 0; i < element.length; ++i) {
results.push(element[i]);
}
}
}
return results;
};
/**
* Query all passed javascript elements
* @param {string|HTMLElement} element - the element to detect
* @param {HTMLElement} element - the context to search
* @param cb - Called with each htmlelement that is found
*/
export function iterate(element: HTMLElement | HTMLElement[] | string, context: HTMLElement, cb: ElementIteratorCallback) {
if (typeId.isString(element)) {
if (context) {
if (matches(context, element)) {
cb(context);
}
else {
iterateQuery(context.querySelectorAll(element), cb);
}
}
else {
iterateQuery(document.querySelectorAll(element), cb);
}
}
else if (element instanceof HTMLElement) {
cb(element);
}
else if (Array.isArray(element)) {
for (var i = 0; i < element.length; ++i) {
cb(element[i]);
}
}
};
function alwaysTrue(node) {
return true;
}
//createNodeIterator is tricky, this will make sure it can be called on ie and modern browsers
var createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return document.createNodeIterator(root, whatToShow);
}
try {
//See if the default version works, no error should occur during the following call.
const iter = createNodeIteratorShim(document, NodeFilter.SHOW_ELEMENT);
} catch (_) {
//If we get an error here the default version does not work, so use the shimmed version for ie.
createNodeIteratorShim = function (root: Node, whatToShow?: number) {
return (<any>document).createNodeIterator(root, whatToShow, alwaysTrue, false);
}
}
/**
* Iterate a node collection using createNodeIterator. There is no query for this version
* as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateNodes(node: Node, whatToShow?: number, cb?: NodeIteratorCallback) {
var iter = createNodeIteratorShim(node, whatToShow);
var resultNode;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Iterate an element collection using createNodeIterator with SHOW_ELEMENT as its arg.
* There is no query for this version as it iterates everything and allows you to extract what is needed.
* @param element - The root element
* @param {NodeFilter} whatToShow - see createNodeIterator, defaults to SHOW_ALL
* @param cb - The function called for each item iterated
*/
export function iterateElementNodes(node: Node, cb?: ElementIteratorCallback) {
var iter = createNodeIteratorShim(node, NodeFilter.SHOW_ELEMENT);
var resultNode: any;
while (resultNode = iter.nextNode()) {
cb(resultNode);
}
}
/**
* Determine if an element matches the given selector.
* @param {type} element
* @param {type} selector
* @returns {type}
*/
export function matches(element: Element, selector: string) {
return element.matches(selector);
}
function nodesToArray(nodes: NodeListOf<Element>, arr: Element[]) {
for (var i = 0; i < nodes.length; ++i) {
arr.push(nodes[i]);
}
}
function iterateQuery(nodes: NodeListOf<Element>, cb: ElementIteratorCallback) {
| for (var i = 0; i < nodes.length; ++i) {
cb(nodes[i]);
}
} | identifier_body | |
cursor.js | GLOBAL.DEBUG = true;
sys = require("sys");
test = require("assert"); |
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
sys.puts("Connecting to " + host + ":" + port);
var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true});
db.open(function(err, db) {
db.collection('test', function(err, collection) {
// Erase all records from collection, if any
collection.remove(function(err, result) {
// Insert 3 records
for(var i = 0; i < 3; i++) {
collection.insert({'a':i});
}
// Cursors don't run their queries until you actually attempt to retrieve data
// from them.
// Find returns a Cursor, which is Enumerable. You can iterate:
collection.find(function(err, cursor) {
cursor.each(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
});
});
// You can turn it into an array
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
sys.puts("count: " + items.length);
});
});
// You can iterate after turning it into an array (the cursor will iterate over
// the copy of the array that it saves internally.)
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
cursor.each(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
});
});
});
// You can get the next object
collection.find(function(err, cursor) {
cursor.nextObject(function(err, item) {
if(item != null) sys.puts(sys.inspect(item));
});
});
// next_object returns null if there are no more objects that match
collection.find(function(err, cursor) {
cursor.nextObject(function(err, item) {
cursor.nextObject(function(err, item) {
cursor.nextObject(function(err, item) {
cursor.nextObject(function(err, item) {
sys.puts("nextObject returned: " + sys.inspect(item));
db.close();
});
});
});
});
});
});
});
}); |
var Db = require('../lib/mongodb').Db,
Connection = require('../lib/mongodb').Connection,
Server = require('../lib/mongodb').Server; | random_line_split |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionComponent } from 'react'
import { isAuthenticated, login } from '../../utils/auth/auth'
import requestDownloadLink from '../../../api/dataselectie/requestDownloadLink'
import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'
const ModalBody = styled.div`
padding: ${themeSpacing(6, 4)};
`
const ButtonBar = styled.div`
> *:not(:last-of-type) {
margin-right: ${themeSpacing(4)};
}
`
interface DataSelectionDownloadModalProps {
url: string
maxDownloadLimit: number
tooManyResults: boolean
onClose: () => void
}
const DataSelectionDownloadModal: FunctionComponent<DataSelectionDownloadModalProps> = ({
url,
maxDownloadLimit,
tooManyResults,
onClose,
}) => {
const [retryCount, setRetryCount] = useState<number>(0)
const result = usePromise(() => {
if (!tooManyResults) {
return requestDownloadLink(url)
}
return Promise.reject()
}, [url, retryCount])
function handleLogin() |
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
onClick={onClose}
icon={<Close />}
/>
</Heading>
</TopBar>
<Divider />
<ModalBody>
{tooManyResults ? (
<>
<Paragraph data-testid="tooManyResults">
Downloads zijn beperkt tot een maximum van {maxDownloadLimit} resultaten. Gebruik de
filters om het aantal resultaten te beperken.
</Paragraph>
<ButtonBar>
<Button type="button" onClick={onClose}>
Sluiten
</Button>
</ButtonBar>
</>
) : (
<>
{!isRejected(result) && <LoadingSpinner />}
{isRejected(result) && (
<>
<Paragraph data-testid="errorMessage">
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.'
? 'Je moet inloggen om te downloaden.'
: 'Er is helaas iets mis gegaan met de download. Probeer het nog eens.'}
</Paragraph>
<ButtonBar>
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.' ? (
<Button type="button" variant="primary" onClick={() => handleLogin()}>
Inloggen
</Button>
) : (
<Button
type="button"
variant="primary"
onClick={() => setRetryCount(retryCount + 1)}
>
Probeer opnieuw
</Button>
)}
<Button type="button" onClick={onClose}>
Annuleren
</Button>
</ButtonBar>
</>
)}
</>
)}
</ModalBody>
</Modal>
)
}
export default DataSelectionDownloadModal
| {
login()
} | identifier_body |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionComponent } from 'react'
import { isAuthenticated, login } from '../../utils/auth/auth'
import requestDownloadLink from '../../../api/dataselectie/requestDownloadLink'
import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'
const ModalBody = styled.div`
padding: ${themeSpacing(6, 4)};
`
const ButtonBar = styled.div`
> *:not(:last-of-type) {
margin-right: ${themeSpacing(4)};
}
`
interface DataSelectionDownloadModalProps {
url: string
maxDownloadLimit: number
tooManyResults: boolean
onClose: () => void
}
const DataSelectionDownloadModal: FunctionComponent<DataSelectionDownloadModalProps> = ({
url,
maxDownloadLimit,
tooManyResults,
onClose,
}) => {
const [retryCount, setRetryCount] = useState<number>(0)
const result = usePromise(() => {
if (!tooManyResults) {
return requestDownloadLink(url)
}
return Promise.reject()
}, [url, retryCount])
function | () {
login()
}
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
onClick={onClose}
icon={<Close />}
/>
</Heading>
</TopBar>
<Divider />
<ModalBody>
{tooManyResults ? (
<>
<Paragraph data-testid="tooManyResults">
Downloads zijn beperkt tot een maximum van {maxDownloadLimit} resultaten. Gebruik de
filters om het aantal resultaten te beperken.
</Paragraph>
<ButtonBar>
<Button type="button" onClick={onClose}>
Sluiten
</Button>
</ButtonBar>
</>
) : (
<>
{!isRejected(result) && <LoadingSpinner />}
{isRejected(result) && (
<>
<Paragraph data-testid="errorMessage">
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.'
? 'Je moet inloggen om te downloaden.'
: 'Er is helaas iets mis gegaan met de download. Probeer het nog eens.'}
</Paragraph>
<ButtonBar>
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.' ? (
<Button type="button" variant="primary" onClick={() => handleLogin()}>
Inloggen
</Button>
) : (
<Button
type="button"
variant="primary"
onClick={() => setRetryCount(retryCount + 1)}
>
Probeer opnieuw
</Button>
)}
<Button type="button" onClick={onClose}>
Annuleren
</Button>
</ButtonBar>
</>
)}
</>
)}
</ModalBody>
</Modal>
)
}
export default DataSelectionDownloadModal
| handleLogin | identifier_name |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionComponent } from 'react'
import { isAuthenticated, login } from '../../utils/auth/auth'
import requestDownloadLink from '../../../api/dataselectie/requestDownloadLink'
import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'
const ModalBody = styled.div`
padding: ${themeSpacing(6, 4)};
`
const ButtonBar = styled.div`
> *:not(:last-of-type) {
margin-right: ${themeSpacing(4)};
}
`
interface DataSelectionDownloadModalProps {
url: string
maxDownloadLimit: number
tooManyResults: boolean
onClose: () => void
}
const DataSelectionDownloadModal: FunctionComponent<DataSelectionDownloadModalProps> = ({
url,
maxDownloadLimit,
tooManyResults,
onClose,
}) => {
const [retryCount, setRetryCount] = useState<number>(0)
const result = usePromise(() => {
if (!tooManyResults) {
return requestDownloadLink(url)
}
return Promise.reject()
}, [url, retryCount])
function handleLogin() {
login()
}
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
onClick={onClose}
icon={<Close />}
/>
</Heading>
</TopBar>
<Divider />
<ModalBody>
{tooManyResults ? (
<>
<Paragraph data-testid="tooManyResults">
Downloads zijn beperkt tot een maximum van {maxDownloadLimit} resultaten. Gebruik de
filters om het aantal resultaten te beperken.
</Paragraph>
<ButtonBar>
<Button type="button" onClick={onClose}>
Sluiten
</Button>
</ButtonBar>
</>
) : (
<>
{!isRejected(result) && <LoadingSpinner />}
{isRejected(result) && (
<>
<Paragraph data-testid="errorMessage">
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.'
? 'Je moet inloggen om te downloaden.'
: 'Er is helaas iets mis gegaan met de download. Probeer het nog eens.'}
</Paragraph>
<ButtonBar>
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.' ? (
<Button type="button" variant="primary" onClick={() => handleLogin()}>
Inloggen
</Button>
) : (
<Button
type="button"
variant="primary"
onClick={() => setRetryCount(retryCount + 1)}
>
Probeer opnieuw
</Button>
)}
<Button type="button" onClick={onClose}>
Annuleren
</Button>
</ButtonBar>
</>
)}
</> |
export default DataSelectionDownloadModal | )}
</ModalBody>
</Modal>
)
} | random_line_split |
DataSelectionDownloadModal.tsx | import { Close } from '@amsterdam/asc-assets'
import { Button, Divider, Heading, Modal, Paragraph, themeSpacing, TopBar } from '@amsterdam/asc-ui'
import usePromise, { isFulfilled, isRejected } from '@amsterdam/use-promise'
import { useState } from 'react'
import styled from 'styled-components'
import type { FunctionComponent } from 'react'
import { isAuthenticated, login } from '../../utils/auth/auth'
import requestDownloadLink from '../../../api/dataselectie/requestDownloadLink'
import LoadingSpinner from '../LoadingSpinner/LoadingSpinner'
const ModalBody = styled.div`
padding: ${themeSpacing(6, 4)};
`
const ButtonBar = styled.div`
> *:not(:last-of-type) {
margin-right: ${themeSpacing(4)};
}
`
interface DataSelectionDownloadModalProps {
url: string
maxDownloadLimit: number
tooManyResults: boolean
onClose: () => void
}
const DataSelectionDownloadModal: FunctionComponent<DataSelectionDownloadModalProps> = ({
url,
maxDownloadLimit,
tooManyResults,
onClose,
}) => {
const [retryCount, setRetryCount] = useState<number>(0)
const result = usePromise(() => {
if (!tooManyResults) |
return Promise.reject()
}, [url, retryCount])
function handleLogin() {
login()
}
if (isFulfilled(result)) {
onClose()
return null
}
return (
<Modal open onClose={onClose}>
<TopBar>
<Heading as="h4">
Downloaden
<Button
variant="blank"
title="Sluit"
type="button"
size={30}
onClick={onClose}
icon={<Close />}
/>
</Heading>
</TopBar>
<Divider />
<ModalBody>
{tooManyResults ? (
<>
<Paragraph data-testid="tooManyResults">
Downloads zijn beperkt tot een maximum van {maxDownloadLimit} resultaten. Gebruik de
filters om het aantal resultaten te beperken.
</Paragraph>
<ButtonBar>
<Button type="button" onClick={onClose}>
Sluiten
</Button>
</ButtonBar>
</>
) : (
<>
{!isRejected(result) && <LoadingSpinner />}
{isRejected(result) && (
<>
<Paragraph data-testid="errorMessage">
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.'
? 'Je moet inloggen om te downloaden.'
: 'Er is helaas iets mis gegaan met de download. Probeer het nog eens.'}
</Paragraph>
<ButtonBar>
{!isAuthenticated() &&
result?.reason.message === 'Unable to request download, no token present.' ? (
<Button type="button" variant="primary" onClick={() => handleLogin()}>
Inloggen
</Button>
) : (
<Button
type="button"
variant="primary"
onClick={() => setRetryCount(retryCount + 1)}
>
Probeer opnieuw
</Button>
)}
<Button type="button" onClick={onClose}>
Annuleren
</Button>
</ButtonBar>
</>
)}
</>
)}
</ModalBody>
</Modal>
)
}
export default DataSelectionDownloadModal
| {
return requestDownloadLink(url)
} | conditional_block |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import {IJenkinsJob} from 'jenkins-api-ts-typings';
import {JenkinsDataRetrieverService} from './JenkinsDataRetrieverService';
import {JenkinsServiceId} from './JenkinsServiceId';
/**
* Retrieve the jenkins job's details from each job url
*/
export class JenkinsJobService extends JenkinsDataRetrieverService {
constructor(private config: ConfigService, private proxy: ProxyService, private util: UtilService, private LOGGER: Logger, private jobList: Array<IJenkinsJob>) {
super();
}
async execute() {
if (this.util.isInvalid(this.jobList)) {
this.LOGGER.error("Empty or null job list received");
this.completedSuccessfully = false;
this.allItemsRetrievedSuccessfully = false;
this.complete = true;
return;
}
let jobPromises: Array<Promise<JSON>> = new Array<Promise<JSON>>();
let i = 0;
for (let job of this.jobList) {
i++;
this.LOGGER.debug("Retrieving job details for:", job.name, "(", i, "/", this.jobList.length, ")");
let jobUrl: string = this.getJobApiUrl(job.url, this.config);
jobPromises.push(this.proxy.proxy(jobUrl)
.first()
.toPromise()
.catch(() => {
this.LOGGER.warn("Error retrieving details for job", job.name);
this.allItemsRetrievedSuccessfully = false;
}));
}
await Promise.all(jobPromises)
.then(values => {
for (let jobJson of <Array<JSON>> values) {
if (this.util.isInvalid(jobJson) || !(<JSON> jobJson).hasOwnProperty("name")) {
this.LOGGER.warn("No job details found for:", jobJson);
this.allItemsRetrievedSuccessfully = false;
continue;
}
let job = this.util.getJobByName(this.jobList, jobJson["name"]);
if (job === undefined) {
this.LOGGER.warn("No job with name", jobJson["name"], "found");
this.allItemsRetrievedSuccessfully = false;
continue;
}
job.fromJson(jobJson);
job.upstreamProjects = this.getUpstreamProjects(jobJson, job);
job.downstreamProjects = this.getDownstreamProjects(jobJson, job);
this.LOGGER.debug("Updated details for job:", job.name);
}
this.completedSuccessfully = true;
this.complete = true;
});
this.LOGGER.info("Job details updated:", this.jobList);
this.completedSuccessfully = true;
this.complete = true;
}
/**
* Get the jobs
*/
getData(): Array<IJenkinsJob> {
if (this.util.isInvalid(this.jobList)) {
return new Array<IJenkinsJob>();
}
return this.jobList;
}
getServiceId() {
return JenkinsServiceId.Jobs;
}
private getUpstreamProjects(jobJson: JSON, job: IJenkinsJob): Array<IJenkinsJob> {
let upstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("upstreamProjects")) {
this.LOGGER.debug("No upstream projects found for:", job);
return upstreamProjects;
}
for (let upstreamJobJson of (jobJson["upstreamProjects"] as Array<JSON>)) {
let upstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, upstreamJobJson["name"]);
if (upstreamJob === undefined) {
continue;
}
upstreamProjects.push(upstreamJob);
}
return upstreamProjects;
}
private getDownstreamProjects(jobJson: JSON, job: IJenkinsJob) {
let downstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("downstreamProjects")) {
this.LOGGER.debug("No downstream projects found for:", job);
return downstreamProjects;
}
for (let downstreamJobJson of (jobJson["downstreamProjects"] as Array<JSON>)) {
let downstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, downstreamJobJson["name"]);
if (downstreamJob === undefined) |
downstreamProjects.push(downstreamJob);
}
return downstreamProjects;
}
private getJobApiUrl(jobUrl: string, config: ConfigService) {
if (jobUrl === undefined || jobUrl === null || jobUrl.length === 0) {
return undefined;
}
/** Remove trailing slash ('/') from root url, if present, then concatenate the jenkins api suffix */
return jobUrl.replace(/\/$/, "") + '/' + config.apiSuffix;
}
}
| {
continue;
} | conditional_block |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import {IJenkinsJob} from 'jenkins-api-ts-typings';
import {JenkinsDataRetrieverService} from './JenkinsDataRetrieverService';
import {JenkinsServiceId} from './JenkinsServiceId';
/**
* Retrieve the jenkins job's details from each job url
*/
export class JenkinsJobService extends JenkinsDataRetrieverService {
constructor(private config: ConfigService, private proxy: ProxyService, private util: UtilService, private LOGGER: Logger, private jobList: Array<IJenkinsJob>) {
super();
}
async execute() {
if (this.util.isInvalid(this.jobList)) {
this.LOGGER.error("Empty or null job list received");
this.completedSuccessfully = false;
this.allItemsRetrievedSuccessfully = false;
this.complete = true;
return;
}
let jobPromises: Array<Promise<JSON>> = new Array<Promise<JSON>>();
let i = 0;
for (let job of this.jobList) {
i++;
this.LOGGER.debug("Retrieving job details for:", job.name, "(", i, "/", this.jobList.length, ")");
let jobUrl: string = this.getJobApiUrl(job.url, this.config);
jobPromises.push(this.proxy.proxy(jobUrl)
.first()
.toPromise()
.catch(() => {
this.LOGGER.warn("Error retrieving details for job", job.name);
this.allItemsRetrievedSuccessfully = false;
}));
}
await Promise.all(jobPromises)
.then(values => {
for (let jobJson of <Array<JSON>> values) {
if (this.util.isInvalid(jobJson) || !(<JSON> jobJson).hasOwnProperty("name")) {
this.LOGGER.warn("No job details found for:", jobJson);
this.allItemsRetrievedSuccessfully = false;
continue;
}
let job = this.util.getJobByName(this.jobList, jobJson["name"]);
if (job === undefined) {
this.LOGGER.warn("No job with name", jobJson["name"], "found");
this.allItemsRetrievedSuccessfully = false;
continue;
}
job.fromJson(jobJson);
job.upstreamProjects = this.getUpstreamProjects(jobJson, job);
job.downstreamProjects = this.getDownstreamProjects(jobJson, job);
this.LOGGER.debug("Updated details for job:", job.name);
}
this.completedSuccessfully = true;
this.complete = true;
});
this.LOGGER.info("Job details updated:", this.jobList);
this.completedSuccessfully = true;
this.complete = true;
}
/**
* Get the jobs
*/
getData(): Array<IJenkinsJob> {
if (this.util.isInvalid(this.jobList)) {
return new Array<IJenkinsJob>();
}
return this.jobList;
}
getServiceId() {
return JenkinsServiceId.Jobs;
}
private getUpstreamProjects(jobJson: JSON, job: IJenkinsJob): Array<IJenkinsJob> {
let upstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("upstreamProjects")) {
this.LOGGER.debug("No upstream projects found for:", job);
return upstreamProjects;
}
for (let upstreamJobJson of (jobJson["upstreamProjects"] as Array<JSON>)) {
let upstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, upstreamJobJson["name"]);
if (upstreamJob === undefined) {
continue;
}
upstreamProjects.push(upstreamJob);
}
return upstreamProjects;
}
private | (jobJson: JSON, job: IJenkinsJob) {
let downstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("downstreamProjects")) {
this.LOGGER.debug("No downstream projects found for:", job);
return downstreamProjects;
}
for (let downstreamJobJson of (jobJson["downstreamProjects"] as Array<JSON>)) {
let downstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, downstreamJobJson["name"]);
if (downstreamJob === undefined) {
continue;
}
downstreamProjects.push(downstreamJob);
}
return downstreamProjects;
}
private getJobApiUrl(jobUrl: string, config: ConfigService) {
if (jobUrl === undefined || jobUrl === null || jobUrl.length === 0) {
return undefined;
}
/** Remove trailing slash ('/') from root url, if present, then concatenate the jenkins api suffix */
return jobUrl.replace(/\/$/, "") + '/' + config.apiSuffix;
}
}
| getDownstreamProjects | identifier_name |
jenkins-job.service.ts | import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/first';
import {ConfigService} from '../../config/services/config.service';
import {ProxyService} from '../../proxy/services/proxy.service';
import {UtilService} from '../../util/services/util.service'
import {Logger} from 'angular2-logger/core';
import {IJenkinsJob} from 'jenkins-api-ts-typings';
import {JenkinsDataRetrieverService} from './JenkinsDataRetrieverService';
import {JenkinsServiceId} from './JenkinsServiceId';
/**
* Retrieve the jenkins job's details from each job url
*/
export class JenkinsJobService extends JenkinsDataRetrieverService {
constructor(private config: ConfigService, private proxy: ProxyService, private util: UtilService, private LOGGER: Logger, private jobList: Array<IJenkinsJob>) {
super();
}
async execute() {
if (this.util.isInvalid(this.jobList)) {
this.LOGGER.error("Empty or null job list received");
this.completedSuccessfully = false;
this.allItemsRetrievedSuccessfully = false;
this.complete = true;
return;
}
let jobPromises: Array<Promise<JSON>> = new Array<Promise<JSON>>();
let i = 0;
for (let job of this.jobList) {
i++;
this.LOGGER.debug("Retrieving job details for:", job.name, "(", i, "/", this.jobList.length, ")");
let jobUrl: string = this.getJobApiUrl(job.url, this.config);
jobPromises.push(this.proxy.proxy(jobUrl)
.first()
.toPromise()
.catch(() => {
this.LOGGER.warn("Error retrieving details for job", job.name);
this.allItemsRetrievedSuccessfully = false;
}));
}
await Promise.all(jobPromises)
.then(values => {
for (let jobJson of <Array<JSON>> values) {
if (this.util.isInvalid(jobJson) || !(<JSON> jobJson).hasOwnProperty("name")) {
this.LOGGER.warn("No job details found for:", jobJson);
this.allItemsRetrievedSuccessfully = false;
continue;
}
let job = this.util.getJobByName(this.jobList, jobJson["name"]);
if (job === undefined) {
this.LOGGER.warn("No job with name", jobJson["name"], "found");
this.allItemsRetrievedSuccessfully = false;
continue;
}
job.fromJson(jobJson);
job.upstreamProjects = this.getUpstreamProjects(jobJson, job);
job.downstreamProjects = this.getDownstreamProjects(jobJson, job);
this.LOGGER.debug("Updated details for job:", job.name);
}
this.completedSuccessfully = true;
this.complete = true;
});
this.LOGGER.info("Job details updated:", this.jobList);
this.completedSuccessfully = true;
this.complete = true;
}
/**
* Get the jobs
*/
getData(): Array<IJenkinsJob> {
if (this.util.isInvalid(this.jobList)) {
return new Array<IJenkinsJob>();
}
return this.jobList;
}
getServiceId() {
return JenkinsServiceId.Jobs;
}
private getUpstreamProjects(jobJson: JSON, job: IJenkinsJob): Array<IJenkinsJob> |
private getDownstreamProjects(jobJson: JSON, job: IJenkinsJob) {
let downstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("downstreamProjects")) {
this.LOGGER.debug("No downstream projects found for:", job);
return downstreamProjects;
}
for (let downstreamJobJson of (jobJson["downstreamProjects"] as Array<JSON>)) {
let downstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, downstreamJobJson["name"]);
if (downstreamJob === undefined) {
continue;
}
downstreamProjects.push(downstreamJob);
}
return downstreamProjects;
}
private getJobApiUrl(jobUrl: string, config: ConfigService) {
if (jobUrl === undefined || jobUrl === null || jobUrl.length === 0) {
return undefined;
}
/** Remove trailing slash ('/') from root url, if present, then concatenate the jenkins api suffix */
return jobUrl.replace(/\/$/, "") + '/' + config.apiSuffix;
}
}
| {
let upstreamProjects: Array<IJenkinsJob> = new Array<IJenkinsJob>();
if (!jobJson.hasOwnProperty("upstreamProjects")) {
this.LOGGER.debug("No upstream projects found for:", job);
return upstreamProjects;
}
for (let upstreamJobJson of (jobJson["upstreamProjects"] as Array<JSON>)) {
let upstreamJob: IJenkinsJob = this.util.getJobByName(this.jobList, upstreamJobJson["name"]);
if (upstreamJob === undefined) {
continue;
}
upstreamProjects.push(upstreamJob);
}
return upstreamProjects;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.