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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
089e820ec62b7adde7d6546e | train | class | class StrongFilterUsersField(FilterUsersField):
"""
Version of the FilterUsersField that always actually uses and shows this filter
When using this field:
use SelectMobileWorkerFieldHack instead of SelectMobileWorkerField
if using ProjectReportParametersMixin make sure filter... | class StrongFilterUsersField(FilterUsersField):
| """
Version of the FilterUsersField that always actually uses and shows this filter
When using this field:
use SelectMobileWorkerFieldHack instead of SelectMobileWorkerField
if using ProjectReportParametersMixin make sure filter_users_field_class is set to this
"""
al... | reports/partials/checkbox.html"
def update_context(self):
self.context['label'] = self.label
self.context[self.slug] = self.request.GET.get(self.slug, False)
self.context['checked'] = self.request.GET.get(self.slug, False)
class StrongFilterUsersField(FilterUsersField):
| 64 | 64 | 81 | 9 | 55 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | StrongFilterUsersField | StrongFilterUsersField | 203 | 211 | 203 | 203 | 6d3fba1ff8d9959422ca4107be8a882d86310af1 | bigcode/the-stack | train |
43648c20ab4c8cd6799ff485 | train | class | class UserOrGroupField(ReportSelectField):
"""
To Use: Subclass and specify what the field options should be
"""
slug = "view_by"
name = "View by Users or Groups"
cssId = "view_by_select"
cssClasses = "span2"
default_option = "Users"
def update_params(self):
self.selecte... | class UserOrGroupField(ReportSelectField):
| """
To Use: Subclass and specify what the field options should be
"""
slug = "view_by"
name = "View by Users or Groups"
cssId = "view_by_select"
cssClasses = "span2"
default_option = "Users"
def update_params(self):
self.selected = self.request.GET.get(self.slug, '')
... | When using this field:
use SelectMobileWorkerFieldHack instead of SelectMobileWorkerField
if using ProjectReportParametersMixin make sure filter_users_field_class is set to this
"""
always_show_filter = True
can_be_empty = True
class UserOrGroupField(ReportSelectField):
| 64 | 64 | 105 | 10 | 53 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | UserOrGroupField | UserOrGroupField | 214 | 226 | 214 | 214 | 5d9305a0c4bc9b7a431d82939e67fb5dff78fb2e | bigcode/the-stack | train |
34b888d7bc772e3d54f2e023 | train | class | class SelectProgramField(ReportSelectField):
slug = "program"
name = ugettext_noop("Program")
cssId = "program_select"
default_option = 'All'
def update_params(self):
self.selected = self.request.GET.get('program')
user = WebUser.get_by_username(str(self.request.user))
if no... | class SelectProgramField(ReportSelectField):
| slug = "program"
name = ugettext_noop("Program")
cssId = "program_select"
default_option = 'All'
def update_params(self):
self.selected = self.request.GET.get('program')
user = WebUser.get_by_username(str(self.request.user))
if not self.selected and \
self.selecte... | "view_by_select"
cssClasses = "span2"
default_option = "Users"
def update_params(self):
self.selected = self.request.GET.get(self.slug, '')
self.options = [{'val': 'groups', 'text': 'Groups'}]
class SelectProgramField(ReportSelectField):
| 64 | 64 | 148 | 9 | 55 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | SelectProgramField | SelectProgramField | 229 | 244 | 229 | 229 | 37eb2ce43b12fcc363862d5fc5b3cdc73368861e | bigcode/the-stack | train |
afc97ca4663961b7d75e16b2 | train | class | class ReportSelectField(ReportField):
slug = "generic_select"
name = ugettext_noop("Generic Select")
template = "reports/dont_use_fields/select_generic.html"
default_option = ugettext_noop("Select Something...")
options = [dict(val="val", text="text")]
cssId = "generic_select_box"
cssClasses... | class ReportSelectField(ReportField):
| slug = "generic_select"
name = ugettext_noop("Generic Select")
template = "reports/dont_use_fields/select_generic.html"
default_option = ugettext_noop("Select Something...")
options = [dict(val="val", text="text")]
cssId = "generic_select_box"
cssClasses = "span4"
selected = None
hid... | self.parent_report = parent_report
def render(self):
if not self.template: return ""
self.context["slug"] = self.slug
self.update_context()
return render_to_string(self.template, self.context)
def update_context(self):
"""
If your select field needs some contex... | 91 | 91 | 305 | 8 | 82 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | ReportSelectField | ReportSelectField | 50 | 87 | 50 | 50 | fc2aa6a62d80572cf955b19460de5c57ea3fa4ff | bigcode/the-stack | train |
23288bc2764cac9feeed4e1b | train | class | class BooleanField(ReportField):
slug = "checkbox"
label = "hello"
template = "reports/partials/checkbox.html"
def update_context(self):
self.context['label'] = self.label
self.context[self.slug] = self.request.GET.get(self.slug, False)
self.context['checked'] = self.request.GET... | class BooleanField(ReportField):
| slug = "checkbox"
label = "hello"
template = "reports/partials/checkbox.html"
def update_context(self):
self.context['label'] = self.label
self.context[self.slug] = self.request.GET.get(self.slug, False)
self.context['checked'] = self.request.GET.get(self.slug, False)
| _to_options(self.users)
self.context['group_options'] = self.group_options
@staticmethod
def users_to_options(user_list):
return [dict(val=user.user_id,
text=user.raw_username,
is_active=user.is_active) for user in user_list]
class BooleanField(ReportField):
| 64 | 64 | 78 | 7 | 57 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | BooleanField | BooleanField | 192 | 200 | 192 | 192 | 3b31540bfff10bc6b6dd9dae2faca0d21cc58fac | bigcode/the-stack | train |
0710e7addbd61a10096400df | train | class | class SelectMobileWorkerMixin(object):
slug = "select_mw"
name = ugettext_noop("Select Mobile Worker")
@classmethod
def get_default_text(cls, user_filter, default_option=None):
default = default_option or cls.default_option
if user_filter[HQUserType.ADMIN].show or \
user_filt... | class SelectMobileWorkerMixin(object):
| slug = "select_mw"
name = ugettext_noop("Select Mobile Worker")
@classmethod
def get_default_text(cls, user_filter, default_option=None):
default = default_option or cls.default_option
if user_filter[HQUserType.ADMIN].show or \
user_filter[HQUserType.DEMO_USER].show or user_f... | )
self.context['show_user_filter'] = show_filter
self.context['toggle_users'] = toggle
self.context['can_be_empty'] = self.can_be_empty
@classmethod
def get_user_filter(cls, request):
return get_user_toggle(request)
class SelectMobileWorkerMixin(object):
| 64 | 64 | 109 | 7 | 57 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | SelectMobileWorkerMixin | SelectMobileWorkerMixin | 108 | 118 | 108 | 108 | 5c4ec185542a97a5bc7c6bac232c39ffb9a97475 | bigcode/the-stack | train |
92f16607fc88b8974d0469fa | train | class | class SelectFilteredMobileWorkerField(SelectMobileWorkerField):
"""
This is a little field for use when a client really wants to filter by
individuals from a specific group. Since by default we still want to
show all the data, no filtering is done unless the special group filter
is ... | class SelectFilteredMobileWorkerField(SelectMobileWorkerField):
| """
This is a little field for use when a client really wants to filter by
individuals from a specific group. Since by default we still want to
show all the data, no filtering is done unless the special group filter
is selected.
"""
slug = "select_filtered_mw"
name = uge... | self.user_filter, _ = self.filter_users_field_class.get_user_filter(self.request)
self.individual = self.request.GET.get('individual', '')
self.default_option = self.get_default_text(self.user_filter)
self.users = util.user_list(self.domain)
self.update_params()
self.context['... | 114 | 114 | 383 | 12 | 101 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | SelectFilteredMobileWorkerField | SelectFilteredMobileWorkerField | 148 | 189 | 148 | 148 | 72ae7a797ae23865a9251c72cf6a8ae91191b507 | bigcode/the-stack | train |
63c775075b2cb73818f2fd11 | train | class | class ReportMultiSelectField(ReportSelectField):
template = "reports/dont_use_fields/multiselect_generic.html"
selected = []
# auto_select
default_option = []
# enfore as_combo = False ?
def update_params(self):
self.selected = self.request.GET.getlist(self.slug) or self.default_option... | class ReportMultiSelectField(ReportSelectField):
| template = "reports/dont_use_fields/multiselect_generic.html"
selected = []
# auto_select
default_option = []
# enfore as_combo = False ?
def update_params(self):
self.selected = self.request.GET.getlist(self.slug) or self.default_option
| dict(val=program.get_id, text=program.name) for program in self.programs]
self.options = opts
class GroupFieldMixin():
slug = "group"
name = ugettext_noop("Group")
cssId = "group_select"
class ReportMultiSelectField(ReportSelectField):
| 64 | 64 | 71 | 10 | 54 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | ReportMultiSelectField | ReportMultiSelectField | 253 | 262 | 253 | 253 | 86ad9cc6ffb9598647ebaa699b093bdc90347bb2 | bigcode/the-stack | train |
6ada09cec51da98cd3b58cae | train | class | class FilterUsersField(ReportField):
# TODO: move all this to UserTypeFilter
slug = "ufilter"
template = "reports/dont_use_fields/filter_users.html"
always_show_filter = False
can_be_empty = False
def update_context(self):
toggle, show_filter = self.get_user_filter(self.request)
... | class FilterUsersField(ReportField):
# TODO: move all this to UserTypeFilter
| slug = "ufilter"
template = "reports/dont_use_fields/filter_users.html"
always_show_filter = False
can_be_empty = False
def update_context(self):
toggle, show_filter = self.get_user_filter(self.request)
self.context['show_user_filter'] = show_filter
self.context['toggle_user... | default=self.default_option,
cssId=self.cssId,
cssClasses=self.cssClasses,
label=self.name,
selected=self.selected,
use_combo_box=self.as_combo,
placeholder=self.placeholder,
)
class FilterUsersField(ReportField):
# TODO: move all this... | 64 | 64 | 129 | 20 | 44 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | FilterUsersField | FilterUsersField | 90 | 105 | 90 | 91 | 3d5e33cd995ec3fa1ed4f25fbdb08061869778af | bigcode/the-stack | train |
cb6fca61a7edc942b280c9a2 | train | class | class SelectMobileWorkerField(SelectMobileWorkerMixin, ReportField):
template = "reports/dont_use_fields/select_mobile_worker.html"
default_option = ugettext_noop("All Mobile Workers")
filter_users_field_class = FilterUsersField
def __init__(self, request, domain=None, timezone=pytz.utc, parent_report=... | class SelectMobileWorkerField(SelectMobileWorkerMixin, ReportField):
| template = "reports/dont_use_fields/select_mobile_worker.html"
default_option = ugettext_noop("All Mobile Workers")
filter_users_field_class = FilterUsersField
def __init__(self, request, domain=None, timezone=pytz.utc, parent_report=None, filter_users_field_class=None):
super(SelectMobileWorke... | .default_option
if user_filter[HQUserType.ADMIN].show or \
user_filter[HQUserType.DEMO_USER].show or user_filter[HQUserType.UNKNOWN].show:
default = _('%s & Others') % _(default)
return default
class SelectMobileWorkerField(SelectMobileWorkerMixin, ReportField):
| 71 | 71 | 237 | 14 | 56 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | SelectMobileWorkerField | SelectMobileWorkerField | 121 | 145 | 121 | 121 | 754897edcb0393707e5fa5550d3112721dc11ec0 | bigcode/the-stack | train |
cb8c1bc57c5a3aa67f04a874 | train | class | class ReportField(CacheableRequestMixIn):
slug = ""
template = ""
def __init__(self, request, domain=None, timezone=pytz.utc, parent_report=None):
warnings.warn(
"ReportField (%s) is deprecated. Use ReportFilter instead." % (
self.__class__.__name__
),
... | class ReportField(CacheableRequestMixIn):
| slug = ""
template = ""
def __init__(self, request, domain=None, timezone=pytz.utc, parent_report=None):
warnings.warn(
"ReportField (%s) is deprecated. Use ReportFilter instead." % (
self.__class__.__name__
),
DeprecationWarning,
)
... | .apps.reports.models import HQUserType
from django.utils.translation import ugettext_noop
from django.utils.translation import ugettext as _
from corehq.apps.reports.cache import CacheableRequestMixIn
import uuid
from corehq.apps.users.models import WebUser
class ReportField(CacheableRequestMixIn):
| 64 | 64 | 186 | 9 | 54 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | ReportField | ReportField | 21 | 48 | 21 | 21 | f32f99d1a8c0f42b7761bcca560ad52d7ff3074c | bigcode/the-stack | train |
ecad92c73d8b1ac979f0521e | train | class | class MultiSelectGroupField(GroupFieldMixin, ReportMultiSelectField):
default_option = ['_all']
placeholder = 'Click to select groups'
help_text = "Start typing to select one or more groups"
@property
def options(self):
self.groups = Group.get_reporting_groups(self.domain)
opts = [d... | class MultiSelectGroupField(GroupFieldMixin, ReportMultiSelectField):
| default_option = ['_all']
placeholder = 'Click to select groups'
help_text = "Start typing to select one or more groups"
@property
def options(self):
self.groups = Group.get_reporting_groups(self.domain)
opts = [dict(val=group.get_id, text=group.name) for group in self.groups]
... | iselect_generic.html"
selected = []
# auto_select
default_option = []
# enfore as_combo = False ?
def update_params(self):
self.selected = self.request.GET.getlist(self.slug) or self.default_option
class MultiSelectGroupField(GroupFieldMixin, ReportMultiSelectField):
| 64 | 64 | 109 | 14 | 49 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | MultiSelectGroupField | MultiSelectGroupField | 265 | 275 | 265 | 265 | 91fd041c7ab3862fdf8a2db6311992681a469f64 | bigcode/the-stack | train |
9f77bfc525f246bc0aaae318 | train | class | class GroupFieldMixin():
slug = "group"
name = ugettext_noop("Group")
cssId = "group_select"
| class GroupFieldMixin():
| slug = "group"
name = ugettext_noop("Group")
cssId = "group_select"
| hip(self.domain):
self.selected = user.get_domain_membership(self.domain).program_id
self.programs = Program.by_domain(self.domain)
opts = [dict(val=program.get_id, text=program.name) for program in self.programs]
self.options = opts
class GroupFieldMixin():
| 64 | 64 | 29 | 5 | 58 | SEL-Columbia/commcare-hq | corehq/apps/reports/dont_use/fields.py | Python | GroupFieldMixin | GroupFieldMixin | 247 | 250 | 247 | 247 | 3cdc83e47b2fb1b004f570d99351d7e4a7f6eeee | bigcode/the-stack | train |
5df52f69733b1da88d28b25b | train | function | def _construct_sparse_coder(Estimator):
# XXX: hard-coded assumption that n_features=3
dictionary = np.array(
[[0, 1, 0], [-1, -1, 2], [1, 1, 1], [0, 1, 1], [0, 2, 1]],
dtype=np.float64,
)
return Estimator(dictionary=dictionary)
| def _construct_sparse_coder(Estimator):
# XXX: hard-coded assumption that n_features=3
| dictionary = np.array(
[[0, 1, 0], [-1, -1, 2], [1, 1, 1], [0, 1, 1], [0, 2, 1]],
dtype=np.float64,
)
return Estimator(dictionary=dictionary)
| return Estimator(steps=[("clf", LogisticRegression())])
elif Estimator.__name__ == "FeatureUnion":
return Estimator(transformer_list=[("transformer", FunctionTransformer())])
def _construct_sparse_coder(Estimator):
# XXX: hard-coded assumption that n_features=3
| 64 | 64 | 90 | 22 | 42 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | _construct_sparse_coder | _construct_sparse_coder | 188 | 194 | 188 | 189 | 2b5fe129cba16bed056f6318e500c71ae4190663 | bigcode/the-stack | train |
f95ca4eb1541c98bdcb5db94 | train | function | def _construct_compose_pipeline_instance(Estimator):
# Minimal / degenerate instances: only useful to test the docstrings.
if Estimator.__name__ == "ColumnTransformer":
return Estimator(transformers=[("transformer", "passthrough", [0, 1])])
elif Estimator.__name__ == "Pipeline":
return Estim... | def _construct_compose_pipeline_instance(Estimator):
# Minimal / degenerate instances: only useful to test the docstrings.
| if Estimator.__name__ == "ColumnTransformer":
return Estimator(transformers=[("transformer", "passthrough", [0, 1])])
elif Estimator.__name__ == "Pipeline":
return Estimator(steps=[("clf", LogisticRegression())])
elif Estimator.__name__ == "FeatureUnion":
return Estimator(transformer... | ignore list" % modname,
)
def _construct_searchcv_instance(SearchCV):
return SearchCV(LogisticRegression(), {"C": [0.1, 1]})
def _construct_compose_pipeline_instance(Estimator):
# Minimal / degenerate instances: only useful to test the docstrings.
| 64 | 64 | 114 | 26 | 38 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | _construct_compose_pipeline_instance | _construct_compose_pipeline_instance | 178 | 185 | 178 | 179 | 3acf30c0a494f9b996ebd2888dd38db65f866cb3 | bigcode/the-stack | train |
a6f6a18d97199715a0aabdb5 | train | function | def _get_all_fitted_attributes(estimator):
"Get all the fitted attributes of an estimator including properties"
# attributes
fit_attr = list(estimator.__dict__.keys())
# properties
with warnings.catch_warnings():
warnings.filterwarnings("error", category=FutureWarning)
for name in ... | def _get_all_fitted_attributes(estimator):
| "Get all the fitted attributes of an estimator including properties"
# attributes
fit_attr = list(estimator.__dict__.keys())
# properties
with warnings.catch_warnings():
warnings.filterwarnings("error", category=FutureWarning)
for name in dir(estimator.__class__):
obj =... | it_attr).difference(fit_attr_names)
undocumented_attrs = set(undocumented_attrs).difference(skipped_attributes)
if undocumented_attrs:
raise AssertionError(
f"Undocumented attributes for {Estimator.__name__}: {undocumented_attrs}"
)
def _get_all_fitted_attributes(estimator):
| 64 | 64 | 159 | 10 | 54 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | _get_all_fitted_attributes | _get_all_fitted_attributes | 318 | 340 | 318 | 318 | fba366388a266ba4118d0404769b05f6402ddf1a | bigcode/the-stack | train |
a67f0a768109684924a3438a | train | function | @pytest.mark.parametrize("name, Estimator", all_estimators())
def test_fit_docstring_attributes(name, Estimator):
pytest.importorskip("numpydoc")
from numpydoc import docscrape
doc = docscrape.ClassDoc(Estimator)
attributes = doc["Attributes"]
if Estimator.__name__ in (
"HalvingRandomSearc... | @pytest.mark.parametrize("name, Estimator", all_estimators())
def test_fit_docstring_attributes(name, Estimator):
| pytest.importorskip("numpydoc")
from numpydoc import docscrape
doc = docscrape.ClassDoc(Estimator)
attributes = doc["Attributes"]
if Estimator.__name__ in (
"HalvingRandomSearchCV",
"RandomizedSearchCV",
"HalvingGridSearchCV",
"GridSearchCV",
):
est = _c... | _construct_searchcv_instance(SearchCV):
return SearchCV(LogisticRegression(), {"C": [0.1, 1]})
def _construct_compose_pipeline_instance(Estimator):
# Minimal / degenerate instances: only useful to test the docstrings.
if Estimator.__name__ == "ColumnTransformer":
return Estimator(transformers=[("... | 256 | 256 | 995 | 24 | 232 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | test_fit_docstring_attributes | test_fit_docstring_attributes | 197 | 315 | 197 | 198 | 2598f202310fa4b7cf8d66017fa43c0d620cbd17 | bigcode/the-stack | train |
cb0fce6dc4b4839aba49cdc0 | train | function | @ignore_warnings(category=FutureWarning)
def test_tabs():
# Test that there are no tabs in our source files
for importer, modname, ispkg in walk_packages(sklearn.__path__, prefix="sklearn."):
if IS_PYPY and (
"_svmlight_format_io" in modname
or "feature_extraction._hashing_fast"... | @ignore_warnings(category=FutureWarning)
def test_tabs():
# Test that there are no tabs in our source files
| for importer, modname, ispkg in walk_packages(sklearn.__path__, prefix="sklearn."):
if IS_PYPY and (
"_svmlight_format_io" in modname
or "feature_extraction._hashing_fast" in modname
):
continue
# because we don't import
mod = importlib.import_mo... | string_parameters(func)
msg = "\n".join(incorrect)
if len(incorrect) > 0:
raise AssertionError("Docstring Error:\n" + msg)
@ignore_warnings(category=FutureWarning)
def test_tabs():
# Test that there are no tabs in our source files
| 64 | 64 | 174 | 26 | 38 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | test_tabs | test_tabs | 150 | 171 | 150 | 152 | 8c82ec1a33bd0c31e0b816fd5b7a3c59ca041ff4 | bigcode/the-stack | train |
a26f9c7ff8e0cffdd0126170 | train | function | @pytest.mark.filterwarnings("ignore::FutureWarning")
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.skipif(IS_PYPY, reason="test segfaults on PyPy")
def test_docstring_parameters():
# Test module docstring formatting
# Skip test if numpydoc is not found
pytest.importorskip(
... | @pytest.mark.filterwarnings("ignore::FutureWarning")
@pytest.mark.filterwarnings("ignore::DeprecationWarning")
@pytest.mark.skipif(IS_PYPY, reason="test segfaults on PyPy")
def test_docstring_parameters():
# Test module docstring formatting
# Skip test if numpydoc is not found
| pytest.importorskip(
"numpydoc", reason="numpydoc is required to test the docstrings"
)
# XXX unreached code as of v0.22
from numpydoc import docscrape
incorrect = []
for name in PUBLIC_MODULES:
if name.endswith(".conftest"):
# pytest tooling, not part of the scikit... | ignore args / docstring of
_DOCSTRING_IGNORES = [
"sklearn.utils.deprecation.load_mlcomp",
"sklearn.pipeline.make_pipeline",
"sklearn.pipeline.make_union",
"sklearn.utils.extmath.safe_sparse_dot",
"sklearn.utils._joblib",
]
# Methods where y param should be ignored if y=None by default
_METHODS_IG... | 210 | 210 | 700 | 68 | 141 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | test_docstring_parameters | test_docstring_parameters | 67 | 147 | 67 | 73 | 6b02337b86f9dbba61f44f9a62606a68ac5f2269 | bigcode/the-stack | train |
07d157c41b829badef5074b6 | train | function | def _construct_searchcv_instance(SearchCV):
return SearchCV(LogisticRegression(), {"C": [0.1, 1]})
| def _construct_searchcv_instance(SearchCV):
| return SearchCV(LogisticRegression(), {"C": [0.1, 1]})
| except IOError: # user probably should have run "make clean"
continue
assert "\t" not in source, (
'"%s" has tabs, please remove them ',
"or add it to the ignore list" % modname,
)
def _construct_searchcv_instance(SearchCV):
| 64 | 64 | 29 | 9 | 55 | 13rianlucero/CrabAgePrediction | crabageprediction/venv/Lib/site-packages/sklearn/tests/test_docstring_parameters.py | Python | _construct_searchcv_instance | _construct_searchcv_instance | 174 | 175 | 174 | 174 | 36f37d9d65c6fec37f889b688a5454420a0fdc99 | bigcode/the-stack | train |
b40002866f38a55b0de92964 | train | class | class ImageTrain():
"""画像を使用した学習を提供するユーティリティです。
"""
def __init__(self):
pass
@classmethod
def train_image_classification(
cls,
train_data:tf.data.Dataset, train_size:int, batch_size:int,
validation_data:tf.data.Dataset, validation_size:int,
shuffle_size... | class ImageTrain():
| """画像を使用した学習を提供するユーティリティです。
"""
def __init__(self):
pass
@classmethod
def train_image_classification(
cls,
train_data:tf.data.Dataset, train_size:int, batch_size:int,
validation_data:tf.data.Dataset, validation_size:int,
shuffle_size:int,
model:... | from typing import List
import tensorflow as tf
from tftk.image.dataset import ImageDatasetUtil
from tftk import ResumeExecutor
from tftk import IS_ON_COLABOLATORY_WITH_GOOGLE_DRIVE, Colaboratory
from PIL import Image
from tftk.image.dataset import ImageUtil
import matplotlib.pyplot as plt
import numpy as np
import c... | 84 | 256 | 2,161 | 4 | 79 | kitfactory/tftk | tftk/train/image.py | Python | ImageTrain | ImageTrain | 14 | 288 | 14 | 14 | ef48dc56a00420c87002f848fa79f992d71ce283 | bigcode/the-stack | train |
7f0fec70af3ef8e963f05a8a | train | class | class PythonPredictor:
def __init__(self, config):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"using device: {self.device}")
self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
self.model = GPT2LMHeadModel.from_pretrained("gpt2").to(self.device)
def p... | class PythonPredictor:
| def __init__(self, config):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"using device: {self.device}")
self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
self.model = GPT2LMHeadModel.from_pretrained("gpt2").to(self.device)
def predict(self, payload):
... | to your `cortex version` (e.g. for version 0.19.*, run `git checkout -b 0.19` or switch to the `0.19` branch on GitHub)
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
class PythonPredictor:
| 64 | 64 | 149 | 5 | 58 | honeypotz-eu/cortex | examples/pytorch/text-generator/predictor.py | Python | PythonPredictor | PythonPredictor | 7 | 18 | 7 | 7 | cb2321747327367863c038206abc8118371355ef | bigcode/the-stack | train |
34a03ce3f46b1225d9937db4 | train | class | class HolidaysRequest(models.Model):
""" Leave Requests Access specifications
- a regular employee / user
- can see all leaves;
- cannot see name field of leaves belonging to other user as it may contain
private information that we don't want to share to other people than
HR people... | class HolidaysRequest(models.Model):
| """ Leave Requests Access specifications
- a regular employee / user
- can see all leaves;
- cannot see name field of leaves belonging to other user as it may contain
private information that we don't want to share to other people than
HR people;
- can modify only its own not... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com)
import logging
import math
from collections import namedtuple
from datetime import datetime, date, timedelta, time
from dateutil.rrule import rrule, DAILY... | 253 | 256 | 14,404 | 6 | 247 | Yomy1996/P1 | odoo-14.0/addons/hr_holidays/models/hr_leave.py | Python | HolidaysRequest | HolidaysRequest | 30 | 1,264 | 30 | 30 | 05175723480fa5146c3126838aa54a1a7354a99d | bigcode/the-stack | train |
646254c6bca417db867523ea | train | class | class RobustMultitaskRegressor(TensorflowMultiTaskRegressor):
"""Implements a neural network for robust multitasking.
Key idea is to have bypass layers that feed directly from features to task
output. Hopefully will allow tasks to route around bad multitasking.
"""
def __init__(self,
n_task... | class RobustMultitaskRegressor(TensorflowMultiTaskRegressor):
| """Implements a neural network for robust multitasking.
Key idea is to have bypass layers that feed directly from features to task
output. Hopefully will allow tasks to route around bad multitasking.
"""
def __init__(self,
n_tasks,
n_features,
logdir=None,
... | _layer = model_ops.dropout(bypass_layer, bypass_dropouts[i],
training)
prev_bypass_layer = bypass_layer
prev_bypass_layer_size = bypass_layer_sizes[i]
top_bypass_layer = prev_bypass_layer
if num_bypass_layers > 0:
# task_layer has... | 256 | 256 | 1,428 | 15 | 241 | weiwang2330/deepchem | deepchem/models/tensorflow_models/robust_multitask.py | Python | RobustMultitaskRegressor | RobustMultitaskRegressor | 172 | 330 | 172 | 172 | 65fc37c0eeeb8d28ef14aca750f541492aa1ad7f | bigcode/the-stack | train |
de6b323ada29acb2515748a7 | train | class | class RobustMultitaskClassifier(TensorflowMultiTaskClassifier):
"""Implements a neural network for robust multitasking.
Key idea is to have bypass layers that feed directly from features to task
output. Hopefully will allow tasks to route around bad multitasking.
"""
def __init__(self,
n_ta... | class RobustMultitaskClassifier(TensorflowMultiTaskClassifier):
| """Implements a neural network for robust multitasking.
Key idea is to have bypass layers that feed directly from features to task
output. Hopefully will allow tasks to route around bad multitasking.
"""
def __init__(self,
n_tasks,
n_features,
logdir=None,
... | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import warnings
import numpy as np
import tensorflow as tf
from deepchem.nn import model_ops
from deepchem.models.tensorflow_models import TensorflowGraph
from deepchem.models.tensorflow_models.fcnet import T... | 102 | 256 | 1,408 | 13 | 88 | weiwang2330/deepchem | deepchem/models/tensorflow_models/robust_multitask.py | Python | RobustMultitaskClassifier | RobustMultitaskClassifier | 15 | 169 | 15 | 15 | fd491d5ca4e935a457a20de6699bb0839ab88019 | bigcode/the-stack | train |
cc34e3bf31938847f01cdab0 | train | function | def ishares_to_redis_set(symbol):
filename = get_filename(symbol)
key = "symbol-set-" + symbol
df = pd.read_csv(filename, sep=',')
tseries = df['Ticker']
tickers = tseries.values
tickers = map(str.lower, tickers)
tickers = tuple(tickers)
for i, name in enumerate(tickers):
util.r... | def ishares_to_redis_set(symbol):
| filename = get_filename(symbol)
key = "symbol-set-" + symbol
df = pd.read_csv(filename, sep=',')
tseries = df['Ticker']
tickers = tseries.values
tickers = map(str.lower, tickers)
tickers = tuple(tickers)
for i, name in enumerate(tickers):
util.redis_set_write(key,tickers[i])
| )
#names = map(str.lower,names)
names = tuple(names)
for i, name in enumerate(tickers):
print(tickers[i],names[i])
# Read the symbol from a csv file
# and write it out to a redis set
def ishares_to_redis_set(symbol):
| 64 | 64 | 92 | 9 | 54 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | ishares_to_redis_set | ishares_to_redis_set | 50 | 60 | 50 | 50 | 62913785d3d446a1cb4383e272d4b5fa29893530 | bigcode/the-stack | train |
644793094e6672166009747f | train | function | def process(symbol):
#ishares(symbol)
#ishares_to_json(symbol)
ishares_to_redis_set(symbol)
| def process(symbol):
#ishares(symbol)
#ishares_to_json(symbol)
| ishares_to_redis_set(symbol)
| check_args(arg):
group = {'pff','iwv'}
return(arg in group)
def get_filename(symbol):
filename = path_bmtop + ishares_dir + symbol + ".csv"
return(filename)
def process(symbol):
#ishares(symbol)
#ishares_to_json(symbol)
| 64 | 64 | 27 | 18 | 46 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | process | process | 70 | 73 | 70 | 72 | bf1d81cca605b72ea7439e73616e79f95c64d012 | bigcode/the-stack | train |
07d79284381a4b272ee0ae78 | train | function | def arg_process():
default = 'pff'
num = len(sys.argv)
if num > 1:
arg = sys.argv[1]
else:
arg = default
val = check_args(arg)
if val:
symbol = arg
else:
symbol = default
return(symbol)
| def arg_process():
| default = 'pff'
num = len(sys.argv)
if num > 1:
arg = sys.argv[1]
else:
arg = default
val = check_args(arg)
if val:
symbol = arg
else:
symbol = default
return(symbol)
| '}
return(arg in group)
def get_filename(symbol):
filename = path_bmtop + ishares_dir + symbol + ".csv"
return(filename)
def process(symbol):
#ishares(symbol)
#ishares_to_json(symbol)
ishares_to_redis_set(symbol)
def arg_process():
| 64 | 64 | 69 | 4 | 60 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | arg_process | arg_process | 75 | 87 | 75 | 75 | 9a02b6d6cc18abc9d9495ae49051de139be0ecac | bigcode/the-stack | train |
1c70a4e14510985206733a95 | train | function | def check_args(arg):
group = {'pff','iwv'}
return(arg in group)
| def check_args(arg):
| group = {'pff','iwv'}
return(arg in group)
| , sep=',')
tseries = df['Ticker']
tickers = tseries.values
tickers = map(str.lower, tickers)
tickers = tuple(tickers)
for i, name in enumerate(tickers):
util.redis_set_write(key,tickers[i])
def check_args(arg):
| 64 | 64 | 21 | 5 | 59 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | check_args | check_args | 62 | 64 | 62 | 62 | e13551650c9f0db10933746fd056724a6986df31 | bigcode/the-stack | train |
7a640f06fee65f92cec621eb | train | function | def ishares(symbol):
filename = get_filename(symbol)
df = pd.read_csv(filename, sep=',')
tseries = df['Ticker']
tickers = tseries.values
nseries = df['Name']
names = nseries.values
# convert strings in array to lowercase
tickers = map(str.lower, tickers)
tickers = tuple(tickers)
... | def ishares(symbol):
| filename = get_filename(symbol)
df = pd.read_csv(filename, sep=',')
tseries = df['Ticker']
tickers = tseries.values
nseries = df['Name']
names = nseries.values
# convert strings in array to lowercase
tickers = map(str.lower, tickers)
tickers = tuple(tickers)
#names = map(str.lowe... | )
d = {}
for s, n in zip(symbols, names):
d[s] = n
myjson = json.dumps(d)
print(myjson)
# Read the company name and symbol from a csv file
# and write it out to some other format
def ishares(symbol):
| 64 | 64 | 117 | 5 | 58 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | ishares | ishares | 33 | 46 | 33 | 33 | e16adc729e5eed4f537c4114c531d11fe85fe1b6 | bigcode/the-stack | train |
9fa52c68f35bccb79e108de9 | train | function | def ishares_to_json(filename):
filename = get_filename(symbol)
df = pd.read_csv(filename, sep=',')
sseries = df['Ticker']
svalues = sseries.values
# convert strings in array to lowercase
svlc = map(str.lower, svalues)
symbols = tuple(svlc)
nseries = df['Name']
nvalues = nseries.val... | def ishares_to_json(filename):
| filename = get_filename(symbol)
df = pd.read_csv(filename, sep=',')
sseries = df['Ticker']
svalues = sseries.values
# convert strings in array to lowercase
svlc = map(str.lower, svalues)
symbols = tuple(svlc)
nseries = df['Name']
nvalues = nseries.values
names = tuple(nvalues)
... |
from bluemesa.redis import util
path_bmtop = os.environ['BMTOP']
ishares_dir = "/equity-etf/data/ishares/"
# Read the company name and symbol from a csv file
# and write the data out to json
def ishares_to_json(filename):
| 64 | 64 | 129 | 7 | 56 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | ishares_to_json | ishares_to_json | 12 | 29 | 12 | 12 | 6d22da389462c85fe00afaa635f2fa8f43a41340 | bigcode/the-stack | train |
e2b8deb787f41845c57cf3f6 | train | function | def get_filename(symbol):
filename = path_bmtop + ishares_dir + symbol + ".csv"
return(filename)
| def get_filename(symbol):
| filename = path_bmtop + ishares_dir + symbol + ".csv"
return(filename)
| tickers = map(str.lower, tickers)
tickers = tuple(tickers)
for i, name in enumerate(tickers):
util.redis_set_write(key,tickers[i])
def check_args(arg):
group = {'pff','iwv'}
return(arg in group)
def get_filename(symbol):
| 64 | 64 | 26 | 5 | 59 | stormp/bluemesa | py/bluemesa/groups/ishares.py | Python | get_filename | get_filename | 66 | 68 | 66 | 66 | 54942b7b2100bfe8ba10cf9d2c395c8fb0f54d2e | bigcode/the-stack | train |
8c6b30bc3ce7b86e0bd2f316 | train | function | def loadProtocol(protocolName):
# add proper radio protocols here
if protocolName == 'CC11xx':
from protocol.CC11xx import CC11xx as protocolCls
# benchmark protocols
elif protocolName == 'bench_GMSK':
from protocol.benchmark.bench_GMSK import Bench_GMSK as protocolCls
elif protocol... | def loadProtocol(protocolName):
# add proper radio protocols here
| if protocolName == 'CC11xx':
from protocol.CC11xx import CC11xx as protocolCls
# benchmark protocols
elif protocolName == 'bench_GMSK':
from protocol.benchmark.bench_GMSK import Bench_GMSK as protocolCls
elif protocolName == 'bench_BPSK':
from protocol.benchmark.bench_BPSK impor... | # Copyright: (c) 2021, Edwin G. W. Peters
def loadProtocol(protocolName):
# add proper radio protocols here
| 31 | 64 | 185 | 14 | 16 | mugpahug/pycu-sdr | pyCuSDR/protocol/loadProtocol.py | Python | loadProtocol | loadProtocol | 3 | 20 | 3 | 4 | 5a435a430711c8066c0b4358bf0c1f9eb2cbdd27 | bigcode/the-stack | train |
6210142b51a3f26efe38b71d | train | class | class BColors:
header = "\033[95m"
okgreen = "\033[92m"
warning = "\033[93m"
fail = "\033[91m"
endc = "\033[0m"
| class BColors:
| header = "\033[95m"
okgreen = "\033[92m"
warning = "\033[93m"
fail = "\033[91m"
endc = "\033[0m"
| class BColors:
| 4 | 64 | 51 | 4 | 0 | weastur/dikort | dikort/print.py | Python | BColors | BColors | 1 | 6 | 1 | 1 | 7a71f88639a7c478d2814a75d9959054596e3a23 | bigcode/the-stack | train |
3afcfbcd508788ebedd73a19 | train | function | def print_success(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.okgreen)
| def print_success(*args, sep=" ", end="\n"):
| _print_formatted(*args, sep=sep, end=end, formatter=BColors.okgreen)
| print_formatted(*args, sep=sep, end=end, formatter=BColors.fail)
def print_warning(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.warning)
def print_success(*args, sep=" ", end="\n"):
| 64 | 64 | 34 | 13 | 51 | weastur/dikort | dikort/print.py | Python | print_success | print_success | 21 | 22 | 21 | 21 | a24a129ce9e3c642cddbe2de2aefa489884c7c57 | bigcode/the-stack | train |
4b6e8a0dcc898b0aca492d6e | train | function | def print_warning(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.warning)
| def print_warning(*args, sep=" ", end="\n"):
| _print_formatted(*args, sep=sep, end=end, formatter=BColors.warning)
| print_formatted(*args, sep=sep, end=end, formatter=BColors.header)
def print_error(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.fail)
def print_warning(*args, sep=" ", end="\n"):
| 64 | 64 | 33 | 13 | 51 | weastur/dikort | dikort/print.py | Python | print_warning | print_warning | 17 | 18 | 17 | 17 | 3a6de5055dc9365fd1a96ca9d31e0f274c791627 | bigcode/the-stack | train |
6cb3e39c26ef05597ed50c99 | train | function | def print_header(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.header)
| def print_header(*args, sep=" ", end="\n"):
| _print_formatted(*args, sep=sep, end=end, formatter=BColors.header)
| class BColors:
header = "\033[95m"
okgreen = "\033[92m"
warning = "\033[93m"
fail = "\033[91m"
endc = "\033[0m"
def print_header(*args, sep=" ", end="\n"):
| 64 | 64 | 33 | 13 | 51 | weastur/dikort | dikort/print.py | Python | print_header | print_header | 9 | 10 | 9 | 9 | 44f72d595dbf1ec28bb9edd4be576521a218a393 | bigcode/the-stack | train |
d80b661d218e470632889e57 | train | function | def print_error(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.fail)
| def print_error(*args, sep=" ", end="\n"):
| _print_formatted(*args, sep=sep, end=end, formatter=BColors.fail)
| fail = "\033[91m"
endc = "\033[0m"
def print_header(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.header)
def print_error(*args, sep=" ", end="\n"):
| 64 | 64 | 33 | 13 | 51 | weastur/dikort | dikort/print.py | Python | print_error | print_error | 13 | 14 | 13 | 13 | 4ed926e25144e7a35f86646215973efe8dc6d988 | bigcode/the-stack | train |
d3a21c2634e541cfb6f9a4da | train | function | def _print_formatted(*args, sep=" ", end="\n", formatter=None):
line = sep.join(args)
print(f"{formatter}{line}{BColors.endc}", end=end)
| def _print_formatted(*args, sep=" ", end="\n", formatter=None):
| line = sep.join(args)
print(f"{formatter}{line}{BColors.endc}", end=end)
| sep=sep, end=end, formatter=BColors.warning)
def print_success(*args, sep=" ", end="\n"):
_print_formatted(*args, sep=sep, end=end, formatter=BColors.okgreen)
def _print_formatted(*args, sep=" ", end="\n", formatter=None):
| 64 | 64 | 41 | 18 | 46 | weastur/dikort | dikort/print.py | Python | _print_formatted | _print_formatted | 25 | 27 | 25 | 25 | bc260f3d888f9bad4de073a0d52486085ea3a900 | bigcode/the-stack | train |
c843cbb6b49692ccd412989f | train | class | class Migration(migrations.Migration):
dependencies = [
('gel2mdt', '0019_auto_20180711_0552'),
]
operations = [
migrations.AddField(
model_name='gelinterpretationreport',
name='has_germline_variant',
field=models.BooleanField(default=False),
),
... | class Migration(migrations.Migration):
| dependencies = [
('gel2mdt', '0019_auto_20180711_0552'),
]
operations = [
migrations.AddField(
model_name='gelinterpretationreport',
name='has_germline_variant',
field=models.BooleanField(default=False),
),
migrations.AddField(
... | # Generated by Django 2.0.1 on 2018-10-08 10:44
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 199 | 7 | 30 | pdl30/GeL2MDT | gelweb/gel2mdt/migrations/0020_auto_20181008_1044.py | Python | Migration | Migration | 6 | 33 | 6 | 7 | 1bbff9e4cc28f27261c44affb1e1574a19c076b3 | bigcode/the-stack | train |
7c97537addbaa3925d545ce4 | train | class | class PHPFPMCheck(AgentCheck):
"""
Tracks basic php-fpm metrics via the status module
Requires php-fpm pools to have the status option.
See http://www.php.net/manual/de/install.fpm.configuration.php#pm.status-path for more details
"""
SERVICE_CHECK_NAME = 'php_fpm.can_ping'
GAUGES = {
... | class PHPFPMCheck(AgentCheck):
| """
Tracks basic php-fpm metrics via the status module
Requires php-fpm pools to have the status option.
See http://www.php.net/manual/de/install.fpm.configuration.php#pm.status-path for more details
"""
SERVICE_CHECK_NAME = 'php_fpm.can_ping'
GAUGES = {
'listen queue': 'php_fpm.li... | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# 3p
import requests
# project
from checks import AgentCheck
from util import headers
class PHPFPMCheck(AgentCheck):
| 64 | 256 | 925 | 9 | 54 | joewilliams/dd-agent | checks.d/php_fpm.py | Python | PHPFPMCheck | PHPFPMCheck | 13 | 123 | 13 | 13 | c04e7d44905b8bab3adfc27b87c394d2500a9cfd | bigcode/the-stack | train |
c7b1b4860b40c645e995b301 | train | class | class TestServer:
def teardown_method(self, method) -> None:
if self.server is not None:
self.server.stop()
def test_should_call_get_action(self):
# given
self._start_http_server(JsonGet("/test", lambda params: {'status': 'ok'}))
# when
result = requests.ge... | class TestServer:
| def teardown_method(self, method) -> None:
if self.server is not None:
self.server.stop()
def test_should_call_get_action(self):
# given
self._start_http_server(JsonGet("/test", lambda params: {'status': 'ok'}))
# when
result = requests.get(f"http://localhos... | import logging
import pytest
import requests
from .server import JsonGet, http_server, Action, JsonPost, Redirect, StaticResources
logging.basicConfig()
PORT = 9999
class TestServer:
| 43 | 256 | 1,198 | 4 | 38 | rzarajczyk/actions-server | src/actions_server/test_server.py | Python | TestServer | TestServer | 13 | 163 | 13 | 14 | 7d7acdf14b2ef784e8a27fdf7d93c14578bd941f | bigcode/the-stack | train |
14ce1d4ad1e03a5ec7ac85b3 | train | function | def setup_logging(action, level, clear_handlers=False):
root = logging.getLogger()
root.setLevel(logging.DEBUG)
if clear_handlers:
for hdl in root.handlers:
root.removeHandler(hdl)
hdl = logging.StreamHandler()
hdl.setLevel(level)
root.addHandler(hdl)
| def setup_logging(action, level, clear_handlers=False):
| root = logging.getLogger()
root.setLevel(logging.DEBUG)
if clear_handlers:
for hdl in root.handlers:
root.removeHandler(hdl)
hdl = logging.StreamHandler()
hdl.setLevel(level)
root.addHandler(hdl)
| Error:
from configparser import RawConfigParser, NoOptionError
import sys
from traceback import format_exception
from setproctitle import setproctitle
from runscript.lock import assert_lock
logger = logging.getLogger('runscript.cli')
def setup_logging(action, level, clear_handlers=False):
| 64 | 64 | 67 | 11 | 53 | lorien/runscript | runscript/cli.py | Python | setup_logging | setup_logging | 19 | 29 | 19 | 19 | ebb411a3eac439314d1c2b15c7e75ee7aa2b5e94 | bigcode/the-stack | train |
54720d4ad44a0e27dc11e19d | train | function | def process_command_line():
# Use custom excepthook that prints traceback via logging system
# using FATAL level
sys.excepthook = custom_excepthook
# Add current directory to python path
cur_dir = os.path.realpath(os.getcwd())
sys.path.insert(0, cur_dir)
parser = ArgumentParser()
parse... | def process_command_line():
# Use custom excepthook that prints traceback via logging system
# using FATAL level
| sys.excepthook = custom_excepthook
# Add current directory to python path
cur_dir = os.path.realpath(os.getcwd())
sys.path.insert(0, cur_dir)
parser = ArgumentParser()
parser.add_argument('action', type=str)
parser.add_argument('--logging-level', default='debug')
parser.add_argument('-... | .strip() for x in value.split(',')]
else:
return value
def load_config():
cur_dir = os.getcwd()
config_path = os.path.join(cur_dir, 'run.ini')
config = {
'global': {
'search_path': ['grab.script', 'script'],
},
}
if os.path.exists(config_path):
par... | 199 | 200 | 667 | 26 | 173 | lorien/runscript | runscript/cli.py | Python | process_command_line | process_command_line | 78 | 167 | 78 | 80 | 48762641047c0d1752dfb015462f3a7ad124c5c1 | bigcode/the-stack | train |
60ed2aad9890e4f05f7fccc6 | train | function | def normalize_config_value(section, name, value):
if section == 'global' and name == 'search_path':
return [x.strip() for x in value.split(',')]
else:
return value
| def normalize_config_value(section, name, value):
| if section == 'global' and name == 'search_path':
return [x.strip() for x in value.split(',')]
else:
return value
| None
for mod_name in mod_names:
try:
mod_file, mod_path, mod_info = imp.find_module(mod_name, path)
except ImportError:
return False
else:
path = [mod_path]
return True
def normalize_config_value(section, name, value):
| 64 | 64 | 44 | 10 | 53 | lorien/runscript | runscript/cli.py | Python | normalize_config_value | normalize_config_value | 45 | 49 | 45 | 45 | 30ce3a8cfc564a01dfb585e3dc3b34232490e26d | bigcode/the-stack | train |
590bac0fad01794740b1817e | train | function | def load_config():
cur_dir = os.getcwd()
config_path = os.path.join(cur_dir, 'run.ini')
config = {
'global': {
'search_path': ['grab.script', 'script'],
},
}
if os.path.exists(config_path):
parser = RawConfigParser()
parser.read(config_path)
for ... | def load_config():
| cur_dir = os.getcwd()
config_path = os.path.join(cur_dir, 'run.ini')
config = {
'global': {
'search_path': ['grab.script', 'script'],
},
}
if os.path.exists(config_path):
parser = RawConfigParser()
parser.read(config_path)
for section in parser.s... | False
else:
path = [mod_path]
return True
def normalize_config_value(section, name, value):
if section == 'global' and name == 'search_path':
return [x.strip() for x in value.split(',')]
else:
return value
def load_config():
| 64 | 64 | 123 | 4 | 59 | lorien/runscript | runscript/cli.py | Python | load_config | load_config | 52 | 71 | 52 | 52 | f30fc018d5ee27b41513a9933443ae2258c2de26 | bigcode/the-stack | train |
8b256f0b838df6500c787a8b | train | function | def custom_excepthook(etype, evalue, etb):
logging.fatal('\n'.join(format_exception(etype, evalue, etb)))
| def custom_excepthook(etype, evalue, etb):
| logging.fatal('\n'.join(format_exception(etype, evalue, etb)))
| in parser.sections():
if not section in config:
config[section] = {}
for key, val in parser.items(section):
config[section][key] = normalize_config_value(section, key, val)
return config
def custom_excepthook(etype, evalue, etb):
| 64 | 64 | 34 | 15 | 48 | lorien/runscript | runscript/cli.py | Python | custom_excepthook | custom_excepthook | 74 | 75 | 74 | 74 | 238f29f78a4004dea4713f8ad1168fc23821ad67 | bigcode/the-stack | train |
9d0a197d07d6db19f85d7ffc | train | function | def module_is_importable(path):
mod_names = path.split('.')
path = None
for mod_name in mod_names:
try:
mod_file, mod_path, mod_info = imp.find_module(mod_name, path)
except ImportError:
return False
else:
path = [mod_path]
return True
| def module_is_importable(path):
| mod_names = path.split('.')
path = None
for mod_name in mod_names:
try:
mod_file, mod_path, mod_info = imp.find_module(mod_name, path)
except ImportError:
return False
else:
path = [mod_path]
return True
| ):
root = logging.getLogger()
root.setLevel(logging.DEBUG)
if clear_handlers:
for hdl in root.handlers:
root.removeHandler(hdl)
hdl = logging.StreamHandler()
hdl.setLevel(level)
root.addHandler(hdl)
def module_is_importable(path):
| 64 | 64 | 72 | 7 | 57 | lorien/runscript | runscript/cli.py | Python | module_is_importable | module_is_importable | 32 | 42 | 32 | 32 | b019e80c20b9631065db2be7d7901989d1a56a72 | bigcode/the-stack | train |
49646b9ddea7a4e00ea84454 | train | function | def approach1():
d = {}
# O(n)
for w in wordlist:
# O(klogk)
w_s = ''.join(sorted(w))
if d.get(w_s, None):
d[w_s].append(w)
else:
d[w_s] = [w]
for k, v in d.items():
if v:
print(v)
| def approach1():
| d = {}
# O(n)
for w in wordlist:
# O(klogk)
w_s = ''.join(sorted(w))
if d.get(w_s, None):
d[w_s].append(w)
else:
d[w_s] = [w]
for k, v in d.items():
if v:
print(v)
| '''
Print all the anagrams in a list of words
'''
from __future__ import print_function
wordlist = ['abba',
'baba',
'caret',
'cater']
# Using a lookup table
def approach1():
| 51 | 64 | 82 | 4 | 46 | amitsaha/playground | recipes/print_anagrams.py | Python | approach1 | approach1 | 13 | 25 | 13 | 13 | dfc685338e921505aecf4f65b0dcf6f75ff8ee08 | bigcode/the-stack | train |
799e0b105095b01aa7796ef2 | train | function | def point_detecting(img_input,filter_kernel):
size_img_input=img_input.shape
kernel_size=filter_kernel.shape
decenter=int((kernel_size[1]-1)/2)
new_img=np.zeros(img_input.shape)
for i in range(0,size_img_input[0]):
for j in range(0,size_img_input[1]):
H=np.zeros((kernel_s... | def point_detecting(img_input,filter_kernel):
| size_img_input=img_input.shape
kernel_size=filter_kernel.shape
decenter=int((kernel_size[1]-1)/2)
new_img=np.zeros(img_input.shape)
for i in range(0,size_img_input[0]):
for j in range(0,size_img_input[1]):
H=np.zeros((kernel_size[0],kernel_size[1])).astype('int')
... | import cv2
import numpy as np
import copy
import sys
def point_detecting(img_input,filter_kernel):
| 25 | 79 | 265 | 10 | 14 | yunchen-yang/CV_classes | Project3_data/Project3_pointdetecting.py | Python | point_detecting | point_detecting | 6 | 25 | 6 | 6 | d48f13604d2b6f044ffc033c67e5517bd0b37ce5 | bigcode/the-stack | train |
99b624eb63844e8d0414e6d4 | train | function | def thresholding(img_mat,T):
img_t=np.zeros(img_mat.shape).astype('uint8')
for x in range(0,img_mat.shape[0]):
for y in range(0,img_mat.shape[1]):
if abs(img_mat[x,y])>=T:
img_t[x,y]=255
else:
continue
return img_t
| def thresholding(img_mat,T):
| img_t=np.zeros(img_mat.shape).astype('uint8')
for x in range(0,img_mat.shape[0]):
for y in range(0,img_mat.shape[1]):
if abs(img_mat[x,y])>=T:
img_t[x,y]=255
else:
continue
return img_t
| 1):
G[decenter+x,decenter+y]=H[decenter+x,decenter+y]*filter_kernel[decenter+x,decenter+y]
new_img[i,j]=sum(sum(G))
else:
new_img[i,j]=0
return new_img
def thresholding(img_mat,T):
| 64 | 64 | 77 | 7 | 56 | yunchen-yang/CV_classes | Project3_data/Project3_pointdetecting.py | Python | thresholding | thresholding | 27 | 35 | 27 | 27 | e00945aea15310ca4678cdb165a509db017580dc | bigcode/the-stack | train |
775f815608947daa9dd7b213 | train | class | class SpyService(Flask):
def __init__(self, import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
... | class SpyService(Flask):
| def __init__(self, import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
... | from flask import Flask
from .spy import WeChatSpy
from queue import Queue
from threading import Thread
from .command import *
class SpyService(Flask):
| 35 | 106 | 355 | 7 | 28 | ChengxiX/PyWeChatSpy | PyWeChatSpy/service.py | Python | SpyService | SpyService | 8 | 54 | 8 | 8 | c052d16dfbc3f8e81be26a97d3360271ff81941b | bigcode/the-stack | train |
f8a153bc835219b5400de9db | train | function | def main(argv):
"""Builds, trains, and evaluates the model."""
#assert len(argv) == 1
(train, test) = imports85.dataset()
print(train)
print("-----")
print(test)
exit(0)
print("got dataset")
# Switch the labels to units of thousands for better convergence.
def to_thousands(features, labels):
ret... | def main(argv):
| """Builds, trains, and evaluates the model."""
#assert len(argv) == 1
(train, test) = imports85.dataset()
print(train)
print("-----")
print(test)
exit(0)
print("got dataset")
# Switch the labels to units of thousands for better convergence.
def to_thousands(features, labels):
return features, la... | License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on... | 195 | 195 | 651 | 4 | 190 | grebtsew/Object-and-Facial-detection-in-python | Learning & Documentation/Create Models in Tensorflow/linear_regression.py | Python | main | main | 30 | 106 | 30 | 30 | 3827c9e1dff5462623139d6defea7500d66541d1 | bigcode/the-stack | train |
3cf96f93cddba88bbeea5d34 | train | class | class PillarFeatureNet(nn.Module):
def __init__(self,
num_input_features=4,
use_norm=True,
num_filters=(64,),
with_distance=False,
voxel_size=(0.2, 0.2, 4),
pc_range=(0, -40, -3, 70.4, 40, 1)):
"""
... | class PillarFeatureNet(nn.Module):
| def __init__(self,
num_input_features=4,
use_norm=True,
num_filters=(64,),
with_distance=False,
voxel_size=(0.2, 0.2, 4),
pc_range=(0, -40, -3, 70.4, 40, 1)):
"""
Pillar Feature Net.
The net... | d(in_channels, self.units, 1, bias=False)
self.bn = nn.BatchNorm2d(self.units, eps=1e-03, momentum=0.01)
def forward(self, inputs):
# x = self.linear(inputs)
x = self.conv(inputs)
# x = self.norm(x.permute(0, 2, 1).contiguous()).permute(0, 2, 1).contiguous()
x = self.bn(x)
... | 256 | 256 | 1,159 | 8 | 247 | guochunhe/Vitis-AI | models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/pytorch/models/pointpillars.py | Python | PillarFeatureNet | PillarFeatureNet | 108 | 208 | 108 | 108 | bb72c2d051685c17a7484e905e8dea4f591215d0 | bigcode/the-stack | train |
316a517644a671c20e8b795e | train | class | class PointPillarsScatter(nn.Module):
def __init__(self,
output_shape,
num_input_features=64):
"""
Point Pillar's Scatter.
Converts learned features from dense tensor to sparse pseudo image. This replaces SECOND's
second.pytorch.voxelnet.SparseMiddle... | class PointPillarsScatter(nn.Module):
| def __init__(self,
output_shape,
num_input_features=64):
"""
Point Pillar's Scatter.
Converts learned features from dense tensor to sparse pseudo image. This replaces SECOND's
second.pytorch.voxelnet.SparseMiddleExtractor.
:param output_shape... | regard to whether pillar was empty. Need to ensure that
# empty pillars remain set to zeros.
voxel_count = features.shape[1]
mask = get_paddings_indicator(num_voxels, voxel_count, axis=0)
mask = torch.unsqueeze(mask, -1).type_as(features)
features *= mask
features = fea... | 132 | 132 | 443 | 9 | 123 | guochunhe/Vitis-AI | models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/pytorch/models/pointpillars.py | Python | PointPillarsScatter | PointPillarsScatter | 211 | 262 | 211 | 211 | 0eedb9f3a53e11af347f8d68087c00ac0ce5b815 | bigcode/the-stack | train |
ec8167d28b468bf5f9f92218 | train | class | class PFNLayer(nn.Module):
def __init__(self,
in_channels,
out_channels,
use_norm=True,
last_layer=False):
"""
Pillar Feature Net Layer.
The Pillar Feature Net could be composed of a series of these layers, but the PointPill... | class PFNLayer(nn.Module):
| def __init__(self,
in_channels,
out_channels,
use_norm=True,
last_layer=False):
"""
Pillar Feature Net Layer.
The Pillar Feature Net could be composed of a series of these layers, but the PointPillars paper results only
... | OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF O... | 167 | 167 | 557 | 7 | 159 | guochunhe/Vitis-AI | models/AI-Model-Zoo/VAI-1.3-Model-Zoo-Code/PyTorch/pt_pointpillars_kitti_12000_100_10.8G_1.3/code/train/second/pytorch/models/pointpillars.py | Python | PFNLayer | PFNLayer | 51 | 105 | 51 | 51 | 083056d253f328c9b00bb7df1ea30496b837804a | bigcode/the-stack | train |
d65ec6dbe691a761181ba3cc | train | function | def filename_to_object(filename):
"""
Given a filename create a defoe.generic_xml.document.Document. If
an error arises during its creation this is caught and returned as
a string.
:param filename: filename
:type filename: str or unicode
:return: tuple of form (Document, None) or (filename,... | def filename_to_object(filename):
| """
Given a filename create a defoe.generic_xml.document.Document. If
an error arises during its creation this is caught and returned as
a string.
:param filename: filename
:type filename: str or unicode
:return: tuple of form (Document, None) or (filename, error message),
if there was ... | """
Given a filename create a defoe.generic_xml.document.Document.
"""
from defoe.generic_xml.document import Document
def filename_to_object(filename):
| 29 | 64 | 141 | 6 | 22 | akrause2014/defoe | defoe/generic_xml/setup.py | Python | filename_to_object | filename_to_object | 8 | 25 | 8 | 8 | 83dede926460bd586c3f7ed6c6efbab8c2730b69 | bigcode/the-stack | train |
d8c87dc4ec6c0370550eb4e4 | train | function | def weight_average(my_list=[]):
if my_list == []:
return 0
num = 0
den = 0
for t in my_list:
num += t[0] * t[1]
den += t[1]
return num / den
| def weight_average(my_list=[]):
| if my_list == []:
return 0
num = 0
den = 0
for t in my_list:
num += t[0] * t[1]
den += t[1]
return num / den
| #!/usr/bin/python3
def weight_average(my_list=[]):
| 13 | 64 | 63 | 7 | 5 | gogomillan/holbertonschool-higher_level_programming | 0x04-python-more_data_structures/100-weight_average.py | Python | weight_average | weight_average | 2 | 10 | 2 | 2 | a50c3be4c711e897f73c7f5c017ed2b9fc03dc87 | bigcode/the-stack | train |
5566ab87359ebf7eec239ebd | train | class | class PropertyGeometry(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,). T... | class PropertyGeometry(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... | """
Precisely APIs
Enhance & enrich your data, applications, business processes, and workflows with rich location, information, and identify APIs. # noqa: E501
The version of the OpenAPI document: 11.9.3
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F4... | 184 | 256 | 1,973 | 6 | 177 | PreciselyData/PreciselyAPIsSDK-Python | com/precisely/apis/model/property_geometry.py | Python | PropertyGeometry | PropertyGeometry | 33 | 265 | 33 | 33 | 05adedaf8f1ced16d2bbfc8177728f0ecf348795 | bigcode/the-stack | train |
c41cbc4d716e5aed81e05807 | train | class | class GridSearch(LineSearch):
def init_search(self):
'''
convert a dict of param ranges into
a list of cartesian products of param_range
e.g. {'a': [1,2], 'b': [3]} into
[{'a': 1, 'b': 3}, {'a': 2, 'b': 3}]
note that this is order-preserving, as required by design
... | class GridSearch(LineSearch):
| def init_search(self):
'''
convert a dict of param ranges into
a list of cartesian products of param_range
e.g. {'a': [1,2], 'b': [3]} into
[{'a': 1, 'b': 3}, {'a': 2, 'b': 3}]
note that this is order-preserving, as required by design
'''
range_vals = ... | import copy
import itertools
from rl.hyperoptimizer.line_search import LineSearch
class GridSearch(LineSearch):
| 22 | 64 | 155 | 6 | 15 | AsimKhan2019/OpenAI-Lab | rl/hyperoptimizer/grid_search.py | Python | GridSearch | GridSearch | 6 | 21 | 6 | 7 | 92466e26005bbaf92a3378387c743067e7f665f3 | bigcode/the-stack | train |
d517651af4e0be8c7a941f88 | train | class | class ApiConfig(AppConfig):
name = 'api'
| class ApiConfig(AppConfig):
| name = 'api'
| from django.apps import AppConfig
class ApiConfig(AppConfig):
| 13 | 64 | 12 | 6 | 6 | ES2-UFPI/404-api | api/apps.py | Python | ApiConfig | ApiConfig | 4 | 5 | 4 | 4 | 1f78be181b7b8f8ecc8edf4baf42ba537f230c5b | bigcode/the-stack | train |
445a7d32b92bf80083915156 | train | class | class BillRequestSubmitSmRespCallbackingTestCases(RouterPBProxy, SmppServerTestCases,
SubmitSmTestCaseTools):
@defer.inlineCallbacks
def test_unrated_route_limited_submit_sm_count(self):
yield self.connect('127.0.0.1', self.pbPort)
mt_c = MtMessag... | class BillRequestSubmitSmRespCallbackingTestCases(RouterPBProxy, SmppServerTestCases,
SubmitSmTestCaseTools):
@defer.inlineCallbacks
| def test_unrated_route_limited_submit_sm_count(self):
yield self.connect('127.0.0.1', self.pbPort)
mt_c = MtMessagingCredential()
mt_c.setQuota('balance', 2.0)
mt_c.setQuota('submit_sm_count', 10)
user = User(1, Group(1), 'username', 'password', mt_c)
yield self.prepa... | _connector(add_route = False)
# Will not add connector to SMPPClientManagerPB
yield self.SMPPClientManagerPBProxy.connect('127.0.0.1', self.CManagerPort)
# Bind and send a SMS MT through smpps interface
self._bind_smpps(self.u1)
self.smpps_proto.dataReceived(self.encoder.encode... | 256 | 256 | 1,519 | 35 | 221 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | BillRequestSubmitSmRespCallbackingTestCases | BillRequestSubmitSmRespCallbackingTestCases | 296 | 431 | 296 | 299 | 808deebd90b57e5d68b246886aaa1b3ea077def7 | bigcode/the-stack | train |
7d34b28f3c3a083e53b44367 | train | class | class SubmitSmDeliveryTestCases(RouterPBProxy, SmppServerTestCases):
@defer.inlineCallbacks
def provision_user_connector(self, add_route = True):
# provision user
g1 = Group(1)
yield self.group_add(g1)
self.c1 = SmppClientConnector(id_generator())
u1_password = 'password... | class SubmitSmDeliveryTestCases(RouterPBProxy, SmppServerTestCases):
@defer.inlineCallbacks
| def provision_user_connector(self, add_route = True):
# provision user
g1 = Group(1)
yield self.group_add(g1)
self.c1 = SmppClientConnector(id_generator())
u1_password = 'password'
self.u1 = User(1, g1, 'username', u1_password)
yield self.user_add(self.u1)
... | pps_proto.system_id = user.username
self.smpps_factory.addBoundConnection(self.smpps_proto, user)
class SMPPClientTestCases(SmppServerTestCases):
@defer.inlineCallbacks
def setUp(self, interceptorpb_client = None):
yield SmppServerTestCases.setUp(self, interceptorpb_client)
# Add inte... | 256 | 256 | 1,519 | 24 | 232 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | SubmitSmDeliveryTestCases | SubmitSmDeliveryTestCases | 158 | 294 | 158 | 160 | c666a415fb361eda4689bfb19fdd1c98127ec1a3 | bigcode/the-stack | train |
e2fc7a4e7e41741d32e530d9 | train | class | class LastProtoSMPPServerFactory(SMPPServerFactory):
"""This a SMPPServerFactory used to keep track of the last protocol instance for
testing purpose"""
lastProto = None
def buildProtocol(self, addr):
self.lastProto = SMPPServerFactory.buildProtocol(self, addr)
return self.lastProto
| class LastProtoSMPPServerFactory(SMPPServerFactory):
| """This a SMPPServerFactory used to keep track of the last protocol instance for
testing purpose"""
lastProto = None
def buildProtocol(self, addr):
self.lastProto = SMPPServerFactory.buildProtocol(self, addr)
return self.lastProto
| .protocols.smpp.test.smsc_simulator import *
@defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
waitDeferred = defer.Deferred()
reactor.callLater(seconds, waitDeferred.callback, None)
yield waitDeferred
class LastProtoSMPPServerFactory(SMPPServerFactory):
| 64 | 64 | 70 | 12 | 51 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | LastProtoSMPPServerFactory | LastProtoSMPPServerFactory | 33 | 40 | 33 | 33 | 4c42f1ec83ce68ea2090d2e34b7606d3c6408b8a | bigcode/the-stack | train |
8c357a8717d73df0971b61c4 | train | class | class LastProtoSMPPClientFactory(SMPPClientFactory):
"""This a SMPPClientFactory used to keep track of the last protocol instance for
testing purpose"""
lastProto = None
def buildProtocol(self, addr):
self.lastProto = SMPPClientFactory.buildProtocol(self, addr)
return self.lastProto
| class LastProtoSMPPClientFactory(SMPPClientFactory):
| """This a SMPPClientFactory used to keep track of the last protocol instance for
testing purpose"""
lastProto = None
def buildProtocol(self, addr):
self.lastProto = SMPPClientFactory.buildProtocol(self, addr)
return self.lastProto
| ServerFactory used to keep track of the last protocol instance for
testing purpose"""
lastProto = None
def buildProtocol(self, addr):
self.lastProto = SMPPServerFactory.buildProtocol(self, addr)
return self.lastProto
class LastProtoSMPPClientFactory(SMPPClientFactory):
| 64 | 64 | 70 | 12 | 51 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | LastProtoSMPPClientFactory | LastProtoSMPPClientFactory | 41 | 48 | 41 | 41 | 37c383ecddcee61b607210d1f03fa11d3e8a3068 | bigcode/the-stack | train |
bd7523f4252925287c04638f | train | class | class SmppServerTestCases(HappySMSCTestCase):
@defer.inlineCallbacks
def setUp(self, interceptorpb_client = None):
yield HappySMSCTestCase.setUp(self)
self.encoder = pdu_encoding.PDUEncoder()
# SMPPServerConfig init
self.smpps_config = SMPPServerConfig()
# Portal init... | class SmppServerTestCases(HappySMSCTestCase):
@defer.inlineCallbacks
| def setUp(self, interceptorpb_client = None):
yield HappySMSCTestCase.setUp(self)
self.encoder = pdu_encoding.PDUEncoder()
# SMPPServerConfig init
self.smpps_config = SMPPServerConfig()
# Portal init
_portal = portal.Portal(SmppsRealm(self.smpps_config.id, self.pbR... | s.smpp.test.smsc_simulator import *
@defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
waitDeferred = defer.Deferred()
reactor.callLater(seconds, waitDeferred.callback, None)
yield waitDeferred
class LastProtoSMPPServerFactory(SMPPServerFactory):
"""This a SMPPServerFactory used to keep t... | 210 | 210 | 703 | 19 | 190 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | SmppServerTestCases | SmppServerTestCases | 50 | 132 | 50 | 52 | c4ef685c37fe3631582fcd665086d04f2d942eee | bigcode/the-stack | train |
0669f2b1114dd3abaf07f733 | train | function | @defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
waitDeferred = defer.Deferred()
reactor.callLater(seconds, waitDeferred.callback, None)
yield waitDeferred
| @defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
| waitDeferred = defer.Deferred()
reactor.callLater(seconds, waitDeferred.callback, None)
yield waitDeferred
| SM, DataSM
from jasmin.protocols.smpp.operations import SMPPOperationFactory
from twisted.cred import portal
from twisted.test import proto_helpers
from jasmin.protocols.smpp.test.smsc_simulator import *
@defer.inlineCallbacks
def waitFor(seconds):
# Wait seconds
| 64 | 64 | 41 | 16 | 48 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | waitFor | waitFor | 26 | 31 | 26 | 28 | 624a1ef36e842be6cd9e5368b4d6e4926c3b099d | bigcode/the-stack | train |
fc5c3390f2ea1bede7912cb2 | train | class | class SubmitSmRespDeliveryTestCases(RouterPBProxy, SMPPClientTestCases,
SubmitSmTestCaseTools):
"""These test cases will cover different scenarios of SMPPs behaviour when delivering
submit_sm and:
- Receiving ESME_ROK: depending on the registered_delivery, sen... | class SubmitSmRespDeliveryTestCases(RouterPBProxy, SMPPClientTestCases,
SubmitSmTestCaseTools):
| """These test cases will cover different scenarios of SMPPs behaviour when delivering
submit_sm and:
- Receiving ESME_ROK: depending on the registered_delivery, send or not a receipt to SMPPc
- Receiving an Error:
1# send SMPPc a deliver_sm containing error
2# Dont bill user if is defined
... | mitSmPDU))
# Wait 1 seconds for submit_sm_resp
yield waitFor(1)
yield self.stopSmppClientConnectors()
# Run tests
# Assert quotas were updated
callArgs = assertionUser.mt_credential.updateQuota.call_args_list
self.assertEquals(callArgs[0][0][0], 'balance')
... | 256 | 256 | 2,325 | 25 | 231 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | SubmitSmRespDeliveryTestCases | SubmitSmRespDeliveryTestCases | 433 | 625 | 433 | 434 | f84daeedfdf46ee56913f6361c58ea210ba476c6 | bigcode/the-stack | train |
7a9fb457809391cb3a0a9427 | train | class | class SMPPClientTestCases(SmppServerTestCases):
@defer.inlineCallbacks
def setUp(self, interceptorpb_client = None):
yield SmppServerTestCases.setUp(self, interceptorpb_client)
# Add interceptorpb_client to smpp client manager
if interceptorpb_client is not None:
self.clien... | class SMPPClientTestCases(SmppServerTestCases):
@defer.inlineCallbacks
| def setUp(self, interceptorpb_client = None):
yield SmppServerTestCases.setUp(self, interceptorpb_client)
# Add interceptorpb_client to smpp client manager
if interceptorpb_client is not None:
self.clientManager_f.addInterceptorPBClient(interceptorpb_client)
# SMPPClien... | SMPPSessionStates.BOUND_TRX
self.smpps_proto.user = user
self.smpps_proto.system_id = user.username
self.smpps_factory.addBoundConnection(self.smpps_proto, user)
class SMPPClientTestCases(SmppServerTestCases):
@defer.inlineCallbacks
| 64 | 64 | 209 | 20 | 44 | balsagoth/jasmin | jasmin/routing/test/test_router_smpps.py | Python | SMPPClientTestCases | SMPPClientTestCases | 134 | 156 | 134 | 136 | b61c662b0596797950d4bda777371b8046bcae80 | bigcode/the-stack | train |
94eac7a71ee98f23e572ca9e | train | class | class RecentChatSerializer(serializers.ModelSerializer):
recentMessages_ReceivedAndSend = serializers.SerializerMethodField('get_recentMessageRandS')
class Meta:
fields= ['username','recentMessages_ReceivedAndSend']
model = Person
def get_recentMessageRandS(self,obj):
query = Chat.objects.filter(Q(user_recevi... | class RecentChatSerializer(serializers.ModelSerializer):
| recentMessages_ReceivedAndSend = serializers.SerializerMethodField('get_recentMessageRandS')
class Meta:
fields= ['username','recentMessages_ReceivedAndSend']
model = Person
def get_recentMessageRandS(self,obj):
query = Chat.objects.filter(Q(user_recevied=obj.id) | Q(user_sent=obj.id)).order_by('-sent_time')
... | =self.context.id)
return user.id
def get_userName(self,obj):
user=Person.objects.get(id=self.context.id)
return user.username
# def get_receivingUser(self,obj):
# print(self.kwargs['pk'])
# user = Person.objects.get(id=self.kwargs['pk'])
# return user
class RecentChatSerializer(serializers.ModelSerializ... | 81 | 81 | 273 | 8 | 72 | amal-san/ChatStreak | api/serializers.py | Python | RecentChatSerializer | RecentChatSerializer | 60 | 89 | 60 | 60 | c45a4b189eb211ccb666d83ebb56586fc1bce755 | bigcode/the-stack | train |
70ed51b5a231a6baca110af0 | train | class | class UserSerializerWithToken(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)
def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
... | class UserSerializerWithToken(serializers.ModelSerializer):
| token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)
def get_token(self, obj):
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(obj)
token = jwt... | Meta:
fields = '__all__'
model = GroupChat
def get_sender(self,obj):
return GroupChat.objects.user.values()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id','username','password')
class UserSerializerWithToken(serializers.ModelSerializer):
| 64 | 64 | 150 | 9 | 55 | amal-san/ChatStreak | api/serializers.py | Python | UserSerializerWithToken | UserSerializerWithToken | 168 | 191 | 168 | 169 | 5d0a85bd98f7fe442bb5eb774c18b9d8ad4c916d | bigcode/the-stack | train |
9ee6de2fee127a680535d2df | train | class | class PersonSerializer(serializers.ModelSerializer):
recentMessages_ReceivedAndSend = serializers.SerializerMethodField('get_recentMessageRandS')
message_send = serializers.SerializerMethodField('get_messageSent')
message_recieved = serializers.SerializerMethodField('get_messageRecieved')
message_recieved_count = s... | class PersonSerializer(serializers.ModelSerializer):
| recentMessages_ReceivedAndSend = serializers.SerializerMethodField('get_recentMessageRandS')
message_send = serializers.SerializerMethodField('get_messageSent')
message_recieved = serializers.SerializerMethodField('get_messageRecieved')
message_recieved_count = serializers.SerializerMethodField('get_messageRecieved... | messageRandSset = set(messageRandSlist)
for q2 in query:
if tuple((q2.user_sent_id ,q2.user_recevied_id)) in messageRandSset:
queryset.append(q2)
try:
messageRandSset.remove(tuple((q2.user_sent_id,q2.user_recevied_id)))
messageRandSset.remove(tuple((q2.user_recevied_id,q2.user_sent_id)))
... | 143 | 143 | 477 | 7 | 136 | amal-san/ChatStreak | api/serializers.py | Python | PersonSerializer | PersonSerializer | 93 | 144 | 93 | 93 | 2e8fda7e1fa7ef04c43e7239f19bb1eabe0b8472 | bigcode/the-stack | train |
da806170dbef5b913aae8453 | train | class | class MessageSerializer(serializers.ModelSerializer):
user_id = serializers.SerializerMethodField('get_userId')
user_sent_username = serializers.CharField(source='user_sent.username')
user_recevied_username =serializers.CharField(source='user_recevied.username')
username = serializers.SerializerMethodField('get_use... | class MessageSerializer(serializers.ModelSerializer):
| user_id = serializers.SerializerMethodField('get_userId')
user_sent_username = serializers.CharField(source='user_sent.username')
user_recevied_username =serializers.CharField(source='user_recevied.username')
username = serializers.SerializerMethodField('get_userName')
class Meta:
fields = ( 'user_id','userna... | .settings import api_settings
from api.models import Person
from django.http import JsonResponse
from django.forms.models import model_to_dict
import json
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id','username','password')
class MessageSerializer... | 63 | 64 | 165 | 7 | 56 | amal-san/ChatStreak | api/serializers.py | Python | MessageSerializer | MessageSerializer | 26 | 47 | 26 | 26 | d32eec05719a1f4b2d09808a53d11eaa7c3f18fe | bigcode/the-stack | train |
67986ca57de8c7aa99415880 | train | class | class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id','username','password')
| class UserSerializer(serializers.ModelSerializer):
| class Meta:
model = Person
fields = ('id','username','password')
| _framework import serializers
from .models import *
from django.db.models import Q
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from api.models import Person
from django.http import JsonResponse
from django.forms.models import model_to_dict
import json
class UserSerializer... | 64 | 64 | 26 | 7 | 56 | amal-san/ChatStreak | api/serializers.py | Python | UserSerializer | UserSerializer | 15 | 19 | 15 | 16 | d518b97a2e9cc177aa8089f8845e6a2ae46d871d | bigcode/the-stack | train |
1b8e00b5ef6dbb94a4e11023 | train | class | class GroupSerializer(serializers.ModelSerializer):
sender= serializers.SerializerMethodField('get_sender')
class Meta:
fields = '__all__'
model = GroupChat
def get_sender(self,obj):
return GroupChat.objects.user.values()
| class GroupSerializer(serializers.ModelSerializer):
| sender= serializers.SerializerMethodField('get_sender')
class Meta:
fields = '__all__'
model = GroupChat
def get_sender(self,obj):
return GroupChat.objects.user.values()
| in=id_list).order_by('-sent_time')
return queryRandS.values( 'id','user_sent_id','user_recevied_id',
'user_sent__username','user_recevied__username',
'message','sent_time','delivered_time')
class GroupSerializer(serializers.ModelSerializer):
| 63 | 64 | 49 | 7 | 56 | amal-san/ChatStreak | api/serializers.py | Python | GroupSerializer | GroupSerializer | 148 | 157 | 148 | 149 | c94e7ec58cf46c2659d62c4c4d92e1913a7baaf4 | bigcode/the-stack | train |
8e84c8de0c75a1af8bf97e14 | train | class | class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id','username','password')
| class UserSerializer(serializers.ModelSerializer):
| class Meta:
model = Person
fields = ('id','username','password')
| sent_time','delivered_time')
class GroupSerializer(serializers.ModelSerializer):
sender= serializers.SerializerMethodField('get_sender')
class Meta:
fields = '__all__'
model = GroupChat
def get_sender(self,obj):
return GroupChat.objects.user.values()
class UserSerializer(serializers.ModelSerializer):
| 64 | 64 | 26 | 7 | 57 | amal-san/ChatStreak | api/serializers.py | Python | UserSerializer | UserSerializer | 161 | 165 | 161 | 162 | d518b97a2e9cc177aa8089f8845e6a2ae46d871d | bigcode/the-stack | train |
70b063fda0a9d879fbde3927 | train | class | class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('id','username','email','first_name','last_name') | class UserSearchSerializer(serializers.ModelSerializer):
| class Meta:
model = Person
fields = ('id','username','email','first_name','last_name') | ', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
class Meta:
model = Person
fields = ('token', 'username', 'password')
class UserSearchSerializer(serializers.Mod... | 63 | 64 | 33 | 8 | 55 | amal-san/ChatStreak | api/serializers.py | Python | UserSearchSerializer | UserSearchSerializer | 195 | 199 | 195 | 196 | 4f0c88517d79697517cad4089dbca45440077377 | bigcode/the-stack | train |
db9cd0464ceb44aaed4e9ae6 | train | function | def run_fn(fn_args: FnArgs):
"""Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
"""
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(
fn_args.train_files, tf_transform_output, batch_size=_TRA... | def run_fn(fn_args: FnArgs):
| """Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
"""
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(
fn_args.train_files, tf_transform_output, batch_size=_TRAIN_BATCH_SIZE)
eval_datase... | used in the serving signature."""
feature_spec = tf_transform_output.raw_feature_spec()
feature_spec.pop(_LABEL_KEY)
parsed_features = tf.io.parse_example(serialized_tf_examples, feature_spec)
transformed_features = model.tft_layer(parsed_features)
return model(transformed_features)
return ser... | 84 | 84 | 281 | 9 | 75 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | run_fn | run_fn | 123 | 158 | 123 | 123 | 87fa6a650b945d8f9090b83bd44a40a38498f636 | bigcode/the-stack | train |
10111690ba7ed2a52329b113 | train | function | def _input_fn(file_pattern: List[Text],
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
"""Generates features and label for tuning/training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
tf_transform_output: A TFTra... | def _input_fn(file_pattern: List[Text],
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
| """Generates features and label for tuning/training.
Args:
file_pattern: List of paths or patterns of input tfrecord files.
tf_transform_output: A TFTransformOutput.
batch_size: representing the number of consecutive elements of returned
dataset to combine in a single batch
Returns:
A data... | 'input_word_ids': input_word_ids,
'input_mask': input_mask,
'segment_ids': segment_ids
}
def _input_fn(file_pattern: List[Text],
tf_transform_output: tft.TFTransformOutput,
batch_size: int = 200) -> tf.data.Dataset:
| 64 | 64 | 212 | 37 | 27 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | _input_fn | _input_fn | 73 | 98 | 73 | 75 | a5d84a656befa4870f24bb66dcd67286a2151745 | bigcode/the-stack | train |
2065a58549957eb4c25c7740 | train | function | def preprocessing_fn(inputs):
"""tf.transform's callback function for preprocessing inputs.
Args:
inputs: map from feature keys to raw not-yet-transformed features.
Returns:
Map from string feature key to transformed feature Tensors.
"""
input_word_ids, input_mask, segment_ids = _tokenize(inputs[_FE... | def preprocessing_fn(inputs):
| """tf.transform's callback function for preprocessing inputs.
Args:
inputs: map from feature keys to raw not-yet-transformed features.
Returns:
Map from string feature key to transformed feature Tensors.
"""
input_word_ids, input_mask, segment_ids = _tokenize(inputs[_FEATURE_KEY_A],
... | ize(sequence_a, sequence_b):
"""Tokenize the two sentences and insert appropriate tokens."""
processor = BertPreprocessor(_BERT_LINK)
return processor.tokenize_sentence_pair(
tf.reshape(sequence_a, [-1]), tf.reshape(sequence_b, [-1]), _MAX_LEN)
def preprocessing_fn(inputs):
| 64 | 64 | 118 | 5 | 59 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | preprocessing_fn | preprocessing_fn | 53 | 70 | 53 | 53 | f2033a085a3555451d80e2cbdb1481606996b27a | bigcode/the-stack | train |
91265a0d90109a0304b7d52b | train | function | def _gzip_reader_fn(filenames):
"""Small utility returning a record reader that can read gzip'ed files."""
return tf.data.TFRecordDataset(filenames, compression_type='GZIP')
| def _gzip_reader_fn(filenames):
| """Small utility returning a record reader that can read gzip'ed files."""
return tf.data.TFRecordDataset(filenames, compression_type='GZIP')
| -12/2'
_EPOCHS = 1
_EVAL_BATCH_SIZE = 32
_FEATURE_KEY_A = 'sentence1'
_FEATURE_KEY_B = 'sentence2'
_LABEL_KEY = 'label'
_MAX_LEN = 128
_TRAIN_BATCH_SIZE = 32
def _gzip_reader_fn(filenames):
| 64 | 64 | 40 | 8 | 55 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | _gzip_reader_fn | _gzip_reader_fn | 41 | 43 | 41 | 41 | d88e5ecdcd65caa11fb22a3b3761d7b93ba6f14f | bigcode/the-stack | train |
652ce0407937bf019e32482a | train | function | def _tokenize(sequence_a, sequence_b):
"""Tokenize the two sentences and insert appropriate tokens."""
processor = BertPreprocessor(_BERT_LINK)
return processor.tokenize_sentence_pair(
tf.reshape(sequence_a, [-1]), tf.reshape(sequence_b, [-1]), _MAX_LEN)
| def _tokenize(sequence_a, sequence_b):
| """Tokenize the two sentences and insert appropriate tokens."""
processor = BertPreprocessor(_BERT_LINK)
return processor.tokenize_sentence_pair(
tf.reshape(sequence_a, [-1]), tf.reshape(sequence_b, [-1]), _MAX_LEN)
| _MAX_LEN = 128
_TRAIN_BATCH_SIZE = 32
def _gzip_reader_fn(filenames):
"""Small utility returning a record reader that can read gzip'ed files."""
return tf.data.TFRecordDataset(filenames, compression_type='GZIP')
def _tokenize(sequence_a, sequence_b):
| 64 | 64 | 62 | 10 | 54 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | _tokenize | _tokenize | 46 | 50 | 46 | 46 | 76f05534e4e8aff5d393efb4e157df0cfc8e7f2d | bigcode/the-stack | train |
6bd6ffd74f8ac70dc83ea947 | train | function | def _get_serve_tf_examples_fn(model, tf_transform_output):
"""Returns a function that parses a serialized tf.Example."""
model.tft_layer = tf_transform_output.transform_features_layer()
@tf.function
def serve_tf_examples_fn(serialized_tf_examples):
"""Returns the output to be used in the serving signature... | def _get_serve_tf_examples_fn(model, tf_transform_output):
| """Returns a function that parses a serialized tf.Example."""
model.tft_layer = tf_transform_output.transform_features_layer()
@tf.function
def serve_tf_examples_fn(serialized_tf_examples):
"""Returns the output to be used in the serving signature."""
feature_spec = tf_transform_output.raw_feature_spe... | _features_dataset(
file_pattern=file_pattern,
batch_size=batch_size,
features=transformed_feature_spec,
reader=_gzip_reader_fn,
label_key=_LABEL_KEY)
return dataset.prefetch(tf.data.experimental.AUTOTUNE)
def _get_serve_tf_examples_fn(model, tf_transform_output):
| 64 | 64 | 129 | 14 | 50 | Anon-Artist/tfx | tfx/examples/bert/mrpc/bert_mrpc_utils.py | Python | _get_serve_tf_examples_fn | _get_serve_tf_examples_fn | 101 | 117 | 101 | 101 | 29cf70d8109b8a84a9928823570cc9116808e955 | bigcode/the-stack | train |
3d780675ee8e74557abcd8be | train | function | def test_dropout_convenience_functions():
from lasagne.layers.noise import (dropout_channels, spatial_dropout,
dropout_locations)
assert dropout_channels((10, 20)).shared_axes == ()
assert dropout_channels((None, None, None)).shared_axes == (2,)
assert dropout_chann... | def test_dropout_convenience_functions():
| from lasagne.layers.noise import (dropout_channels, spatial_dropout,
dropout_locations)
assert dropout_channels((10, 20)).shared_axes == ()
assert dropout_channels((None, None, None)).shared_axes == (2,)
assert dropout_channels((1, 2, 3, 4)).shared_axes == (2, 3)
... | ))
result = DropoutLayer(input_layer).get_output_for(input)
result_eval1 = result.eval()
set_rng(RandomState(seed))
result = DropoutLayer(input_layer).get_output_for(input)
result_eval2 = result.eval()
set_rng(rng) # reset to original RNG for other tests
assert... | 89 | 89 | 297 | 8 | 81 | BenjaminBossan/Lasagne | lasagne/tests/layers/test_noise.py | Python | test_dropout_convenience_functions | test_dropout_convenience_functions | 101 | 115 | 101 | 101 | 5e14ecd453136c1b715c1da06b3212d7f386abea | bigcode/the-stack | train |
167067be671108112af809de | train | class | class TestGaussianNoiseLayer:
@pytest.fixture
def layer(self):
from lasagne.layers.noise import GaussianNoiseLayer
return GaussianNoiseLayer(Mock(output_shape=(None,)))
@pytest.fixture(params=[(100, 100), (None, 100)])
def input_layer(self, request):
from lasagne.layers.input im... | class TestGaussianNoiseLayer:
@pytest.fixture
| def layer(self):
from lasagne.layers.noise import GaussianNoiseLayer
return GaussianNoiseLayer(Mock(output_shape=(None,)))
@pytest.fixture(params=[(100, 100), (None, 100)])
def input_layer(self, request):
from lasagne.layers.input import InputLayer
return InputLayer(request.... | _axes == (2, 3, 4, 5)
assert dropout_locations((10, 20)).shared_axes == (1,)
assert dropout_locations((None, None, None)).shared_axes == (1,)
assert dropout_locations((1, 2, 3, 4)).shared_axes == (1,)
assert dropout_locations((1, 2, 3, 4, 5, 6)).shared_axes == (1,)
class TestGaussianNoiseLayer:
@pyt... | 108 | 109 | 365 | 11 | 97 | BenjaminBossan/Lasagne | lasagne/tests/layers/test_noise.py | Python | TestGaussianNoiseLayer | TestGaussianNoiseLayer | 118 | 158 | 118 | 119 | 2450c0e5779521529f0ea9c548a9479568119576 | bigcode/the-stack | train |
446163658ac8faa6ae6f4ac4 | train | class | class TestDropoutLayer:
@pytest.fixture(params=[(100, 100), (None, 100)])
def input_layer(self, request):
from lasagne.layers.input import InputLayer
return InputLayer(request.param)
@pytest.fixture
def layer(self, input_layer):
from lasagne.layers.noise import DropoutLayer
... | class TestDropoutLayer:
@pytest.fixture(params=[(100, 100), (None, 100)])
| def input_layer(self, request):
from lasagne.layers.input import InputLayer
return InputLayer(request.param)
@pytest.fixture
def layer(self, input_layer):
from lasagne.layers.noise import DropoutLayer
return DropoutLayer(input_layer)
@pytest.fixture
def layer_no_res... | from mock import Mock
import numpy
import numpy as np
from numpy.random import RandomState
import theano
import pytest
from lasagne.random import get_rng, set_rng
class TestDropoutLayer:
@pytest.fixture(params=[(100, 100), (None, 100)])
| 62 | 256 | 934 | 24 | 37 | BenjaminBossan/Lasagne | lasagne/tests/layers/test_noise.py | Python | TestDropoutLayer | TestDropoutLayer | 11 | 98 | 11 | 12 | 988620595a615462d8fbdb9bb0f75fb0a42dc790 | bigcode/the-stack | train |
5121c14086809f1f7ebc1c9d | train | function | def test_ones():
# shape/len[, dtype=]
assert cupy.ones(10).tolist() == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
assert cupy.ones(10, dtype=int).tolist() == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
assert cupy.ones((2, 3)).tolist() == [[1, 1, 1], [1, 1, 1]]
assert cupy.ones((2, 3), dtype=int).tolist() == [[1, 1, 1], [1... | def test_ones():
# shape/len[, dtype=]
| assert cupy.ones(10).tolist() == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
assert cupy.ones(10, dtype=int).tolist() == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
assert cupy.ones((2, 3)).tolist() == [[1, 1, 1], [1, 1, 1]]
assert cupy.ones((2, 3), dtype=int).tolist() == [[1, 1, 1], [1, 1, 1]]
| 0, 0], [0, 0, 0]]
assert cupy.zeros((2, 3), dtype=int).tolist() == [[0, 0, 0], [0, 0, 0]]
def test_ones():
# shape/len[, dtype=]
| 63 | 64 | 166 | 14 | 49 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_ones | test_ones | 65 | 70 | 65 | 66 | de0d2e890fef63e063abad322ffb33de54bb093a | bigcode/the-stack | train |
bdd8d9a24a5d302c1e00089e | train | function | def test_broadcast_to():
# array, shape
assert numpy.broadcast_to(numpy.array([[1], [2], [3], [4], [5]]), (5, 2)).tolist() == [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
assert numpy.broadcast_to(numpy.array([1, 2, 3, 4, 5]), (2, 5)).tolist() == [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
assert cupy.broadcast_to(c... | def test_broadcast_to():
# array, shape
| assert numpy.broadcast_to(numpy.array([[1], [2], [3], [4], [5]]), (5, 2)).tolist() == [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
assert numpy.broadcast_to(numpy.array([1, 2, 3, 4, 5]), (2, 5)).tolist() == [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
assert cupy.broadcast_to(cupy.array([[1], [2], [3], [4], [5]]), (5, 2)... | 3.3])).tolist() == [1.1, 2.2, 3.3]
assert cupy.atleast_1d(cupy.array([1.1, 2.2, 3.3])).tolist() == [1.1, 2.2, 3.3]
def test_broadcast_to():
# array, shape
| 79 | 79 | 264 | 12 | 67 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_broadcast_to | test_broadcast_to | 232 | 237 | 232 | 233 | f45f92cb0054c08bf7a81dbdcef3c715a73231a4 | bigcode/the-stack | train |
6a9086e3d486acf18a3694e1 | train | function | def test_count_nonzero():
# array
assert numpy.count_nonzero(numpy.array([])) == cupy.count_nonzero(cupy.array([]))
assert numpy.count_nonzero(numpy.array([2, 0, 0, 1])) == cupy.count_nonzero(cupy.array([2, 0, 0, 1]))
| def test_count_nonzero():
# array
| assert numpy.count_nonzero(numpy.array([])) == cupy.count_nonzero(cupy.array([]))
assert numpy.count_nonzero(numpy.array([2, 0, 0, 1])) == cupy.count_nonzero(cupy.array([2, 0, 0, 1]))
| ([False, False]))
assert numpy.any(numpy.array([False, True])) == cupy.any(cupy.array([False, True]))
assert numpy.any(numpy.array([True, True])) == cupy.any(cupy.array([True, True]))
def test_count_nonzero():
# array
| 63 | 64 | 74 | 10 | 53 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_count_nonzero | test_count_nonzero | 310 | 313 | 310 | 311 | e4906d39c78a0b3fae34c0d8715229f42f24602f | bigcode/the-stack | train |
c76e5d9b59674c75a55f5cb2 | train | function | def test_ceil():
# array
assert numpy.ceil(numpy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).tolist() == cupy.ceil(cupy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).tolist()
assert numpy.ceil(numpy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).dtype.kind == "f"
assert cupy.ceil(cupy.array([3... | def test_ceil():
# array
| assert numpy.ceil(numpy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).tolist() == cupy.ceil(cupy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).tolist()
assert numpy.ceil(numpy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).dtype.kind == "f"
assert cupy.ceil(cupy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, ... | ([3.3, 2.2, 5.5, 2.2, 1.1]), cupy.array([4.4, 2.2, 5.5, 1.1, 5.5])).tolist()
def test_ceil():
# array
| 64 | 64 | 214 | 9 | 55 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_ceil | test_ceil | 285 | 289 | 285 | 286 | 68789a246da4f42406fc6814f31ddd967dd55cbe | bigcode/the-stack | train |
0adc4768b1784139fdef2a18 | train | function | def test_sqrt():
# array
assert numpy.sqrt(numpy.array([1, 4, 9, 16, 25])).tolist() == cupy.sqrt(cupy.array([1, 4, 9, 16, 25])).tolist()
assert numpy.sqrt(numpy.array([1.1, 4.4, 9.9, 16.16, 25.25])).tolist() == cupy.sqrt(cupy.array([1.1, 4.4, 9.9, 16.16, 25.25])).tolist()
| def test_sqrt():
# array
| assert numpy.sqrt(numpy.array([1, 4, 9, 16, 25])).tolist() == cupy.sqrt(cupy.array([1, 4, 9, 16, 25])).tolist()
assert numpy.sqrt(numpy.array([1.1, 4.4, 9.9, 16.16, 25.25])).tolist() == cupy.sqrt(cupy.array([1.1, 4.4, 9.9, 16.16, 25.25])).tolist()
| 3, 4, 5]), (2, 5)).tolist() == [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
############################ ufuncs
def test_sqrt():
# array
| 64 | 64 | 125 | 9 | 54 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_sqrt | test_sqrt | 242 | 245 | 242 | 243 | 407f0a3f657adba9a677c1dd67d9f773084b0291 | bigcode/the-stack | train |
64dd91a8a50202880010aa59 | train | function | def test_meshgrid():
# *arrays, indexing="ij"
np_one = numpy.array([2, 3, 5, 7, 9])
np_two = numpy.array([11, 13, 17, 19])
np_three = numpy.array([21, 23, 29])
np_a, np_b = numpy.meshgrid(np_one, np_two, indexing="ij")
np_x, np_y, np_z = numpy.meshgrid(np_one, np_two, np_three, indexing="ij")
... | def test_meshgrid():
# *arrays, indexing="ij"
| np_one = numpy.array([2, 3, 5, 7, 9])
np_two = numpy.array([11, 13, 17, 19])
np_three = numpy.array([21, 23, 29])
np_a, np_b = numpy.meshgrid(np_one, np_two, indexing="ij")
np_x, np_y, np_z = numpy.meshgrid(np_one, np_two, np_three, indexing="ij")
cp_one = cupy.array([2, 3, 5, 7, 9])
cp_two... | 30, 5).tolist()
assert cupy.arange(10, dtype=float).dtype.kind == "f"
assert cupy.arange(10, 15, dtype=float).dtype.kind == "f"
assert cupy.arange(10, 30, 5, dtype=float).dtype.kind == "f"
def test_meshgrid():
# *arrays, indexing="ij"
| 82 | 82 | 274 | 14 | 68 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_meshgrid | test_meshgrid | 101 | 119 | 101 | 102 | d6de51905b5e5650a9f9b598a768b3b0158c7d5d | bigcode/the-stack | train |
e076f081959fa0cdacd38c78 | train | function | def test_any():
# array
assert numpy.any(numpy.array([])) == cupy.any(cupy.array([]))
assert numpy.any(numpy.array([False, False])) == cupy.any(cupy.array([False, False]))
assert numpy.any(numpy.array([False, True])) == cupy.any(cupy.array([False, True]))
assert numpy.any(numpy.array([True, True])) ... | def test_any():
# array
| assert numpy.any(numpy.array([])) == cupy.any(cupy.array([]))
assert numpy.any(numpy.array([False, False])) == cupy.any(cupy.array([False, False]))
assert numpy.any(numpy.array([False, True])) == cupy.any(cupy.array([False, True]))
assert numpy.any(numpy.array([True, True])) == cupy.any(cupy.array([True... | upy.array([False, False]))
assert numpy.all(numpy.array([False, True])) == cupy.all(cupy.array([False, True]))
assert numpy.all(numpy.array([True, True])) == cupy.all(cupy.array([True, True]))
def test_any():
# array
| 63 | 64 | 98 | 8 | 55 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_any | test_any | 302 | 307 | 302 | 303 | e5772345e316991d61c27d09dd8bfb6627860987 | bigcode/the-stack | train |
7c012b4ab24808f1e960845e | train | function | def test_argmax():
# array[, axis=]
assert numpy.argmax(numpy.array([2, 5, 1, 4]), axis=None) == cupy.argmax(cupy.array([2, 5, 1, 4]), axis=None)
assert numpy.argmax(numpy.array([[2, 5], [1, 4]]), axis=None) == cupy.argmax(cupy.array([[2, 5], [1, 4]]), axis=None)
| def test_argmax():
# array[, axis=]
| assert numpy.argmax(numpy.array([2, 5, 1, 4]), axis=None) == cupy.argmax(cupy.array([2, 5, 1, 4]), axis=None)
assert numpy.argmax(numpy.array([[2, 5], [1, 4]]), axis=None) == cupy.argmax(cupy.array([[2, 5], [1, 4]]), axis=None)
| ]), axis=None)
assert numpy.argmin(numpy.array([[2, 5], [1, 4]]), axis=None) == cupy.argmin(cupy.array([[2, 5], [1, 4]]), axis=None)
def test_argmax():
# array[, axis=]
| 64 | 64 | 102 | 12 | 52 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_argmax | test_argmax | 342 | 345 | 342 | 343 | 69f8fd56fb4e94a10d94f8e44b02fc24bea095fe | bigcode/the-stack | train |
520337300fadeb088368943c | train | function | def test_logical_and():
# array1, array2
assert numpy.logical_and(numpy.array([False, False, True, True]), numpy.array([False, True, False, True])).tolist() == cupy.logical_and(cupy.array([False, False, True, True]), cupy.array([False, True, False, True])).tolist()
| def test_logical_and():
# array1, array2
| assert numpy.logical_and(numpy.array([False, False, True, True]), numpy.array([False, True, False, True])).tolist() == cupy.logical_and(cupy.array([False, False, True, True]), cupy.array([False, True, False, True])).tolist()
| tolist()
numpy.bitwise_or(np_array1, np_array2, np_arrayout)
cupy.bitwise_or(cp_array1, cp_array2, cp_arrayout)
assert np_arrayout.tolist() == cp_arrayout.tolist()
def test_logical_and():
# array1, array2
| 64 | 64 | 75 | 14 | 50 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_logical_and | test_logical_and | 275 | 277 | 275 | 276 | 3ef013a3be75b1ed4331c6795a554b9b5492a26e | bigcode/the-stack | train |
9cec04a6bf4bd0dd6ba8435c | train | function | def test_argmin():
# array[, axis=]
assert numpy.argmin(numpy.array([2, 5, 1, 4]), axis=None) == cupy.argmin(cupy.array([2, 5, 1, 4]), axis=None)
assert numpy.argmin(numpy.array([[2, 5], [1, 4]]), axis=None) == cupy.argmin(cupy.array([[2, 5], [1, 4]]), axis=None)
| def test_argmin():
# array[, axis=]
| assert numpy.argmin(numpy.array([2, 5, 1, 4]), axis=None) == cupy.argmin(cupy.array([2, 5, 1, 4]), axis=None)
assert numpy.argmin(numpy.array([[2, 5], [1, 4]]), axis=None) == cupy.argmin(cupy.array([[2, 5], [1, 4]]), axis=None)
| , 4]))
def test_max():
# array
assert numpy.max(numpy.array([2, 5, 1, 4])) == cupy.max(cupy.array([2, 5, 1, 4]))
def test_argmin():
# array[, axis=]
| 63 | 64 | 106 | 12 | 51 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_argmin | test_argmin | 336 | 339 | 336 | 337 | 3dd3cc7af2f5af4ce679b025582630e0b81ae9ef | bigcode/the-stack | train |
d49c11e4c242c7761be3d785 | train | function | def test_frombuffer():
# array[, dtype=]
np_array = numpy.frombuffer(b"one two three", dtype=np.uint8)
cp_array = cupy.frombuffer(b"one two three", dtype=np.uint8)
assert cp_array.tolist() == np_array.tolist()
| def test_frombuffer():
# array[, dtype=]
| np_array = numpy.frombuffer(b"one two three", dtype=np.uint8)
cp_array = cupy.frombuffer(b"one two three", dtype=np.uint8)
assert cp_array.tolist() == np_array.tolist()
| assert cp_array2[2] == 99.9
cp_array3 = cupy.asarray(cp_array1, dtype=int)
assert cp_array3.tolist() == [1, 2, 99, 4, 5]
def test_frombuffer():
# array[, dtype=]
| 64 | 64 | 60 | 12 | 52 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_frombuffer | test_frombuffer | 50 | 54 | 50 | 51 | 5b209416456f1960ec98415d73345f03042f36e9 | bigcode/the-stack | train |
d47c4640a3d6f0effbed89cc | train | function | def test_all():
# array
assert numpy.all(numpy.array([])) == cupy.all(cupy.array([]))
assert numpy.all(numpy.array([False, False])) == cupy.all(cupy.array([False, False]))
assert numpy.all(numpy.array([False, True])) == cupy.all(cupy.array([False, True]))
assert numpy.all(numpy.array([True, True])) ... | def test_all():
# array
| assert numpy.all(numpy.array([])) == cupy.all(cupy.array([]))
assert numpy.all(numpy.array([False, False])) == cupy.all(cupy.array([False, False]))
assert numpy.all(numpy.array([False, True])) == cupy.all(cupy.array([False, True]))
assert numpy.all(numpy.array([True, True])) == cupy.all(cupy.array([True... | cupy.ceil(cupy.array([3.3, 2.0, 1.9, 2.1, 5.5, 1.9, 2.0, 2.1])).dtype.kind == "f"
############################ reducers
def test_all():
# array
| 64 | 64 | 98 | 8 | 55 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_all | test_all | 294 | 299 | 294 | 295 | 65e6969696f62dcffc9f9b0ac42fc73fed96d055 | bigcode/the-stack | train |
4ebd1afec81030813d8f8b1c | train | function | def test_atleast_1d():
# *arrays
assert numpy.atleast_1d(numpy.array([1.1, 2.2, 3.3])).tolist() == [1.1, 2.2, 3.3]
assert cupy.atleast_1d(cupy.array([1.1, 2.2, 3.3])).tolist() == [1.1, 2.2, 3.3]
| def test_atleast_1d():
# *arrays
| assert numpy.atleast_1d(numpy.array([1.1, 2.2, 3.3])).tolist() == [1.1, 2.2, 3.3]
assert cupy.atleast_1d(cupy.array([1.1, 2.2, 3.3])).tolist() == [1.1, 2.2, 3.3]
| tolist() == [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]
def test_atleast_1d():
# *arrays
| 64 | 64 | 102 | 13 | 51 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_atleast_1d | test_atleast_1d | 226 | 229 | 226 | 227 | 7ec6c7d4f9c3829292bda3291415f185eae7210d | bigcode/the-stack | train |
da81a7997b4f32a2984e0c85 | train | function | def test_sum():
# array
assert numpy.sum(numpy.array([2, 5, 0, 4])) == cupy.sum(cupy.array([2, 5, 0, 4]))
| def test_sum():
# array
| assert numpy.sum(numpy.array([2, 5, 0, 4])) == cupy.sum(cupy.array([2, 5, 0, 4]))
| ([])) == cupy.count_nonzero(cupy.array([]))
assert numpy.count_nonzero(numpy.array([2, 0, 0, 1])) == cupy.count_nonzero(cupy.array([2, 0, 0, 1]))
def test_sum():
# array
| 63 | 64 | 46 | 8 | 55 | uccross/awkward-1.0 | tests-cuda/test_0388-abstract-all-uses-of-numpy.py | Python | test_sum | test_sum | 316 | 318 | 316 | 317 | e796290c684c7b048c04cb53898e739b87c1439a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.