index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,346 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/hdiplot.py | 10,11 | 1,54 | plot_hdi | 12,54 | 11,54 | """Bokeh hdiplot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show):
FILL_FUNC_BODY | """Bokeh hdiplot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show):
"""Bokeh HDI plot."""
FILL_FUNC... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
plot_kwargs = {} if plot_kwargs is None else plot_kwargs
plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", color))
plot_kwargs.setdefault("a... | """Bokeh HDI plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
plot_kwargs = {} if plot_kwargs is None else plot_kwargs
plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", color))
... | 84 | 119 | 460 | 579 | """Bokeh hdiplot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show):
FILL_FUNC_BODY | """Bokeh hdiplot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show):
"""Bokeh HDI plot."""
FILL_FUNC... | |
44,347 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/bokeh/separationplot.py | 10,29 | 1,108 | plot_separation | 30,108 | 29,108 | """Bokeh separation plot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_separation(
y,
y_hat,
y_hat_line,
label_y_hat,
expected_events,
figsize,
textsize,
c... | """Bokeh separation plot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_separation(
y,
y_hat,
y_hat_line,
label_y_hat,
expected_events,
figsize,
textsize,
c... | if backend_kwargs is None:
backend_kwargs = {}
if plot_kwargs is None:
plot_kwargs = {}
# plot_kwargs.setdefault("color", "#2a2eec")
# if color:
plot_kwargs["color"] = vectorized_to_hex(color)
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
... | """Matplotlib separation plot."""
if backend_kwargs is None:
backend_kwargs = {}
if plot_kwargs is None:
plot_kwargs = {}
# plot_kwargs.setdefault("color", "#2a2eec")
# if color:
plot_kwargs["color"] = vectorized_to_hex(color)
backend_kwargs = {
**backend_kwarg_def... | 148 | 187 | 744 | 931 | """Bokeh separation plot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_separation(
y,
y_hat,
y_hat_line,
label_y_hat,
expected_events,
figsize,
textsize,
c... | """Bokeh separation plot."""
import numpy as np
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from .. import show_layout
from . import backend_kwarg_defaults, create_axes_grid
def plot_separation(
y,
y_hat,
y_hat_line,
label_y_hat,
expected_events,
figsize,
textsize,
c... | |
44,348 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/autocorrplot.py | 11,24 | 1,73 | plot_autocorr | 25,73 | 24,73 | """Matplotlib Autocorrplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats import autocorr
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_autocorr(
axes,
plotters,
max_lag,
figsize,
rows,
cols,
... | """Matplotlib Autocorrplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats import autocorr
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_autocorr(
axes,
plotters,
max_lag,
figsize,
rows,
cols,
... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, titlesize, xt_labelsize, linewidth, _ = _scale_fig_size(
figsize, textsize, rows, cols
)
backend_kwargs.setdefault("figsize", figsize)
... | """Matplotlib autocorrplot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, titlesize, xt_labelsize, linewidth, _ = _scale_fig_size(
figsize, textsize, rows, cols
)
backend_kwa... | 103 | 162 | 556 | 718 | """Matplotlib Autocorrplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats import autocorr
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_autocorr(
axes,
plotters,
max_lag,
figsize,
rows,
cols,
... | """Matplotlib Autocorrplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats import autocorr
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_autocorr(
axes,
plotters,
max_lag,
figsize,
rows,
cols,
... | |
44,349 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/bfplot.py | 8,26 | 1,79 | plot_bf | 27,79 | 26,79 | import matplotlib.pyplot as plt
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
def plot_bf(
ax,
bf_10,
bf_01,
prior,
posterior,
ref_val,
prior_at_ref_val,
post... | import matplotlib.pyplot as plt
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
def plot_bf(
ax,
bf_10,
bf_01,
prior,
posterior,
ref_val,
prior_at_ref_val,
post... | if backend_kwargs is None:
backend_kwargs = {}
if hist_kwargs is None:
hist_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, _, linewidth, _ = _scale_fig_size(figsize, textsize, 1, 1)
plot_kwargs = matplotlib_kwarg_... | """Matplotlib Bayes Factor plot."""
if backend_kwargs is None:
backend_kwargs = {}
if hist_kwargs is None:
hist_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, _, linewidth, _ = _scale_fig_size(figsize, textsize, 1,... | 94 | 194 | 554 | 748 | import matplotlib.pyplot as plt
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
def plot_bf(
ax,
bf_10,
bf_01,
prior,
posterior,
ref_val,
prior_at_ref_val,
post... | import matplotlib.pyplot as plt
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
def plot_bf(
ax,
bf_10,
bf_01,
prior,
posterior,
ref_val,
prior_at_ref_val,
post... | |
44,350 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/densityplot.py | 14,37 | 1,195 | plot_density | 38,104 | 37,104 | """Matplotlib Densityplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from ....stats import hdi
from ....stats.density_utils import get_bins, kde
from ...plot_utils import _scale_fig_size, calculate_point_estimate
from . import backend_kwarg_defaults, backend_show, create_axes_... | """Matplotlib Densityplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from ....stats import hdi
from ....stats.density_utils import get_bins, kde
from ...plot_utils import _scale_fig_size, calculate_point_estimate
from . import backend_kwarg_defaults, backend_show, create_axes_... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if colors == "cycle":
colors = [
prop
for _, prop in zip(
range(n_data), cycle(plt.rcParams["axes.prop_cycle"].by_ke... | """Matplotlib densityplot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if colors == "cycle":
colors = [
prop
for _, prop in zip(
range(n_data), cycle(plt... | 127 | 1,285 | 618 | 1,903 | """Matplotlib Densityplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from ....stats import hdi
from ....stats.density_utils import get_bins, kde
from ...plot_utils import _scale_fig_size, calculate_point_estimate
from . import backend_kwarg_defaults, backend_show, create_axes_... | """Matplotlib Densityplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from ....stats import hdi
from ....stats.density_utils import get_bins, kde
from ...plot_utils import _scale_fig_size, calculate_point_estimate
from . import backend_kwarg_defaults, backend_show, create_axes_... | |
44,351 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/distcomparisonplot.py | 11,27 | 1,120 | plot_dist_comparison | 28,120 | 27,120 | """Matplotlib Density Comparison plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
lege... | """Matplotlib Density Comparison plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
lege... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if prior_kwargs is None:
prior_kwargs = {}
if posterior_kwargs is None:
posterior_kwargs = {}
if observed_kwargs is None:
observed... | """Matplotlib Density Comparison plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if prior_kwargs is None:
prior_kwargs = {}
if posterior_kwargs is None:
posterior_kwargs = {}
... | 236 | 174 | 1,040 | 1,214 | """Matplotlib Density Comparison plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
lege... | """Matplotlib Density Comparison plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...distplot import plot_dist
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show
def plot_dist_comparison(
ax,
nvars,
ngroups,
figsize,
dc_plotters,
lege... | |
44,352 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/distplot.py | 124,125 | 1,179 | _histplot_mpl_op | 126,179 | 125,179 | """Matplotlib distplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
import numpy as np
from ....stats.density_utils import get_bins
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_... | """Matplotlib distplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
import numpy as np
from ....stats.density_utils import get_bins
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_... | bins = hist_kwargs.pop("bins", None)
if is_circular == "degrees":
if bins is None:
bins = get_bins(values)
values = np.deg2rad(values)
bins = np.deg2rad(bins)
elif is_circular:
labels = [
"0",
f"{np.pi/4:.2f}",
f"{np.pi/2:.2f}... | """Add a histogram for the data to the axes."""
bins = hist_kwargs.pop("bins", None)
if is_circular == "degrees":
if bins is None:
bins = get_bins(values)
values = np.deg2rad(values)
bins = np.deg2rad(bins)
elif is_circular:
labels = [
"0",
... | 106 | 1,055 | 548 | 1,603 | """Matplotlib distplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
import numpy as np
from ....stats.density_utils import get_bins
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_... | """Matplotlib distplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
import numpy as np
from ....stats.density_utils import get_bins
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_... | |
44,353 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/dotplot.py | 15,38 | 1,117 | plot_dot | 39,117 | 38,117 | """Matplotlib dotplot."""
import math
import warnings
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
from ...plot_utils import plot_point_interval
from ...dotplot im... | """Matplotlib dotplot."""
import math
import warnings
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
from ...plot_utils import plot_point_interval
from ...dotplot im... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {**backend_kwarg_defaults(), **backend_kwargs}
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"] = True
(figsize, _, _, _, auto_linewidth, auto_markersize) = _scale_fig_size(figsize, None)
if plot_k... | """Matplotlib dotplot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {**backend_kwarg_defaults(), **backend_kwargs}
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"] = True
(figsize, _, _, _, auto_linewidth, auto_markersize) = _scale_fig_size... | 199 | 248 | 794 | 1,042 | """Matplotlib dotplot."""
import math
import warnings
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
from ...plot_utils import plot_point_interval
from ...dotplot im... | """Matplotlib dotplot."""
import math
import warnings
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
from ...plot_utils import plot_point_interval
from ...dotplot im... | |
44,354 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/ecdfplot.py | 10,26 | 1,72 | plot_ecdf | 27,72 | 26,72 | """Matplotlib ecdfplot."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
def plot_ecdf(
x_coord,
y_coord,
x_bands,
lower,
higher,
confidence_bands,
plot_k... | """Matplotlib ecdfplot."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
def plot_ecdf(
x_coord,
y_coord,
x_bands,
lower,
higher,
confidence_bands,
plot_k... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
(figsize, _, _, _, _, _) = _scale_fig_size(figsize, None)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"] = True
if ax is None:... | """Matplotlib ecdfplot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
(figsize, _, _, _, _, _) = _scale_fig_size(figsize, None)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squee... | 96 | 181 | 472 | 653 | """Matplotlib ecdfplot."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
def plot_ecdf(
x_coord,
y_coord,
x_bands,
lower,
higher,
confidence_bands,
plot_k... | """Matplotlib ecdfplot."""
import matplotlib.pyplot as plt
from matplotlib.colors import to_hex
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, create_axes_grid, backend_show
def plot_ecdf(
x_coord,
y_coord,
x_bands,
lower,
higher,
confidence_bands,
plot_k... | |
44,355 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/energyplot.py | 15,31 | 1,114 | plot_energy | 32,114 | 31,114 | """Matplotlib energyplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import rcParams as mpl_rcParams
from ....stats import bfmi as e_bfmi
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backe... | """Matplotlib energyplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import rcParams as mpl_rcParams
from ....stats import bfmi as e_bfmi
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backe... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, linewidth, _ = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"]... | """Matplotlib energy plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, linewidth, _ = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", figs... | 213 | 221 | 975 | 1,196 | """Matplotlib energyplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import rcParams as mpl_rcParams
from ....stats import bfmi as e_bfmi
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backe... | """Matplotlib energyplot."""
from itertools import cycle
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import rcParams as mpl_rcParams
from ....stats import bfmi as e_bfmi
from ...kdeplot import plot_kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backe... | |
44,357 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/hdiplot.py | 10,11 | 1,49 | plot_hdi | 12,49 | 11,49 | """Matplotlib hdiplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, ... | """Matplotlib hdiplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, ... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
plot_kwargs = matplotlib_kwarg_dealiaser(plot_kwargs, "plot")
plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", color))
plot_kwargs.setdefau... | """Matplotlib HDI plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
plot_kwargs = matplotlib_kwarg_dealiaser(plot_kwargs, "plot")
plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", c... | 80 | 145 | 428 | 573 | """Matplotlib hdiplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, ... | """Matplotlib hdiplot."""
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
from ...plot_utils import _scale_fig_size, vectorized_to_hex
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, ... | |
44,358 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/kdeplot.py | 13,46 | 1,178 | plot_kde | 47,178 | 46,178 | """Matplotlib kdeplot."""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import _pylab_helpers
import matplotlib.ticker as mticker
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
d... | """Matplotlib kdeplot."""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import _pylab_helpers
import matplotlib.ticker as mticker
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
d... | backend_kwargs = _init_kwargs_dict(backend_kwargs)
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, *_, xt_labelsize, linewidth, markersize = _scale_fig_size(figsize, textsize)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"] =... | """Matplotlib kde plot."""
backend_kwargs = _init_kwargs_dict(backend_kwargs)
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, *_, xt_labelsize, linewidth, markersize = _scale_fig_size(figsize, textsize)
backend_kwargs.setdefault("figsize", figsize)
... | 287 | 315 | 1,634 | 1,949 | """Matplotlib kdeplot."""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import _pylab_helpers
import matplotlib.ticker as mticker
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
d... | """Matplotlib kdeplot."""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import _pylab_helpers
import matplotlib.ticker as mticker
from ...plot_utils import _scale_fig_size, _init_kwargs_dict
from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser
d... | |
44,359 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/lmplot.py | 11,37 | 1,144 | plot_lm | 38,144 | 37,144 | """Matplotlib plot linear regression figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from ...hdiplot import plot_hdi
from . import create_axes_grid, matplotlib_kwarg_dealiaser, backend_show, backend_kwarg_defaults
def plot_lm(
x,
y,
y_model,
y_... | """Matplotlib plot linear regression figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from ...hdiplot import plot_hdi
from . import create_axes_grid, matplotlib_kwarg_dealiaser, backend_show, backend_kwarg_defaults
def plot_lm(
x,
y,
y_model,
y_... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, rows, cols)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs.setdefault("... | """Matplotlib Linear Regression."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, rows, cols)
backend_kwargs.setdefault("figsize", ... | 273 | 266 | 1,675 | 1,941 | """Matplotlib plot linear regression figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from ...hdiplot import plot_hdi
from . import create_axes_grid, matplotlib_kwarg_dealiaser, backend_show, backend_kwarg_defaults
def plot_lm(
x,
y,
y_model,
y_... | """Matplotlib plot linear regression figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from ...hdiplot import plot_hdi
from . import create_axes_grid, matplotlib_kwarg_dealiaser, backend_show, backend_kwarg_defaults
def plot_lm(
x,
y,
y_model,
y_... | |
44,360 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/loopitplot.py | 13,43 | 1,145 | plot_loo_pit | 44,145 | 43,145 | """Matplotlib loopitplot."""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb
from xarray import DataArray
from ....stats.density_utils import kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create... | """Matplotlib loopitplot."""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb
from xarray import DataArray
from ....stats.density_utils import kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
(figsize, _, _, xt_labelsize, linewidth, _) = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze... | """Matplotlib loo pit plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
(figsize, _, _, xt_labelsize, linewidth, _) = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", f... | 310 | 336 | 1,536 | 1,872 | """Matplotlib loopitplot."""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb
from xarray import DataArray
from ....stats.density_utils import kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create... | """Matplotlib loopitplot."""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb
from xarray import DataArray
from ....stats.density_utils import kde
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create... | |
44,361 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/parallelplot.py | 10,25 | 1,59 | plot_parallel | 26,59 | 25,59 | """Matplotlib Parallel coordinates plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_parallel(
ax,
colornd,
colord,
shadend,
diverging_mask,
posterior,
textsi... | """Matplotlib Parallel coordinates plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_parallel(
ax,
colornd,
colord,
shadend,
diverging_mask,
posterior,
textsi... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs["squeeze"] = True
... | """Matplotlib parallel plot."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, 1, 1)
backend_kwargs.setdefault("figsize", figsize)
... | 67 | 171 | 383 | 554 | """Matplotlib Parallel coordinates plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_parallel(
ax,
colornd,
colord,
shadend,
diverging_mask,
posterior,
textsi... | """Matplotlib Parallel coordinates plot."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_parallel(
ax,
colornd,
colord,
shadend,
diverging_mask,
posterior,
textsi... | |
44,363 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/rankplot.py | 11,31 | 1,120 | plot_rank | 32,120 | 31,120 | """Matplotlib rankplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import histogram
from ...plot_utils import _scale_fig_size, compute_ranks
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_rank(
axes,
length_plotters,
rows,
cols,
... | """Matplotlib rankplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import histogram
from ...plot_utils import _scale_fig_size, compute_ranks
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_rank(
axes,
length_plotters,
rows,
cols,
... | if ref_line_kwargs is None:
ref_line_kwargs = {}
ref_line_kwargs.setdefault("linestyle", "--")
ref_line_kwargs.setdefault("color", "k")
if bar_kwargs is None:
bar_kwargs = {}
bar_kwargs.setdefault("align", "center")
if vlines_kwargs is None:
vlines_kwargs = {}
vline... | """Matplotlib rankplot.."""
if ref_line_kwargs is None:
ref_line_kwargs = {}
ref_line_kwargs.setdefault("linestyle", "--")
ref_line_kwargs.setdefault("color", "k")
if bar_kwargs is None:
bar_kwargs = {}
bar_kwargs.setdefault("align", "center")
if vlines_kwargs is None:
... | 221 | 205 | 1,097 | 1,302 | """Matplotlib rankplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import histogram
from ...plot_utils import _scale_fig_size, compute_ranks
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_rank(
axes,
length_plotters,
rows,
cols,
... | """Matplotlib rankplot."""
import matplotlib.pyplot as plt
import numpy as np
from ....stats.density_utils import histogram
from ...plot_utils import _scale_fig_size, compute_ranks
from . import backend_kwarg_defaults, backend_show, create_axes_grid
def plot_rank(
axes,
length_plotters,
rows,
cols,
... | |
44,365 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/backends/matplotlib/tsplot.py | 10,34 | 1,122 | plot_ts | 35,122 | 34,122 | """Matplotlib plot time series figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import create_axes_grid, backend_show, matplotlib_kwarg_dealiaser, backend_kwarg_defaults
def plot_ts(
x_plotters,
y_plotters,
y_mean_plotters,
y_hat_plotters... | """Matplotlib plot time series figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import create_axes_grid, backend_show, matplotlib_kwarg_dealiaser, backend_kwarg_defaults
def plot_ts(
x_plotters,
y_plotters,
y_mean_plotters,
y_hat_plotters... | if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if figsize is None:
figsize = (12, rows * 5)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs.setdefault("squeeze", False)
figsize... | """Matplotlib time series."""
if backend_kwargs is None:
backend_kwargs = {}
backend_kwargs = {
**backend_kwarg_defaults(),
**backend_kwargs,
}
if figsize is None:
figsize = (12, rows * 5)
backend_kwargs.setdefault("figsize", figsize)
backend_kwargs.setdefa... | 220 | 264 | 1,367 | 1,631 | """Matplotlib plot time series figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import create_axes_grid, backend_show, matplotlib_kwarg_dealiaser, backend_kwarg_defaults
def plot_ts(
x_plotters,
y_plotters,
y_mean_plotters,
y_hat_plotters... | """Matplotlib plot time series figure."""
import matplotlib.pyplot as plt
import numpy as np
from ...plot_utils import _scale_fig_size
from . import create_axes_grid, backend_show, matplotlib_kwarg_dealiaser, backend_kwarg_defaults
def plot_ts(
x_plotters,
y_plotters,
y_mean_plotters,
y_hat_plotters... | |
44,366 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/compareplot.py | 10,27 | 1,178 | plot_compare | 27,178 | 27,178 | """Summary plot for model comparison."""
import numpy as np
from ..labels import BaseLabeller
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_compare(
comp_df,
insample_dev=False,
plot_standard_error=True,
plot_ic_diff=True,
order_by_rank=True,
legend=T... | """Summary plot for model comparison."""
import numpy as np
from ..labels import BaseLabeller
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_compare(
comp_df,
insample_dev=False,
plot_standard_error=True,
plot_ic_diff=True,
order_by_rank=True,
legend=T... | r"""Summary plot for model comparison.
Models are compared based on their expected log pointwise predictive density (ELPD).
This plot is in the style of the one used in [2]_. Chapter 6 in the first edition
or 7 in the second.
Notes
-----
The ELPD is estimated either by Pareto smoothed impo... | r"""Summary plot for model comparison.
Models are compared based on their expected log pointwise predictive density (ELPD).
This plot is in the style of the one used in [2]_. Chapter 6 in the first edition
or 7 in the second.
Notes
-----
The ELPD is estimated either by Pareto smoothed impo... | 593 | 178 | 1,861 | 2,039 | """Summary plot for model comparison."""
import numpy as np
from ..labels import BaseLabeller
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_compare(
comp_df,
insample_dev=False,
plot_standard_error=True,
plot_ic_diff=True,
order_by_rank=True,
legend=T... | """Summary plot for model comparison."""
import numpy as np
from ..labels import BaseLabeller
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_compare(
comp_df,
insample_dev=False,
plot_standard_error=True,
plot_ic_diff=True,
order_by_rank=True,
legend=T... | |
44,372 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/energyplot.py | 10,27 | 1,148 | plot_energy | 27,148 | 27,148 | """Plot energy transition distribution in HMC inference."""
import warnings
from ..data import convert_to_dataset
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_energy(
data,
kind=None,
bfmi=True,
figsize=None,
legend=True,
fill_alpha=(1, 0.75),
fi... | """Plot energy transition distribution in HMC inference."""
import warnings
from ..data import convert_to_dataset
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_energy(
data,
kind=None,
bfmi=True,
figsize=None,
legend=True,
fill_alpha=(1, 0.75),
fi... | r"""Plot energy transition distribution and marginal energy distribution in HMC algorithms.
This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS.
The energy function in HMC can identify posteriors with heavy tailed distributions, that
in practice are challenging for ... | r"""Plot energy transition distribution and marginal energy distribution in HMC algorithms.
This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS.
The energy function in HMC can identify posteriors with heavy tailed distributions, that
in practice are challenging for ... | 471 | 187 | 1,368 | 1,555 | """Plot energy transition distribution in HMC inference."""
import warnings
from ..data import convert_to_dataset
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_energy(
data,
kind=None,
bfmi=True,
figsize=None,
legend=True,
fill_alpha=(1, 0.75),
fi... | """Plot energy transition distribution in HMC inference."""
import warnings
from ..data import convert_to_dataset
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_energy(
data,
kind=None,
bfmi=True,
figsize=None,
legend=True,
fill_alpha=(1, 0.75),
fi... | |
44,381 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/plots/separationplot.py | 13,31 | 1,168 | plot_separation | 102,168 | 31,168 | """Separation plot for discrete outcome models."""
import warnings
import numpy as np
import xarray as xr
from ..data import InferenceData
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_separation(
idata=None,
y=None,
y_hat=None,
y_hat_line=False,
expecte... | """Separation plot for discrete outcome models."""
import warnings
import numpy as np
import xarray as xr
from ..data import InferenceData
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_separation(
idata=None,
y=None,
y_hat=None,
y_hat_line=False,
expecte... | label_y_hat = "y_hat"
if idata is not None and not isinstance(idata, InferenceData):
raise ValueError("idata must be of type InferenceData or None")
if idata is None:
if not all(isinstance(arg, (np.ndarray, xr.DataArray)) for arg in (y, y_hat)):
raise ValueError(
... | """Separation plot for binary outcome models.
Model predictions are sorted and plotted using a color code according to
the observed data.
Parameters
----------
idata : InferenceData
:class:`arviz.InferenceData` object.
y : array, DataArray or str
Observed data. If str, ``id... | 205 | 1,023 | 790 | 1,813 | """Separation plot for discrete outcome models."""
import warnings
import numpy as np
import xarray as xr
from ..data import InferenceData
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_separation(
idata=None,
y=None,
y_hat=None,
y_hat_line=False,
expecte... | """Separation plot for discrete outcome models."""
import warnings
import numpy as np
import xarray as xr
from ..data import InferenceData
from ..rcparams import rcParams
from .plot_utils import get_plotting_function
def plot_separation(
idata=None,
y=None,
y_hat=None,
y_hat_line=False,
expecte... | |
44,387 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/utils.py | 745,747 | 721,752 | disable_dask | Dask | 748,752 | 747,752 | class Dask:
"""Class to toggle Dask states.
Warnings
--------
Dask integration is an experimental feature still in progress. It can already be used
but it doesn't work with all stats nor diagnostics yet.
"""
dask_flag = False
dask_kwargs = None
@classmethod
def enable_dask(cls... | class Dask:
"""Class to toggle Dask states.
Warnings
--------
Dask integration is an experimental feature still in progress. It can already be used
but it doesn't work with all stats nor diagnostics yet.
"""
dask_flag = False
dask_kwargs = None
@classmethod
def enable_dask(cls... | cls.dask_flag = False
cls.dask_kwargs = None
| """To disable Dask."""
cls.dask_flag = False
cls.dask_kwargs = None
| 6 | 217 | 28 | 245 | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... |
44,388 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/utils.py | 330,332 | 325,344 | disable_numba | Numba | 333,335 | 332,335 | class Numba:
"""A class to toggle numba states."""
numba_flag = numba_check()
@classmethod
def disable_numba(cls):
FILL_FUNC_BODY @classmethod
def enable_numba(cls):
"""To enable numba."""
if numba_check():
cls.numba_flag = True
else:
raise ValueE... | class Numba:
"""A class to toggle numba states."""
numba_flag = numba_check()
@classmethod
def disable_numba(cls):
"""To disable numba."""
FILL_FUNC_BODY @classmethod
def enable_numba(cls):
"""To enable numba."""
if numba_check():
cls.numba_flag = True
... | cls.numba_flag = False
| """To disable numba."""
cls.numba_flag = False
| 3 | 123 | 14 | 137 | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... |
44,389 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/utils.py | 188,190 | 179,206 | numba_fn | maybe_numba_fn | 191,198 | 190,198 | class maybe_numba_fn: # pylint: disable=invalid-name
"""Wrap a function to (maybe) use a (lazy) jit-compiled version."""
def __init__(self, function, **kwargs):
"""Wrap a function and save compilation keywords."""
self.function = function
kwargs.setdefault("nopython", True)
sel... | class maybe_numba_fn: # pylint: disable=invalid-name
"""Wrap a function to (maybe) use a (lazy) jit-compiled version."""
def __init__(self, function, **kwargs):
"""Wrap a function and save compilation keywords."""
self.function = function
kwargs.setdefault("nopython", True)
sel... | try:
numba = importlib.import_module("numba")
numba_fn = numba.jit(**self.kwargs)(self.function)
except ImportError:
numba_fn = self.function
return numba_fn
| """Memoized compiled function."""
try:
numba = importlib.import_module("numba")
numba_fn = numba.jit(**self.kwargs)(self.function)
except ImportError:
numba_fn = self.function
return numba_fn
| 14 | 210 | 72 | 282 | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... | # pylint: disable=too-many-nested-blocks
"""General utilities."""
import functools
import importlib
import importlib.resources
import re
import warnings
from functools import lru_cache
import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from .rcparams import rcParams
STATIC_FILES = ("static... |
44,390 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/arviz/wrappers/wrap_pymc.py | 31,32 | 7,37 | get_inference_data | PyMCSamplingWrapper | 36,37 | 32,37 | class PyMCSamplingWrapper(SamplingWrapper):
"""PyMC (4.0+) sampling wrapper base class.
See the documentation on :class:`~arviz.SamplingWrapper` for a more detailed
description. An example of ``PyMCSamplingWrapper`` usage can be found
in the :ref:`pymc_refitting` notebook.
Warnings
--------
... | class PyMCSamplingWrapper(SamplingWrapper):
"""PyMC (4.0+) sampling wrapper base class.
See the documentation on :class:`~arviz.SamplingWrapper` for a more detailed
description. An example of ``PyMCSamplingWrapper`` usage can be found
in the :ref:`pymc_refitting` notebook.
Warnings
--------
... | return fitted_model
| """Return sampling result without modifying.
PyMC sampling already returns and InferenceData object.
"""
return fitted_model
| 2 | 285 | 7 | 292 | # pylint: disable=arguments-differ
"""Base class for PyMC interface wrappers."""
from .base import SamplingWrapper
# pylint: disable=abstract-method
class PyMCSamplingWrapper(SamplingWrapper):
"""PyMC (4.0+) sampling wrapper base class.
See the documentation on :class:`~arviz.SamplingWrapper` for a more det... | # pylint: disable=arguments-differ
"""Base class for PyMC interface wrappers."""
from .base import SamplingWrapper
# pylint: disable=abstract-method
class PyMCSamplingWrapper(SamplingWrapper):
"""PyMC (4.0+) sampling wrapper base class.
See the documentation on :class:`~arviz.SamplingWrapper` for a more det... |
44,393 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/doc/sphinxext/gallery_generator.py | 155,157 | 130,321 | title | ExampleGenerator | 157,161 | 157,161 | class ExampleGenerator:
"""Tools for generating an example page from a file"""
_title: Optional[str]
def __init__(self, filename, target_dir, backend, target_dir_orig):
self.filename = filename
self.target_dir = target_dir
self.backend = backend
self._title = None
s... | class ExampleGenerator:
"""Tools for generating an example page from a file"""
_title: Optional[str]
def __init__(self, filename, target_dir, backend, target_dir_orig):
self.filename = filename
self.target_dir = target_dir
self.backend = backend
self._title = None
s... | if self._title is not None:
return self._title
return self.modulename
| if self._title is not None:
return self._title
return self.modulename
| 9 | 1,930 | 29 | 1,959 | """
Sphinx plugin to run example scripts and create a gallery page.
Modified from the seaborn project, which modified the mpld3 project.
Also inspired in bokeh's bokeh_gallery sphinxext.
"""
import glob
import os
import os.path as op
import re
import shutil
import token
import tokenize
from typing import Optional
... | """
Sphinx plugin to run example scripts and create a gallery page.
Modified from the seaborn project, which modified the mpld3 project.
Also inspired in bokeh's bokeh_gallery sphinxext.
"""
import glob
import os
import os.path as op
import re
import shutil
import token
import tokenize
from typing import Optional
... |
44,394 | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz | /home/hieuvd/dung_repo/raw/stars_03/arviz-devs_arviz/arviz/setup.py | 18,19 | 1,78 | get_requirements | 19,23 | 19,23 | import codecs
import os
import re
import setuptools
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt")
RE... | import codecs
import os
import re
import setuptools
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt")
RE... | with codecs.open(REQUIREMENTS_FILE) as buff:
return buff.read().splitlines()
| with codecs.open(REQUIREMENTS_FILE) as buff:
return buff.read().splitlines()
| 6 | 815 | 35 | 850 | import codecs
import os
import re
import setuptools
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt")
RE... | import codecs
import os
import re
import setuptools
from setuptools import find_packages, setup
from setuptools.command.develop import develop
from setuptools.command.install import install
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt")
RE... | |
44,395 | /home/hieuvd/dung_repo/raw/stars_03/arxiv-vanity_arxiv-vanity/arxiv-vanity | /home/hieuvd/dung_repo/raw/stars_03/arxiv-vanity_arxiv-vanity/arxiv-vanity/arxiv_vanity/scraper/arxiv_ids.py | 14,15 | 1,24 | remove_version_from_arxiv_id | 15,19 | 15,19 | import re
# These patterns need to be implemented case insensitive (e.g. [vV])
# because Django doesn't let us add re.I to re_path() in URLs
ARXIV_ID_PATTERN = r"([a-zA-Z\-]+(?:\.[a-zA-Z]{2})?/\d{7}|\d+\.\d+)([vV]\d+)?"
ARXIV_ID_RE = re.compile(ARXIV_ID_PATTERN)
ARXIV_URL_RE = re.compile(fr"arxiv.org/[^\/]+/({ARXIV_ID... | import re
# These patterns need to be implemented case insensitive (e.g. [vV])
# because Django doesn't let us add re.I to re_path() in URLs
ARXIV_ID_PATTERN = r"([a-zA-Z\-]+(?:\.[a-zA-Z]{2})?/\d{7}|\d+\.\d+)([vV]\d+)?"
ARXIV_ID_RE = re.compile(ARXIV_ID_PATTERN)
ARXIV_URL_RE = re.compile(fr"arxiv.org/[^\/]+/({ARXIV_ID... | match = ARXIV_ID_RE.match(arxiv_id)
return match.group(1), int(match.group(2)[1:]) if match.group(2) else None
| match = ARXIV_ID_RE.match(arxiv_id)
return match.group(1), int(match.group(2)[1:]) if match.group(2) else None
| 10 | 364 | 55 | 419 | import re
# These patterns need to be implemented case insensitive (e.g. [vV])
# because Django doesn't let us add re.I to re_path() in URLs
ARXIV_ID_PATTERN = r"([a-zA-Z\-]+(?:\.[a-zA-Z]{2})?/\d{7}|\d+\.\d+)([vV]\d+)?"
ARXIV_ID_RE = re.compile(ARXIV_ID_PATTERN)
ARXIV_URL_RE = re.compile(fr"arxiv.org/[^\/]+/({ARXIV_ID... | import re
# These patterns need to be implemented case insensitive (e.g. [vV])
# because Django doesn't let us add re.I to re_path() in URLs
ARXIV_ID_PATTERN = r"([a-zA-Z\-]+(?:\.[a-zA-Z]{2})?/\d{7}|\d+\.\d+)([vV]\d+)?"
ARXIV_ID_RE = re.compile(ARXIV_ID_PATTERN)
ARXIV_URL_RE = re.compile(fr"arxiv.org/[^\/]+/({ARXIV_ID... | |
44,396 | /home/hieuvd/dung_repo/raw/stars_03/arxiv-vanity_arxiv-vanity/arxiv-vanity | /home/hieuvd/dung_repo/raw/stars_03/arxiv-vanity_arxiv-vanity/arxiv-vanity/arxiv_vanity/storage.py | 4,5 | 1,24 | storage_walk | 8,18 | 5,18 | import os
# https://github.com/ephes/homepage/blob/a62d45611c2f3849f0845b8ec4256f130d68db25/homepage/blogs/utils.py
def storage_walk(storage, cur_dir=""):
FILL_FUNC_BODYdef storage_delete_path(storage, root_path):
"""
Resursive delete for Django storage.
"""
for path in storage_walk(storage, root_path)... | import os
# https://github.com/ephes/homepage/blob/a62d45611c2f3849f0845b8ec4256f130d68db25/homepage/blogs/utils.py
def storage_walk(storage, cur_dir=""):
"""
Recursive listdir() for Django storages.
"""
FILL_FUNC_BODYdef storage_delete_path(storage, root_path):
"""
Resursive delete for Django stor... | dirs, files = storage.listdir(cur_dir)
for directory in dirs:
new_dir = os.path.join(cur_dir, directory)
for path in storage_walk(storage, cur_dir=new_dir):
yield path
for fname in files:
path = os.path.join(cur_dir, fname)
yield path
| """
Recursive listdir() for Django storages.
"""
dirs, files = storage.listdir(cur_dir)
for directory in dirs:
new_dir = os.path.join(cur_dir, directory)
for path in storage_walk(storage, cur_dir=new_dir):
yield path
for fname in files:
path = os.path.join(cur... | 29 | 167 | 106 | 273 | import os
# https://github.com/ephes/homepage/blob/a62d45611c2f3849f0845b8ec4256f130d68db25/homepage/blogs/utils.py
def storage_walk(storage, cur_dir=""):
FILL_FUNC_BODYdef storage_delete_path(storage, root_path):
"""
Resursive delete for Django storage.
"""
for path in storage_walk(storage, root_path)... | import os
# https://github.com/ephes/homepage/blob/a62d45611c2f3849f0845b8ec4256f130d68db25/homepage/blogs/utils.py
def storage_walk(storage, cur_dir=""):
"""
Recursive listdir() for Django storages.
"""
FILL_FUNC_BODYdef storage_delete_path(storage, root_path):
"""
Resursive delete for Django stor... | |
44,399 | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced/adbe/asyncio_helper.py | 8,9 | 1,29 | execute_in_parallel | 9,29 | 9,29 | import asyncio
import concurrent.futures
# This code has to be in a separate file since it is conditionally loaded for Python 3.5 and later.
# Executes method method_to_call for each argument in params_list and returns the result_list
def execute_in_parallel(method_to_call, params_list):
FILL_FUNC_BODY | import asyncio
import concurrent.futures
# This code has to be in a separate file since it is conditionally loaded for Python 3.5 and later.
# Executes method method_to_call for each argument in params_list and returns the result_list
def execute_in_parallel(method_to_call, params_list):
FILL_FUNC_BODY |
result_list = []
num_workers = 50
loop = asyncio.get_event_loop()
async def _list_debug_apps_async(params_list2):
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_exe... |
result_list = []
num_workers = 50
loop = asyncio.get_event_loop()
async def _list_debug_apps_async(params_list2):
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_exe... | 40 | 92 | 209 | 301 | import asyncio
import concurrent.futures
# This code has to be in a separate file since it is conditionally loaded for Python 3.5 and later.
# Executes method method_to_call for each argument in params_list and returns the result_list
def execute_in_parallel(method_to_call, params_list):
FILL_FUNC_BODY | import asyncio
import concurrent.futures
# This code has to be in a separate file since it is conditionally loaded for Python 3.5 and later.
# Executes method method_to_call for each argument in params_list and returns the result_list
def execute_in_parallel(method_to_call, params_list):
FILL_FUNC_BODY | |
44,401 | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced/adbe/output_helper.py | 26,27 | 1,48 | print_verbose | 27,33 | 27,33 | import sys
__VERBOSE_MODE = False
def set_verbose(enabled):
global __VERBOSE_MODE
__VERBOSE_MODE = enabled
def print_message(message):
print(message)
def print_error_and_exit(error_string):
print_error(error_string)
sys.exit(1)
def print_error(error_string):
if _is_interactive_terminal(... | import sys
__VERBOSE_MODE = False
def set_verbose(enabled):
global __VERBOSE_MODE
__VERBOSE_MODE = enabled
def print_message(message):
print(message)
def print_error_and_exit(error_string):
print_error(error_string)
sys.exit(1)
def print_error(error_string):
if _is_interactive_terminal(... | if __VERBOSE_MODE:
if _is_interactive_terminal():
message = '%s%s%s' % (BashColors.WARNING, message, BashColors.ENDC)
print(message)
| if __VERBOSE_MODE:
if _is_interactive_terminal():
message = '%s%s%s' % (BashColors.WARNING, message, BashColors.ENDC)
print(message)
| 12 | 363 | 65 | 428 | import sys
__VERBOSE_MODE = False
def set_verbose(enabled):
global __VERBOSE_MODE
__VERBOSE_MODE = enabled
def print_message(message):
print(message)
def print_error_and_exit(error_string):
print_error(error_string)
sys.exit(1)
def print_error(error_string):
if _is_interactive_terminal(... | import sys
__VERBOSE_MODE = False
def set_verbose(enabled):
global __VERBOSE_MODE
__VERBOSE_MODE = enabled
def print_message(message):
print(message)
def print_error_and_exit(error_string):
print_error(error_string)
sys.exit(1)
def print_error(error_string):
if _is_interactive_terminal(... | |
44,402 | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced | /home/hieuvd/dung_repo/raw/stars_03/ashishb_adb-enhanced/adb-enhanced/release.py | 50,51 | 1,128 | _push_new_release_to_git | 51,63 | 51,63 | #!/usr/bin/env python3
import os
import subprocess
import sys
import docopt
_DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0]
_VERSION_FILE_NAME = 'version.txt'
_VERSION_FILE_PATH = os.path.join(
_DIR_OF_THIS_SCRIPT, 'adbe', _VERSION_FILE_NAME)
_README_FILE_NAME = os.path.join('docs', 'README.rst')
_TEST_PYPI_URL ... | #!/usr/bin/env python3
import os
import subprocess
import sys
import docopt
_DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0]
_VERSION_FILE_NAME = 'version.txt'
_VERSION_FILE_PATH = os.path.join(
_DIR_OF_THIS_SCRIPT, 'adbe', _VERSION_FILE_NAME)
_README_FILE_NAME = os.path.join('docs', 'README.rst')
_TEST_PYPI_URL ... | with open(version_file) as file_handle:
version = file_handle.read()
cmds = [
'git add %s' % version_file,
'git commit -m "Setup release %s"' % version,
'git tag %s' % version,
'git push --tags',
]
for cmd in cmds:
_run_cmd_or_fail(cmd)
| with open(version_file) as file_handle:
version = file_handle.read()
cmds = [
'git add %s' % version_file,
'git commit -m "Setup release %s"' % version,
'git tag %s' % version,
'git push --tags',
]
for cmd in cmds:
_run_cmd_or_fail(cmd)
| 37 | 1,118 | 116 | 1,234 | #!/usr/bin/env python3
import os
import subprocess
import sys
import docopt
_DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0]
_VERSION_FILE_NAME = 'version.txt'
_VERSION_FILE_PATH = os.path.join(
_DIR_OF_THIS_SCRIPT, 'adbe', _VERSION_FILE_NAME)
_README_FILE_NAME = os.path.join('docs', 'README.rst')
_TEST_PYPI_URL ... | #!/usr/bin/env python3
import os
import subprocess
import sys
import docopt
_DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0]
_VERSION_FILE_NAME = 'version.txt'
_VERSION_FILE_PATH = os.path.join(
_DIR_OF_THIS_SCRIPT, 'adbe', _VERSION_FILE_NAME)
_README_FILE_NAME = os.path.join('docs', 'README.rst')
_TEST_PYPI_URL ... | |
44,412 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/delivery-pricing/src/pricing/main.py | 78,81 | 1,116 | handler | 84,116 | 81,116 | """
PricingFunction
"""
import json
import math
from typing import List
import os
from aws_lambda_powertools.tracing import Tracer # pylint: disable=import-error
from aws_lambda_powertools.logging.logger import Logger # pylint: disable=import-error
from ecom.apigateway import iam_user_id, response # pylint: disable=i... | """
PricingFunction
"""
import json
import math
from typing import List
import os
from aws_lambda_powertools.tracing import Tracer # pylint: disable=import-error
from aws_lambda_powertools.logging.logger import Logger # pylint: disable=import-error
from ecom.apigateway import iam_user_id, response # pylint: disable=i... |
# Verify that this is a request with IAM credentials
if iam_user_id(event) is None:
logger.warning({"message": "User ARN not found in event"})
return response("Unauthorized", 403)
# Extract the request body
try:
body = json.loads(event["body"])
except Exception as exc: # py... | """
Lambda function handler for /backend/pricing
"""
# Verify that this is a request with IAM credentials
if iam_user_id(event) is None:
logger.warning({"message": "User ARN not found in event"})
return response("Unauthorized", 403)
# Extract the request body
try:
b... | 105 | 884 | 328 | 1,212 | """
PricingFunction
"""
import json
import math
from typing import List
import os
from aws_lambda_powertools.tracing import Tracer # pylint: disable=import-error
from aws_lambda_powertools.logging.logger import Logger # pylint: disable=import-error
from ecom.apigateway import iam_user_id, response # pylint: disable=i... | """
PricingFunction
"""
import json
import math
from typing import List
import os
from aws_lambda_powertools.tracing import Tracer # pylint: disable=import-error
from aws_lambda_powertools.logging.logger import Logger # pylint: disable=import-error
from ecom.apigateway import iam_user_id, response # pylint: disable=i... | |
44,421 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 295,296 | 272,316 | match | IAMPutEventsConditions | 299,316 | 296,316 | class IAMPutEventsConditions(CloudFormationLintRule):
"""
Check that IAM Roles with events:PutEvents action restrict based on event source
"""
id = "E9007"
shortdesct = "IAM PutEvents Condition"
description = "Ensure that IAM roles with event:PutEvents action restrict based on event source"
... | class IAMPutEventsConditions(CloudFormationLintRule):
"""
Check that IAM Roles with events:PutEvents action restrict based on event source
"""
id = "E9007"
shortdesct = "IAM PutEvents Condition"
description = "Ensure that IAM roles with event:PutEvents action restrict based on event source"
... |
matches = []
roles = cfn.get_resources("AWS::IAM::Role")
for role_name, role in roles.items():
found = False
for policy in role.get("Properties", {}).get("Policies", []):
if self._match_policy(policy):
found = True
if fou... | """
Match IAM roles that don't have conditions for events:PutEvents actions
"""
matches = []
roles = cfn.get_resources("AWS::IAM::Role")
for role_name, role in roles.items():
found = False
for policy in role.get("Properties", {}).get("Policies", ... | 34 | 275 | 142 | 417 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,422 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 137,138 | 126,156 | match | LambdaESMDestinationConfig | 141,156 | 138,156 | class LambdaESMDestinationConfig(CloudFormationLintRule):
"""
Check that Lambda Event Source Mapping have a DestinationConfig with OnFailure destination
"""
id = "E9003"
shortdesc = "Lambda EventSourceMapping OnFailure"
description = "Ensure that Lambda Event Source Mapping have a DestinationCo... | class LambdaESMDestinationConfig(CloudFormationLintRule):
"""
Check that Lambda Event Source Mapping have a DestinationConfig with OnFailure destination
"""
id = "E9003"
shortdesc = "Lambda EventSourceMapping OnFailure"
description = "Ensure that Lambda Event Source Mapping have a DestinationCo... |
matches = []
sources = cfn.get_resources("AWS::Lambda::EventSourceMapping")
# Scan through Event Source Mappings
for key, resource in sources.items():
if resource.get("Properties", {}).get("DestinationConfig", {}).get("OnFailure", None) is None:
matches.app... | """
Match EventSourceMapping that don't have a DestinationConfig with OnFailure
"""
matches = []
sources = cfn.get_resources("AWS::Lambda::EventSourceMapping")
# Scan through Event Source Mappings
for key, resource in sources.items():
if resource.ge... | 31 | 160 | 128 | 288 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,423 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 221,222 | 204,240 | match | LambdaInsightsLayer | 225,240 | 222,240 | class LambdaInsightsLayer(CloudFormationLintRule):
"""
Check that Lambda functions have the CloudWatch Lambda Insights Layer
"""
id = "E9005"
shortdesc = "Lambda Insights Layer"
description = "Ensure that Lambda functions use the CloudWatch Lambda Insights Layer"
_message = "Function {} do... | class LambdaInsightsLayer(CloudFormationLintRule):
"""
Check that Lambda functions have the CloudWatch Lambda Insights Layer
"""
id = "E9005"
shortdesc = "Lambda Insights Layer"
description = "Ensure that Lambda functions use the CloudWatch Lambda Insights Layer"
_message = "Function {} do... |
matches = []
functions = cfn.get_resources("AWS::Lambda::Function")
for key, resource in functions.items():
if self._layer_pattern not in resource.get("Properties", {}).get("Layers", []):
matches.append(RuleMatch(
["Resources", key],
... | """
Match Lambda functions that don't have the Lambda Insights Layer
"""
matches = []
functions = cfn.get_resources("AWS::Lambda::Function")
for key, resource in functions.items():
if self._layer_pattern not in resource.get("Properties", {}).get("Layers", ... | 25 | 346 | 114 | 460 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,424 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 252,253 | 240,272 | match | LambdaInsightsPermission | 256,272 | 253,272 | class LambdaInsightsPermission(CloudFormationLintRule):
"""
Check that Lambda functions have the CloudWatch Lambda Insights managed policy
"""
id = "E9006"
shortdesc = "Lambda Insights Permission"
description = "Ensure that Lambda functions have the CloudWatch Lambda Insights managed policy"
... | class LambdaInsightsPermission(CloudFormationLintRule):
"""
Check that Lambda functions have the CloudWatch Lambda Insights managed policy
"""
id = "E9006"
shortdesc = "Lambda Insights Permission"
description = "Ensure that Lambda functions have the CloudWatch Lambda Insights managed policy"
... |
matches = []
function_names = cfn.get_resources("AWS::Lambda::Function").keys()
roles = cfn.get_resources("AWS::IAM::Role")
for function_name in function_names:
if self._policy_arn not in roles[f"{function_name}Role"].get("Properties", {}).get("ManagedPolicyArns", []):
... | """
Match Lambda functions that don't have the right permission for CloudWatch Lambda Insights
"""
matches = []
function_names = cfn.get_resources("AWS::Lambda::Function").keys()
roles = cfn.get_resources("AWS::IAM::Role")
for function_name in function_names:
... | 27 | 181 | 154 | 335 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,425 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 88,89 | 75,126 | match | LambdaLogGroupRule | 92,126 | 89,126 | class LambdaLogGroupRule(CloudFormationLintRule):
"""
Check that all Lambda functions have a Log Group
"""
id = "E9002"
shortdesc = "Lambda Log group"
description = "Ensure that all Lambda functions have a corresponding Log Group"
tags = ["ecommerce", "lambda"]
_message = "Function {}... | class LambdaLogGroupRule(CloudFormationLintRule):
"""
Check that all Lambda functions have a Log Group
"""
id = "E9002"
shortdesc = "Lambda Log group"
description = "Ensure that all Lambda functions have a corresponding Log Group"
tags = ["ecommerce", "lambda"]
_message = "Function {}... |
matches = []
functions = cfn.get_resources("AWS::Lambda::Function")
log_groups = cfn.get_resources("AWS::Logs::LogGroup")
known = []
# Scan log groups for resource names
for resource in log_groups.values():
# This use an autogenerated log group name
... | """
Match functions that don't have a log group
"""
matches = []
functions = cfn.get_resources("AWS::Lambda::Function")
log_groups = cfn.get_resources("AWS::Logs::LogGroup")
known = []
# Scan log groups for resource names
for resource in log_gr... | 89 | 141 | 322 | 463 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,426 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 167,168 | 156,204 | match | LambdaRuleInvokeConfig | 171,204 | 168,204 | class LambdaRuleInvokeConfig(CloudFormationLintRule):
"""
Check that Lambda functions invoked by EventBridge have a corresponding EventInvokeConfig
"""
id = "E9004"
shortdesc = "Lambda EventBridge OnFailure"
description = "Ensure that Lambda functions invoked by EventBring have an Event Invoke ... | class LambdaRuleInvokeConfig(CloudFormationLintRule):
"""
Check that Lambda functions invoked by EventBridge have a corresponding EventInvokeConfig
"""
id = "E9004"
shortdesc = "Lambda EventBridge OnFailure"
description = "Ensure that Lambda functions invoked by EventBring have an Event Invoke ... |
matches = []
function_names = cfn.get_resources("AWS::Lambda::Function").keys()
rules = cfn.get_resources("AWS::Events::Rule")
invoke_configs = cfn.get_resources("AWS::Lambda::EventInvokeConfig")
# Get the list of function names with EventInvokeConfig and OnFailure
inv... | """
Match Events Rules that don't have a corresponding EventInvokeConfig
"""
matches = []
function_names = cfn.get_resources("AWS::Lambda::Function").keys()
rules = cfn.get_resources("AWS::Events::Rule")
invoke_configs = cfn.get_resources("AWS::Lambda::EventInvo... | 81 | 161 | 361 | 522 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,427 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 28,29 | 15,45 | match | MandatoryParametersRule | 32,45 | 29,45 | class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
"""
id = "E9000"
shortdesc = "Mandatory Parameters"
description = "Ensuring that mandatory parameters are present"
tags = ["ecommerce", "parameters"]
_mandatory_parameters = ["Envir... | class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
"""
id = "E9000"
shortdesc = "Mandatory Parameters"
description = "Ensuring that mandatory parameters are present"
tags = ["ecommerce", "parameters"]
_mandatory_parameters = ["Envir... |
mandatory_parameters = copy.deepcopy(self._mandatory_parameters)
for key in cfn.get_parameters().keys():
if key in mandatory_parameters:
mandatory_parameters.remove(key)
return [
RuleMatch(["Parameters"], self._message.format(param))
for par... | """
Match missing mandatory parameters
"""
mandatory_parameters = copy.deepcopy(self._mandatory_parameters)
for key in cfn.get_parameters().keys():
if key in mandatory_parameters:
mandatory_parameters.remove(key)
return [
RuleMat... | 21 | 136 | 100 | 236 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,428 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/lint/rules/custom_rules.py | 58,59 | 45,75 | match | Python39Rule | 62,75 | 59,75 | class Python39Rule(CloudFormationLintRule):
"""
Check for Python3.9 usage
"""
id = "E9001"
shortdesc = "Python3.9 Lambda usage"
description = "Ensure that Python3.9 is used by all Lambda functions"
tags = ["ecommerce", "lambda"]
_runtime = "python3.9"
_message = "Function is using ... | class Python39Rule(CloudFormationLintRule):
"""
Check for Python3.9 usage
"""
id = "E9001"
shortdesc = "Python3.9 Lambda usage"
description = "Ensure that Python3.9 is used by all Lambda functions"
tags = ["ecommerce", "lambda"]
_runtime = "python3.9"
_message = "Function is using ... |
matches = []
for key, value in cfn.get_resources(["AWS::Lambda::Function"]).items():
if value.get("Properties").get("Runtime") != self._runtime:
matches.append(RuleMatch(
["Resources", key],
self._message.format(value.get("Properties"... | """
Match against Lambda functions not using python3.9
"""
matches = []
for key, value in cfn.get_resources(["AWS::Lambda::Function"]).items():
if value.get("Properties").get("Runtime") != self._runtime:
matches.append(RuleMatch(
... | 20 | 153 | 113 | 266 | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... | """
Custom rules for cfn-lint
"""
import copy
import logging
import re
from cfnlint.rules import CloudFormationLintRule, RuleMatch # pylint: disable=import-error
LOGGER = logging.getLogger(__name__)
class MandatoryParametersRule(CloudFormationLintRule):
"""
Check for Mandatory CloudFormation Parameters
... |
44,429 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/src/ecom/ecom/apigateway.py | 16,17 | 1,61 | cognito_user_id | 20,27 | 17,27 | """
API Gateway helpers for Lambda functions
"""
import json
from typing import Dict, Optional, Union
from .helpers import Encoder
__all__ = [
"cognito_user_id", "iam_user_id", "response"
]
def cognito_user_id(event: dict) -> Optional[str]:
FILL_FUNC_BODYdef iam_user_id(event: dict) -> Optional[str]:
"""
... | """
API Gateway helpers for Lambda functions
"""
import json
from typing import Dict, Optional, Union
from .helpers import Encoder
__all__ = [
"cognito_user_id", "iam_user_id", "response"
]
def cognito_user_id(event: dict) -> Optional[str]:
"""
Returns the User ID (sub) from cognito or None
"""
FI... |
try:
return event["requestContext"]["authorizer"]["claims"]["sub"]
except (TypeError, KeyError):
return None
| """
Returns the User ID (sub) from cognito or None
"""
try:
return event["requestContext"]["authorizer"]["claims"]["sub"]
except (TypeError, KeyError):
return None
| 8 | 430 | 47 | 477 | """
API Gateway helpers for Lambda functions
"""
import json
from typing import Dict, Optional, Union
from .helpers import Encoder
__all__ = [
"cognito_user_id", "iam_user_id", "response"
]
def cognito_user_id(event: dict) -> Optional[str]:
FILL_FUNC_BODYdef iam_user_id(event: dict) -> Optional[str]:
"""
... | """
API Gateway helpers for Lambda functions
"""
import json
from typing import Dict, Optional, Union
from .helpers import Encoder
__all__ = [
"cognito_user_id", "iam_user_id", "response"
]
def cognito_user_id(event: dict) -> Optional[str]:
"""
Returns the User ID (sub) from cognito or None
"""
FI... | |
44,430 | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform | /home/hieuvd/dung_repo/raw/stars_03/aws-samples_aws-serverless-ecommerce-platform/aws-serverless-ecommerce-platform/shared/src/ecom/ecom/helpers.py | 19,20 | 14,27 | default | Encoder | 20,27 | 20,27 | class Encoder(json.JSONEncoder):
"""
Helper class to convert a DynamoDB item to JSON
"""
def default(self, o): # pylint: disable=method-hidden
FILL_FUNC_BODY | class Encoder(json.JSONEncoder):
"""
Helper class to convert a DynamoDB item to JSON
"""
def default(self, o): # pylint: disable=method-hidden
FILL_FUNC_BODY | if isinstance(o, datetime) or isinstance(o, date):
return o.isoformat()
if isinstance(o, Decimal):
if abs(o) % 1 > 0:
return float(o)
return int(o)
return super(Encoder, self).default(o) | if isinstance(o, datetime) or isinstance(o, date):
return o.isoformat()
if isinstance(o, Decimal):
if abs(o) % 1 > 0:
return float(o)
return int(o)
return super(Encoder, self).default(o) | 24 | 62 | 84 | 146 | """
Helpers for Lambda functions
"""
from datetime import datetime, date
from decimal import Decimal
import json
__all__ = ["Encoder"]
class Encoder(json.JSONEncoder):
"""
Helper class to convert a DynamoDB item to JSON
"""
def default(self, o): # pylint: disable=method-hidden
FILL_FUNC_BODY | """
Helpers for Lambda functions
"""
from datetime import datetime, date
from decimal import Decimal
import json
__all__ = ["Encoder"]
class Encoder(json.JSONEncoder):
"""
Helper class to convert a DynamoDB item to JSON
"""
def default(self, o): # pylint: disable=method-hidden
FILL_FUNC_BODY |
44,438 | /home/hieuvd/dung_repo/raw/stars_03/beda-software_drf-writable-nested/drf-writable-nested | /home/hieuvd/dung_repo/raw/stars_03/beda-software_drf-writable-nested/drf-writable-nested/manage.py | 17,18 | 1,32 | main | 18,30 | 18,30 | #!/usr/bin/env python3
"""Django's command-line utility for administrative tasks.
This script is needed to recreate test Model migrations. To do that:
$ python manage.py makemigrations tests
This is needed in Django 2.2+ because the test Models have ForeignKeys
to Models outside of this app.
"""
import os
import s... | #!/usr/bin/env python3
"""Django's command-line utility for administrative tasks.
This script is needed to recreate test Model migrations. To do that:
$ python manage.py makemigrations tests
This is needed in Django 2.2+ because the test Models have ForeignKeys
to Models outside of this app.
"""
import os
import s... | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH e... | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH e... | 42 | 125 | 142 | 267 | #!/usr/bin/env python3
"""Django's command-line utility for administrative tasks.
This script is needed to recreate test Model migrations. To do that:
$ python manage.py makemigrations tests
This is needed in Django 2.2+ because the test Models have ForeignKeys
to Models outside of this app.
"""
import os
import s... | #!/usr/bin/env python3
"""Django's command-line utility for administrative tasks.
This script is needed to recreate test Model migrations. To do that:
$ python manage.py makemigrations tests
This is needed in Django 2.2+ because the test Models have ForeignKeys
to Models outside of this app.
"""
import os
import s... | |
44,439 | /home/hieuvd/dung_repo/raw/stars_03/beda-software_drf-writable-nested/drf-writable-nested | /home/hieuvd/dung_repo/raw/stars_03/beda-software_drf-writable-nested/drf-writable-nested/setup.py | 10,11 | 1,68 | get_version | 14,18 | 11,18 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from io import open
from setuptools import setup
def get_version(package):
FILL_FUNC_BODYversion = get_version('drf_writable_nested')
with open('README.md') as f:
long_description = f.read()
setup(
name='drf-writable-nested',
version=ver... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from io import open
from setuptools import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
FILL_FUNC_BODYversion = get_version('drf_writable_nested')
with open('README.md') as f:
... | init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
| """
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
| 9 | 653 | 64 | 717 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from io import open
from setuptools import setup
def get_version(package):
FILL_FUNC_BODYversion = get_version('drf_writable_nested')
with open('README.md') as f:
long_description = f.read()
setup(
name='drf-writable-nested',
version=ver... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from io import open
from setuptools import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
FILL_FUNC_BODYversion = get_version('drf_writable_nested')
with open('README.md') as f:
... | |
44,513 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/examples/compute-df-counts.py | 24,25 | 1,63 | read_corenlp_xml | 25,48 | 25,48 | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
from string import punctuation
import xml.etree.ElementTree as etree
from pke import compute_document_frequency
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]... | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
from string import punctuation
import xml.etree.ElementTree as etree
from pke import compute_document_frequency
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]... | sentences = []
tree = etree.parse(path, etree.XMLParser())
for sentence in tree.iterfind('./document/sentences/sentence'):
# get the character offsets
starts = [int(u.text) for u in
sentence.iterfind('tokens/token/CharacterOffsetBegin')]
ends = [int(u.text) for u in... | sentences = []
tree = etree.parse(path, etree.XMLParser())
for sentence in tree.iterfind('./document/sentences/sentence'):
# get the character offsets
starts = [int(u.text) for u in
sentence.iterfind('tokens/token/CharacterOffsetBegin')]
ends = [int(u.text) for u in... | 68 | 303 | 300 | 603 | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
from string import punctuation
import xml.etree.ElementTree as etree
from pke import compute_document_frequency
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]... | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
from string import punctuation
import xml.etree.ElementTree as etree
from pke import compute_document_frequency
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]... | |
44,514 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/examples/compute-lda_model.py | 23,24 | 1,59 | read_corenlp_xml | 24,47 | 24,47 | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
import xml.etree.ElementTree as etree
from pke import compute_lda_model
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]
# path to the lda model, saved as a gz... | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
import xml.etree.ElementTree as etree
from pke import compute_lda_model
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]
# path to the lda model, saved as a gz... | sentences = []
tree = etree.parse(path, etree.XMLParser())
for sentence in tree.iterfind('./document/sentences/sentence'):
# get the character offsets
starts = [int(u.text) for u in
sentence.iterfind('tokens/token/CharacterOffsetBegin')]
ends = [int(u.text) for u in... | sentences = []
tree = etree.parse(path, etree.XMLParser())
for sentence in tree.iterfind('./document/sentences/sentence'):
# get the character offsets
starts = [int(u.text) for u in
sentence.iterfind('tokens/token/CharacterOffsetBegin')]
ends = [int(u.text) for u in... | 68 | 263 | 300 | 563 | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
import xml.etree.ElementTree as etree
from pke import compute_lda_model
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]
# path to the lda model, saved as a gz... | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
import xml.etree.ElementTree as etree
from pke import compute_lda_model
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]
# path to the lda model, saved as a gz... | |
44,516 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/readers.py | 140,141 | 137,152 | read | PreprocessedReader | 141,152 | 141,152 | class PreprocessedReader(Reader):
"""Reader for preprocessed text."""
def read(self, list_of_sentence_tuples):
FILL_FUNC_BODY | class PreprocessedReader(Reader):
"""Reader for preprocessed text."""
def read(self, list_of_sentence_tuples):
FILL_FUNC_BODY | sentences = []
for sentence_id, sentence in enumerate(list_of_sentence_tuples):
words = [word for word, pos_tag in sentence]
pos_tags = [pos_tag for word, pos_tag in sentence]
shift = 0
sentences.append(Sentence(
words=words,
... | sentences = []
for sentence_id, sentence in enumerate(list_of_sentence_tuples):
words = [word for word, pos_tag in sentence]
pos_tags = [pos_tag for word, pos_tag in sentence]
shift = 0
sentences.append(Sentence(
words=words,
... | 37 | 48 | 119 | 167 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... |
44,517 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/readers.py | 60,61 | 42,119 | read | RawTextReader | 75,119 | 61,119 | class RawTextReader(Reader):
"""Reader for raw text."""
def __init__(self, language=None):
"""Constructor for RawTextReader.
Args:
language (str): language of text to process.
"""
self.language = language
if language is None:
self.language = 'e... | class RawTextReader(Reader):
"""Reader for raw text."""
def __init__(self, language=None):
"""Constructor for RawTextReader.
Args:
language (str): language of text to process.
"""
self.language = language
if language is None:
self.language = 'e... |
nlp = spacy_model
if nlp is None:
# list installed models
installed_models = [m for m in spacy.util.get_installed_models() if m[:2] == self.language]
# select first model for the language
if len(installed_models):
nlp = spacy.load(insta... | """Read the input file and use spacy to pre-process.
Spacy model selection: By default this function will load the spacy
model that is closest to the `language` parameter ('fr' language will
load the spacy model linked to 'fr' or any 'fr_core_web_*' available
model). In order to... | 166 | 345 | 542 | 887 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... |
44,518 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/readers.py | 38,39 | 35,42 | read | Reader | 39,42 | 39,42 | class Reader(object):
"""Reader default class."""
def read(self, path):
FILL_FUNC_BODY | class Reader(object):
"""Reader default class."""
def read(self, path):
FILL_FUNC_BODY | raise NotImplementedError
| raise NotImplementedError
| 2 | 33 | 13 | 46 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... |
44,519 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/readers.py | 122,123 | 119,137 | read | SpacyDocReader | 123,137 | 123,137 | class SpacyDocReader(Reader):
"""Minimal Spacy Doc Reader."""
def read(self, spacy_doc):
FILL_FUNC_BODY | class SpacyDocReader(Reader):
"""Minimal Spacy Doc Reader."""
def read(self, spacy_doc):
FILL_FUNC_BODY | sentences = []
for sentence_id, sentence in enumerate(spacy_doc.sents):
sentences.append(Sentence(
words=[token.text for token in sentence],
pos=[token.pos_ or token.tag_ for token in sentence],
meta={
"lemmas": [token.lemma... | sentences = []
for sentence_id, sentence in enumerate(spacy_doc.sents):
sentences.append(Sentence(
words=[token.text for token in sentence],
pos=[token.pos_ or token.tag_ for token in sentence],
meta={
"lemmas": [token.lemma... | 41 | 42 | 145 | 187 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... |
44,520 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/supervised/api.py | 27,28 | 15,75 | feature_scaling | SupervisedLoadFile | 29,36 | 28,36 | class SupervisedLoadFile(LoadFile):
""" The SupervisedLoadFile class that provides extra base functions for
supervised models. """
def __init__(self):
""" Redefining initializer. """
super(SupervisedLoadFile, self).__init__()
self.instances = {}
""" The instances conta... | class SupervisedLoadFile(LoadFile):
""" The SupervisedLoadFile class that provides extra base functions for
supervised models. """
def __init__(self):
""" Redefining initializer. """
super(SupervisedLoadFile, self).__init__()
self.instances = {}
""" The instances conta... |
candidates = self.instances.keys()
X = [self.instances[u] for u in candidates]
X = MinMaxScaler().fit_transform(X)
for i, candidate in enumerate(candidates):
self.instances[candidate] = X[i]
| """ Scale features to [0,1]. """
candidates = self.instances.keys()
X = [self.instances[u] for u in candidates]
X = MinMaxScaler().fit_transform(X)
for i, candidate in enumerate(candidates):
self.instances[candidate] = X[i]
| 21 | 463 | 81 | 544 | # -*- coding: utf-8 -*-
""" Abstract base class for Supervised models. """
from __future__ import division
from __future__ import absolute_import
import os
from pke.base import LoadFile
from sklearn.preprocessing import MinMaxScaler
from joblib import load as load_model
class SupervisedLoadFile(LoadFile):
"""... | # -*- coding: utf-8 -*-
""" Abstract base class for Supervised models. """
from __future__ import division
from __future__ import absolute_import
import os
from pke.base import LoadFile
from sklearn.preprocessing import MinMaxScaler
from joblib import load as load_model
class SupervisedLoadFile(LoadFile):
"""... |
44,521 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/supervised/feature_based/kea.py | 95,96 | 32,167 | feature_extraction | Kea | 106,140 | 96,140 | class Kea(SupervisedLoadFile):
"""Kea keyphrase extraction model.
Parameterized example::
import pke
# 1. create a Kea extractor.
extractor = pke.supervised.Kea()
# 2. load the content of the document.
stoplist = pke.lang.stopwords.get('en')
extractor.load_doc... | class Kea(SupervisedLoadFile):
"""Kea keyphrase extraction model.
Parameterized example::
import pke
# 1. create a Kea extractor.
extractor = pke.supervised.Kea()
# 2. load the content of the document.
stoplist = pke.lang.stopwords.get('en')
extractor.load_doc... |
# initialize default document frequency counts if none provided
if df is None:
logging.warning('LoadFile._df_counts is hard coded to {}'.format(
self._df_counts))
df = load_document_frequency_file(self._df_counts, delimiter='\t')
# initialize the number ... | """Extract features for each keyphrase candidate. Features are the
tf*idf of the candidate and its first occurrence relative to the
document.
Args:
df (dict): document frequencies, the number of documents should be
specified using the "--NB_DOC--" key.
... | 119 | 1,027 | 356 | 1,383 | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""Kea supervised keyphrase extraction model.
Kea is a supervised model for keyphrase extraction that uses two features,
namely TF x IDF and first occurrence, to classify keyphrase candidates as
keyphrase or not. The model is described in:
* Ian Wit... | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""Kea supervised keyphrase extraction model.
Kea is a supervised model for keyphrase extraction that uses two features,
namely TF x IDF and first occurrence, to classify keyphrase candidates as
keyphrase or not. The model is described in:
* Ian Wit... |
44,523 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/graph_based/positionrank.py | 101,102 | 27,184 | build_word_graph | PositionRank | 116,146 | 102,146 | class PositionRank(SingleRank):
"""PositionRank keyphrase extraction model.
Parameterized example::
import pke
# define the valid Part-of-Speeches to occur in the graph
pos = {'NOUN', 'PROPN', 'ADJ'}
# define the grammar for selecting the keyphrase candidates
grammar... | class PositionRank(SingleRank):
"""PositionRank keyphrase extraction model.
Parameterized example::
import pke
# define the valid Part-of-Speeches to occur in the graph
pos = {'NOUN', 'PROPN', 'ADJ'}
# define the grammar for selecting the keyphrase candidates
grammar... |
if pos is None:
pos = {'NOUN', 'PROPN', 'ADJ'}
# flatten document as a sequence of only valid (word, position) tuples
text = []
for i, sentence in enumerate(self.sentences):
shift = sum([s.length for s in self.sentences[0:i]])
for j, word in enumerat... | """Build the graph representation of the document.
In the graph, nodes are words that passes a Part-of-Speech filter. Two
nodes are connected if the words corresponding to these nodes co-occur
within a `window` of contiguous tokens. The weight of an edge is
computed based on the... | 128 | 1,302 | 370 | 1,672 | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""PositionRank keyphrase extraction model.
PositionRank is an unsupervised model for keyphrase extraction from scholarly
documents that incorporates information from all positions of a word's
occurrences into a biased PageRank. The model is describe... | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""PositionRank keyphrase extraction model.
PositionRank is an unsupervised model for keyphrase extraction from scholarly
documents that incorporates information from all positions of a word's
occurrences into a biased PageRank. The model is describe... |
44,524 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/graph_based/singlerank.py | 65,66 | 24,142 | build_word_graph | SingleRank | 82,107 | 66,107 | class SingleRank(TextRank):
"""SingleRank keyphrase extraction model.
This model is an extension of the TextRank model that uses the number of
co-occurrences to weigh edges in the graph.
Parameterized example::
import pke
# define the set of valid Part-of-Speeches
pos = {'NOU... | class SingleRank(TextRank):
"""SingleRank keyphrase extraction model.
This model is an extension of the TextRank model that uses the number of
co-occurrences to weigh edges in the graph.
Parameterized example::
import pke
# define the set of valid Part-of-Speeches
pos = {'NOU... |
if pos is None:
pos = {'NOUN', 'PROPN', 'ADJ'}
# flatten document as a sequence of (word, pass_syntactic_filter) tuples
text = [(word, sentence.pos[i] in pos) for sentence in self.sentences
for i, word in enumerate(sentence.stems)]
# add nodes to the graph
... | """Build a graph representation of the document in which nodes/vertices
are words and edges represent co-occurrence relation. Syntactic filters
can be applied to select only words of certain Part-of-Speech.
Co-occurrence relations can be controlled using the distance (window)
bet... | 98 | 993 | 313 | 1,306 | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""SingleRank keyphrase extraction model.
Simple extension of the TextRank model described in:
* Xiaojun Wan and Jianguo Xiao.
CollabRank: Towards a Collaborative Approach to Single-Document Keyphrase
Extraction.
*In proceedings of the COLING*... | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""SingleRank keyphrase extraction model.
Simple extension of the TextRank model described in:
* Xiaojun Wan and Jianguo Xiao.
CollabRank: Towards a Collaborative Approach to Single-Document Keyphrase
Extraction.
*In proceedings of the COLING*... |
44,525 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/graph_based/textrank.py | 130,135 | 27,186 | candidate_weighting | TextRank | 150,186 | 135,186 | class TextRank(LoadFile):
"""TextRank for keyword extraction.
This model builds a graph that represents the text. A graph based ranking
algorithm is then applied to extract the lexical units (here the words) that
are most important in the text.
In this implementation, nodes are words of certain pa... | class TextRank(LoadFile):
"""TextRank for keyword extraction.
This model builds a graph that represents the text. A graph based ranking
algorithm is then applied to extract the lexical units (here the words) that
are most important in the text.
In this implementation, nodes are words of certain pa... |
if pos is None:
pos = {'NOUN', 'PROPN', 'ADJ'}
# build the word graph
self.build_word_graph(window=window, pos=pos)
# compute the word scores using the unweighted PageRank formulae
w = nx.pagerank(self.graph, alpha=0.85, tol=0.0001, weight=None)
# generate... | """Tailored candidate ranking method for TextRank. Keyphrase candidates
are either composed from the T-percent highest-ranked words as in the
original paper or extracted using the `candidate_selection()` method.
Candidates are ranked using the sum of their (normalized?) words.
A... | 140 | 1,281 | 451 | 1,732 | # -*- coding: utf-8 -*-
# Authors: Ygor Gallina, Florian Boudin
# Date: 10-18-2018
"""TextRank keyphrase extraction model.
Implementation of the TextRank model for keyword extraction described in:
* Rada Mihalcea and Paul Tarau.
TextRank: Bringing Order into Texts
*In Proceedings of EMNLP*, 2004.
"""
from __fu... | # -*- coding: utf-8 -*-
# Authors: Ygor Gallina, Florian Boudin
# Date: 10-18-2018
"""TextRank keyphrase extraction model.
Implementation of the TextRank model for keyword extraction described in:
* Rada Mihalcea and Paul Tarau.
TextRank: Bringing Order into Texts
*In Proceedings of EMNLP*, 2004.
"""
from __fu... |
44,527 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/statistical/firstphrases.py | 57,58 | 14,64 | candidate_weighting | FirstPhrases | 59,64 | 58,64 | class FirstPhrases(LoadFile):
"""Baseline model that extracts the first phrases of a document.
Parameterized example::
import pke
# define the set of valid Part-of-Speeches
pos = {'NOUN', 'PROPN', 'ADJ'}
# 1. create a FirstPhrases baseline extractor.
extractor = pke.u... | class FirstPhrases(LoadFile):
"""Baseline model that extracts the first phrases of a document.
Parameterized example::
import pke
# define the set of valid Part-of-Speeches
pos = {'NOUN', 'PROPN', 'ADJ'}
# 1. create a FirstPhrases baseline extractor.
extractor = pke.u... |
# rank candidates using inverse position
for k in self.candidates.keys():
# the '-' ensures that the first item will have the higher weight
self.weights[k] = -min(self.candidates[k].offsets)
| """Candidate weighting function using position."""
# rank candidates using inverse position
for k in self.candidates.keys():
# the '-' ensures that the first item will have the higher weight
self.weights[k] = -min(self.candidates[k].offsets)
| 26 | 405 | 67 | 472 | # -*- coding: utf-8 -*-
# Author: ygor Gallina
# Date: 19-10-2018
"""StupidKE keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pke.base import LoadFile
class FirstPhrases(LoadFile):
"""Baseline model that extracts t... | # -*- coding: utf-8 -*-
# Author: ygor Gallina
# Date: 19-10-2018
"""StupidKE keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pke.base import LoadFile
class FirstPhrases(LoadFile):
"""Baseline model that extracts t... |
44,528 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/statistical/kpminer.py | 61,62 | 27,153 | candidate_selection | KPMiner | 72,94 | 62,94 | class KPMiner(LoadFile):
"""KP-Miner keyphrase extraction model.
Parameterized example::
import pke
# 1. create a KPMiner extractor.
extractor = pke.unsupervised.KPMiner()
# 2. load the content of the document.
extractor.load_document(input='path/to/input',
... | class KPMiner(LoadFile):
"""KP-Miner keyphrase extraction model.
Parameterized example::
import pke
# 1. create a KPMiner extractor.
extractor = pke.unsupervised.KPMiner()
# 2. load the content of the document.
extractor.load_document(input='path/to/input',
... |
# select ngrams from 1 to 5 grams
self.ngram_selection(n=5)
# filter candidates containing stopwords
self.candidate_filtering()
# further filter candidates using lasf and cutoff
# Python 2/3 compatible
for k in list(self.candidates):
# get the cand... | """The candidate selection as described in the KP-Miner paper.
Args:
lasf (int): least allowable seen frequency, defaults to 3.
cutoff (int): the number of words after which candidates are
filtered out, defaults to 400.
stoplist (list): the stoplist f... | 68 | 1,164 | 202 | 1,366 | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""KP-Miner keyphrase extraction model.
Statistical approach to keyphrase extraction described in:
* Samhaa R. El-Beltagy and Ahmed Rafea.
KP-Miner: Participation in SemEval-2.
*Proceedings of SemEval*, pages 190-193, 2010.
"""
from __future__... | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""KP-Miner keyphrase extraction model.
Statistical approach to keyphrase extraction described in:
* Samhaa R. El-Beltagy and Ahmed Rafea.
KP-Miner: Participation in SemEval-2.
*Proceedings of SemEval*, pages 190-193, 2010.
"""
from __future__... |
44,529 | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke | /home/hieuvd/dung_repo/raw/stars_03/boudinfl_pke/pke/pke/unsupervised/statistical/tfidf.py | 63,64 | 18,91 | candidate_weighting | TfIdf | 70,91 | 64,91 | class TfIdf(LoadFile):
"""TF*IDF keyphrase extraction model.
Parameterized example::
import string
import pke
# 1. create a TfIdf extractor.
extractor = pke.unsupervised.TfIdf()
# 2. load the content of the document.
stoplist = list(string.punctuation)
... | class TfIdf(LoadFile):
"""TF*IDF keyphrase extraction model.
Parameterized example::
import string
import pke
# 1. create a TfIdf extractor.
extractor = pke.unsupervised.TfIdf()
# 2. load the content of the document.
stoplist = list(string.punctuation)
... |
# initialize default document frequency counts if none provided
if df is None:
logging.warning('LoadFile._df_counts is hard coded to {}'.format(
self._df_counts))
df = load_document_frequency_file(self._df_counts, delimiter='\t')
# initialize the number ... | """Candidate weighting function using document frequencies.
Args:
df (dict): document frequencies, the number of documents should be
specified using the "--NB_DOC--" key.
"""
# initialize default document frequency counts if none provided
if df is No... | 87 | 520 | 250 | 770 | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""TF-IDF keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import logging
from pke.base import LoadFile
from pke.utils import load_document_frequ... | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""TF-IDF keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import logging
from pke.base import LoadFile
from pke.utils import load_document_frequ... |
44,625 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agent.py | 11,12 | 1,231 | load_npz_no_strict | 12,21 | 12,21 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
FILL_FUNC_BODYclass Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
FILL_FUNC_BODYclass Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_... | try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
with numpy.load(filename) as f:
d = serializers.NpzDeserializer(f, strict=False)
d.load(obj)
| try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
with numpy.load(filename) as f:
d = serializers.NpzDeserializer(f, strict=False)
d.load(obj)
| 17 | 1,661 | 89 | 1,750 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
FILL_FUNC_BODYclass Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
FILL_FUNC_BODYclass Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_... | |
44,626 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agent.py | 33,35 | 21,92 | act | Agent | 40,42 | 35,42 | class Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_and_train(self, obs, reward):
"""Select an action for training.
Returns:
~object: action
"""
raise NotImplementedError()
@abstractmethod
def act(self, obs):
FILL... | class Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
@abstractmethod
def act_and_train(self, obs, reward):
"""Select an action for training.
Returns:
~object: action
"""
raise NotImplementedError()
@abstractmethod
def act(self, obs):
... | raise NotImplementedError()
| """Select an action for evaluation.
Returns:
~object: action
"""
raise NotImplementedError()
| 2 | 416 | 12 | 428 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... |
44,627 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agent.py | 128,129 | 92,153 | __load | AttributeSavingMixin | 129,153 | 129,153 | class AttributeSavingMixin(object):
"""Mixin that provides save and load functionalities."""
@abstractproperty
def saved_attributes(self):
"""Specify attribute names to save or load as a tuple of str."""
pass
def save(self, dirname):
"""Save internal states."""
self.__s... | class AttributeSavingMixin(object):
"""Mixin that provides save and load functionalities."""
@abstractproperty
def saved_attributes(self):
"""Specify attribute names to save or load as a tuple of str."""
pass
def save(self, dirname):
"""Save internal states."""
self.__s... | ancestors.append(self)
for attr in self.saved_attributes:
assert hasattr(self, attr)
attr_value = getattr(self, attr)
if attr_value is None:
continue
if isinstance(attr_value, AttributeSavingMixin):
assert not any(
... | ancestors.append(self)
for attr in self.saved_attributes:
assert hasattr(self, attr)
attr_value = getattr(self, attr)
if attr_value is None:
continue
if isinstance(attr_value, AttributeSavingMixin):
assert not any(
... | 66 | 353 | 249 | 602 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... |
44,628 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agent.py | 182,184 | 167,231 | batch_act_and_train | BatchAgent | 192,194 | 184,194 | class BatchAgent(Agent, metaclass=ABCMeta):
"""Abstract agent class that can interact with a batch of envs."""
@abstractmethod
def batch_act(self, batch_obs):
"""Select a batch of actions for evaluation.
Args:
batch_obs (Sequence of ~object): Observations.
Returns:
... | class BatchAgent(Agent, metaclass=ABCMeta):
"""Abstract agent class that can interact with a batch of envs."""
@abstractmethod
def batch_act(self, batch_obs):
"""Select a batch of actions for evaluation.
Args:
batch_obs (Sequence of ~object): Observations.
Returns:
... | raise NotImplementedError()
| """Select a batch of actions for training.
Args:
batch_obs (Sequence of ~object): Observations.
Returns:
Sequence of ~object: Actions.
"""
raise NotImplementedError()
| 2 | 519 | 12 | 531 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import os
from chainer import serializers
import numpy
import warnings
def load_npz_no_strict(filename, obj):
try:
serializers.load_npz(filename, obj)
except KeyError as e:
warnings.warn(repr(e))
w... |
44,629 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/al.py | 23,24 | 7,69 | _compute_y_and_t | AL | 24,69 | 24,69 | class AL(dqn.DQN):
"""Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.alpha ... | class AL(dqn.DQN):
"""Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.alpha ... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... | 105 | 174 | 538 | 712 | import chainer
from chainer import functions as F
from chainerrl.agents import dqn
class AL(dqn.DQN):
"""Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arg... | import chainer
from chainer import functions as F
from chainerrl.agents import dqn
class AL(dqn.DQN):
"""Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arg... |
44,630 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/categorical_double_dqn.py | 12,13 | 7,46 | _compute_target_values | CategoricalDoubleDQN | 14,46 | 13,46 | class CategoricalDoubleDQN(categorical_dqn.CategoricalDQN):
"""Categorical Double DQN.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY | class CategoricalDoubleDQN(categorical_dqn.CategoricalDQN):
"""Categorical Double DQN.
"""
def _compute_target_values(self, exp_batch):
"""Compute a batch of target return distributions."""
FILL_FUNC_BODY |
batch_next_state = exp_batch['next_state']
batch_rewards = exp_batch['reward']
batch_terminal = exp_batch['is_state_terminal']
with chainer.using_config('train', False):
if self.recurrent:
target_next_qout, _ = self.target_model.n_step_forward(
... | """Compute a batch of target return distributions."""
batch_next_state = exp_batch['next_state']
batch_rewards = exp_batch['reward']
batch_terminal = exp_batch['is_state_terminal']
with chainer.using_config('train', False):
if self.recurrent:
target_... | 80 | 79 | 479 | 558 | import chainer
from chainerrl.agents import categorical_dqn
from chainerrl.agents.categorical_dqn import _apply_categorical_projection
class CategoricalDoubleDQN(categorical_dqn.CategoricalDQN):
"""Categorical Double DQN.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY | import chainer
from chainerrl.agents import categorical_dqn
from chainerrl.agents.categorical_dqn import _apply_categorical_projection
class CategoricalDoubleDQN(categorical_dqn.CategoricalDQN):
"""Categorical Double DQN.
"""
def _compute_target_values(self, exp_batch):
"""Compute a batch of ta... |
44,631 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/double_dqn.py | 12,13 | 6,43 | _compute_target_values | DoubleDQN | 13,43 | 13,43 | class DoubleDQN(dqn.DQN):
"""Double DQN.
See: http://arxiv.org/abs/1509.06461.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY | class DoubleDQN(dqn.DQN):
"""Double DQN.
See: http://arxiv.org/abs/1509.06461.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY |
batch_next_state = exp_batch['next_state']
with chainer.using_config('train', False):
if self.recurrent:
next_qout, _ = self.model.n_step_forward(
batch_next_state,
exp_batch['next_recurrent_state'],
output_mode='c... |
batch_next_state = exp_batch['next_state']
with chainer.using_config('train', False):
if self.recurrent:
next_qout, _ = self.model.n_step_forward(
batch_next_state,
exp_batch['next_recurrent_state'],
output_mode='c... | 57 | 79 | 334 | 413 | import chainer
from chainerrl.agents import dqn
class DoubleDQN(dqn.DQN):
"""Double DQN.
See: http://arxiv.org/abs/1509.06461.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY | import chainer
from chainerrl.agents import dqn
class DoubleDQN(dqn.DQN):
"""Double DQN.
See: http://arxiv.org/abs/1509.06461.
"""
def _compute_target_values(self, exp_batch):
FILL_FUNC_BODY |
44,632 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/double_iqn.py | 17,18 | 7,66 | _compute_target_values | DoubleIQN | 23,66 | 18,66 | class DoubleIQN(iqn.IQN):
"""IQN with DoubleDQN-like target computation.
For computing targets, rather than have the target network
output the Q-value of its highest-valued action, the
target network outputs the Q-value of the primary network's
highest valued action.
"""
def _compute_targ... | class DoubleIQN(iqn.IQN):
"""IQN with DoubleDQN-like target computation.
For computing targets, rather than have the target network
output the Q-value of its highest-valued action, the
target network outputs the Q-value of the primary network's
highest valued action.
"""
def _compute_targ... | batch_next_state = exp_batch['next_state']
batch_rewards = exp_batch['reward']
batch_terminal = exp_batch['is_state_terminal']
batch_size = len(exp_batch['reward'])
taus_tilde = self.xp.random.uniform(
0, 1, size=(batch_size, self.quantile_thresholds_K)).astype('f')
... | """Compute a batch of target return distributions.
Returns:
chainer.Variable: (batch_size, N_prime).
"""
batch_next_state = exp_batch['next_state']
batch_rewards = exp_batch['reward']
batch_terminal = exp_batch['is_state_terminal']
batch_size = len(ex... | 107 | 146 | 645 | 791 | import chainer
import chainer.functions as F
from chainerrl.agents import iqn
class DoubleIQN(iqn.IQN):
"""IQN with DoubleDQN-like target computation.
For computing targets, rather than have the target network
output the Q-value of its highest-valued action, the
target network outputs the Q-value o... | import chainer
import chainer.functions as F
from chainerrl.agents import iqn
class DoubleIQN(iqn.IQN):
"""IQN with DoubleDQN-like target computation.
For computing targets, rather than have the target network
output the Q-value of its highest-valued action, the
target network outputs the Q-value o... |
44,633 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/double_pal.py | 9,10 | 7,63 | _compute_y_and_t | DoublePAL | 10,63 | 10,63 | class DoublePAL(pal.PAL):
def _compute_y_and_t(self, exp_batch):
FILL_FUNC_BODY | class DoublePAL(pal.PAL):
def _compute_y_and_t(self, exp_batch):
FILL_FUNC_BODY |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... | 124 | 40 | 680 | 720 | import chainer
from chainer import functions as F
from chainerrl.agents import pal
class DoublePAL(pal.PAL):
def _compute_y_and_t(self, exp_batch):
FILL_FUNC_BODY | import chainer
from chainer import functions as F
from chainerrl.agents import pal
class DoublePAL(pal.PAL):
def _compute_y_and_t(self, exp_batch):
FILL_FUNC_BODY |
44,634 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/dpp.py | 38,39 | 10,82 | _compute_y_and_t | AbstractDPP | 39,82 | 39,82 | class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qout):
raise NotImplementedError()
def _compute_target_values(self, exp_batch):
batch_next_state = exp_batch['next_state']... | class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qout):
raise NotImplementedError()
def _compute_target_values(self, exp_batch):
batch_next_state = exp_batch['next_state']... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... | 97 | 317 | 512 | 829 | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... |
44,635 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/dpp.py | 95,96 | 82,99 | _l_operator | DPP | 96,99 | 96,99 | class DPP(AbstractDPP):
"""Dynamic Policy Programming with softmax operator.
Args:
eta (float): Positive constant.
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.eta = kwargs.pop('eta', 1.0)
super().__init__(*args, **kwargs)
def _l_operator(... | class DPP(AbstractDPP):
"""Dynamic Policy Programming with softmax operator.
Args:
eta (float): Positive constant.
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.eta = kwargs.pop('eta', 1.0)
super().__init__(*args, **kwargs)
def _l_operator(... | return qout.compute_expectation(self.eta)
| return qout.compute_expectation(self.eta)
| 2 | 124 | 20 | 144 | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... |
44,636 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/dpp.py | 122,123 | 116,124 | _l_operator | DPPGreedy | 123,124 | 123,124 | class DPPGreedy(AbstractDPP):
"""Dynamic Policy Programming with max operator.
This algorithm corresponds to DPP with eta = infinity.
"""
def _l_operator(self, qout):
FILL_FUNC_BODY | class DPPGreedy(AbstractDPP):
"""Dynamic Policy Programming with max operator.
This algorithm corresponds to DPP with eta = infinity.
"""
def _l_operator(self, qout):
FILL_FUNC_BODY | return qout.max
| return qout.max
| 2 | 65 | 8 | 73 | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... |
44,637 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/dpp.py | 112,113 | 99,116 | _l_operator | DPPL | 113,116 | 113,116 | class DPPL(AbstractDPP):
"""Dynamic Policy Programming with L operator.
Args:
eta (float): Positive constant.
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.eta = kwargs.pop('eta', 1.0)
super().__init__(*args, **kwargs)
def _l_operator(self,... | class DPPL(AbstractDPP):
"""Dynamic Policy Programming with L operator.
Args:
eta (float): Positive constant.
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
self.eta = kwargs.pop('eta', 1.0)
super().__init__(*args, **kwargs)
def _l_operator(self,... | return F.logsumexp(self.eta * qout.q_values, axis=1) / self.eta
| return F.logsumexp(self.eta * qout.q_values, axis=1) / self.eta
| 7 | 124 | 33 | 157 | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... | from abc import ABCMeta
from abc import abstractmethod
import chainer
import chainer.functions as F
from chainerrl.agents.dqn import DQN
class AbstractDPP(DQN, metaclass=ABCMeta):
"""Dynamic Policy Programming.
See: https://arxiv.org/abs/1004.2027.
"""
@abstractmethod
def _l_operator(self, qou... |
44,638 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/nsq.py | 81,82 | 18,193 | update | NSQ | 82,126 | 82,126 | class NSQ(AttributeSavingMixin, AsyncAgent):
"""Asynchronous N-step Q-Learning.
See http://arxiv.org/abs/1602.01783
Args:
q_function (A3CModel): Model to train
optimizer (chainer.Optimizer): optimizer used to train the model
t_max (int): The model is updated after every t_max local... | class NSQ(AttributeSavingMixin, AsyncAgent):
"""Asynchronous N-step Q-Learning.
See http://arxiv.org/abs/1602.01783
Args:
q_function (A3CModel): Model to train
optimizer (chainer.Optimizer): optimizer used to train the model
t_max (int): The model is updated after every t_max local... | assert self.t_start < self.t
# Update
if statevar is None:
R = 0
else:
with state_kept(self.target_q_function):
R = float(self.target_q_function(statevar).max.array)
loss = 0
for i in reversed(range(self.t_start, self.t)):
... | assert self.t_start < self.t
# Update
if statevar is None:
R = 0
else:
with state_kept(self.target_q_function):
R = float(self.target_q_function(statevar).max.array)
loss = 0
for i in reversed(range(self.t_start, self.t)):
... | 138 | 1,469 | 500 | 1,969 | import copy
from logging import getLogger
import multiprocessing as mp
import chainer
from chainer import functions as F
import numpy as np
from chainerrl.agent import AsyncAgent
from chainerrl.agent import AttributeSavingMixin
from chainerrl.misc import async_
from chainerrl.misc.batch_states import batch_states
fro... | import copy
from logging import getLogger
import multiprocessing as mp
import chainer
from chainer import functions as F
import numpy as np
from chainerrl.agent import AsyncAgent
from chainerrl.agent import AttributeSavingMixin
from chainerrl.misc import async_
from chainerrl.misc.batch_states import batch_states
fro... |
44,639 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/pal.py | 23,24 | 7,71 | _compute_y_and_t | PAL | 24,71 | 24,71 | class PAL(dqn.DQN):
"""Persistent Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
... | class PAL(dqn.DQN):
"""Persistent Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
For other arguments, see DQN.
"""
def __init__(self, *args, **kwargs):
... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... |
batch_state = exp_batch['state']
batch_size = len(exp_batch['reward'])
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... | 113 | 177 | 594 | 771 | import chainer
from chainer import functions as F
from chainerrl.agents import dqn
class PAL(dqn.DQN):
"""Persistent Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
F... | import chainer
from chainer import functions as F
from chainerrl.agents import dqn
class PAL(dqn.DQN):
"""Persistent Advantage Learning.
See: http://arxiv.org/abs/1512.04860.
Args:
alpha (float): Weight of (persistent) advantages. Convergence
is guaranteed only for alpha in [0, 1).
F... |
44,640 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/agents/residual_dqn.py | 34,35 | 5,58 | _compute_y_and_t | ResidualDQN | 35,54 | 35,54 | class ResidualDQN(DQN):
"""DQN that allows maxQ also backpropagate gradients."""
def __init__(self, *args, **kwargs):
self.grad_scale = kwargs.pop('grad_scale', 1.0)
super().__init__(*args, **kwargs)
def sync_target_network(self):
pass
def _compute_target_values(self, exp_batc... | class ResidualDQN(DQN):
"""DQN that allows maxQ also backpropagate gradients."""
def __init__(self, *args, **kwargs):
self.grad_scale = kwargs.pop('grad_scale', 1.0)
super().__init__(*args, **kwargs)
def sync_target_network(self):
pass
def _compute_target_values(self, exp_batc... |
batch_state = exp_batch['state']
# Compute Q-values for current states
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... |
batch_state = exp_batch['state']
# Compute Q-values for current states
if self.recurrent:
qout, _ = self.model.n_step_forward(
batch_state, exp_batch['recurrent_state'],
output_mode='concat')
else:
qout = self.model(batch_state)
... | 44 | 371 | 210 | 581 | from chainerrl.agents.dqn import DQN
from chainerrl.functions import scale_grad
class ResidualDQN(DQN):
"""DQN that allows maxQ also backpropagate gradients."""
def __init__(self, *args, **kwargs):
self.grad_scale = kwargs.pop('grad_scale', 1.0)
super().__init__(*args, **kwargs)
def sync... | from chainerrl.agents.dqn import DQN
from chainerrl.functions import scale_grad
class ResidualDQN(DQN):
"""DQN that allows maxQ also backpropagate gradients."""
def __init__(self, *args, **kwargs):
self.grad_scale = kwargs.pop('grad_scale', 1.0)
super().__init__(*args, **kwargs)
def sync... |
44,641 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/env.py | 19,21 | 5,24 | close | Env | 21,24 | 21,24 | class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
raise NotImplementedError()
@abstractmethod
de... | class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
raise NotImplementedError()
@abstractmethod
de... | raise NotImplementedError()
| raise NotImplementedError()
| 2 | 110 | 14 | 124 | from abc import ABCMeta
from abc import abstractmethod
class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
... | from abc import ABCMeta
from abc import abstractmethod
class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
... |
44,642 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/env.py | 41,43 | 24,57 | seed | VectorEnv | 43,45 | 43,45 | class VectorEnv(object, metaclass=ABCMeta):
"""Parallel RL learning environments."""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self, mask):
"""Reset envs.
Args:
mask (Sequence of bool): Mask array that specifi... | class VectorEnv(object, metaclass=ABCMeta):
"""Parallel RL learning environments."""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self, mask):
"""Reset envs.
Args:
mask (Sequence of bool): Mask array that specifi... | raise NotImplementedError()
| raise NotImplementedError()
| 2 | 220 | 12 | 232 | from abc import ABCMeta
from abc import abstractmethod
class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
... | from abc import ABCMeta
from abc import abstractmethod
class Env(object, metaclass=ABCMeta):
"""RL learning environment.
This serves a minimal interface for RL agents.
"""
@abstractmethod
def step(self, action):
raise NotImplementedError()
@abstractmethod
def reset(self):
... |
44,643 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/envs/abc.py | 117,118 | 7,154 | step | ABC | 118,152 | 118,152 | class ABC(env.Env):
"""Toy problem only for testing RL agents.
# State space
The state space consists of N discrete states plus the terminal state.
# Observation space
Observations are one-hot vectors that represents which state it is now.
state 0 -> observation [1, 0, ..., 0]
s... | class ABC(env.Env):
"""Toy problem only for testing RL agents.
# State space
The state space consists of N discrete states plus the terminal state.
# Observation space
Observations are one-hot vectors that represents which state it is now.
state 0 -> observation [1, 0, ..., 0]
s... | if isinstance(self.action_space, spaces.Box):
assert isinstance(action, np.ndarray)
action = np.clip(action,
self.action_space.low,
self.action_space.high)
if self.deterministic:
action = np.argmax(acti... | if isinstance(self.action_space, spaces.Box):
assert isinstance(action, np.ndarray)
action = np.clip(action,
self.action_space.low,
self.action_space.high)
if self.deterministic:
action = np.argmax(acti... | 87 | 1,170 | 316 | 1,486 | from gym import spaces
import numpy as np
from chainerrl import env
class ABC(env.Env):
"""Toy problem only for testing RL agents.
# State space
The state space consists of N discrete states plus the terminal state.
# Observation space
Observations are one-hot vectors that represents which st... | from gym import spaces
import numpy as np
from chainerrl import env
class ABC(env.Env):
"""Toy problem only for testing RL agents.
# State space
The state space consists of N discrete states plus the terminal state.
# Observation space
Observations are one-hot vectors that represents which st... |
44,644 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/envs/multiprocess_vector_env.py | 12,13 | 1,135 | worker | 13,40 | 13,40 | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
FILL_FUNC_BODYclass MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in... | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
FILL_FUNC_BODYclass MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in... | # Ignore CTRL+C in the worker process
signal.signal(signal.SIGINT, signal.SIG_IGN)
env = env_fn()
try:
while True:
cmd, data = remote.recv()
if cmd == 'step':
ob, reward, done, info = env.step(data)
remote.send((ob, reward, done, info))
... | # Ignore CTRL+C in the worker process
signal.signal(signal.SIGINT, signal.SIG_IGN)
env = env_fn()
try:
while True:
cmd, data = remote.recv()
if cmd == 'step':
ob, reward, done, info = env.step(data)
remote.send((ob, reward, done, info))
... | 68 | 1,082 | 259 | 1,341 | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
FILL_FUNC_BODYclass MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in... | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
FILL_FUNC_BODYclass MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in... | |
44,645 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/envs/multiprocess_vector_env.py | 100,101 | 40,135 | close | MultiprocessVectorEnv | 101,108 | 101,108 | class MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in its own subprocess.
Args:
env_fns (list of callable): List of callables, each of which
returns gym.Env that is run in its own subprocess.
"""
def __init__(self, env_fns):
if np.__ver... | class MultiprocessVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run in its own subprocess.
Args:
env_fns (list of callable): List of callables, each of which
returns gym.Env that is run in its own subprocess.
"""
def __init__(self, env_fns):
if np.__ver... | self._assert_not_closed()
self.closed = True
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
| self._assert_not_closed()
self.closed = True
for remote in self.remotes:
remote.send(('close', None))
for p in self.ps:
p.join()
| 15 | 971 | 61 | 1,032 | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
# Ignore CTRL+C in the worker process
signal.signal(signal.SIGINT, signal.SIG_IGN)
env = env_fn()... | from multiprocessing import Pipe
from multiprocessing import Process
import signal
import warnings
from cached_property import cached_property
import numpy as np
import chainerrl
def worker(remote, env_fn):
# Ignore CTRL+C in the worker process
signal.signal(signal.SIGINT, signal.SIG_IGN)
env = env_fn()... |
44,646 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/envs/serial_vector_env.py | 23,24 | 6,47 | step | SerialVectorEnv | 24,28 | 24,28 | class SerialVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run sequentially.
The purpose of this VectorEnv is to help debugging. For speed, you should
use MultiprocessVectorEnv if possible.
Args:
env_fns (list of gym.Env): List of gym.Env.
"""
def __init__(self, en... | class SerialVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run sequentially.
The purpose of this VectorEnv is to help debugging. For speed, you should
use MultiprocessVectorEnv if possible.
Args:
env_fns (list of gym.Env): List of gym.Env.
"""
def __init__(self, en... | results = [env.step(a) for env, a in zip(self.envs, actions)]
self.last_obs, rews, dones, infos = zip(*results)
return self.last_obs, rews, dones, infos
| results = [env.step(a) for env, a in zip(self.envs, actions)]
self.last_obs, rews, dones, infos = zip(*results)
return self.last_obs, rews, dones, infos
| 20 | 364 | 66 | 430 | import numpy as np
import chainerrl
class SerialVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run sequentially.
The purpose of this VectorEnv is to help debugging. For speed, you should
use MultiprocessVectorEnv if possible.
Args:
env_fns (list of gym.Env): List of gym.... | import numpy as np
import chainerrl
class SerialVectorEnv(chainerrl.env.VectorEnv):
"""VectorEnv where each env is run sequentially.
The purpose of this VectorEnv is to help debugging. For speed, you should
use MultiprocessVectorEnv if possible.
Args:
env_fns (list of gym.Env): List of gym.... |
44,647 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/experiments/prepare_output_dir.py | 17,19 | 1,96 | prepare_output_dir | 48,96 | 19,96 | import argparse
import datetime
import json
import os
import subprocess
import sys
import tempfile
import chainerrl
def is_under_git_control():
"""Return true iff the current directory is under git control."""
return chainerrl.misc.is_return_code_zero(['git', 'rev-parse'])
def prepare_output_dir(args, user... | import argparse
import datetime
import json
import os
import subprocess
import sys
import tempfile
import chainerrl
def is_under_git_control():
"""Return true iff the current directory is under git control."""
return chainerrl.misc.is_return_code_zero(['git', 'rev-parse'])
def prepare_output_dir(args, user... | time_str = datetime.datetime.now().strftime(time_format)
if user_specified_dir is not None:
if os.path.exists(user_specified_dir):
if not os.path.isdir(user_specified_dir):
raise RuntimeError(
'{} is not a directory'.format(user_specified_dir))
out... | """Prepare a directory for outputting training results.
An output directory, which ends with the current datetime string,
is created. Then the following infomation is saved into the directory:
args.txt: command line arguments
command.txt: command itself
environ.txt: environmental v... | 144 | 453 | 659 | 1,112 | import argparse
import datetime
import json
import os
import subprocess
import sys
import tempfile
import chainerrl
def is_under_git_control():
"""Return true iff the current directory is under git control."""
return chainerrl.misc.is_return_code_zero(['git', 'rev-parse'])
def prepare_output_dir(args, user... | import argparse
import datetime
import json
import os
import subprocess
import sys
import tempfile
import chainerrl
def is_under_git_control():
"""Return true iff the current directory is under git control."""
return chainerrl.misc.is_return_code_zero(['git', 'rev-parse'])
def prepare_output_dir(args, user... | |
44,648 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/experiments/train_agent.py | 22,25 | 1,161 | train_agent | 25,87 | 25,87 | import logging
import os
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
from chainerrl.misc.ask_yes_no import ask_yes_no
def save_agent_replay_buffer(agent, t, outdir, suffix='', logger=None):
logger = logger or logging.getLogger(__name__)
filenam... | import logging
import os
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
from chainerrl.misc.ask_yes_no import ask_yes_no
def save_agent_replay_buffer(agent, t, outdir, suffix='', logger=None):
logger = logger or logging.getLogger(__name__)
filenam... |
logger = logger or logging.getLogger(__name__)
episode_r = 0
episode_idx = 0
# o_0, r_0
obs = env.reset()
r = 0
t = step_offset
if hasattr(agent, 't'):
agent.t = step_offset
episode_len = 0
try:
while t < steps:
# a_t
action = agent.a... |
logger = logger or logging.getLogger(__name__)
episode_r = 0
episode_idx = 0
# o_0, r_0
obs = env.reset()
r = 0
t = step_offset
if hasattr(agent, 't'):
agent.t = step_offset
episode_len = 0
try:
while t < steps:
# a_t
action = agent.a... | 182 | 1,178 | 608 | 1,786 | import logging
import os
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
from chainerrl.misc.ask_yes_no import ask_yes_no
def save_agent_replay_buffer(agent, t, outdir, suffix='', logger=None):
logger = logger or logging.getLogger(__name__)
filenam... | import logging
import os
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
from chainerrl.misc.ask_yes_no import ask_yes_no
def save_agent_replay_buffer(agent, t, outdir, suffix='', logger=None):
logger = logger or logging.getLogger(__name__)
filenam... | |
44,651 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorer.py | 8,10 | 5,18 | select_action | Explorer | 17,18 | 10,18 | class Explorer(object, metaclass=ABCMeta):
"""Abstract explorer."""
@abstractmethod
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY | class Explorer(object, metaclass=ABCMeta):
"""Abstract explorer."""
@abstractmethod
def select_action(self, t, greedy_action_func, action_value=None):
"""Select an action.
Args:
t: current time step
greedy_action_func: function with no argument that returns an action
... | raise NotImplementedError()
| """Select an action.
Args:
t: current time step
greedy_action_func: function with no argument that returns an action
action_value (ActionValue): ActionValue object
"""
raise NotImplementedError()
| 2 | 115 | 10 | 125 | from abc import ABCMeta
from abc import abstractmethod
class Explorer(object, metaclass=ABCMeta):
"""Abstract explorer."""
@abstractmethod
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY | from abc import ABCMeta
from abc import abstractmethod
class Explorer(object, metaclass=ABCMeta):
"""Abstract explorer."""
@abstractmethod
def select_action(self, t, greedy_action_func, action_value=None):
"""Select an action.
Args:
t: current time step
greedy_action_... |
44,652 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/additive_gaussian.py | 26,27 | 6,38 | select_action | AdditiveGaussian | 27,35 | 27,35 | class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
low (float, array_like of floats, or None): Lower bound of action
space used to clip an action afte... | class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
low (float, array_like of floats, or None): Lower bound of action
space used to clip an action afte... | a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
| a = greedy_action_func()
noise = np.random.normal(
scale=self.scale, size=a.shape).astype(np.float32)
if self.low is not None or self.high is not None:
return np.clip(a + noise, self.low, self.high)
else:
return a + noise
| 29 | 283 | 99 | 382 | import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
low (float, array_like of floats, or None): Lower bound of... | import numpy as np
from chainerrl import explorer
class AdditiveGaussian(explorer.Explorer):
"""Additive Gaussian noise to actions.
Each action must be numpy.ndarray.
Args:
scale (float or array_like of floats): Scale parameter.
low (float, array_like of floats, or None): Lower bound of... |
44,653 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/additive_ou.py | 36,37 | 8,56 | select_action | AdditiveOU | 37,53 | 37,53 | class AdditiveOU(explorer.Explorer):
"""Additive Ornstein-Uhlenbeck process.
Used in https://arxiv.org/abs/1509.02971 for exploration.
Args:
mu (float): Mean of the OU process
theta (float): Friction to pull towards the mean
sigma (float or ndarray): Scale of noise
start_wi... | class AdditiveOU(explorer.Explorer):
"""Additive Ornstein-Uhlenbeck process.
Used in https://arxiv.org/abs/1509.02971 for exploration.
Args:
mu (float): Mean of the OU process
theta (float): Friction to pull towards the mean
sigma (float or ndarray): Scale of noise
start_wi... | a = greedy_action_func()
if self.ou_state is None:
if self.start_with_mu:
self.ou_state = np.full(a.shape, self.mu, dtype=np.float32)
else:
sigma_stable = (self.sigma /
np.sqrt(2 * self.theta - self.theta ** 2))
... | a = greedy_action_func()
if self.ou_state is None:
if self.start_with_mu:
self.ou_state = np.full(a.shape, self.mu, dtype=np.float32)
else:
sigma_stable = (self.sigma /
np.sqrt(2 * self.theta - self.theta ** 2))
... | 45 | 400 | 206 | 606 | from logging import getLogger
import numpy as np
from chainerrl import explorer
class AdditiveOU(explorer.Explorer):
"""Additive Ornstein-Uhlenbeck process.
Used in https://arxiv.org/abs/1509.02971 for exploration.
Args:
mu (float): Mean of the OU process
theta (float): Friction to pul... | from logging import getLogger
import numpy as np
from chainerrl import explorer
class AdditiveOU(explorer.Explorer):
"""Additive Ornstein-Uhlenbeck process.
Used in https://arxiv.org/abs/1509.02971 for exploration.
Args:
mu (float): Mean of the OU process
theta (float): Friction to pul... |
44,654 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/epsilon_greedy.py | 8,10 | 1,83 | select_action_epsilon_greedily | 10,16 | 10,16 | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
FILL_FUNC_BODYclass ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args... | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
FILL_FUNC_BODYclass ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args... | if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action_func(), True
| if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action_func(), True
| 11 | 831 | 46 | 877 | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
FILL_FUNC_BODYclass ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args... | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
FILL_FUNC_BODYclass ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args... | |
44,655 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/epsilon_greedy.py | 32,33 | 16,43 | select_action | ConstantEpsilonGreedy | 33,39 | 33,39 | class ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args:
epsilon: epsilon used
random_action_func: function with no argument that returns action
logger: logger used
"""
def __init__(self, epsilon, random_action_func,
logger=getLo... | class ConstantEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with constant epsilon.
Args:
epsilon: epsilon used
random_action_func: function with no argument that returns action
logger: logger used
"""
def __init__(self, epsilon, random_action_func,
logger=getLo... | a, greedy = select_action_epsilon_greedily(
self.epsilon, self.random_action_func, greedy_action_func)
greedy_str = 'greedy' if greedy else 'non-greedy'
self.logger.debug('t:%s a:%s %s', t, a, greedy_str)
return a
| a, greedy = select_action_epsilon_greedily(
self.epsilon, self.random_action_func, greedy_action_func)
greedy_str = 'greedy' if greedy else 'non-greedy'
self.logger.debug('t:%s a:%s %s', t, a, greedy_str)
return a
| 22 | 205 | 98 | 303 | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action... | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action... |
44,656 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/epsilon_greedy.py | 73,74 | 43,83 | select_action | LinearDecayEpsilonGreedy | 74,81 | 74,81 | class LinearDecayEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with linearly decayed epsilon
Args:
start_epsilon: max value of epsilon
end_epsilon: min value of epsilon
decay_steps: how many steps it takes for epsilon to decay
random_action_func: function with no argument that ret... | class LinearDecayEpsilonGreedy(explorer.Explorer):
"""Epsilon-greedy with linearly decayed epsilon
Args:
start_epsilon: max value of epsilon
end_epsilon: min value of epsilon
decay_steps: how many steps it takes for epsilon to decay
random_action_func: function with no argument that ret... | self.epsilon = self.compute_epsilon(t)
a, greedy = select_action_epsilon_greedily(
self.epsilon, self.random_action_func, greedy_action_func)
greedy_str = 'greedy' if greedy else 'non-greedy'
self.logger.debug('t:%s a:%s %s', t, a, greedy_str)
return a
| self.epsilon = self.compute_epsilon(t)
a, greedy = select_action_epsilon_greedily(
self.epsilon, self.random_action_func, greedy_action_func)
greedy_str = 'greedy' if greedy else 'non-greedy'
self.logger.debug('t:%s a:%s %s', t, a, greedy_str)
return a
| 25 | 385 | 113 | 498 | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action... | from logging import getLogger
import numpy as np
from chainerrl import explorer
def select_action_epsilon_greedily(epsilon, random_action_func,
greedy_action_func):
if np.random.rand() < epsilon:
return random_action_func(), False
else:
return greedy_action... |
44,657 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/explorers/greedy.py | 7,8 | 4,12 | select_action | Greedy | 8,10 | 8,10 | class Greedy(explorer.Explorer):
"""No exploration"""
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY def __repr__(self):
return 'Greedy()'
| class Greedy(explorer.Explorer):
"""No exploration"""
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY def __repr__(self):
return 'Greedy()'
| return greedy_action_func()
| return greedy_action_func()
| 2 | 70 | 13 | 83 | from chainerrl import explorer
class Greedy(explorer.Explorer):
"""No exploration"""
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY def __repr__(self):
return 'Greedy()'
| from chainerrl import explorer
class Greedy(explorer.Explorer):
"""No exploration"""
def select_action(self, t, greedy_action_func, action_value=None):
FILL_FUNC_BODY def __repr__(self):
return 'Greedy()'
|
44,658 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/functions/arctanh.py | 33,34 | 1,44 | arctanh | 43,44 | 34,44 | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... | return Arctanh().apply((x,))[0]
| """Elementwise inverse hyperbolic tangent function.
Args:
x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Arctanh().apply((x,))[0]
| 2 | 387 | 17 | 404 | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... | |
44,659 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/functions/arctanh.py | 19,20 | 7,33 | forward | Arctanh | 20,26 | 20,26 | class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argname'):
# typecheck._argname is introduced by Chainer v6
type_check._argname(in_types, ('x',))
x_type, =... | class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argname'):
# typecheck._argname is introduced by Chainer v6
type_check._argname(in_types, ('x',))
x_type, =... | self.retain_inputs((0,))
x, = inputs
xp = cuda.get_array_module(x)
y = xp.arctanh(x)
return utils.force_array(y, dtype=x.dtype),
| self.retain_inputs((0,))
x, = inputs
xp = cuda.get_array_module(x)
y = xp.arctanh(x)
return utils.force_array(y, dtype=x.dtype),
| 13 | 207 | 76 | 283 | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... | from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Arctanh(function_node.FunctionNode):
"""Elementwise inverse hyperbolic tangent function."""
def check_type_forward(self, in_types):
if hasattr(type_check, '_argnam... |
44,660 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/functions/scale_grad.py | 25,26 | 1,27 | scale_grad | 26,27 | 26,27 | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... | return ScaleGrad(scale=scale)(x)
| return ScaleGrad(scale=scale)(x)
| 2 | 170 | 14 | 184 | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... | |
44,661 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/functions/scale_grad.py | 21,22 | 7,25 | backward | ScaleGrad | 22,25 | 22,25 | class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(s... | class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(s... | return tuple(g * self.scale for g in gy)
| return tuple(g * self.scale for g in gy)
| 8 | 121 | 21 | 142 | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
... |
44,662 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/links/empirical_normalization.py | 51,52 | 5,110 | experience | EmpiricalNormalization | 53,81 | 52,81 | class EmpiricalNormalization(chainer.Link):
"""Normalize mean and variance of values based on emprical values.
Args:
shape (int or tuple of int): Shape of input values except batch axis.
batch_axis (int): Batch axis.
eps (float): Small value for stability.
dtype (dtype): Dtype o... | class EmpiricalNormalization(chainer.Link):
"""Normalize mean and variance of values based on emprical values.
Args:
shape (int or tuple of int): Shape of input values except batch axis.
batch_axis (int): Batch axis.
eps (float): Small value for stability.
dtype (dtype): Dtype o... |
if self.until is not None and self.count >= self.until:
return
if isinstance(x, chainer.Variable):
x = x.array
count_x = x.shape[self.batch_axis]
if count_x == 0:
return
xp = self.xp
self.count += count_x
rate = x.dtype.typ... | """Learn input values without computing the output values of them"""
if self.until is not None and self.count >= self.until:
return
if isinstance(x, chainer.Variable):
x = x.array
count_x = x.shape[self.batch_axis]
if count_x == 0:
return
... | 76 | 840 | 275 | 1,115 | import chainer
import numpy as np
class EmpiricalNormalization(chainer.Link):
"""Normalize mean and variance of values based on emprical values.
Args:
shape (int or tuple of int): Shape of input values except batch axis.
batch_axis (int): Batch axis.
eps (float): Small value for stabi... | import chainer
import numpy as np
class EmpiricalNormalization(chainer.Link):
"""Normalize mean and variance of values based on emprical values.
Args:
shape (int or tuple of int): Shape of input values except batch axis.
batch_axis (int): Batch axis.
eps (float): Small value for stabi... |
44,663 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/links/noisy_chain.py | 28,29 | 1,64 | _map_links | 29,60 | 29,60 | """Noisy Networks
See http://arxiv.org/abs/1706.10295
"""
import chainer
from chainer.links import Linear
from chainerrl.links.noisy_linear import FactorizedNoisyLinear
from chainerrl.links.sequence import Sequence
def to_factorized_noisy(link, *args, **kwargs):
"""Add noisiness to components of given link
... | """Noisy Networks
See http://arxiv.org/abs/1706.10295
"""
import chainer
from chainer.links import Linear
from chainerrl.links.noisy_linear import FactorizedNoisyLinear
from chainerrl.links.sequence import Sequence
def to_factorized_noisy(link, *args, **kwargs):
"""Add noisiness to components of given link
... | if isinstance(link, chainer.Chain):
children_names = link._children.copy()
for name in children_names:
child = getattr(link, name)
new_child = func(child)
if new_child is child:
_map_links(func, child)
else:
delattr(link... | if isinstance(link, chainer.Chain):
children_names = link._children.copy()
for name in children_names:
child = getattr(link, name)
new_child = func(child)
if new_child is child:
_map_links(func, child)
else:
delattr(link... | 86 | 282 | 349 | 631 | """Noisy Networks
See http://arxiv.org/abs/1706.10295
"""
import chainer
from chainer.links import Linear
from chainerrl.links.noisy_linear import FactorizedNoisyLinear
from chainerrl.links.sequence import Sequence
def to_factorized_noisy(link, *args, **kwargs):
"""Add noisiness to components of given link
... | """Noisy Networks
See http://arxiv.org/abs/1706.10295
"""
import chainer
from chainer.links import Linear
from chainerrl.links.noisy_linear import FactorizedNoisyLinear
from chainerrl.links.sequence import Sequence
def to_factorized_noisy(link, *args, **kwargs):
"""Add noisiness to components of given link
... | |
44,664 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/links/sequence.py | 9,10 | 1,42 | accept_variable_arguments | 10,17 | 10,17 | from inspect import Parameter
from inspect import signature
import chainer
from chainerrl.recurrent import RecurrentChainMixin
def accept_variable_arguments(func):
FILL_FUNC_BODYclass Sequence(chainer.ChainList, RecurrentChainMixin):
"""Sequential callable Link that consists of other Links."""
def __init__... | from inspect import Parameter
from inspect import signature
import chainer
from chainerrl.recurrent import RecurrentChainMixin
def accept_variable_arguments(func):
FILL_FUNC_BODYclass Sequence(chainer.ChainList, RecurrentChainMixin):
"""Sequential callable Link that consists of other Links."""
def __init__... | for param in signature(func).parameters.values():
if param.kind in (Parameter.VAR_POSITIONAL,
Parameter.VAR_KEYWORD):
return True
return False
| for param in signature(func).parameters.values():
if param.kind in (Parameter.VAR_POSITIONAL,
Parameter.VAR_KEYWORD):
return True
return False
| 13 | 325 | 56 | 381 | from inspect import Parameter
from inspect import signature
import chainer
from chainerrl.recurrent import RecurrentChainMixin
def accept_variable_arguments(func):
FILL_FUNC_BODYclass Sequence(chainer.ChainList, RecurrentChainMixin):
"""Sequential callable Link that consists of other Links."""
def __init__... | from inspect import Parameter
from inspect import signature
import chainer
from chainerrl.recurrent import RecurrentChainMixin
def accept_variable_arguments(func):
FILL_FUNC_BODYclass Sequence(chainer.ChainList, RecurrentChainMixin):
"""Sequential callable Link that consists of other Links."""
def __init__... | |
44,665 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/links/stateless_recurrent_branched.py | 18,19 | 7,33 | n_step_forward | StatelessRecurrentBranched | 19,33 | 19,33 | class StatelessRecurrentBranched(
StatelessRecurrentChainList, chainer.ChainList):
"""Stateless recurrent parallel link.
This is a recurrent analog to chainerrl.links.Branched. It bundles
multiple links that implements `StatelessRecurrent`.
Args:
*links: Child links. Each link should b... | class StatelessRecurrentBranched(
StatelessRecurrentChainList, chainer.ChainList):
"""Stateless recurrent parallel link.
This is a recurrent analog to chainerrl.links.Branched. It bundles
multiple links that implements `StatelessRecurrent`.
Args:
*links: Child links. Each link should b... | if recurrent_state is None:
n = len(self)
recurrent_state = [None] * n
child_ys, rs = tuple(zip(*[
call_recurrent_link(link, sequences, rs, output_mode)
for link, rs in zip(self, recurrent_state)]))
if output_mode == 'concat':
return ch... | if recurrent_state is None:
n = len(self)
recurrent_state = [None] * n
child_ys, rs = tuple(zip(*[
call_recurrent_link(link, sequences, rs, output_mode)
for link, rs in zip(self, recurrent_state)]))
if output_mode == 'concat':
return ch... | 55 | 131 | 187 | 318 | import chainer
from chainerrl.links.stateless_recurrent import call_recurrent_link
from chainerrl.links.stateless_recurrent import StatelessRecurrentChainList
class StatelessRecurrentBranched(
StatelessRecurrentChainList, chainer.ChainList):
"""Stateless recurrent parallel link.
This is a recurrent ... | import chainer
from chainerrl.links.stateless_recurrent import call_recurrent_link
from chainerrl.links.stateless_recurrent import StatelessRecurrentChainList
class StatelessRecurrentBranched(
StatelessRecurrentChainList, chainer.ChainList):
"""Stateless recurrent parallel link.
This is a recurrent ... |
44,666 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/links/stateless_recurrent_sequential.py | 28,29 | 12,82 | n_step_forward | StatelessRecurrentSequential | 29,67 | 29,67 | class StatelessRecurrentSequential(
StatelessRecurrentChainList, chainer.Sequential):
"""Sequential model that can contain stateless recurrent links.
This link a stateless recurrent analog to chainer.Sequential. It supports
the stateless recurrent interface by automatically detecting recurrent
... | class StatelessRecurrentSequential(
StatelessRecurrentChainList, chainer.Sequential):
"""Sequential model that can contain stateless recurrent links.
This link a stateless recurrent analog to chainer.Sequential. It supports
the stateless recurrent interface by automatically detecting recurrent
... | assert sequences
assert output_mode in ['split', 'concat']
if recurrent_state is None:
recurrent_state_queue = [None] * len(self.recurrent_children)
else:
assert len(recurrent_state) == len(self.recurrent_children)
recurrent_state_queue = list(reversed... | assert sequences
assert output_mode in ['split', 'concat']
if recurrent_state is None:
recurrent_state_queue = [None] * len(self.recurrent_children)
else:
assert len(recurrent_state) == len(self.recurrent_children)
recurrent_state_queue = list(reversed... | 129 | 330 | 495 | 825 | from cached_property import cached_property
import chainer
import numpy as np
from chainerrl.links.stateless_recurrent import call_recurrent_link
from chainerrl.links.stateless_recurrent import concatenate_sequences
from chainerrl.links.stateless_recurrent import is_recurrent_link
from chainerrl.links.stateless_recurr... | from cached_property import cached_property
import chainer
import numpy as np
from chainerrl.links.stateless_recurrent import call_recurrent_link
from chainerrl.links.stateless_recurrent import concatenate_sequences
from chainerrl.links.stateless_recurrent import is_recurrent_link
from chainerrl.links.stateless_recurr... |
44,667 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/ask_yes_no.py | 2,3 | 1,9 | ask_yes_no | 3,9 | 3,9 |
def ask_yes_no(question):
FILL_FUNC_BODY |
def ask_yes_no(question):
FILL_FUNC_BODY | while True:
choice = input("{} [y/N]: ".format(question)).lower()
if choice in ['y', 'ye', 'yes']:
return True
elif choice in ['n', 'no']:
return False
| while True:
choice = input("{} [y/N]: ".format(question)).lower()
if choice in ['y', 'ye', 'yes']:
return True
elif choice in ['n', 'no']:
return False
| 22 | 21 | 65 | 86 |
def ask_yes_no(question):
FILL_FUNC_BODY |
def ask_yes_no(question):
FILL_FUNC_BODY | |
44,669 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/collections.py | 86,87 | 6,103 | extend | RandomAccessQueue | 87,90 | 87,90 | class RandomAccessQueue(object):
"""FIFO queue with fast indexing
Operations getitem, setitem, append, popleft, and len
are amortized O(1)-time, if this data structure is used ephemerally.
"""
def __init__(self, *args, **kwargs):
self.maxlen = kwargs.pop('maxlen', None)
assert self... | class RandomAccessQueue(object):
"""FIFO queue with fast indexing
Operations getitem, setitem, append, popleft, and len
are amortized O(1)-time, if this data structure is used ephemerally.
"""
def __init__(self, *args, **kwargs):
self.maxlen = kwargs.pop('maxlen', None)
assert self... | self._queue_back.extend(xs)
self._apply_maxlen()
| self._queue_back.extend(xs)
self._apply_maxlen()
| 2 | 877 | 25 | 902 | import itertools
from chainerrl.misc.random import sample_n_k
class RandomAccessQueue(object):
"""FIFO queue with fast indexing
Operations getitem, setitem, append, popleft, and len
are amortized O(1)-time, if this data structure is used ephemerally.
"""
def __init__(self, *args, **kwargs):
... | import itertools
from chainerrl.misc.random import sample_n_k
class RandomAccessQueue(object):
"""FIFO queue with fast indexing
Operations getitem, setitem, append, popleft, and len
are amortized O(1)-time, if this data structure is used ephemerally.
"""
def __init__(self, *args, **kwargs):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.