uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb0f43454ce5e9f453bae97e | train | function | def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
"""
Draw histogram of the DataFrame's series using matplotlib / pylab.
Parameters
... | def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False,
sharey=False, figsize=None, layout=None, bins=10, **kwds):
| """
Draw histogram of the DataFrame's series using matplotlib / pylab.
Parameters
----------
data : DataFrame
column : string or sequence
If passed, will be used to limit data to a subset of columns
by : object, optional
If passed, then used to form histograms for separate g... | .rcParams['patch.facecolor'])
def plot_group(group, ax):
xvals = group[x].values
yvals = group[y].values
ax.scatter(xvals, yvals, **kwargs)
ax.grid(grid)
if by is not None:
fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax)
else:
if ax is N... | 211 | 211 | 706 | 57 | 153 | springcoil/pandas | pandas/tools/plotting.py | Python | hist_frame | hist_frame | 2,718 | 2,788 | 2,718 | 2,720 | f82fbf7f0584e8a78528a0d15f133584a6455b97 | bigcode/the-stack | train |
a1319fb140b313f2acedff6d | train | function | def _get_all_lines(ax):
lines = ax.get_lines()
if hasattr(ax, 'right_ax'):
lines += ax.right_ax.get_lines()
if hasattr(ax, 'left_ax'):
lines += ax.left_ax.get_lines()
return lines
| def _get_all_lines(ax):
| lines = ax.get_lines()
if hasattr(ax, 'right_ax'):
lines += ax.right_ax.get_lines()
if hasattr(ax, 'left_ax'):
lines += ax.left_ax.get_lines()
return lines
| _remove_ylables_from_axis(ax)
def _flatten(axes):
if not com.is_list_like(axes):
return np.array([axes])
elif isinstance(axes, (np.ndarray, Index)):
return axes.ravel()
return np.array(axes)
def _get_all_lines(ax):
| 64 | 64 | 54 | 7 | 57 | springcoil/pandas | pandas/tools/plotting.py | Python | _get_all_lines | _get_all_lines | 3,364 | 3,373 | 3,364 | 3,364 | 4b68fdb1dd9cdc31e7d9f35dc71b3f3fe3bd211d | bigcode/the-stack | train |
17276c72e0c566eb9659d43a | train | function | def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
rot=0, grid=True, ax=None, figsize=None,
layout=None, **kwds):
"""
Make box plots from DataFrameGroupBy data.
Parameters
----------
grouped : Grouped DataFrame
subpl... | def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None,
rot=0, grid=True, ax=None, figsize=None,
layout=None, **kwds):
| """
Make box plots from DataFrameGroupBy data.
Parameters
----------
grouped : Grouped DataFrame
subplots :
* ``False`` - no subplots will be used
* ``True`` - create a subplot for each group
column : column name or list of names, or vector
Can be any valid input to ... | plotlib Axes
"""
def plot_group(group, ax):
ax.hist(group.dropna().values, bins=bins, **kwargs)
xrot = xrot or rot
fig, axes = _grouped_plot(plot_group, data, column=column,
by=by, sharex=sharex, sharey=sharey, ax=ax,
figsize=figsize,... | 210 | 210 | 700 | 41 | 168 | springcoil/pandas | pandas/tools/plotting.py | Python | boxplot_frame_groupby | boxplot_frame_groupby | 2,907 | 2,979 | 2,907 | 2,909 | f2dca0d98efebe20ea88f01eb364d95e133a935f | bigcode/the-stack | train |
6301b27702e4bb1119a1bf77 | train | function | def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds):
"""
Draw histogram of the input series using matplotlib
Parameters
----------
by : object, optional
If passed, then used to form histogr... | def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None,
xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds):
| """
Draw histogram of the input series using matplotlib
Parameters
----------
by : object, optional
If passed, then used to form histograms for separate groups
ax : matplotlib axis object
If not passed, uses gca()
grid : boolean, default True
Whether to show axis gri... | ax=ax, squeeze=False,
sharex=sharex, sharey=sharey, figsize=figsize,
layout=layout)
_axes = _flatten(axes)
for i, col in enumerate(com._try_sort(data.columns)):
ax = _axes[i]
ax.hist(data[col].dropna().values, bins=bins, **kwds)
ax.se... | 184 | 184 | 616 | 42 | 141 | springcoil/pandas | pandas/tools/plotting.py | Python | hist_series | hist_series | 2,791 | 2,861 | 2,791 | 2,792 | 2d403983d53c46650a45ad25cc588fff75331ee4 | bigcode/the-stack | train |
00e665c971b37339e09a29ee | train | function | def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
color=None):
import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, compat.string_types):
import matplotlib.cm as cm
cmap = colorma... | def _get_standard_colors(num_colors=None, colormap=None, color_type='default',
color=None):
| import matplotlib.pyplot as plt
if color is None and colormap is not None:
if isinstance(colormap, compat.string_types):
import matplotlib.cm as cm
cmap = colormap
colormap = cm.get_cmap(colormap)
if colormap is None:
raise ValueError("Col... | 'xtick.direction': 'in',
'xtick.major.pad': 6.0,
'xtick.major.size': 0.0,
'xtick.minor.pad': 6.0,
'xtick.minor.size': 0.0,
'ytick.color': '#555555',
'ytick.direction': 'in',
'ytick.major.pad': 6.0,
'ytick.major.size': 0.0,
'ytick.minor.pad': 6.0,
'ytick.minor.size'... | 173 | 173 | 577 | 22 | 151 | springcoil/pandas | pandas/tools/plotting.py | Python | _get_standard_colors | _get_standard_colors | 102 | 170 | 102 | 103 | 86e45bca45b0deb6ff8c8b9ce7fd3554274b98d7 | bigcode/the-stack | train |
d5a29d27676f091e15a81cd8 | train | function | def _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey):
if nplots > 1:
# first find out the ax layout, so that we can correctly handle 'gaps"
layout = np.zeros((nrows+1,ncols+1), dtype=np.bool)
for ax in axarr:
layout[ax.rowNum, ax.colNum] = ax.get_visible()... | def _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey):
| if nplots > 1:
# first find out the ax layout, so that we can correctly handle 'gaps"
layout = np.zeros((nrows+1,ncols+1), dtype=np.bool)
for ax in axarr:
layout[ax.rowNum, ax.colNum] = ax.get_visible()
if sharex and nrows > 1:
for ax in axarr:
... | axis.set_minor_formatter(ticker.FormatStrFormatter(''))
for label in ax.get_yticklabels(minor=True):
label.set_visible(False)
except Exception: # pragma no cover
pass
ax.yaxis.get_label().set_visible(False)
def _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)... | 80 | 80 | 267 | 26 | 54 | springcoil/pandas | pandas/tools/plotting.py | Python | _handle_shared_axes | _handle_shared_axes | 3,329 | 3,352 | 3,329 | 3,329 | 1380525374c24fb6762a4b572fc528d1a33742eb | bigcode/the-stack | train |
c8c2a084d8c7026f31371d29 | train | function | def _gca():
import matplotlib.pyplot as plt
return plt.gca()
| def _gca():
| import matplotlib.pyplot as plt
return plt.gca()
| are int
locs = locs.astype(int)
axes[0][0].yaxis.set_ticklabels(locs)
_set_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0)
return axes
def _gca():
| 64 | 64 | 18 | 5 | 58 | springcoil/pandas | pandas/tools/plotting.py | Python | _gca | _gca | 361 | 363 | 361 | 361 | ab814a3ee7afd58e0cd24e00f1d1dc69439a73d9 | bigcode/the-stack | train |
1369d55b58b198d787e3f238 | train | class | class ScatterPlot(MPLPlot):
_kind = 'scatter'
_layout_type = 'single'
def __init__(self, data, x, y, c=None, **kwargs):
MPLPlot.__init__(self, data, **kwargs)
if x is None or y is None:
raise ValueError( 'scatter requires and x and y column')
if com.is_integer(x) and not... | class ScatterPlot(MPLPlot):
| _kind = 'scatter'
_layout_type = 'single'
def __init__(self, data, x, y, c=None, **kwargs):
MPLPlot.__init__(self, data, **kwargs)
if x is None or y is None:
raise ValueError( 'scatter requires and x and y column')
if com.is_integer(x) and not self.data.columns.holds_int... | :
err = self.errors[kw]
# user provided label-matched dataframe of errors
if isinstance(err, (DataFrame, dict)):
if label is not None and label in err.keys():
err = err[label]
else:
er... | 206 | 206 | 688 | 7 | 199 | springcoil/pandas | pandas/tools/plotting.py | Python | ScatterPlot | ScatterPlot | 1,422 | 1,498 | 1,422 | 1,422 | 0a5ff50f652e31788c98e9361ce5c09bd806345b | bigcode/the-stack | train |
a3d3a712021c40b683331858 | train | class | class PiePlot(MPLPlot):
_kind = 'pie'
_layout_type = 'horizontal'
def __init__(self, data, kind=None, **kwargs):
data = data.fillna(value=0)
if (data < 0).any().any():
raise ValueError("{0} doesn't allow negative values".format(kind))
MPLPlot.__init__(self, data, kind=ki... | class PiePlot(MPLPlot):
| _kind = 'pie'
_layout_type = 'horizontal'
def __init__(self, data, kind=None, **kwargs):
data = data.fillna(value=0)
if (data < 0).any().any():
raise ValueError("{0} doesn't allow negative values".format(kind))
MPLPlot.__init__(self, data, kind=kind, **kwargs)
def _... | None:
msg = ('bw_method was added in Scipy 0.11.0.' +
' Scipy version in use is %s.' % spv)
warnings.warn(msg)
y = gkde.evaluate(ind)
lines = MPLPlot._plot(ax, ind, y, style=style, **kwds)
return lines
def _make_plot_keywords(self, kw... | 148 | 148 | 495 | 7 | 141 | springcoil/pandas | pandas/tools/plotting.py | Python | PiePlot | PiePlot | 2,046 | 2,108 | 2,046 | 2,046 | 9191d7eaf03a89f7d5028ab71fe1124580a2d2d5 | bigcode/the-stack | train |
48ac17db8d33e0bf66d67619 | train | class | class HistPlot(LinePlot):
_kind = 'hist'
def __init__(self, data, bins=10, bottom=0, **kwargs):
self.bins = bins # use mpl default
self.bottom = bottom
# Do not call LinePlot.__init__ which may fill nan
MPLPlot.__init__(self, data, **kwargs)
def _args_adjust(self):
... | class HistPlot(LinePlot):
| _kind = 'hist'
def __init__(self, data, bins=10, bottom=0, **kwargs):
self.bins = bins # use mpl default
self.bottom = bottom
# Do not call LinePlot.__init__ which may fill nan
MPLPlot.__init__(self, data, **kwargs)
def _args_adjust(self):
if com.is_integer(s... | )
ax.set_xticklabels(ticklabels)
if name is not None and self.use_index:
ax.set_xlabel(name)
class BarhPlot(BarPlot):
_kind = 'barh'
_default_rot = 0
orientation = 'horizontal'
@property
def _start_base(self):
return self.left
@classmethod
def _plot(cl... | 201 | 201 | 673 | 6 | 195 | springcoil/pandas | pandas/tools/plotting.py | Python | HistPlot | HistPlot | 1,912 | 1,991 | 1,912 | 1,912 | a5c36d40c5d42beee6a4d245c0c11d78ff458551 | bigcode/the-stack | train |
0873eed1e0a56d8f27860c9e | train | class | class BoxPlot(LinePlot):
_kind = 'box'
_layout_type = 'horizontal'
_valid_return_types = (None, 'axes', 'dict', 'both')
# namedtuple to hold results
BP = namedtuple("Boxplot", ['ax', 'lines'])
def __init__(self, data, return_type=None, **kwargs):
# Do not call LinePlot.__init__ which m... | class BoxPlot(LinePlot):
| _kind = 'box'
_layout_type = 'horizontal'
_valid_return_types = (None, 'axes', 'dict', 'both')
# namedtuple to hold results
BP = namedtuple("Boxplot", ['ax', 'lines'])
def __init__(self, data, return_type=None, **kwargs):
# Do not call LinePlot.__init__ which may fill nan
if re... | return ''
else:
return label
idx = [com.pprint_thing(v) for v in self.data.index]
labels = kwds.pop('labels', idx)
# labels is used for each wedge's labels
# Blank out labels for values of 0 so they don't overlap
... | 256 | 256 | 1,277 | 6 | 250 | springcoil/pandas | pandas/tools/plotting.py | Python | BoxPlot | BoxPlot | 2,111 | 2,260 | 2,111 | 2,111 | fe52aa151d79ac33e9386388aca8d8dd77e086ab | bigcode/the-stack | train |
f9f89171806a439b6b562203 | train | function | def _get_standard_kind(kind):
return {'density': 'kde'}.get(kind, kind)
| def _get_standard_kind(kind):
| return {'density': 'kde'}.get(kind, kind)
| ick.direction': 'in',
'ytick.major.pad': 6.0,
'ytick.major.size': 0.0,
'ytick.minor.pad': 6.0,
'ytick.minor.size': 0.0
}
def _get_standard_kind(kind):
| 64 | 64 | 22 | 7 | 57 | springcoil/pandas | pandas/tools/plotting.py | Python | _get_standard_kind | _get_standard_kind | 99 | 100 | 99 | 99 | fe497661d4e427771a970128130fbe010ba4e386 | bigcode/the-stack | train |
4a5683e9568ebc36a4f90d21 | train | class | class BarPlot(MPLPlot):
_kind = 'bar'
_default_rot = 90
orientation = 'vertical'
def __init__(self, data, **kwargs):
self.bar_width = kwargs.pop('width', 0.5)
pos = kwargs.pop('position', 0.5)
kwargs.setdefault('align', 'center')
self.tick_pos = np.arange(len(data))
... | class BarPlot(MPLPlot):
| _kind = 'bar'
_default_rot = 90
orientation = 'vertical'
def __init__(self, data, **kwargs):
self.bar_width = kwargs.pop('width', 0.5)
pos = kwargs.pop('position', 0.5)
kwargs.setdefault('align', 'center')
self.tick_pos = np.arange(len(data))
self.bottom = kwarg... | ]
else:
start = np.zeros(len(y))
if not 'color' in kwds:
kwds['color'] = lines[0].get_color()
ax.fill_between(xdata, start, y_values, **kwds)
cls._update_stacker(ax, stacking_id, y)
return lines
def _add_legend_handle(self, handle, label, index=None... | 256 | 256 | 1,060 | 7 | 249 | springcoil/pandas | pandas/tools/plotting.py | Python | BarPlot | BarPlot | 1,773 | 1,887 | 1,773 | 1,773 | c95db29396f2dc53489e7e884a156840d8bd7c95 | bigcode/the-stack | train |
021ac68eb5dd1f400175f5fd | train | function | def autocorrelation_plot(series, ax=None, **kwds):
"""Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
kwds : keywords
Options to pass to matplotlib plotting method
Returns:
-----------
ax: Matplotlib axi... | def autocorrelation_plot(series, ax=None, **kwds):
| """Autocorrelation plot for time series.
Parameters:
-----------
series: Time series
ax: Matplotlib axis object, optional
kwds : keywords
Options to pass to matplotlib plotting method
Returns:
-----------
ax: Matplotlib axis object
"""
import matplotlib.pyplot as pl... | ` is hardcoded in matplotlibs scatter method
kwds.setdefault('c', plt.rcParams['patch.facecolor'])
data = series.values
y1 = data[:-lag]
y2 = data[lag:]
if ax is None:
ax = plt.gca()
ax.set_xlabel("y(t)")
ax.set_ylabel("y(t + %s)" % lag)
ax.scatter(y1, y2, **kwds)
return ax
... | 112 | 112 | 375 | 13 | 98 | springcoil/pandas | pandas/tools/plotting.py | Python | autocorrelation_plot | autocorrelation_plot | 726 | 765 | 726 | 726 | f8366890cc07bdf6450b42d645b0cc4e33267296 | bigcode/the-stack | train |
43beba1a3aa67265f7f6a1ee | train | class | class vector3:
def __init__(self, a=0, b=0, c=0):
self.x = a
self.y = b
self.z = c
def __add__(self, other):
return vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __radd__(self, other):
return vector3(self.x + other.x, self.y + other.y, self.z + ... | class vector3:
| def __init__(self, a=0, b=0, c=0):
self.x = a
self.y = b
self.z = c
def __add__(self, other):
return vector3(self.x + other.x, self.y + other.y, self.z + other.z)
def __radd__(self, other):
return vector3(self.x + other.x, self.y + other.y, self.z + other.z)
de... | class vector3:
| 4 | 111 | 373 | 4 | 0 | kimomi/FromPaper | MarchingCubes/vector3.py | Python | vector3 | vector3 | 1 | 42 | 1 | 2 | 412026036b9ac4f5a94481ec0148a067337007c0 | bigcode/the-stack | train |
a4a290f8b118fb50844e6d3c | train | function | def bandcamp_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
html = get_html(url)
trackinfo = json.loads(r1(r'(\[{"video_poster_url".*}\]),', html))
for track in trackinfo:
track_num = track['track_num']
title = '%s. %s' % (track_num, track['title'])
file_url = ... | def bandcamp_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
| html = get_html(url)
trackinfo = json.loads(r1(r'(\[{"video_poster_url".*}\]),', html))
for track in trackinfo:
track_num = track['track_num']
title = '%s. %s' % (track_num, track['title'])
file_url = 'http:' + track['file']['mp3-128']
mime, ext, size = url_info(file_url)
... | #!/usr/bin/env python
__all__ = ['bandcamp_download']
from ..common import *
def bandcamp_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
| 40 | 64 | 152 | 20 | 20 | helloqingfeng/you-get | src/you_get/extractors/bandcamp.py | Python | bandcamp_download | bandcamp_download | 7 | 18 | 7 | 7 | 1eb6e0422af8e0e4454fec464fd225f3a861ecf1 | bigcode/the-stack | train |
2902325e6ff650707095b608 | train | class | class TestTree(unittest.TestCase):
def setUp(self):
self.species = TreeSpecies("birch", 0.1, 10, 3, 0.8, 79, 2)
def test_create(self):
t = Tree(self.species, 100, 200)
self.assertEqual(self.species, t.species)
self.assertEqual(3, t.size)
self.assertEqual(100, t.x)
... | class TestTree(unittest.TestCase):
| def setUp(self):
self.species = TreeSpecies("birch", 0.1, 10, 3, 0.8, 79, 2)
def test_create(self):
t = Tree(self.species, 100, 200)
self.assertEqual(self.species, t.species)
self.assertEqual(3, t.size)
self.assertEqual(100, t.x)
self.assertEqual(200, t.y)
... | import math
import unittest
from forest.treespecies import TreeSpecies
from forest.tree import Tree
class TestTree(unittest.TestCase):
| 28 | 256 | 935 | 7 | 20 | DaveTCode/ProceduralForest | tests/TestTree.py | Python | TestTree | TestTree | 7 | 108 | 7 | 8 | d2096d6b45972b697ec8b434ba31d6a2a2f716a4 | bigcode/the-stack | train |
cb989adc9b12676122a5936a | train | function | def init_dal():
pass
| def init_dal():
| pass
| init_mail(app, conf['mail'])
init_teardown(app)
def init_cliapp(app, conf):
app.commands.update(load_handlers(app, 'Command', path=os.path.join(module_path, 'commands')))
def init_wsapp(app, conf):
init_ws(app, conf)
def init_dal():
| 64 | 64 | 8 | 5 | 59 | oboforty/Clarinet-site | emeapp/modules/eme_utils/__module__.py | Python | init_dal | init_dal | 30 | 31 | 30 | 30 | e35ce0898f9afe83b6bc7b31286e7f2769fd71dd | bigcode/the-stack | train |
def455b488223a7309815827 | train | function | def init_wsapp(app, conf):
init_ws(app, conf)
| def init_wsapp(app, conf):
| init_ws(app, conf)
| conf):
init_jinja(app, webconf)
init_mail(app, conf['mail'])
init_teardown(app)
def init_cliapp(app, conf):
app.commands.update(load_handlers(app, 'Command', path=os.path.join(module_path, 'commands')))
def init_wsapp(app, conf):
| 63 | 64 | 15 | 8 | 55 | oboforty/Clarinet-site | emeapp/modules/eme_utils/__module__.py | Python | init_wsapp | init_wsapp | 26 | 27 | 26 | 26 | d207671487b2102c1328923dd96dbaddb21e5557 | bigcode/the-stack | train |
aa8a164c44c011e513ed3bd5 | train | function | def init_cliapp(app, conf):
app.commands.update(load_handlers(app, 'Command', path=os.path.join(module_path, 'commands')))
| def init_cliapp(app, conf):
| app.commands.update(load_handlers(app, 'Command', path=os.path.join(module_path, 'commands')))
| (__file__))
conf = load_settings(os.path.join(module_path, 'config.ini'))
sys.path.append(module_path)
def init_webapp(app, webconf):
init_jinja(app, webconf)
init_mail(app, conf['mail'])
init_teardown(app)
def init_cliapp(app, conf):
| 64 | 64 | 29 | 8 | 56 | oboforty/Clarinet-site | emeapp/modules/eme_utils/__module__.py | Python | init_cliapp | init_cliapp | 22 | 23 | 22 | 22 | 26952020c2731ea7f5d65a652d78c46243881ee1 | bigcode/the-stack | train |
04b18e1cf0b81e46ab7fc28f | train | function | def init_webapp(app, webconf):
init_jinja(app, webconf)
init_mail(app, conf['mail'])
init_teardown(app)
| def init_webapp(app, webconf):
| init_jinja(app, webconf)
init_mail(app, conf['mail'])
init_teardown(app)
| init_jinja
from .services.mail import init_mail
from .services.teardown import init_teardown
module_path = os.path.dirname(os.path.realpath(__file__))
conf = load_settings(os.path.join(module_path, 'config.ini'))
sys.path.append(module_path)
def init_webapp(app, webconf):
| 64 | 64 | 33 | 9 | 55 | oboforty/Clarinet-site | emeapp/modules/eme_utils/__module__.py | Python | init_webapp | init_webapp | 16 | 19 | 16 | 16 | 847d8452cb521f64aa9bcdd1c3023f7980e7e582 | bigcode/the-stack | train |
63f0175c79bcc7aa9ad46d82 | train | function | def init_migration():
pass
| def init_migration():
| pass
| init_teardown(app)
def init_cliapp(app, conf):
app.commands.update(load_handlers(app, 'Command', path=os.path.join(module_path, 'commands')))
def init_wsapp(app, conf):
init_ws(app, conf)
def init_dal():
pass
def init_migration():
| 64 | 64 | 8 | 5 | 58 | oboforty/Clarinet-site | emeapp/modules/eme_utils/__module__.py | Python | init_migration | init_migration | 34 | 35 | 34 | 34 | 7fc2038105f82de7c17b1345564413c736821eb8 | bigcode/the-stack | train |
f4ac7726f159825b2bfc3e3e | train | function | def to_py(obj):
if hasattr(obj, 'toPyObject'):
return obj.toPyObject()
return obj
| def to_py(obj):
| if hasattr(obj, 'toPyObject'):
return obj.toPyObject()
return obj
| 5.QtNetwork import QNetworkRequest
except ImportError:
from PyQt4.QtCore import QObject
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtWebKit import QWebElement
from PyQt4.QtNetwork import QNetworkRequest
def to_py(obj):
| 64 | 64 | 26 | 5 | 58 | rmcwilliams2004/PAscrape | slyd/slyd/splash/qtutils.py | Python | to_py | to_py | 13 | 16 | 13 | 13 | 8a07829eaa74cc6e34fc1757e4a1b7ad996c0334 | bigcode/the-stack | train |
59e7ff070ab87211a09b6926 | train | class | class Agent():
def __init__(self, id, t, sex, θ, B, rule):
self.id = id
self.birth = t
self.sex = sex
self.θ = θ
self.b = B
self.observed_ρ = 1
self.true_ρ = 1
self.rule = rule
self.matches = 0
self.rs_given = 0 # ids of agents that we... | class Agent():
| def __init__(self, id, t, sex, θ, B, rule):
self.id = id
self.birth = t
self.sex = sex
self.θ = θ
self.b = B
self.observed_ρ = 1
self.true_ρ = 1
self.rule = rule
self.matches = 0
self.rs_given = 0 # ids of agents that were given rs
... | import numpy as np
from scipy.stats import cumfreq, beta, bernoulli
import random
class Agent():
| 24 | 117 | 391 | 3 | 20 | patohdzs/project-tinder | code/abm/utils.py | Python | Agent | Agent | 6 | 50 | 6 | 6 | 3b198a2d5c57a128b17bb47f118b744c46dbc18d | bigcode/the-stack | train |
9e92c1107485d0ea80f52c36 | train | function | def simulate_game(T, μ_star, ω_star, exog_params, batch=0, matches='random'):
Bm, Bw, bm_vals, bw_vals, δ, um, uw, Fm, Fw, λm, λw = exog_params
simulation = []
men = []
women = []
for t in range(0,T):
# Add new agents
for i, θ in enumerate(Fm.rvs(size=λm)):
men.app... | def simulate_game(T, μ_star, ω_star, exog_params, batch=0, matches='random'):
| Bm, Bw, bm_vals, bw_vals, δ, um, uw, Fm, Fw, λm, λw = exog_params
simulation = []
men = []
women = []
for t in range(0,T):
# Add new agents
for i, θ in enumerate(Fm.rvs(size=λm)):
men.append(Agent(t*λm + i, t, 'Male', θ, Bm, μ_star))
for i, θ in en... | return {'batch' : batch,
'id' : self.id,
'time' : t,
'birth' : self.birth,
'sex' : self.sex,
'attractiveness' : self.θ,
'budget' : self.b,
'observed_rate' : self.observed_ρ,
'true... | 141 | 143 | 479 | 23 | 118 | patohdzs/project-tinder | code/abm/utils.py | Python | simulate_game | simulate_game | 53 | 96 | 53 | 53 | f961bb44056c47d2a072baa51c46ddc5fec0b416 | bigcode/the-stack | train |
213691890b4d2fc135c163ef | train | class | class Scheme:
__slots__ = ('name', )
slashed = False # Do NOT include // separator between scheme and remainder.
def __init__(self, name:Stringy):
self.name = str(name).strip().lower()
def __eq__(self, other:'SchemeLike'):
if isinstance(other, str):
return self.name == other
if isinstance(other, ... | class Scheme:
| __slots__ = ('name', )
slashed = False # Do NOT include // separator between scheme and remainder.
def __init__(self, name:Stringy):
self.name = str(name).strip().lower()
def __eq__(self, other:'SchemeLike'):
if isinstance(other, str):
return self.name == other
if isinstance(other, self.__class__... | from .typing import Union, Stringy
class Scheme:
| 12 | 64 | 179 | 3 | 8 | amcgregor/uri | uri/scheme.py | Python | Scheme | Scheme | 4 | 32 | 4 | 4 | 4390ade15b4fcd39c2a4056a9db2cc42f47dc604 | bigcode/the-stack | train |
32fa1c95a995b09a89d033ee | train | class | class URLScheme(Scheme):
__slots__ = ()
slashed = True # DO include // separator between scheme and remainder.
def is_relative(self, uri) -> bool:
return not uri._host or not uri._path.is_absolute()
| class URLScheme(Scheme):
| __slots__ = ()
slashed = True # DO include // separator between scheme and remainder.
def is_relative(self, uri) -> bool:
return not uri._host or not uri._path.is_absolute()
| -> bool:
return not (self == other)
def __bytes__(self) -> bytes:
return self.name.encode('ascii')
def __str__(self) -> str:
return self.name
def is_relative(self, uri) -> bool:
return False
class URLScheme(Scheme):
| 64 | 64 | 54 | 6 | 57 | amcgregor/uri | uri/scheme.py | Python | URLScheme | URLScheme | 35 | 41 | 35 | 35 | 51317ee00dae006ca7afb6371f649990976d1d1d | bigcode/the-stack | train |
0472c27520ee383e600ab59f | train | class | class MpParser(BaseParser):
""""""
root = mp_phrase
def interpret(self, result, start, end):
compound = Compound(
melting_points=[
MeltingPoint(
value=first(result.xpath('./mp/value/text()')),
units=first(result.xpath('./mp/units/t... | class MpParser(BaseParser):
| """"""
root = mp_phrase
def interpret(self, result, start, end):
compound = Compound(
melting_points=[
MeltingPoint(
value=first(result.xpath('./mp/value/text()')),
units=first(result.xpath('./mp/units/text()'))
)
... | orded') | I('obtained') | I('yielded')).hide() + ZeroOrMore(Not(mp) + Not(cem) + Any()).hide() + mp)('mp_phrase')
mp_phrase = cem_mp_phrase | to_give_mp_phrase | obtained_mp_phrase
class MpParser(BaseParser):
| 64 | 64 | 118 | 6 | 57 | MB9991/test_demo- | chemdataextractor_batteries/chemdataextractor/parse/mp.py | Python | MpParser | MpParser | 53 | 70 | 53 | 53 | 1184ea698526d3904fd2976efa9d780e78e33f0e | bigcode/the-stack | train |
470b6f6b4ffe45cba4bb45af | train | function | def send_performance(name, response_time, allowed):
"""Sends Performance data to Pushbullet API
Args:
name (string): The name of the endpoint that the alert is raised for
response_time (float): The average response time for the alert
allowed (float): The allowed response time for the se... | def send_performance(name, response_time, allowed):
| """Sends Performance data to Pushbullet API
Args:
name (string): The name of the endpoint that the alert is raised for
response_time (float): The average response time for the alert
allowed (float): The allowed response time for the service
"""
url = 'https://api.pushbullet.com/... | message via contact form",
"device_iden": DEVID,
"type": "note"}
headers = {'Access-Token': PBKEY, 'content-type': 'application/json'}
requests.post(url, data=json.dumps(content), headers=headers)
def send_performance(name, response_time, allowed):
| 64 | 64 | 180 | 11 | 53 | anant-j/API-Toolkit | pushbullet_handler.py | Python | send_performance | send_performance | 44 | 59 | 44 | 44 | b0b99dc445cee70fe2386698b2b4bdf68b37356d | bigcode/the-stack | train |
1525fb0074df1a0c72700697 | train | function | def send_form(formData):
"""Sends Form data to Pushbullet API
Args:
formData (dict): Hashmap containing form data
"""
url = 'https://api.pushbullet.com/v2/pushes'
content = {
"body": f'Name: {formData["name"]} \nEmail: {formData["email"]} \nAbout: {formData["about"]} \nMessage: {fo... | def send_form(formData):
| """Sends Form data to Pushbullet API
Args:
formData (dict): Hashmap containing form data
"""
url = 'https://api.pushbullet.com/v2/pushes'
content = {
"body": f'Name: {formData["name"]} \nEmail: {formData["email"]} \nAbout: {formData["about"]} \nMessage: {formData["message"]}',
... | visited your Website @ {req["Page"]}',
"device_iden": DEVID,
"type": "note"}
headers = {'Access-Token': PBKEY, 'content-type': 'application/json'}
requests.post(url, data=json.dumps(content), headers=headers)
def send_form(formData):
| 64 | 64 | 165 | 6 | 58 | anant-j/API-Toolkit | pushbullet_handler.py | Python | send_form | send_form | 28 | 41 | 28 | 28 | e7d5a163f6cc4e12e6f03035fa3e3478ccc8a7de | bigcode/the-stack | train |
c9eb845c2b2da67adcf67a0c | train | function | def send_analytics(req, fingerprint):
"""Sends analytics data to Pushbullet API
Args:
req (dict): Hashmap containing request information
"""
url = 'https://api.pushbullet.com/v2/pushes'
content = {
"body": f'Carrier: {req["org"]} \nOS: {req["Operating System"]} \nBrowser: {req["Brow... | def send_analytics(req, fingerprint):
| """Sends analytics data to Pushbullet API
Args:
req (dict): Hashmap containing request information
"""
url = 'https://api.pushbullet.com/v2/pushes'
content = {
"body": f'Carrier: {req["org"]} \nOS: {req["Operating System"]} \nBrowser: {req["Browser"]} \nDate-Time: {req["Date & Time"... | .path.dirname(os.path.abspath(__file__))
with open(f'{my_directory}/secrets/keys.json') as f:
api_keys = json.load(f)
PBKEY = api_keys["Pushbullet"]["Key"]
DEVID = api_keys["Pushbullet"]["DeviceID"]
def send_analytics(req, fingerprint):
| 63 | 64 | 201 | 8 | 55 | anant-j/API-Toolkit | pushbullet_handler.py | Python | send_analytics | send_analytics | 12 | 25 | 12 | 12 | a8d365ee442fc14a8c0a5d8d2e09725dedbbe3a5 | bigcode/the-stack | train |
f0830403dfdd935a13b7bd3b | train | function | def delete():
"""Deletes all notifications via Pushbullet API"""
url = "https://api.pushbullet.com/v2/pushes"
headers = {'Access-Token': PBKEY}
requests.delete(url, headers=headers)
| def delete():
| """Deletes all notifications via Pushbullet API"""
url = "https://api.pushbullet.com/v2/pushes"
headers = {'Access-Token': PBKEY}
requests.delete(url, headers=headers)
| is : {allowed}',
"title": "Performance Alert",
"device_iden": DEVID,
"type": "note"}
headers = {'Access-Token': PBKEY, 'content-type': 'application/json'}
requests.post(url, data=json.dumps(content), headers=headers)
def delete():
| 64 | 64 | 48 | 3 | 61 | anant-j/API-Toolkit | pushbullet_handler.py | Python | delete | delete | 62 | 66 | 62 | 62 | 4bdc03757514ba5b02cb8b7b5692dc0c0f930acc | bigcode/the-stack | train |
f1f8093e55ef358dd271b37c | train | function | def main():
s = Simulator(mode="gui", image_width=512, image_height=512, device_idx=0)
scene = InteractiveIndoorScene(
"Rs_int",
texture_randomization=False,
object_randomization=False,
load_object_categories=["chair"],
load_room_types=["living_room"],
)
s.import_... | def main():
| s = Simulator(mode="gui", image_width=512, image_height=512, device_idx=0)
scene = InteractiveIndoorScene(
"Rs_int",
texture_randomization=False,
object_randomization=False,
load_object_categories=["chair"],
load_room_types=["living_room"],
)
s.import_ig_scene(sce... | from igibson.scenes.igibson_indoor_scene import InteractiveIndoorScene
from igibson.simulator import Simulator
def main():
| 30 | 64 | 92 | 3 | 26 | suresh-guttikonda/iGibson | igibson/examples/demo/scene_interactive_partial_loading_example.py | Python | main | main | 5 | 18 | 5 | 5 | f1431815f25e0a17f8bf730070293a27ccdd178d | bigcode/the-stack | train |
f153220ff51fa73a67f5636b | train | function | @contextlib.contextmanager
def tempfile_from_dftrack(track, suffix):
"""
Saves pandas.DataFrame track table to a temporary tab-separated ASCII text
file with a unique name (to prevent clashes when running x2sys_cross),
adding a suffix extension to the end.
Parameters
----------
track : pand... | @contextlib.contextmanager
def tempfile_from_dftrack(track, suffix):
| """
Saves pandas.DataFrame track table to a temporary tab-separated ASCII text
file with a unique name (to prevent clashes when running x2sys_cross),
adding a suffix extension to the end.
Parameters
----------
track : pandas.DataFrame
A table holding track data with coordinate (x, y... | import pandas as pd
from pygmt.clib import Session
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import (
GMTTempFile,
build_arg_string,
data_kind,
dummy_context,
fmt_docstring,
kwargs_to_strings,
unique_name,
use_alias,
)
@contextlib.contextmanager
def tempfile_from_df... | 80 | 80 | 267 | 15 | 65 | jbusecke/pygmt | pygmt/src/x2sys_cross.py | Python | tempfile_from_dftrack | tempfile_from_dftrack | 23 | 55 | 23 | 24 | 8f82b18ea74d1f0a5a1bab788a9a512a952b60c8 | bigcode/the-stack | train |
92eeee29feb7bcaecd82ea9c | train | function | @fmt_docstring
@use_alias(
A="combitable",
C="runtimes",
D="override",
I="interpolation",
R="region",
S="speed",
T="tag",
Q="coe",
V="verbose",
W="numpoints",
Z="trackvalues",
)
@kwargs_to_strings(R="sequence")
def x2sys_cross(tracks=None, outfile=None, **kwargs):
r"""
... | @fmt_docstring
@use_alias(
A="combitable",
C="runtimes",
D="override",
I="interpolation",
R="region",
S="speed",
T="tag",
Q="coe",
V="verbose",
W="numpoints",
Z="trackvalues",
)
@kwargs_to_strings(R="sequence")
def x2sys_cross(tracks=None, outfile=None, **kwargs):
| r"""
Calculate crossovers between track data files.
Determines all intersections between ("external cross-overs") or within
("internal cross-overs") tracks (Cartesian or geographic), and report the
time, position, distance along track, heading and speed along each track
segment, and the crossov... | File extension, e.g. xyz, tsv, etc.
Yields
------
tmpfilename : str
A temporary tab-separated value file with a unique name holding the
track data. E.g. 'track-1a2b3c4.tsv'.
"""
try:
tmpfilename = f"track-{unique_name()[:7]}.{suffix}"
track.to_csv(
path_... | 256 | 256 | 1,899 | 96 | 160 | jbusecke/pygmt | pygmt/src/x2sys_cross.py | Python | x2sys_cross | x2sys_cross | 58 | 241 | 58 | 73 | 536d27287b668a4e8df5ad01822a81234f6a76ea | bigcode/the-stack | train |
7c5860d70337dcc2f686f653 | train | class | class DepthE2EAgent(Agent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
model_file_path: Path = Path("./ROAR_Sim/data/weights/depth_model_1.h5")
print(model_file_path.exists(), model_file_path)
self.model:keras.models.Model = keras.models.load_model(model_file_path.as_po... | class DepthE2EAgent(Agent):
| def __init__(self, **kwargs):
super().__init__(**kwargs)
model_file_path: Path = Path("./ROAR_Sim/data/weights/depth_model_1.h5")
print(model_file_path.exists(), model_file_path)
self.model:keras.models.Model = keras.models.load_model(model_file_path.as_posix())
def run_step(sel... | , VehicleControl
from pathlib import Path
from tensorflow import keras
import tensorflow as tf
import numpy as np
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
class DepthE2EAgent(Agent):
| 64 | 64 | 216 | 9 | 55 | mkscheble/ROAR | ROAR/agent_module/depth_e2e_agent.py | Python | DepthE2EAgent | DepthE2EAgent | 13 | 29 | 13 | 13 | 4b20ae0e7bc64196b437e981d2bbaf1f53cf2f40 | bigcode/the-stack | train |
014c89e8119890e798654583 | train | function | def test_EstimateContrast_inputs():
input_map = dict(beta_images=dict(copyfile=False,
mandatory=True,
),
contrasts=dict(mandatory=True,
),
group_contrast=dict(xor=['use_derivs'],
),
ignore_exception=dict(deprecated='1.0.0',
nohash=True,
usedefault=True,
),
matlab_cmd=dict... | def test_EstimateContrast_inputs():
| input_map = dict(beta_images=dict(copyfile=False,
mandatory=True,
),
contrasts=dict(mandatory=True,
),
group_contrast=dict(xor=['use_derivs'],
),
ignore_exception=dict(deprecated='1.0.0',
nohash=True,
usedefault=True,
),
matlab_cmd=dict(),
mfile=dict(usedefault=True,
... | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import EstimateContrast
def test_EstimateContrast_inputs():
| 39 | 65 | 219 | 8 | 30 | mfalkiewicz/nipype | nipype/interfaces/spm/tests/test_auto_EstimateContrast.py | Python | test_EstimateContrast_inputs | test_EstimateContrast_inputs | 6 | 40 | 6 | 6 | 642981acc3143a2d15fc77e3245a833b1d7493c3 | bigcode/the-stack | train |
a7c44f2e06da8017d6ffdb84 | train | function | def test_EstimateContrast_outputs():
output_map = dict(con_images=dict(),
ess_images=dict(),
spmF_images=dict(),
spmT_images=dict(),
spm_mat_file=dict(),
)
outputs = EstimateContrast.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata... | def test_EstimateContrast_outputs():
| output_map = dict(con_images=dict(),
ess_images=dict(),
spmF_images=dict(),
spmT_images=dict(),
spm_mat_file=dict(),
)
outputs = EstimateContrast.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr... | ',
usedefault=True,
),
)
inputs = EstimateContrast.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_EstimateContrast_outputs():
| 64 | 64 | 90 | 8 | 55 | mfalkiewicz/nipype | nipype/interfaces/spm/tests/test_auto_EstimateContrast.py | Python | test_EstimateContrast_outputs | test_EstimateContrast_outputs | 43 | 54 | 43 | 43 | 860142742fb71b481143e3951f4714171b208756 | bigcode/the-stack | train |
4731cbbcbc3d131f8e3cc314 | train | class | class DefaultClusterResolver(ClusterResolver):
def __init__(self, eureka_client_config: EurekaClientConfig):
self._eureka_client_config = eureka_client_config
def get_cluster_endpoints(self) -> List[EurekaEndpoint]:
eureka_server_service_urls = self._eureka_client_config.eureka_server_service_u... | class DefaultClusterResolver(ClusterResolver):
| def __init__(self, eureka_client_config: EurekaClientConfig):
self._eureka_client_config = eureka_client_config
def get_cluster_endpoints(self) -> List[EurekaEndpoint]:
eureka_server_service_urls = self._eureka_client_config.eureka_server_service_urls
return [DefaultEndpoint(service_ur... | ureka_client_config import EurekaClientConfig
from eureka.client.discovery.shared.resolver.eureka_endpoint import DefaultEndpoint, EurekaEndpoint
class ClusterResolver(ABC):
@abstractmethod
def get_cluster_endpoints(self) -> List[EurekaEndpoint]:
raise NotImplemented
class DefaultClusterResolver(Clust... | 64 | 64 | 88 | 8 | 55 | haribo0915/Spring-Cloud-in-Python | eureka/client/discovery/shared/resolver/cluster_resolver.py | Python | DefaultClusterResolver | DefaultClusterResolver | 19 | 26 | 19 | 19 | be0cf3f42802c6fb09b56b5ebe018f6bbbfc96f5 | bigcode/the-stack | train |
534195e3cba76c16f5a169af | train | class | class ClusterResolver(ABC):
@abstractmethod
def get_cluster_endpoints(self) -> List[EurekaEndpoint]:
raise NotImplemented
| class ClusterResolver(ABC):
@abstractmethod
| def get_cluster_endpoints(self) -> List[EurekaEndpoint]:
raise NotImplemented
| 8599@gmail.com)"
__license__ = "Apache 2.0"
# scip plugin
from eureka.client.discovery.eureka_client_config import EurekaClientConfig
from eureka.client.discovery.shared.resolver.eureka_endpoint import DefaultEndpoint, EurekaEndpoint
class ClusterResolver(ABC):
@abstractmethod
| 64 | 64 | 30 | 11 | 52 | haribo0915/Spring-Cloud-in-Python | eureka/client/discovery/shared/resolver/cluster_resolver.py | Python | ClusterResolver | ClusterResolver | 13 | 16 | 13 | 14 | c09ab2184ddec775667211a0bef51dd7809d2cd4 | bigcode/the-stack | train |
55c2ad930b30c0f6bfa55364 | train | class | class VersionedExplorationInteractionIdsMapping:
"""Domain object representing the mapping of state names to interaction ids
in an exploration.
"""
def __init__(self, version, state_interaction_ids_dict):
"""Initialises an VersionedExplorationInteractionIdsMapping domain
object.
... | class VersionedExplorationInteractionIdsMapping:
| """Domain object representing the mapping of state names to interaction ids
in an exploration.
"""
def __init__(self, version, state_interaction_ids_dict):
"""Initialises an VersionedExplorationInteractionIdsMapping domain
object.
Args:
version: int. The version of ... | added_state_names
self.deleted_state_names = deleted_state_names
self.new_to_old_state_names = new_to_old_state_names
self.old_to_new_state_names = {
value: key for key, value in new_to_old_state_names.items()
}
class VersionedExplorationInteractionIdsMapping:
| 64 | 64 | 128 | 9 | 55 | yash10019coder/oppia | core/domain/exp_domain.py | Python | VersionedExplorationInteractionIdsMapping | VersionedExplorationInteractionIdsMapping | 537 | 552 | 537 | 537 | 8eb6db95af48688df8c95f43b478a97d8357c070 | bigcode/the-stack | train |
151967b4b02dcec836040ccd | train | class | class ExplorationCommitLogEntry:
"""Value object representing a commit to an exploration."""
def __init__(
self, created_on, last_updated, user_id, exploration_id,
commit_type, commit_message, commit_cmds, version,
post_commit_status, post_commit_community_owned,
... | class ExplorationCommitLogEntry:
| """Value object representing a commit to an exploration."""
def __init__(
self, created_on, last_updated, user_id, exploration_id,
commit_type, commit_message, commit_cmds, version,
post_commit_status, post_commit_community_owned,
post_commit_is_private):
... | [],
'allowed_values': {'property_name': EXPLORATION_PROPERTIES}
}, {
'name': CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION,
'required_attribute_names': ['from_version', 'to_version'],
'optional_attribute_names': [],
'user_id_attribute_names': []
}, {
'name': exp_mo... | 180 | 180 | 603 | 6 | 174 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExplorationCommitLogEntry | ExplorationCommitLogEntry | 363 | 428 | 363 | 363 | 35647ff7f9704f2dce70c745fb7bb02d33784f34 | bigcode/the-stack | train |
4044cc5d2728570f453819ee | train | class | class ExplorationChange(change_domain.BaseChange):
"""Domain object class for an exploration change.
IMPORTANT: Ensure that all changes to this class (and how these cmds are
interpreted in general) preserve backward-compatibility with the
exploration snapshots in the datastore. Do not modify the defini... | class ExplorationChange(change_domain.BaseChange):
| """Domain object class for an exploration change.
IMPORTANT: Ensure that all changes to this class (and how these cmds are
interpreted in general) preserve backward-compatibility with the
exploration snapshots in the datastore. Do not modify the definitions of
cmd keys that already exist.
NOTE... | (?!\()(.)' % trig_fn, r'%s(\1)' % trig_fn, math_expression)
# The pylatexenc lib outputs the unicode values of special characters like
# sqrt and pi, which is why they need to be replaced with their
# corresponding text values before performing validation. Other unicode
# characters will be left in the... | 256 | 256 | 1,289 | 8 | 247 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExplorationChange | ExplorationChange | 221 | 360 | 221 | 221 | 48091e3d9cdd792f08a39a9875750bf3c714859f | bigcode/the-stack | train |
16fa64255b017d811d9015d1 | train | class | class ExplorationVersionsDiff:
"""Domain object for the difference between two versions of an Oppia
exploration.
Attributes:
added_state_names: list(str). Names of the states added to the
exploration from prev_exp_version to current_exp_version. It stores
the newest names of... | class ExplorationVersionsDiff:
| """Domain object for the difference between two versions of an Oppia
exploration.
Attributes:
added_state_names: list(str). Names of the states added to the
exploration from prev_exp_version to current_exp_version. It stores
the newest names of the added states.
dele... | ):
"""Returns a dict representing this ExpVersionReference domain object.
Returns:
dict. A dict, mapping all fields of ExpVersionReference instance.
"""
return {
'exp_id': self.exp_id,
'version': self.version
}
def validate(self):
... | 166 | 166 | 554 | 5 | 161 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExplorationVersionsDiff | ExplorationVersionsDiff | 472 | 534 | 472 | 472 | 300ace9752cffb13cc060ad2c69b095c9a014e33 | bigcode/the-stack | train |
99cf5756ab0332b6aec8447a | train | class | class ExplorationChangeMergeVerifier:
"""Class to check for mergeability.
Attributes:
added_state_names: list(str). Names of the states added to the
exploration from prev_exp_version to current_exp_version. It
stores the latest name of the added state.
deleted_state_name... | class ExplorationChangeMergeVerifier:
| """Class to check for mergeability.
Attributes:
added_state_names: list(str). Names of the states added to the
exploration from prev_exp_version to current_exp_version. It
stores the latest name of the added state.
deleted_state_names: list(str). Names of the states dele... | id of the user.
Returns:
bool. Whether the exploration is solely owned by the user.
"""
return user_id in self.owner_ids and len(self.owner_ids) == 1
def does_user_have_any_role(self, user_id):
"""Checks if a given user has any role within the exploration.
Arg... | 256 | 256 | 3,812 | 6 | 250 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExplorationChangeMergeVerifier | ExplorationChangeMergeVerifier | 2,801 | 3,207 | 2,801 | 2,801 | ce5d7800f8a4485d1baa487fe25337f02b9c0193 | bigcode/the-stack | train |
e419e0aadc393d2283b78c3f | train | function | def clean_math_expression(math_expression):
"""Cleans a given math expression and formats it so that it is compatible
with the new interactions' validators.
Args:
math_expression: str. The string representing the math expression.
Returns:
str. The correctly formatted string representin... | def clean_math_expression(math_expression):
| """Cleans a given math expression and formats it so that it is compatible
with the new interactions' validators.
Args:
math_expression: str. The string representing the math expression.
Returns:
str. The correctly formatted string representing the math expression.
"""
unicode_t... | parameters for logging.
CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION = (
'migrate_states_schema_to_latest_version')
# These are categories to which answers may be classified. These values should
# not be changed because they are persisted in the data store within answer
# logs.
# Represents answers classified usi... | 234 | 234 | 783 | 7 | 227 | yash10019coder/oppia | core/domain/exp_domain.py | Python | clean_math_expression | clean_math_expression | 140 | 218 | 140 | 140 | 666823c980ab93e7bf743f0f937c20db634da9c9 | bigcode/the-stack | train |
9ee0442cd223a836fca68734 | train | class | class Exploration(translation_domain.BaseTranslatableObject):
"""Domain object for an Oppia exploration."""
def __init__(
self, exploration_id, title, category, objective,
language_code, tags, blurb, author_notes,
states_schema_version, init_state_name, states_dict,
... | class Exploration(translation_domain.BaseTranslatableObject):
| """Domain object for an Oppia exploration."""
def __init__(
self, exploration_id, title, category, objective,
language_code, tags, blurb, author_notes,
states_schema_version, init_state_name, states_dict,
param_specs_dict, param_changes_list, version,
... | _state_name)
elif old_state_name in new_to_old_state_names:
new_to_old_state_names[new_state_name] = (
new_to_old_state_names.pop(old_state_name))
else:
new_to_old_state_names[new_state_name] = old_state_name
self.a... | 256 | 256 | 15,125 | 10 | 245 | yash10019coder/oppia | core/domain/exp_domain.py | Python | Exploration | Exploration | 555 | 2,503 | 555 | 555 | d929af9148cbaeaa50e550d2f1535d7f82d0b3c8 | bigcode/the-stack | train |
53ef82c98f2415ca188c7de8 | train | class | class ExplorationSummary:
"""Domain object for an Oppia exploration summary."""
def __init__(
self, exploration_id, title, category, objective,
language_code, tags, ratings, scaled_average_rating, status,
community_owned, owner_ids, editor_ids, voice_artist_ids,
... | class ExplorationSummary:
| """Domain object for an Oppia exploration summary."""
def __init__(
self, exploration_id, title, category, objective,
language_code, tags, ratings, scaled_average_rating, status,
community_owned, owner_ids, editor_ids, voice_artist_ids,
viewer_ids, contributor_id... | representation of State domain object.
- title: str. The exploration title.
- objective: str. The exploration objective.
- language_code: str. The language code of the exploration.
- correctness_feedback_enabled: str. Whether to show correctness
... | 256 | 256 | 2,475 | 4 | 251 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExplorationSummary | ExplorationSummary | 2,506 | 2,798 | 2,506 | 2,506 | eb48d6479952d1a1fc247167331740a006602811 | bigcode/the-stack | train |
9b6a3af60f66c285fc78ee81 | train | class | class ExpVersionReference:
"""Value object representing an exploration ID and a version number."""
def __init__(self, exp_id, version):
"""Initializes an ExpVersionReference domain object.
Args:
exp_id: str. ID of the exploration.
version: int. Version of the exploratio... | class ExpVersionReference:
| """Value object representing an exploration ID and a version number."""
def __init__(self, exp_id, version):
"""Initializes an ExpVersionReference domain object.
Args:
exp_id: str. ID of the exploration.
version: int. Version of the exploration.
"""
self... | ploration_id,
'commit_type': self.commit_type,
'commit_message': self.commit_message,
'version': self.version,
'post_commit_status': self.post_commit_status,
'post_commit_community_owned': self.post_commit_community_owned,
'post_commit_is_private':... | 75 | 75 | 251 | 5 | 70 | yash10019coder/oppia | core/domain/exp_domain.py | Python | ExpVersionReference | ExpVersionReference | 431 | 469 | 431 | 431 | c1008fa1428cb8c5a363515ccbef6a72a8ca273b | bigcode/the-stack | train |
19ab7b6ccae95f2d1599a864 | train | class | class CMakeExtension(Extension):
def __init__(self, name):
# don't invoke the original build_ext for this special extension
super().__init__(name, sources=[])
| class CMakeExtension(Extension):
| def __init__(self, name):
# don't invoke the original build_ext for this special extension
super().__init__(name, sources=[])
| to this StackOverflow question:
# https://stackoverflow.com/questions/42585210/extending-setuptools-extension-to-use-cmake-in-setup-py
import os
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig
class CMakeExtension(Extension):
| 64 | 64 | 39 | 7 | 56 | pgrit/SimpleImageIO | setup.py | Python | CMakeExtension | CMakeExtension | 10 | 13 | 10 | 10 | ce65ed81a64f24705aad279e4f353c474a3f9d61 | bigcode/the-stack | train |
304746e5e8b516ac985b0a34 | train | class | class build_ext(build_ext_orig):
def run(self):
for ext in self.extensions:
self.build_cmake(ext)
super().run()
def build_cmake(self, ext):
cwd = pathlib.Path().absolute()
# these dirs will be created in build_py, so if you don't have
# any python sources to... | class build_ext(build_ext_orig):
| def run(self):
for ext in self.extensions:
self.build_cmake(ext)
super().run()
def build_cmake(self, ext):
cwd = pathlib.Path().absolute()
# these dirs will be created in build_py, so if you don't have
# any python sources to bundle, the dirs will be missing... | make-in-setup-py
import os
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig
class CMakeExtension(Extension):
def __init__(self, name):
# don't invoke the original build_ext for this special extension
super().__init__(name, ... | 79 | 79 | 266 | 7 | 72 | pgrit/SimpleImageIO | setup.py | Python | build_ext | build_ext | 15 | 44 | 15 | 15 | c80b243ff20aa17e09f67e045fdd2140522773e9 | bigcode/the-stack | train |
016a139da6cb399156396abf | train | class | class PluginsContext(object):
def __init__(self, app, session, plugins_data):
self.app = app
self.session = session
self.plugins_data = plugins_data
def getvar(self, var):
try:
var = self.plugins_data._get(var)
return var
except KeyError:
... | class PluginsContext(object):
| def __init__(self, app, session, plugins_data):
self.app = app
self.session = session
self.plugins_data = plugins_data
def getvar(self, var):
try:
var = self.plugins_data._get(var)
return var
except KeyError:
return None
def setva... | class PluginsContext(object):
| 5 | 109 | 364 | 5 | 0 | eocete-devo/pCraft | pcraft/PluginsContext.py | Python | PluginsContext | PluginsContext | 1 | 58 | 1 | 1 | 45bae2524f78c63c81c9dcbda18230f96d406920 | bigcode/the-stack | train |
c83e75958b45efe4203a0c7f | train | class | class TestUntestedModules(unittest.TestCase):
def test_untested_modules_can_be_imported(self):
untested = ('encodings',)
with warnings_helper.check_warnings(quiet=True):
for name in untested:
try:
import_helper.import_module('test.test_{}'.format(name)... | class TestUntestedModules(unittest.TestCase):
| def test_untested_modules_can_be_imported(self):
untested = ('encodings',)
with warnings_helper.check_warnings(quiet=True):
for name in untested:
try:
import_helper.import_module('test.test_{}'.format(name))
except unittest.SkipTest:
... | """Do a minimal test of all the modules that aren't otherwise tested."""
import importlib
from test import support
from test.support import import_helper
from test.support import warnings_helper
import unittest
class TestUntestedModules(unittest.TestCase):
| 49 | 92 | 307 | 9 | 39 | oleksandr-pavlyk/cpython | Lib/test/test_sundry.py | Python | TestUntestedModules | TestUntestedModules | 8 | 50 | 8 | 8 | 12003487df0fcd3893eebbc9a9ea88ed9c96e53d | bigcode/the-stack | train |
dab8942a8ea5e029a9a8d258 | train | function | def main(output_h5parm, ncpu, ra, dec,
array_name, start_time, time_resolution, duration,
field_of_view_diameter, avg_direction_spacing, east_wind, north_wind, time_block_size):
Nd = get_num_directions(avg_direction_spacing, field_of_view_diameter)
logger.info(f"Number of directions to simulat... | def main(output_h5parm, ncpu, ra, dec,
array_name, start_time, time_resolution, duration,
field_of_view_diameter, avg_direction_spacing, east_wind, north_wind, time_block_size):
| Nd = get_num_directions(avg_direction_spacing, field_of_view_diameter)
logger.info(f"Number of directions to simulate: {Nd}")
Nf = 1
Nt = int(duration / time_resolution) + 1
time_block_size = min(time_block_size, Nt)
logger.info(f"Number of times to simulate: {Nt}")
dp = create_empty_datapac... | np.eye(K_new_new.shape[0]))
return L_new
# K_old_old = f_K(X_old, X_old)
# K_old_new = f_K(X_old, X_new)
# L = jnp.linalg.cholesky(K_old_old + 1e-6 * jnp.eye(K_old_old.shape[0]))
# JT = solve_triangular(L, K_old_new, lower=True)
# C = K_new_new - JT.T @ JT
# LC = jnp.linalg.cholesky(C + 1e-6... | 256 | 256 | 1,063 | 49 | 206 | Joshuaalbert/bayes_gain_screens | bin/simulate_ionosphere_phase_screen.py | Python | main | main | 49 | 136 | 49 | 51 | 8210491a5d91fe0b077ecbeef1522f43ca319f79 | bigcode/the-stack | train |
33c17e81118e06ae23fce34e | train | function | def compute_conditional_moments(kernel:TomographicKernel, X_new, wind_velocity):
f_K = lambda X1, X2: kernel(X1, X2, bottom=300., width=50., l=4., sigma=1., wind_velocity=wind_velocity)
K_new_new = f_K(X_new, X_new)
L_new = jnp.linalg.cholesky(K_new_new + 1e-6*jnp.eye(K_new_new.shape[0]))
return L_new
| def compute_conditional_moments(kernel:TomographicKernel, X_new, wind_velocity):
| f_K = lambda X1, X2: kernel(X1, X2, bottom=300., width=50., l=4., sigma=1., wind_velocity=wind_velocity)
K_new_new = f_K(X_new, X_new)
L_new = jnp.linalg.cholesky(K_new_new + 1e-6*jnp.eye(K_new_new.shape[0]))
return L_new
|
n = -V * np.log(1. - pp) / (avg_spacing/60.)**2 / np.pi / 2.
n = max(int(n), 50)
return n
def compute_conditional_moments(kernel:TomographicKernel, X_new, wind_velocity):
| 64 | 64 | 106 | 19 | 44 | Joshuaalbert/bayes_gain_screens | bin/simulate_ionosphere_phase_screen.py | Python | compute_conditional_moments | compute_conditional_moments | 31 | 35 | 31 | 31 | 4ce8bbedd96f06e611831fb857686e66938a7e20 | bigcode/the-stack | train |
bcbc2c82c68d37fe56e67ad4 | train | function | def add_args(parser):
parser.register("type", "bool", lambda v: v.lower() == "true")
parser.add_argument('--output_h5parm', help='H5Parm file to file to place the simulated differential TEC',
default=None, type=str, required=True)
parser.add_argument('--ra', help='RA in degrees in IC... | def add_args(parser):
| parser.register("type", "bool", lambda v: v.lower() == "true")
parser.add_argument('--output_h5parm', help='H5Parm file to file to place the simulated differential TEC',
default=None, type=str, required=True)
parser.add_argument('--ra', help='RA in degrees in ICRS frame.',
... | ):
# plt.plot(dtec[d, a,:],alpha=0.3)
# plt.title(f"{antenna_labels[a]}")
plt.show()
def debug_main():
main(output_h5parm='test_datapack.h5',
ncpu=1,
ra=120.,
dec=30.,
array_name='lofar',
start_time=None,
time_resolution=10.,
du... | 134 | 134 | 447 | 5 | 129 | Joshuaalbert/bayes_gain_screens | bin/simulate_ionosphere_phase_screen.py | Python | add_args | add_args | 153 | 180 | 153 | 153 | b9c49489703ffb14e02db25e8925c793d3c1cf4d | bigcode/the-stack | train |
f9929359f686d1be19046ac6 | train | function | def debug_main():
main(output_h5parm='test_datapack.h5',
ncpu=1,
ra=120.,
dec=30.,
array_name='lofar',
start_time=None,
time_resolution=10.,
duration=600.,
field_of_view_diameter=4.,
avg_direction_spacing=8.,
east_wind=150.,
... | def debug_main():
| main(output_h5parm='test_datapack.h5',
ncpu=1,
ra=120.,
dec=30.,
array_name='lofar',
start_time=None,
time_resolution=10.,
duration=600.,
field_of_view_diameter=4.,
avg_direction_spacing=8.,
east_wind=150.,
north_wind... | # ax.set_title(f"{} {times[i]}")
# plt.show()
# for d in range(Nd):
# plt.plot(dtec[d, a,:],alpha=0.3)
# plt.title(f"{antenna_labels[a]}")
plt.show()
def debug_main():
| 64 | 64 | 94 | 4 | 60 | Joshuaalbert/bayes_gain_screens | bin/simulate_ionosphere_phase_screen.py | Python | debug_main | debug_main | 138 | 151 | 138 | 138 | 3d16f5c22faac240020a84bd902c433368643b9d | bigcode/the-stack | train |
2b078945e62d07c2e98687bd | train | function | def get_num_directions(avg_spacing, field_of_view_diameter):
V = 2.*np.pi*(field_of_view_diameter/2.)**2
pp = 0.5
n = -V * np.log(1. - pp) / (avg_spacing/60.)**2 / np.pi / 2.
n = max(int(n), 50)
return n
| def get_num_directions(avg_spacing, field_of_view_diameter):
| V = 2.*np.pi*(field_of_view_diameter/2.)**2
pp = 0.5
n = -V * np.log(1. - pp) / (avg_spacing/60.)**2 / np.pi / 2.
n = max(int(n), 50)
return n
| 5parm.utils import create_empty_datapack
import astropy.units as au
import astropy.coordinates as ac
import pylab as plt
import numpy as np
ARRAYS = {'lofar': DataPack.lofar_array_hba}
def get_num_directions(avg_spacing, field_of_view_diameter):
| 64 | 64 | 86 | 14 | 50 | Joshuaalbert/bayes_gain_screens | bin/simulate_ionosphere_phase_screen.py | Python | get_num_directions | get_num_directions | 24 | 29 | 24 | 24 | c112d2509c275982afd1f85bc6dcb224bf67bf19 | bigcode/the-stack | train |
f339e56a447633a0d6af8377 | train | class | class DailymotionBaseInfoExtractor(InfoExtractor):
@staticmethod
def _build_request(url):
"""Build a request with the family filter disabled"""
request = sanitized_Request(url)
request.add_header('Cookie', 'family_filter=off; ff=off')
return request
def _download_webpage_han... | class DailymotionBaseInfoExtractor(InfoExtractor):
@staticmethod
| def _build_request(url):
"""Build a request with the family filter disabled"""
request = sanitized_Request(url)
request.add_header('Cookie', 'family_filter=off; ff=off')
return request
def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
request = self._build_... | (
determine_ext,
error_to_compat_str,
ExtractorError,
int_or_none,
parse_iso8601,
sanitized_Request,
str_to_int,
unescapeHTML,
mimetype2ext,
)
class DailymotionBaseInfoExtractor(InfoExtractor):
@staticmethod
| 64 | 64 | 147 | 15 | 49 | NessDan/youtube-dl | youtube_dl/extractor/dailymotion.py | Python | DailymotionBaseInfoExtractor | DailymotionBaseInfoExtractor | 23 | 37 | 23 | 24 | 10e02850d39fdaa63bbfd352cd8f1e4a4cd8c70d | bigcode/the-stack | train |
8485410d1a8d16b5da559e6e | train | class | class DailymotionIE(DailymotionBaseInfoExtractor):
_VALID_URL = r'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)'
IE_NAME = 'dailymotion'
_FORMATS = [
('stream_h264_ld_url', 'ld'),
('stream_h264_url', 'standard'),
('stream_h... | class DailymotionIE(DailymotionBaseInfoExtractor):
| _VALID_URL = r'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)'
IE_NAME = 'dailymotion'
_FORMATS = [
('stream_h264_ld_url', 'ld'),
('stream_h264_url', 'standard'),
('stream_h264_hq_url', 'hq'),
('stream_h264_hd_url', ... | # coding: utf-8
from __future__ import unicode_literals
import re
import json
import itertools
from .common import InfoExtractor
from ..utils import (
determine_ext,
error_to_compat_str,
ExtractorError,
int_or_none,
parse_iso8601,
sanitized_Request,
str_to_int,
unescapeHTML,
mimet... | 243 | 256 | 2,930 | 12 | 231 | NessDan/youtube-dl | youtube_dl/extractor/dailymotion.py | Python | DailymotionIE | DailymotionIE | 40 | 326 | 40 | 40 | 255ae6c0a51d5b307a0a60fca6256fde9cf10079 | bigcode/the-stack | train |
eb58dd6743fc7e71b588dffc | train | class | class DailymotionUserIE(DailymotionPlaylistIE):
IE_NAME = 'dailymotion:user'
_VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
_PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
_TESTS = [{
'url': 'https://www.d... | class DailymotionUserIE(DailymotionPlaylistIE):
| IE_NAME = 'dailymotion:user'
_VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
_PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
_TESTS = [{
'url': 'https://www.dailymotion.com/user/nqtv',
'info_dict': ... | _PAGES_INDICATOR, webpage) is None:
break
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
playlist_id = mobj.group('id')
webpage = self._download_webpage(url, playlist_id)
return {
'_type': 'playlist',
'id': playlist_id,
... | 114 | 114 | 382 | 12 | 102 | NessDan/youtube-dl | youtube_dl/extractor/dailymotion.py | Python | DailymotionUserIE | DailymotionUserIE | 380 | 418 | 380 | 380 | c3584e3f1467748af51c52aafb3f5cb0c74a630c | bigcode/the-stack | train |
438ac8a1a067c6b3dec07f69 | train | class | class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
IE_NAME = 'dailymotion:playlist'
_VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>[^/?#&]+)'
_MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
_PAGE_TEMPLATE = 'http... | class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
| IE_NAME = 'dailymotion:playlist'
_VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>[^/?#&]+)'
_MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
_PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
_TESTS = [{
... | ERROR: type should be string, got "https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,\n video_id, note=False)\n except ExtractorError as err:\n self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))\n return {}\n info = json.loads(sub_list)\n if (info['total'] > 0):\n sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])\n return sub_lang_list\n self._downloader.report_warning('video doesn\\'t have subtitles')\n return {}\nclass DailymotionPlaylistIE(DailymotionBaseInfoExtractor):\n" | 155 | 156 | 523 | 13 | 142 | NessDan/youtube-dl | youtube_dl/extractor/dailymotion.py | Python | DailymotionPlaylistIE | DailymotionPlaylistIE | 329 | 377 | 329 | 329 | 882aea27cff95a9e8f7bd62cc3bd3385eca91aa0 | bigcode/the-stack | train |
7609023597df2ec9137cfa46 | train | function | def main():
files = [os.path.join(root, file) for root, dir, files in os.walk('.') for file in files]
no_symlink = 'You cannot use symlinks in typeshed, please copy {} to its link.'
for file in files:
_, ext = os.path.splitext(file)
if ext == '.pyi' and os.path.islink(file):
rais... | def main():
| files = [os.path.join(root, file) for root, dir, files in os.walk('.') for file in files]
no_symlink = 'You cannot use symlinks in typeshed, please copy {} to its link.'
for file in files:
_, ext = os.path.splitext(file)
if ext == '.pyi' and os.path.islink(file):
raise ValueError... | current/futures/_base.pyi'},
{'stdlib/3/concurrent/futures/thread.pyi', 'third_party/2/concurrent/futures/thread.pyi'},
{'stdlib/3/concurrent/futures/process.pyi', 'third_party/2/concurrent/futures/process.pyi'},
]
def main():
| 64 | 64 | 186 | 3 | 61 | stevenkaras/typeshed | tests/check_consistent.py | Python | main | main | 27 | 39 | 27 | 27 | 7105c797d6fea1c3040c9fd36ed05729402c6626 | bigcode/the-stack | train |
6b775c4553b13237bcb7a730 | train | function | def lazy_import():
from datadog_api_client.v2.model.permissions_type import PermissionsType
globals()["PermissionsType"] = PermissionsType
| def lazy_import():
| from datadog_api_client.v2.model.permissions_type import PermissionsType
globals()["PermissionsType"] = PermissionsType
|
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
| 64 | 64 | 30 | 4 | 60 | rchenzheng/datadog-api-client-python | src/datadog_api_client/v2/model/relationship_to_permission_data.py | Python | lazy_import | lazy_import | 25 | 28 | 25 | 25 | d938fadfa9d2bddc6e25796b250d5cf267e5eba6 | bigcode/the-stack | train |
aba74458b873bc77cee685b2 | train | class | class RelationshipToPermissionData(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (v... | class RelationshipToPermissionData(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_client.v2.model_uti... | 189 | 256 | 1,167 | 8 | 180 | rchenzheng/datadog-api-client-python | src/datadog_api_client/v2/model/relationship_to_permission_data.py | Python | RelationshipToPermissionData | RelationshipToPermissionData | 31 | 173 | 31 | 31 | 47d42f701a253de3ae310bd1c3568a083191204c | bigcode/the-stack | train |
40e2c243cd4abb8e352b32b3 | train | class | class ChatHandler:
def __init__(self):
self.model = Model()
self.name = "User"
def generate_html_with_waiting_status(self, telegram_chat, session_id):
logger.info(f"Waiting to process chat with {telegram_chat['name']}")
self.name = telegram_chat["name"]
f = open(f"app/t... | class ChatHandler:
| def __init__(self):
self.model = Model()
self.name = "User"
def generate_html_with_waiting_status(self, telegram_chat, session_id):
logger.info(f"Waiting to process chat with {telegram_chat['name']}")
self.name = telegram_chat["name"]
f = open(f"app/templates/{session_i... | import logging
import jinja2
import matplotlib.pyplot as plt
from flask import render_template
from app.model.model import Model
logger = logging.getLogger(__name__)
class ChatHandler:
| 39 | 146 | 488 | 4 | 35 | valntinaf/consiliarius | app/chat/handler.py | Python | ChatHandler | ChatHandler | 12 | 57 | 12 | 12 | 770bf8e976f8dfaff6cbb961a6042ca862c691b4 | bigcode/the-stack | train |
e5c66ebf989e16a65de17424 | train | class | class S2D(Craft):
def __init__(self, scope='S2D'):
super(S2D, self).__init__(scope)
def run(self, x):
y = tf.sparse.to_dense(x)
return y
| class S2D(Craft):
| def __init__(self, scope='S2D'):
super(S2D, self).__init__(scope)
def run(self, x):
y = tf.sparse.to_dense(x)
return y
| Sparse --------------------------------------- #
class D2S(Craft):
def __init__(self, scope='D2S'):
super(D2S, self).__init__(scope)
def run(self, x):
y = tf.sparse.from_dense(x)
return y
class S2D(Craft):
| 64 | 64 | 53 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | S2D | S2D | 561 | 567 | 561 | 561 | 912ef8ebac8f962aca0b31796622b33ca27d6b2a | bigcode/the-stack | train |
dc9ba8073233cab21352150b | train | class | class Identity(Craft):
def __init__(self, scope='IDENTITY'):
super(Identity, self).__init__(scope)
def run(self, x):
return x
| class Identity(Craft):
| def __init__(self, scope='IDENTITY'):
super(Identity, self).__init__(scope)
def run(self, x):
return x
| ='EMBED'):
super(Embed, self).__init__(scope)
self.embd = layers.Embedding(ntoken, token_dim, embeddings_regularizer=regularizers.l2(1))
def run(self, x):
y = self.embd(x)
return y
class Identity(Craft):
| 64 | 64 | 39 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Identity | Identity | 422 | 427 | 422 | 422 | c921e60a0516f873ecc1d92008dfcf5d07c81414 | bigcode/the-stack | train |
c7dd7b2556fae614bfb8b258 | train | class | class XavierNorm(object):
def __init__(self):
self.iniz = 'GlorotNormalV2'
| class XavierNorm(object):
| def __init__(self):
self.iniz = 'GlorotNormalV2'
| init__(self):
pass
def __enter__(self):
return False
def __exit__(self, *args):
pass
# -------------------------------------- Layer --------------------------------------- #
class Void(object):
def __init__(self):
self.iniz = 'ConstantV2'
class XavierNorm(object):
| 64 | 64 | 25 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | XavierNorm | XavierNorm | 194 | 196 | 194 | 194 | e45e077449d79716338fc39bd39d17b69d4b204d | bigcode/the-stack | train |
cbd3137de7fdfa17748bb9fc | train | class | class Zeros(object):
def __init__(self):
self.iniz = 'ZerosV2'
| class Zeros(object):
| def __init__(self):
self.iniz = 'ZerosV2'
| __(self):
self.iniz = 'RandomUniformV2'
class Orthog(object):
def __init__(self):
self.iniz = 'OrthogonalV2'
class Ones(object):
def __init__(self):
self.iniz = 'OnesV2'
class Zeros(object):
| 64 | 64 | 22 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Zeros | Zeros | 218 | 220 | 218 | 218 | b54ae04c74f5c762ce3b1b753c28a05f2461c116 | bigcode/the-stack | train |
241a114e1766da72612b38a9 | train | class | class _AP(layers.Layer):
def __init__(self, dim):
super(_AP, self).__init__()
if dim == 1:
self.pool = layers.GlobalAveragePooling1D()
elif dim == 2:
self.pool = layers.GlobalAveragePooling2D()
elif dim == 3:
self.pool = layers.GlobalAveragePooling... | class _AP(layers.Layer):
| def __init__(self, dim):
super(_AP, self).__init__()
if dim == 1:
self.pool = layers.GlobalAveragePooling1D()
elif dim == 2:
self.pool = layers.GlobalAveragePooling2D()
elif dim == 3:
self.pool = layers.GlobalAveragePooling3D()
def call(self, ... | = [(padding[2*d], padding[2*d+1]) for d in range(dim-1, -1, -1)]
self.pad = pad_fn(padding)
def run(self, x):
y = self.pool(self.pad(x))
return y
class _AP(layers.Layer):
| 64 | 64 | 141 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | _AP | _AP | 815 | 829 | 815 | 815 | 5975dbe1c71ceca1d9a75347297a0383b3fc18a2 | bigcode/the-stack | train |
148e6e6f4e25d9f63113aa1b | train | class | class LRelu(Craft):
def __init__(self, alpha=0.2, scope='LRELU'):
super(LRelu, self).__init__(scope)
self.actv = layers.LeakyReLU(alpha)
def run(self, x):
y = self.actv(x)
return y
| class LRelu(Craft):
| def __init__(self, alpha=0.2, scope='LRELU'):
super(LRelu, self).__init__(scope)
self.actv = layers.LeakyReLU(alpha)
def run(self, x):
y = self.actv(x)
return y
| class Relu(Craft):
def __init__(self, scope='RELU'):
super(Relu, self).__init__(scope)
self.actv = layers.ReLU()
def run(self, x):
y = self.actv(x)
return y
class LRelu(Craft):
| 64 | 64 | 69 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | LRelu | LRelu | 886 | 893 | 886 | 886 | 82b88cb7e0f5662ebd4989e97e0e62c681cda947 | bigcode/the-stack | train |
44035addc1c4522b41899eba | train | class | class SigmXE(Craft):
def __init__(self, scope='SIGMXE'):
super(SigmXE, self).__init__(scope)
self.cost = losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(y, x)
return z/x.shape[0]
| class SigmXE(Craft):
| def __init__(self, scope='SIGMXE'):
super(SigmXE, self).__init__(scope)
self.cost = losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(y, x)
return z/x.shape[0]
| super(MSE, self).__init__(scope)
self.cost = losses.MeanSquaredError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
class SigmXE(Craft):
| 63 | 64 | 79 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | SigmXE | SigmXE | 1,158 | 1,165 | 1,158 | 1,158 | 3494d97af6343d149fb7cb702bf2c1ba75299244 | bigcode/the-stack | train |
4034330c04322dee2500b2d3 | train | class | class StepLR(object):
def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor, staircase=True)
| class StepLR(object):
| def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call__(self, lr):
return optimizers.schedules.ExponentialDecay(lr, self.period, self.factor, staircase=True)
| (s, tf.float32) / tf.cast(self.warmup, tf.float32)
return tf.cond(step<self.warmup, lambda:warmlr(step), lambda:self.scheduler(step-self.warmup))
def get_config(self):
return self.scheduler.get_config()
class StepLR(object):
| 64 | 64 | 58 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | StepLR | StepLR | 1,234 | 1,240 | 1,234 | 1,234 | dc7f9f3183f44f5fe64ec993e9bf51e0c75bd48d | bigcode/the-stack | train |
98d5840a2573fb04f54e0613 | train | class | class Reshape(Craft):
def __init__(self, scope='RESHAPE'):
super(Reshape, self).__init__(scope)
def run(self, x, shape):
y = tf.reshape(x, shape)
return y
| class Reshape(Craft):
| def __init__(self, scope='RESHAPE'):
super(Reshape, self).__init__(scope)
def run(self, x, shape):
y = tf.reshape(x, shape)
return y
| = tf.transpose(x) @ m @ x
if not in_pair:
return eigval_max
else:
eigvec_max = (m @ x) / eigval_max
return eigval_max, eigvec_max
# ------------------------------------- Resizer -------------------------------------- #
class Reshape(Craft):
| 64 | 64 | 52 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Reshape | Reshape | 718 | 724 | 718 | 718 | 1dc8d3a9329356f5014a7261cc7df94996365dee | bigcode/the-stack | train |
2b4d2ddcb4d49d576653df9b | train | class | class D2S(Craft):
def __init__(self, scope='D2S'):
super(D2S, self).__init__(scope)
def run(self, x):
y = tf.sparse.from_dense(x)
return y
| class D2S(Craft):
| def __init__(self, scope='D2S'):
super(D2S, self).__init__(scope)
def run(self, x):
y = tf.sparse.from_dense(x)
return y
| (Craft):
def __init__(self, scope='CONCAT'):
super(Concat, self).__init__(scope)
def run(self, t, axis=-1):
y = tf.concat(t, axis)
return y
# ------------------------------------- Sparse --------------------------------------- #
class D2S(Craft):
| 64 | 64 | 53 | 7 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | D2S | D2S | 551 | 557 | 551 | 551 | ca02d210cc701c069eb6d47e3dd751f55ef15a2e | bigcode/the-stack | train |
7167eb57894cbed7edd4469c | train | class | class Tanh(Craft):
def __init__(self, scope='TANH'):
super(Tanh, self).__init__(scope)
def run(self, x):
y = tf.math.tanh(x)
return y
| class Tanh(Craft):
| def __init__(self, scope='TANH'):
super(Tanh, self).__init__(scope)
def run(self, x):
y = tf.math.tanh(x)
return y
| __(self, alpha=0.2, scope='LRELU'):
super(LRelu, self).__init__(scope)
self.actv = layers.LeakyReLU(alpha)
def run(self, x):
y = self.actv(x)
return y
class Tanh(Craft):
| 64 | 64 | 50 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Tanh | Tanh | 897 | 903 | 897 | 897 | 603ad43c9c1169fd4e736564dc3724bb1c80a860 | bigcode/the-stack | train |
413823a81001693ab179af42 | train | class | class Nesterov(Craft):
def __init__(self, hull, lr, mmnt=0.9, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='NESTEROV'):
super(Nesterov, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
... | class Nesterov(Craft):
| def __init__(self, hull, lr, mmnt=0.9, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='NESTEROV'):
super(Nesterov, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
self.grad_accum... | getVar()
target += tf.add_n(self.hull.losses)
curr_grads = self.hull._rudder.gradient(target, self.update_var)
curr_grads = [g if g is not None else tf.zeros_like(v) for g, v in zip(curr_grads, self.update_var)]
if self.cnt == 0:
self.grads = curr_grads
else:
... | 182 | 183 | 610 | 7 | 175 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Nesterov | Nesterov | 1,346 | 1,402 | 1,346 | 1,346 | 133f05d3fe3a8dc70bbd374a1c6db069ca053588 | bigcode/the-stack | train |
74c6d3dcbe0b414629bb0fb7 | train | class | class AvgPool(Craft):
def __init__(self, kernel: tuple, stride=2, padding=0, scope='APOOL'):
super(AvgPool, self).__init__(scope)
dim = len(kernel)
is_global = True if kernel[-1]<0 else False
if is_global:
assert padding == 0
if dim == 1:
if is_global... | class AvgPool(Craft):
| def __init__(self, kernel: tuple, stride=2, padding=0, scope='APOOL'):
super(AvgPool, self).__init__(scope)
dim = len(kernel)
is_global = True if kernel[-1]<0 else False
if is_global:
assert padding == 0
if dim == 1:
if is_global:
self... | 2:
self.pool = layers.GlobalAveragePooling2D()
elif dim == 3:
self.pool = layers.GlobalAveragePooling3D()
def call(self, x):
if backend.image_data_format() == 'channels_first':
return tf.expand_dims(tf.expand_dims(self.pool(x), axis=-1), axis=-1)
else:
... | 99 | 99 | 332 | 6 | 93 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | AvgPool | AvgPool | 831 | 869 | 831 | 831 | 3e82e59226f195f42ad68dcecf10d1f3b27e3fbe | bigcode/the-stack | train |
772f5f7f66c6a9d37c8991c8 | train | class | class Sftp(Craft):
def __init__(self, scope='SFTP'):
super(Sftp, self).__init__(scope)
def run(self, x):
y = tf.math.softplus(x)
return y
| class Sftp(Craft):
| def __init__(self, scope='SFTP'):
super(Sftp, self).__init__(scope)
def run(self, x):
y = tf.math.softplus(x)
return y
| def __init__(self, axis=-1, scope='SFTM'):
super(Sftm, self).__init__(scope)
self.actv = layers.Softmax(axis)
def run(self, x):
y = self.actv(x)
return y
class Sftp(Craft):
| 64 | 64 | 49 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Sftp | Sftp | 928 | 934 | 928 | 928 | b2fa03842a51b658d817b0126eec95fd7dadf526 | bigcode/the-stack | train |
b990b2b9e54c7403f4a02665 | train | class | class Permute(Craft):
def __init__(self, scope='PERMUTE'):
super(Permute, self).__init__(scope)
def run(self, x, order):
y = tf.transpose(x, order)
return y
| class Permute(Craft):
| def __init__(self, scope='PERMUTE'):
super(Permute, self).__init__(scope)
def run(self, x, order):
y = tf.transpose(x, order)
return y
| ----- Resizer -------------------------------------- #
class Reshape(Craft):
def __init__(self, scope='RESHAPE'):
super(Reshape, self).__init__(scope)
def run(self, x, shape):
y = tf.reshape(x, shape)
return y
class Permute(Craft):
| 64 | 64 | 53 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Permute | Permute | 728 | 734 | 728 | 728 | 1c08114235ace7179cb0cca3cdd163a447a6fb37 | bigcode/the-stack | train |
1d60ede758daf8025cf7cc80 | train | class | class GraphConvAdj(Craft):
def __init__(self, in_chs, out_chs, w_init=XavierNorm(), b_init=Zeros(), scope='GRAPHCONVADJ'):
super(GraphConvAdj, self).__init__(scope)
self.w = self.add_weight(
shape=(in_chs, out_chs), initializer=w_init.iniz, trainable=True
)
self.has_bias ... | class GraphConvAdj(Craft):
| def __init__(self, in_chs, out_chs, w_init=XavierNorm(), b_init=Zeros(), scope='GRAPHCONVADJ'):
super(GraphConvAdj, self).__init__(scope)
self.w = self.add_weight(
shape=(in_chs, out_chs), initializer=w_init.iniz, trainable=True
)
self.has_bias = False if isinstance(b_ini... | iz, bias_initializer=b_init.iniz,
kernel_regularizer=regularizers.l2(1), bias_regularizer=regularizers.l2(1))
def run(self, x):
y = self.conv(self.exter_pad(self.inter_pad(x)))
return y
class GraphConvAdj(Craft):
| 64 | 64 | 183 | 7 | 56 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | GraphConvAdj | GraphConvAdj | 362 | 378 | 362 | 362 | 711543d5a1a3d16b54ab9ef408683c9956929b32 | bigcode/the-stack | train |
f049255eba35f1a06a614d82 | train | class | class Craft(Model):
def __init__(self, scope):
super(Craft, self).__init__()
self.scope = scope
self.__pods = []
self.__dict = {}
self.__formulated = False
def run(self, *args, **kwargs):
raise NotImplementedError
# @tf.function
def _run(self, *args, **k... | class Craft(Model):
| def __init__(self, scope):
super(Craft, self).__init__()
self.scope = scope
self.__pods = []
self.__dict = {}
self.__formulated = False
def run(self, *args, **kwargs):
raise NotImplementedError
# @tf.function
def _run(self, *args, **kwargs):
retu... | ',
'Conv', 'TransConv', 'GraphConvAdj', 'Dense', 'Embed', 'Identity',
'Mean', 'Max', 'Min', 'Sum', 'Dot',
'QR', 'Eigen', 'MaxEigen',
'Reshape', 'Permute', 'Upscale', 'MaxPool', 'AvgPool',
'EMA', 'Retroact',
'Sqrt',
'Concat',
'D2S', ... | 255 | 256 | 895 | 4 | 251 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Craft | Craft | 63 | 164 | 63 | 63 | b8a7c2d952c7c36260d48718cc45b043f359af08 | bigcode/the-stack | train |
c6990a097d0b48e01f0d0808 | train | class | class MaxEigen(Craft):
def __init__(self, niters=3, scope='MAXEIGEN'):
super(MaxEigen, self).__init__(scope)
self.niters = niters
def run(self, m, in_pair=True):
assert (m==tf.transpose(m)).all(), 'NEBULAE ERROR ⨷ only when m is real symmetric matrix can MaxEigen be applied.'
x ... | class MaxEigen(Craft):
| def __init__(self, niters=3, scope='MAXEIGEN'):
super(MaxEigen, self).__init__(scope)
self.niters = niters
def run(self, m, in_pair=True):
assert (m==tf.transpose(m)).all(), 'NEBULAE ERROR ⨷ only when m is real symmetric matrix can MaxEigen be applied.'
x = tf.random.normal((m.s... | __init__(self, scope='EIGEN'):
super(Eigen, self).__init__(scope)
def run(self, m, in_pair=True):
if in_pair:
return tf.linalg.eig(m)
else:
return tf.linalg.eigvals(m)
class MaxEigen(Craft):
| 64 | 64 | 190 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | MaxEigen | MaxEigen | 696 | 712 | 696 | 696 | 87e7b8634f15d1d8956d8cb2b6faaa7a905fa91b | bigcode/the-stack | train |
2d4da443c349486d1ebb890e | train | class | class Concat(Craft):
def __init__(self, scope='CONCAT'):
super(Concat, self).__init__(scope)
def run(self, t, axis=-1):
y = tf.concat(t, axis)
return y
| class Concat(Craft):
| def __init__(self, scope='CONCAT'):
super(Concat, self).__init__(scope)
def run(self, t, axis=-1):
y = tf.concat(t, axis)
return y
| -------------------------------------- #
class Sqrt(Craft):
def __init__(self, scope='SQRT'):
super(Sqrt, self).__init__(scope)
def run(self, t):
y = tf.sqrt(t)
return y
# ------------------------------------ Polyadic -------------------------------------- #
class Concat(Craft):
| 64 | 64 | 53 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Concat | Concat | 539 | 545 | 539 | 539 | fdce77a3a9af6c64717940d588b59dbba74c01d8 | bigcode/the-stack | train |
41f05c64fc3de0b260bc4a1a | train | class | class TransConv(Craft):
def __init__(self, in_chs, out_chs, out_size, kernel: tuple, stride=1, padding=0, dilation=1, group=1,
w_init=XavierNorm(), b_init=Zeros(), scope='TRANSCONV'):
'''
Args:
- in_chs: input channel
- out_chs: output channel
- out_size: out... | class TransConv(Craft):
| def __init__(self, in_chs, out_chs, out_size, kernel: tuple, stride=1, padding=0, dilation=1, group=1,
w_init=XavierNorm(), b_init=Zeros(), scope='TRANSCONV'):
'''
Args:
- in_chs: input channel
- out_chs: output channel
- out_size: output size
- kerne... | = self.pad(x)
y = self.conv(x)
return y
class _Interpad(layers.Layer):
def __init__(self, stride: list):
super(_Interpad, self).__init__()
self.stride = stride
def call(self, x):
dim = len(x.shape)
size = x.shape[2:]
assert len(size) == len(self.strid... | 207 | 207 | 692 | 6 | 201 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | TransConv | TransConv | 297 | 358 | 297 | 297 | b5e30b36f257c2af941797f05cea65fed1360c5f | bigcode/the-stack | train |
77b855733727f7aa0dfcf407 | train | class | class MSE(Craft):
def __init__(self, scope='MSE'):
super(MSE, self).__init__(scope)
self.cost = losses.MeanSquaredError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
| class MSE(Craft):
| def __init__(self, scope='MSE'):
super(MSE, self).__init__(scope)
self.cost = losses.MeanSquaredError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
| '):
super(MAE, self).__init__(scope)
self.cost = losses.MeanAbsoluteError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
class MSE(Craft):
| 63 | 64 | 74 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | MSE | MSE | 1,147 | 1,154 | 1,147 | 1,147 | cf1bb81ce30e6172ee055bd70374207c333aede5 | bigcode/the-stack | train |
a47e7852feedbdf6c01d7296 | train | class | class Uniform(object):
def __init__(self):
self.iniz = 'RandomUniformV2'
| class Uniform(object):
| def __init__(self):
self.iniz = 'RandomUniformV2'
| self.iniz = 'GlorotNormalV2'
class XavierUnif(object):
def __init__(self):
self.iniz = 'GlorotUniformV2'
class Normal(object):
def __init__(self):
self.iniz = 'RandomNormalV2'
class Uniform(object):
| 64 | 64 | 22 | 4 | 60 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Uniform | Uniform | 206 | 208 | 206 | 206 | a906ab0a5008d5e9c37c7d53c9e4c8d4891a07f9 | bigcode/the-stack | train |
e35eb50ec79d1a86cd0163dc | train | class | class BN(Craft):
def __init__(self, out_chs, dim, mmnt=0.9, resilient=True, scope='BN'):
super(BN, self).__init__(scope)
self.norm = layers.experimental.SyncBatchNormalization(1, momentum=mmnt, center=resilient, scale=resilient, epsilon=1e-5)
def run(self, x):
y = self.norm(x)
r... | class BN(Craft):
| def __init__(self, out_chs, dim, mmnt=0.9, resilient=True, scope='BN'):
super(BN, self).__init__(scope)
self.norm = layers.experimental.SyncBatchNormalization(1, momentum=mmnt, center=resilient, scale=resilient, epsilon=1e-5)
def run(self, x):
y = self.norm(x)
return y
| def __init__(self, p_drop, dim, scope='DROPOUT'):
super(Dropout, self).__init__(scope)
self.dp = layers.Dropout(p_drop)
def run(self, x):
y = self.dp(x)
return y
class BN(Craft):
| 64 | 64 | 95 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | BN | BN | 951 | 958 | 951 | 951 | b7d52afb6f96b4ee21d04578b3afbeb0c9627c87 | bigcode/the-stack | train |
e4e25bbb894bb4cea3377c20 | train | class | class XavierUnif(object):
def __init__(self):
self.iniz = 'GlorotUniformV2'
| class XavierUnif(object):
| def __init__(self):
self.iniz = 'GlorotUniformV2'
| args):
pass
# -------------------------------------- Layer --------------------------------------- #
class Void(object):
def __init__(self):
self.iniz = 'ConstantV2'
class XavierNorm(object):
def __init__(self):
self.iniz = 'GlorotNormalV2'
class XavierUnif(object):
| 64 | 64 | 26 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | XavierUnif | XavierUnif | 198 | 200 | 198 | 198 | 1d4315efb7b13554dbedaa9ae80084a4ed13a9f9 | bigcode/the-stack | train |
238b86c55fa4caa13e6de95e | train | class | class SpDot(Craft):
def __init__(self, scope='SPDOT'):
super(SpDot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = tf.sparse.sparse_dense_matmul(x, y)
return z
| class SpDot(Craft):
| def __init__(self, scope='SPDOT'):
super(SpDot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = tf.sparse.sparse_dense_matmul(x, y)
return z
| )
return y
class S2D(Craft):
def __init__(self, scope='S2D'):
super(S2D, self).__init__(scope)
def run(self, x):
y = tf.sparse.to_dense(x)
return y
class SpDot(Craft):
| 64 | 64 | 62 | 6 | 57 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | SpDot | SpDot | 571 | 577 | 571 | 571 | 41a689945abcab7b2a3ee94f45dbf98308ba97dc | bigcode/the-stack | train |
e67b3f2f1562e24c8adf9614 | train | class | class Dropout(Craft):
def __init__(self, p_drop, dim, scope='DROPOUT'):
super(Dropout, self).__init__(scope)
self.dp = layers.Dropout(p_drop)
def run(self, x):
y = self.dp(x)
return y
| class Dropout(Craft):
| def __init__(self, p_drop, dim, scope='DROPOUT'):
super(Dropout, self).__init__(scope)
self.dp = layers.Dropout(p_drop)
def run(self, x):
y = self.dp(x)
return y
|
class Sftp(Craft):
def __init__(self, scope='SFTP'):
super(Sftp, self).__init__(scope)
def run(self, x):
y = tf.math.softplus(x)
return y
# ------------------------------------ Distributing ------------------------------------ #
class Dropout(Craft):
| 64 | 64 | 65 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Dropout | Dropout | 940 | 947 | 940 | 940 | 259551eec9f3540b06d17a4d7c4934d380d0dbdb | bigcode/the-stack | train |
aaa5487f2c0b8e72f119b5ae | train | class | class Orthog(object):
def __init__(self):
self.iniz = 'OrthogonalV2'
| class Orthog(object):
| def __init__(self):
self.iniz = 'OrthogonalV2'
| self):
self.iniz = 'GlorotUniformV2'
class Normal(object):
def __init__(self):
self.iniz = 'RandomNormalV2'
class Uniform(object):
def __init__(self):
self.iniz = 'RandomUniformV2'
class Orthog(object):
| 64 | 64 | 23 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Orthog | Orthog | 210 | 212 | 210 | 210 | 505bdcc2c2b6df146ad88b159cc24730061be499 | bigcode/the-stack | train |
4fcae59ce4d477a8e7962c7d | train | class | class Rudder(tf.GradientTape):
def __init__(self):
super(Rudder, self).__init__()
| class Rudder(tf.GradientTape):
| def __init__(self):
super(Rudder, self).__init__()
| ]:
craft = getattr(craft, p)
if paths[-1] == '':
return craft
else:
return craft.__dict[paths[-1]]
def __setitem__(self, key, value):
self.__dict[key] = value
class Rudder(tf.GradientTape):
| 64 | 64 | 24 | 8 | 55 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Rudder | Rudder | 168 | 170 | 168 | 168 | fa4d3147e452c6fbf135554ad532e7a4ac91adde | bigcode/the-stack | train |
f78d4ed63741d27dbdefb20f | train | class | class Min(Craft):
def __init__(self, scope='MIN'):
super(Min, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_min(x)
else:
y = tf.reduce_min(x, axis=axis)
return y
| class Min(Craft):
| def __init__(self, scope='MIN'):
super(Min, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_min(x)
else:
y = tf.reduce_min(x, axis=axis)
return y
| self, scope='MAX'):
super(Max, self).__init__(scope)
def run(self, x, axis=None):
if axis is None:
y = tf.reduce_max(x)
else:
y = tf.reduce_max(x, axis=axis)
return y
class Min(Craft):
| 64 | 64 | 70 | 5 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Min | Min | 626 | 635 | 626 | 626 | 1962668d3677d57cc031b41ddaad69e2ef74150d | bigcode/the-stack | train |
01b96a8694317661099eee48 | train | class | class MAE(Craft):
def __init__(self, scope='MAE'):
super(MAE, self).__init__(scope)
self.cost = losses.MeanAbsoluteError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
| class MAE(Craft):
| def __init__(self, scope='MAE'):
super(MAE, self).__init__(scope)
self.cost = losses.MeanAbsoluteError(reduction=losses.Reduction.SUM)
def run(self, x, y):
z = self.cost(x, y)
return z/x.shape[0]
| _(0, 1))
self.hull.register_buffer(self.name + "_u", u)
def run(self, *args, **kwargs):
self._update_u_v()
return self.craft.run(*args, **kwargs)
'''
# ------------------------------------ Loss ------------------------------------ #
class MAE(Craft):
| 64 | 64 | 74 | 6 | 58 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | MAE | MAE | 1,136 | 1,143 | 1,136 | 1,136 | 86d7558dd31ffe429aa00808fd6f2ba56c3b6c89 | bigcode/the-stack | train |
7556b007778c82dc6e8c2a64 | train | class | class Clip(Craft):
def __init__(self, intrinsic=False, scope='CLIP'):
super(Clip, self).__init__(scope)
if intrinsic:
self.clipper = tfp.math.clip_by_value_preserve_gradient
else:
self.clipper = tf.clip_by_value
def run(self, x, ranges):
if isinstance(ran... | class Clip(Craft):
| def __init__(self, intrinsic=False, scope='CLIP'):
super(Clip, self).__init__(scope)
if intrinsic:
self.clipper = tfp.math.clip_by_value_preserve_gradient
else:
self.clipper = tf.clip_by_value
def run(self, x, ranges):
if isinstance(ranges, tuple):
... | __(self, scope='SPDOT'):
super(SpDot, self).__init__(scope)
def run(self, x, y, in_batch=False):
z = tf.sparse.sparse_dense_matmul(x, y)
return z
# ----------------------------------- Statistics ------------------------------------- #
class Clip(Craft):
| 64 | 64 | 109 | 5 | 59 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Clip | Clip | 583 | 596 | 583 | 583 | d700b300dad6b61e689a12ac88e7720d95c05145 | bigcode/the-stack | train |
ac984eed7cde056a4da2f426 | train | class | class Dense(Craft):
def __init__(self, in_chs, out_chs, axis=-1,
w_init=XavierNorm(), b_init=Zeros(), scope='DENSE'):
super(Dense, self).__init__(scope)
if axis == 0:
raise Exception('NEBULAE ERROR ⨷ you cannot apply dense layer along batch axis.')
else:
... | class Dense(Craft):
| def __init__(self, in_chs, out_chs, axis=-1,
w_init=XavierNorm(), b_init=Zeros(), scope='DENSE'):
super(Dense, self).__init__(scope)
if axis == 0:
raise Exception('NEBULAE ERROR ⨷ you cannot apply dense layer along batch axis.')
else:
self.axis = axis... | if self.has_bias:
self.b = self.add_weight(shape=(out_chs,), initializer=b_init.iniz, trainable=True)
def run(self, x, op):
support = tf.matmul(x, self.w)
y = tf.sparse.sparse_dense_matmul(op, support)
if self.has_bias:
return y + self.b
else:
re... | 87 | 87 | 290 | 5 | 81 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Dense | Dense | 382 | 407 | 382 | 382 | 632e94af5a1bd7f4f88a97ee10be4e56703498b9 | bigcode/the-stack | train |
ca2b54773864858454b20217 | train | class | class Momentum(Craft):
def __init__(self, hull, lr, mmnt=0.9, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='MOMENTUM'):
super(Momentum, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
... | class Momentum(Craft):
| def __init__(self, hull, lr, mmnt=0.9, wd=0, lr_decay=None, warmup=0,
grad_limit=-1, grad_accum=1, update_scope=None, scope='MOMENTUM'):
super(Momentum, self).__init__(scope)
self.hull = hull
self.wd = wd / 2.
self.update_scope = update_scope
self.grad_accum... | CosLR(object):
def __init__(self, period):
self.period = period
def __call__(self, lr):
return optimizers.schedules.CosineDecay(lr, self.period, lr * 0.001)
class ExpLR(object):
def __init__(self, period, factor):
self.period = period
self.factor = factor
def __call... | 182 | 182 | 608 | 5 | 177 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | Momentum | Momentum | 1,283 | 1,342 | 1,283 | 1,283 | 7105f5d611dccf5a0f9e0a20ddd15c5a6382b71f | bigcode/the-stack | train |
4fa4bdd5f2e26f78f0e5d88c | train | class | class WarmUpWrapper(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, warmup, scheduler):
self.warmup = warmup
def retnum(s):
return self.lr
if isinstance(scheduler, (int, float)):
self.lr = tf.cast(scheduler, tf.float32)
self.sched... | class WarmUpWrapper(tf.keras.optimizers.schedules.LearningRateSchedule):
| def __init__(self, warmup, scheduler):
self.warmup = warmup
def retnum(s):
return self.lr
if isinstance(scheduler, (int, float)):
self.lr = tf.cast(scheduler, tf.float32)
self.scheduler = retnum
else:
self.lr = scheduler.get_config()[... | y = tf.argmax(y, axis=-1)
x = tf.argmax(x, axis=-1)
z = tf.reduce_mean(tf.cast(x == y, dtype=data_type))
return z
# ------------------------------------ Optimizer ------------------------------------ #
class WarmUpWrapper(tf.keras.optimizers.schedules.LearningRateSchedule):
| 64 | 64 | 183 | 15 | 49 | SeriaZheng/Nebulae | nebulae/astrobase/craft_tf.py | Python | WarmUpWrapper | WarmUpWrapper | 1,209 | 1,230 | 1,209 | 1,209 | 806bb2d728163f924275ac83c45199515baf5541 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.