Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
ConnectingTestCase.repl_connect | (self, **kwargs) | Return a connection set up for replication
The connection is on "PSYCOPG2_TEST_REPL_DSN" unless overridden by
a *dsn* kwarg.
Should raise a skip test if not available, but guard for None on
old Python versions.
| Return a connection set up for replication | def repl_connect(self, **kwargs):
"""Return a connection set up for replication
The connection is on "PSYCOPG2_TEST_REPL_DSN" unless overridden by
a *dsn* kwarg.
Should raise a skip test if not available, but guard for None on
old Python versions.
"""
if repl_ds... | [
"def",
"repl_connect",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"repl_dsn",
"is",
"None",
":",
"return",
"self",
".",
"skipTest",
"(",
"\"replication tests disabled by default\"",
")",
"if",
"'dsn'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
... | [
132,
4
] | [
160,
19
] | python | en | ['en', 'en', 'en'] | True |
set_current_apps_for_migrations | (apps, schema_editor) |
This is necessary for migrations which do explicit saves on any model that
has an ImplicitRoleFIeld (which generally means anything that has
some RBAC bindings associated with it). This sets the current 'apps' that
the ImplicitRoleFIeld should be using when creating new roles.
|
This is necessary for migrations which do explicit saves on any model that
has an ImplicitRoleFIeld (which generally means anything that has
some RBAC bindings associated with it). This sets the current 'apps' that
the ImplicitRoleFIeld should be using when creating new roles.
| def set_current_apps_for_migrations(apps, schema_editor):
"""
This is necessary for migrations which do explicit saves on any model that
has an ImplicitRoleFIeld (which generally means anything that has
some RBAC bindings associated with it). This sets the current 'apps' that
the ImplicitRoleFIeld s... | [
"def",
"set_current_apps_for_migrations",
"(",
"apps",
",",
"schema_editor",
")",
":",
"set_current_apps",
"(",
"apps",
")"
] | [
3,
0
] | [
10,
26
] | python | en | ['en', 'error', 'th'] | False |
build_narrow_filter | (narrow: Collection[Sequence[str]]) | Changes to this function should come with corresponding changes to
BuildNarrowFilterTest. | Changes to this function should come with corresponding changes to
BuildNarrowFilterTest. | def build_narrow_filter(narrow: Collection[Sequence[str]]) -> Callable[[Mapping[str, Any]], bool]:
"""Changes to this function should come with corresponding changes to
BuildNarrowFilterTest."""
check_supported_events_narrow_filter(narrow)
def narrow_filter(event: Mapping[str, Any]) -> bool:
me... | [
"def",
"build_narrow_filter",
"(",
"narrow",
":",
"Collection",
"[",
"Sequence",
"[",
"str",
"]",
"]",
")",
"->",
"Callable",
"[",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"bool",
"]",
":",
"check_supported_events_narrow_filter",
"(",
"narrow... | [
58,
0
] | [
98,
24
] | python | en | ['en', 'en', 'en'] | True |
parse_index_file | (filename) | Parse index file. | Parse index file. | def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index | [
"def",
"parse_index_file",
"(",
"filename",
")",
":",
"index",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"filename",
")",
":",
"index",
".",
"append",
"(",
"int",
"(",
"line",
".",
"strip",
"(",
")",
")",
")",
"return",
"index"
] | [
16,
0
] | [
21,
16
] | python | en | ['en', 'la', 'en'] | True |
sample_mask | (idx, l) | Create mask. | Create mask. | def sample_mask(idx, l):
"""Create mask."""
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool) | [
"def",
"sample_mask",
"(",
"idx",
",",
"l",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"l",
")",
"mask",
"[",
"idx",
"]",
"=",
"1",
"return",
"np",
".",
"array",
"(",
"mask",
",",
"dtype",
"=",
"np",
".",
"bool",
")"
] | [
24,
0
] | [
28,
40
] | python | en | ['en', 'sm', 'en'] | False |
preprocess_features | (features) | Row-normalize feature matrix and convert to tuple representation | Row-normalize feature matrix and convert to tuple representation | def preprocess_features(features):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
rowsum = (rowsum==0)*1+rowsum
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(f... | [
"def",
"preprocess_features",
"(",
"features",
")",
":",
"rowsum",
"=",
"np",
".",
"array",
"(",
"features",
".",
"sum",
"(",
"1",
")",
")",
"rowsum",
"=",
"(",
"rowsum",
"==",
"0",
")",
"*",
"1",
"+",
"rowsum",
"r_inv",
"=",
"np",
".",
"power",
... | [
81,
0
] | [
89,
19
] | python | en | ['en', 'en', 'en'] | True |
TestSettingMenu.login_only_admin | (self) | Log in with a user that only has permission to access the admin | Log in with a user that only has permission to access the admin | def login_only_admin(self):
""" Log in with a user that only has permission to access the admin """
user = self.create_user(
username='test', password='password')
user.user_permissions.add(Permission.objects.get_by_natural_key(
codename='access_admin', app_label='wagtaila... | [
"def",
"login_only_admin",
"(",
"self",
")",
":",
"user",
"=",
"self",
".",
"create_user",
"(",
"username",
"=",
"'test'",
",",
"password",
"=",
"'password'",
")",
"user",
".",
"user_permissions",
".",
"add",
"(",
"Permission",
".",
"objects",
".",
"get_by... | [
17,
4
] | [
24,
19
] | python | en | ['en', 'en', 'en'] | True |
build_topic_mute_checker | (
cursor: CursorObj, user_profile: UserProfile
) |
This function is similar to the function of the same name
in zerver/lib/topic_mutes.py, but it works without the ORM,
so that we can use it in migrations.
|
This function is similar to the function of the same name
in zerver/lib/topic_mutes.py, but it works without the ORM,
so that we can use it in migrations.
| def build_topic_mute_checker(
cursor: CursorObj, user_profile: UserProfile
) -> Callable[[int, str], bool]:
"""
This function is similar to the function of the same name
in zerver/lib/topic_mutes.py, but it works without the ORM,
so that we can use it in migrations.
"""
query = SQL(
... | [
"def",
"build_topic_mute_checker",
"(",
"cursor",
":",
"CursorObj",
",",
"user_profile",
":",
"UserProfile",
")",
"->",
"Callable",
"[",
"[",
"int",
",",
"str",
"]",
",",
"bool",
"]",
":",
"query",
"=",
"SQL",
"(",
"\"\"\"\n SELECT\n recipient_... | [
24,
0
] | [
51,
19
] | python | en | ['en', 'error', 'th'] | False |
P4Switch.start | ( self, controllers ) | Start up a new P4 switch | Start up a new P4 switch | def start( self, controllers ):
"Start up a new P4 switch"
print "Starting P4 switch", self.name
args = [self.sw_path]
args.extend( ['--name', self.name] )
args.extend( ['--dpid', self.dpid] )
for intf in self.intfs.values():
if not intf.IP():
... | [
"def",
"start",
"(",
"self",
",",
"controllers",
")",
":",
"print",
"\"Starting P4 switch\"",
",",
"self",
".",
"name",
"args",
"=",
"[",
"self",
".",
"sw_path",
"]",
"args",
".",
"extend",
"(",
"[",
"'--name'",
",",
"self",
".",
"name",
"]",
")",
"a... | [
69,
4
] | [
98,
39
] | python | en | ['en', 'en', 'en'] | True |
P4Switch.stop | ( self ) | Terminate IVS switch. | Terminate IVS switch. | def stop( self ):
"Terminate IVS switch."
self.output.flush()
self.cmd( 'kill %' + self.sw_path )
self.cmd( 'wait' )
self.deleteIntfs() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"output",
".",
"flush",
"(",
")",
"self",
".",
"cmd",
"(",
"'kill %'",
"+",
"self",
".",
"sw_path",
")",
"self",
".",
"cmd",
"(",
"'wait'",
")",
"self",
".",
"deleteIntfs",
"(",
")"
] | [
100,
4
] | [
105,
26
] | python | en | ['en', 'co', 'en'] | True |
P4Switch.attach | ( self, intf ) | Connect a data port | Connect a data port | def attach( self, intf ):
"Connect a data port"
print "Connecting data port", intf, "to switch", self.name
self.cmd( 'p4ns-ctl', 'add-port', '--datapath', self.name, intf ) | [
"def",
"attach",
"(",
"self",
",",
"intf",
")",
":",
"print",
"\"Connecting data port\"",
",",
"intf",
",",
"\"to switch\"",
",",
"self",
".",
"name",
"self",
".",
"cmd",
"(",
"'p4ns-ctl'",
",",
"'add-port'",
",",
"'--datapath'",
",",
"self",
".",
"name",
... | [
107,
4
] | [
110,
73
] | python | en | ['es', 'en', 'en'] | True |
P4Switch.detach | ( self, intf ) | Disconnect a data port | Disconnect a data port | def detach( self, intf ):
"Disconnect a data port"
self.cmd( 'p4ns-ctl', 'del-port', '--datapath', self.name, intf ) | [
"def",
"detach",
"(",
"self",
",",
"intf",
")",
":",
"self",
".",
"cmd",
"(",
"'p4ns-ctl'",
",",
"'del-port'",
",",
"'--datapath'",
",",
"self",
".",
"name",
",",
"intf",
")"
] | [
112,
4
] | [
114,
73
] | python | en | ['es', 'en', 'en'] | True |
P4Switch.dpctl | ( self, *args ) | Run dpctl command | Run dpctl command | def dpctl( self, *args ):
"Run dpctl command"
pass | [
"def",
"dpctl",
"(",
"self",
",",
"*",
"args",
")",
":",
"pass"
] | [
116,
4
] | [
118,
12
] | python | fr | ['fr', 'zh', 'sw'] | False |
get_submissions_list_view | (request, *args, **kwargs) | Call the form page's list submissions view class | Call the form page's list submissions view class | def get_submissions_list_view(request, *args, **kwargs):
""" Call the form page's list submissions view class """
page_id = kwargs.get('page_id')
form_page = get_object_or_404(Page, id=page_id).specific
return form_page.serve_submissions_list_view(request, *args, **kwargs) | [
"def",
"get_submissions_list_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"page_id",
"=",
"kwargs",
".",
"get",
"(",
"'page_id'",
")",
"form_page",
"=",
"get_object_or_404",
"(",
"Page",
",",
"id",
"=",
"page_id",
")",
".",... | [
17,
0
] | [
21,
74
] | python | en | ['en', 'en', 'en'] | True |
SafePaginateListView.paginate_queryset | (self, queryset, page_size) | Paginate the queryset if needed with nice defaults on invalid param. | Paginate the queryset if needed with nice defaults on invalid param. | def paginate_queryset(self, queryset, page_size):
"""Paginate the queryset if needed with nice defaults on invalid param."""
paginator = self.get_paginator(
queryset,
page_size,
orphans=self.get_paginate_orphans(),
allow_empty_first_page=self.get_allow_emp... | [
"def",
"paginate_queryset",
"(",
"self",
",",
"queryset",
",",
"page_size",
")",
":",
"paginator",
"=",
"self",
".",
"get_paginator",
"(",
"queryset",
",",
"page_size",
",",
"orphans",
"=",
"self",
".",
"get_paginate_orphans",
"(",
")",
",",
"allow_empty_first... | [
30,
4
] | [
55,
61
] | python | en | ['en', 'en', 'en'] | True |
FormPagesListView.get_queryset | (self) | Return the queryset of form pages for this view | Return the queryset of form pages for this view | def get_queryset(self):
""" Return the queryset of form pages for this view """
queryset = get_forms_for_user(self.request.user)
ordering = self.get_ordering()
if ordering:
if isinstance(ordering, str):
ordering = (ordering,)
queryset = queryset.or... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"queryset",
"=",
"get_forms_for_user",
"(",
"self",
".",
"request",
".",
"user",
")",
"ordering",
"=",
"self",
".",
"get_ordering",
"(",
")",
"if",
"ordering",
":",
"if",
"isinstance",
"(",
"ordering",
",",
"... | [
63,
4
] | [
71,
23
] | python | en | ['en', 'en', 'en'] | True |
DeleteSubmissionsView.get_queryset | (self) | Returns a queryset for the selected submissions | Returns a queryset for the selected submissions | def get_queryset(self):
""" Returns a queryset for the selected submissions """
submission_ids = self.request.GET.getlist('selected-submissions')
submission_class = self.page.get_submission_class()
return submission_class._default_manager.filter(id__in=submission_ids) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"submission_ids",
"=",
"self",
".",
"request",
".",
"GET",
".",
"getlist",
"(",
"'selected-submissions'",
")",
"submission_class",
"=",
"self",
".",
"page",
".",
"get_submission_class",
"(",
")",
"return",
"submiss... | [
81,
4
] | [
85,
78
] | python | en | ['en', 'en', 'en'] | True |
DeleteSubmissionsView.handle_delete | (self, submissions) | Deletes the given queryset | Deletes the given queryset | def handle_delete(self, submissions):
""" Deletes the given queryset """
count = submissions.count()
submissions.delete()
messages.success(
self.request,
ngettext(
'One submission has been deleted.',
'%(count)d submissions have been... | [
"def",
"handle_delete",
"(",
"self",
",",
"submissions",
")",
":",
"count",
"=",
"submissions",
".",
"count",
"(",
")",
"submissions",
".",
"delete",
"(",
")",
"messages",
".",
"success",
"(",
"self",
".",
"request",
",",
"ngettext",
"(",
"'One submission ... | [
87,
4
] | [
98,
9
] | python | en | ['en', 'en', 'en'] | True |
DeleteSubmissionsView.get_success_url | (self) | Returns the success URL to redirect to after a successful deletion | Returns the success URL to redirect to after a successful deletion | def get_success_url(self):
""" Returns the success URL to redirect to after a successful deletion """
return self.success_url | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"success_url"
] | [
100,
4
] | [
102,
31
] | python | en | ['en', 'en', 'en'] | True |
DeleteSubmissionsView.dispatch | (self, request, *args, **kwargs) | Check permissions, set the page and submissions, handle delete | Check permissions, set the page and submissions, handle delete | def dispatch(self, request, *args, **kwargs):
""" Check permissions, set the page and submissions, handle delete """
page_id = kwargs.get('page_id')
if not get_forms_for_user(self.request.user).filter(id=page_id).exists():
raise PermissionDenied
self.page = get_object_or_40... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"page_id",
"=",
"kwargs",
".",
"get",
"(",
"'page_id'",
")",
"if",
"not",
"get_forms_for_user",
"(",
"self",
".",
"request",
".",
"user",
")",
".",
... | [
104,
4
] | [
119,
57
] | python | en | ['en', 'en', 'en'] | True |
DeleteSubmissionsView.get_context_data | (self, **kwargs) | Get the context for this view | Get the context for this view | def get_context_data(self, **kwargs):
""" Get the context for this view """
context = super().get_context_data(**kwargs)
context.update({
'page': self.page,
'submissions': self.submissions,
})
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
".",
"update",
"(",
"{",
"'page'",
":",
"self",
".",
"page",
",",
"'submis... | [
121,
4
] | [
130,
22
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.dispatch | (self, request, *args, **kwargs) | Check permissions and set the form page | Check permissions and set the form page | def dispatch(self, request, *args, **kwargs):
""" Check permissions and set the form page """
self.form_page = kwargs.get('form_page')
if not get_forms_for_user(request.user).filter(pk=self.form_page.id).exists():
raise PermissionDenied
self.is_export = (self.request.GET.g... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"form_page",
"=",
"kwargs",
".",
"get",
"(",
"'form_page'",
")",
"if",
"not",
"get_forms_for_user",
"(",
"request",
".",
"user",
")",
".... | [
143,
4
] | [
159,
57
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_queryset | (self) | Return queryset of form submissions with filter and order_by applied | Return queryset of form submissions with filter and order_by applied | def get_queryset(self):
""" Return queryset of form submissions with filter and order_by applied """
submission_class = self.form_page.get_submission_class()
queryset = submission_class._default_manager.filter(page=self.form_page)
filtering = self.get_filtering()
if filtering an... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"submission_class",
"=",
"self",
".",
"form_page",
".",
"get_submission_class",
"(",
")",
"queryset",
"=",
"submission_class",
".",
"_default_manager",
".",
"filter",
"(",
"page",
"=",
"self",
".",
"form_page",
")"... | [
161,
4
] | [
176,
23
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_paginate_by | (self, queryset) | Get the number of items to paginate by, or ``None`` for no pagination | Get the number of items to paginate by, or ``None`` for no pagination | def get_paginate_by(self, queryset):
""" Get the number of items to paginate by, or ``None`` for no pagination """
if self.is_export:
return None
return self.paginate_by | [
"def",
"get_paginate_by",
"(",
"self",
",",
"queryset",
")",
":",
"if",
"self",
".",
"is_export",
":",
"return",
"None",
"return",
"self",
".",
"paginate_by"
] | [
178,
4
] | [
182,
31
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_validated_ordering | (self) | Return a dict of field names with ordering labels if ordering is valid | Return a dict of field names with ordering labels if ordering is valid | def get_validated_ordering(self):
""" Return a dict of field names with ordering labels if ordering is valid """
orderable_fields = self.orderable_fields or ()
ordering = dict()
if self.is_export:
# Revert to CSV order_by submit_time ascending for backwards compatibility
... | [
"def",
"get_validated_ordering",
"(",
"self",
")",
":",
"orderable_fields",
"=",
"self",
".",
"orderable_fields",
"or",
"(",
")",
"ordering",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"is_export",
":",
"# Revert to CSV order_by submit_time ascending for backwards com... | [
184,
4
] | [
205,
23
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_ordering | (self) | Return the field or fields to use for ordering the queryset | Return the field or fields to use for ordering the queryset | def get_ordering(self):
""" Return the field or fields to use for ordering the queryset """
ordering = self.get_validated_ordering()
return [values[0] + name for name, values in ordering.items()] | [
"def",
"get_ordering",
"(",
"self",
")",
":",
"ordering",
"=",
"self",
".",
"get_validated_ordering",
"(",
")",
"return",
"[",
"values",
"[",
"0",
"]",
"+",
"name",
"for",
"name",
",",
"values",
"in",
"ordering",
".",
"items",
"(",
")",
"]"
] | [
207,
4
] | [
210,
70
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_filtering | (self) | Return filering as a dict for submissions queryset | Return filering as a dict for submissions queryset | def get_filtering(self):
""" Return filering as a dict for submissions queryset """
self.select_date_form = SelectDateForm(self.request.GET)
result = dict()
if self.select_date_form.is_valid():
date_from = self.select_date_form.cleaned_data.get('date_from')
date_t... | [
"def",
"get_filtering",
"(",
"self",
")",
":",
"self",
".",
"select_date_form",
"=",
"SelectDateForm",
"(",
"self",
".",
"request",
".",
"GET",
")",
"result",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"select_date_form",
".",
"is_valid",
"(",
")",
":",
... | [
212,
4
] | [
229,
21
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_filename | (self) | Returns the base filename for the generated spreadsheet data file | Returns the base filename for the generated spreadsheet data file | def get_filename(self):
""" Returns the base filename for the generated spreadsheet data file """
return '{}-export-{}'.format(
self.form_page.slug,
datetime.datetime.today().strftime('%Y-%m-%d')
) | [
"def",
"get_filename",
"(",
"self",
")",
":",
"return",
"'{}-export-{}'",
".",
"format",
"(",
"self",
".",
"form_page",
".",
"slug",
",",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
")"
] | [
231,
4
] | [
236,
9
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.to_row_dict | (self, item) | Orders the submission dictionary for spreadsheet writing | Orders the submission dictionary for spreadsheet writing | def to_row_dict(self, item):
""" Orders the submission dictionary for spreadsheet writing """
row_dict = OrderedDict((field, item.get_data().get(field)) for field in self.list_export)
return row_dict | [
"def",
"to_row_dict",
"(",
"self",
",",
"item",
")",
":",
"row_dict",
"=",
"OrderedDict",
"(",
"(",
"field",
",",
"item",
".",
"get_data",
"(",
")",
".",
"get",
"(",
"field",
")",
")",
"for",
"field",
"in",
"self",
".",
"list_export",
")",
"return",
... | [
243,
4
] | [
246,
23
] | python | en | ['en', 'en', 'en'] | True |
SubmissionsListView.get_context_data | (self, **kwargs) | Return context for view | Return context for view | def get_context_data(self, **kwargs):
""" Return context for view """
context = super().get_context_data(**kwargs)
submissions = context[self.context_object_name]
data_fields = self.form_page.get_data_fields()
data_rows = []
context['submissions'] = submissions
if... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"submissions",
"=",
"context",
"[",
"self",
".",
"context_object_name",
"]",
"data_fields",... | [
248,
4
] | [
294,
22
] | python | en | ['en', 'en', 'en'] | True |
TestTableBlock.test_table_block_render | (self) |
Test a generic render.
|
Test a generic render.
| def test_table_block_render(self):
"""
Test a generic render.
"""
value = {'first_row_is_table_header': False, 'first_col_is_header': False,
'data': [['Test 1', 'Test 2', 'Test 3'], [None, None, None],
[None, None, None]]}
block = TableB... | [
"def",
"test_table_block_render",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
"[",
"'Test 1'",
",",
"'Test 2'",
",",
"'Test 3'",
"]",
",",
"[",
"N... | [
33,
4
] | [
53,
39
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_table_block_alignment_render | (self) |
Test a generic render with some cells aligned.
|
Test a generic render with some cells aligned.
| def test_table_block_alignment_render(self):
"""
Test a generic render with some cells aligned.
"""
value = {'first_row_is_table_header': True, 'first_col_is_header': False,
'cell': [{'row': 0, 'col': 1, 'className': 'htLeft'},
{'row': 1, 'col':... | [
"def",
"test_table_block_alignment_render",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"True",
",",
"'first_col_is_header'",
":",
"False",
",",
"'cell'",
":",
"[",
"{",
"'row'",
":",
"0",
",",
"'col'",
":",
"1",
",",
"'clas... | [
55,
4
] | [
79,
39
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_render_empty_table | (self) |
An empty table should render okay.
|
An empty table should render okay.
| def test_render_empty_table(self):
"""
An empty table should render okay.
"""
block = TableBlock()
result = block.render({
'first_row_is_table_header': False,
'first_col_is_header': False,
'data': [
[None, None, None],
... | [
"def",
"test_render_empty_table",
"(",
"self",
")",
":",
"block",
"=",
"TableBlock",
"(",
")",
"result",
"=",
"block",
".",
"render",
"(",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
... | [
81,
4
] | [
104,
46
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_do_not_render_html | (self) |
Ensure that raw html doesn't render
by default.
|
Ensure that raw html doesn't render
by default.
| def test_do_not_render_html(self):
"""
Ensure that raw html doesn't render
by default.
"""
value = {'first_row_is_table_header': False, 'first_col_is_header': False,
'data': [['<p><strong>Test</strong></p>', None, None], [None, None, None],
... | [
"def",
"test_do_not_render_html",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
"[",
"'<p><strong>Test</strong></p>'",
",",
"None",
",",
"None",
"]",
",... | [
106,
4
] | [
127,
46
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_row_headers | (self) |
Ensure that row headers are properly rendered.
|
Ensure that row headers are properly rendered.
| def test_row_headers(self):
"""
Ensure that row headers are properly rendered.
"""
value = {'first_row_is_table_header': True, 'first_col_is_header': False,
'data': [['Foo', 'Bar', 'Baz'], [None, None, None], [None, None, None]]}
expected = """
<tabl... | [
"def",
"test_row_headers",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"True",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
"[",
"'Foo'",
",",
"'Bar'",
",",
"'Baz'",
"]",
",",
"[",
"None",
",",
"N... | [
129,
4
] | [
149,
46
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_column_headers | (self) |
Ensure that column headers are properly rendered.
|
Ensure that column headers are properly rendered.
| def test_column_headers(self):
"""
Ensure that column headers are properly rendered.
"""
value = {'first_row_is_table_header': False, 'first_col_is_header': True,
'data': [['Foo', 'Bar', 'Baz'], ['one', 'two', 'three'], ['four', 'five', 'six']]}
expected = """
... | [
"def",
"test_column_headers",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"True",
",",
"'data'",
":",
"[",
"[",
"'Foo'",
",",
"'Bar'",
",",
"'Baz'",
"]",
",",
"[",
"'one'",
",",
... | [
151,
4
] | [
169,
46
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_row_and_column_headers | (self) |
Test row and column headers at the same time.
|
Test row and column headers at the same time.
| def test_row_and_column_headers(self):
"""
Test row and column headers at the same time.
"""
value = {'first_row_is_table_header': True, 'first_col_is_header': True,
'data': [['Foo', 'Bar', 'Baz'], ['one', 'two', 'three'], ['four', 'five', 'six']]}
expected = ""... | [
"def",
"test_row_and_column_headers",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"True",
",",
"'first_col_is_header'",
":",
"True",
",",
"'data'",
":",
"[",
"[",
"'Foo'",
",",
"'Bar'",
",",
"'Baz'",
"]",
",",
"[",
"'one'",
... | [
171,
4
] | [
191,
46
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_value_for_and_from_form | (self) |
Make sure we get back good json and make
sure it translates back to python.
|
Make sure we get back good json and make
sure it translates back to python.
| def test_value_for_and_from_form(self):
"""
Make sure we get back good json and make
sure it translates back to python.
"""
value = {'first_row_is_table_header': False, 'first_col_is_header': False,
'data': [['Foo', 1, None], [3.5, 'Bar', 'Baz']]}
block =... | [
"def",
"test_value_for_and_from_form",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
"[",
"'Foo'",
",",
"1",
",",
"None",
"]",
",",
"[",
"3.5",
",... | [
193,
4
] | [
205,
69
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_is_html_renderer | (self) |
Test that settings flow through correctly to
the is_html_renderer method.
|
Test that settings flow through correctly to
the is_html_renderer method.
| def test_is_html_renderer(self):
"""
Test that settings flow through correctly to
the is_html_renderer method.
"""
# TableBlock with default table_options
block1 = TableBlock()
self.assertEqual(block1.is_html_renderer(), False)
# TableBlock with altered t... | [
"def",
"test_is_html_renderer",
"(",
"self",
")",
":",
"# TableBlock with default table_options",
"block1",
"=",
"TableBlock",
"(",
")",
"self",
".",
"assertEqual",
"(",
"block1",
".",
"is_html_renderer",
"(",
")",
",",
"False",
")",
"# TableBlock with altered table_o... | [
207,
4
] | [
220,
57
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_render_with_extra_context | (self) |
Test that extra context variables passed in block.render are passed through
to the template.
|
Test that extra context variables passed in block.render are passed through
to the template.
| def test_render_with_extra_context(self):
"""
Test that extra context variables passed in block.render are passed through
to the template.
"""
block = TableBlock(template="tests/blocks/table_block_with_caption.html")
value = {'first_row_is_table_header': False, 'first_co... | [
"def",
"test_render_with_extra_context",
"(",
"self",
")",
":",
"block",
"=",
"TableBlock",
"(",
"template",
"=",
"\"tests/blocks/table_block_with_caption.html\"",
")",
"value",
"=",
"{",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"F... | [
236,
4
] | [
250,
64
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_table_block_caption_render | (self) |
Test a generic render with caption.
|
Test a generic render with caption.
| def test_table_block_caption_render(self):
"""
Test a generic render with caption.
"""
value = {'table_caption': 'caption', 'first_row_is_table_header': False,
'first_col_is_header': False,
'data': [['Test 1', 'Test 2', 'Test 3'], [None, None, None],
... | [
"def",
"test_table_block_caption_render",
"(",
"self",
")",
":",
"value",
"=",
"{",
"'table_caption'",
":",
"'caption'",
",",
"'first_row_is_table_header'",
":",
"False",
",",
"'first_col_is_header'",
":",
"False",
",",
"'data'",
":",
"[",
"[",
"'Test 1'",
",",
... | [
252,
4
] | [
273,
39
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlock.test_empty_table_block_is_not_rendered | (self) |
Test an empty table is not rendered.
|
Test an empty table is not rendered.
| def test_empty_table_block_is_not_rendered(self):
"""
Test an empty table is not rendered.
"""
value = None
block = TableBlock()
result = block.render(value)
expected = ''
self.assertHTMLEqual(result, expected)
self.assertNotIn('None', result) | [
"def",
"test_empty_table_block_is_not_rendered",
"(",
"self",
")",
":",
"value",
"=",
"None",
"block",
"=",
"TableBlock",
"(",
")",
"result",
"=",
"block",
".",
"render",
"(",
"value",
")",
"expected",
"=",
"''",
"self",
".",
"assertHTMLEqual",
"(",
"result"... | [
275,
4
] | [
285,
40
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockForm.test_default_table_options | (self) |
Test options without any custom table_options provided.
|
Test options without any custom table_options provided.
| def test_default_table_options(self):
"""
Test options without any custom table_options provided.
"""
block = TableBlock()
# check that default_table_options created correctly
self.assertEqual(block.table_options, block.get_table_options())
# check that default_ta... | [
"def",
"test_default_table_options",
"(",
"self",
")",
":",
"block",
"=",
"TableBlock",
"(",
")",
"# check that default_table_options created correctly",
"self",
".",
"assertEqual",
"(",
"block",
".",
"table_options",
",",
"block",
".",
"get_table_options",
"(",
")",
... | [
309,
4
] | [
323,
92
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockForm.test_table_options_language | (self) |
Test that the environment's language is used if no language provided.
|
Test that the environment's language is used if no language provided.
| def test_table_options_language(self):
"""
Test that the environment's language is used if no language provided.
"""
# default must always contain a language value
block = TableBlock()
self.assertIn('language', block.table_options)
# French
translation.act... | [
"def",
"test_table_options_language",
"(",
"self",
")",
":",
"# default must always contain a language value",
"block",
"=",
"TableBlock",
"(",
")",
"self",
".",
"assertIn",
"(",
"'language'",
",",
"block",
".",
"table_options",
")",
"# French",
"translation",
".",
... | [
325,
4
] | [
344,
34
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockForm.test_table_options_context_menu | (self) |
Test how contextMenu is set to default.
|
Test how contextMenu is set to default.
| def test_table_options_context_menu(self):
"""
Test how contextMenu is set to default.
"""
default_context_menu = list(DEFAULT_TABLE_OPTIONS['contextMenu']) # create copy
# confirm the default is correct
table_options = TableBlock().table_options
self.assertEqual... | [
"def",
"test_table_options_context_menu",
"(",
"self",
")",
":",
"default_context_menu",
"=",
"list",
"(",
"DEFAULT_TABLE_OPTIONS",
"[",
"'contextMenu'",
"]",
")",
"# create copy",
"# confirm the default is correct",
"table_options",
"=",
"TableBlock",
"(",
")",
".",
"t... | [
346,
4
] | [
365,
68
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockForm.test_table_options_others | (self) |
Test simple options overrides get passed correctly.
|
Test simple options overrides get passed correctly.
| def test_table_options_others(self):
"""
Test simple options overrides get passed correctly.
"""
block_1_opts = TableBlock(table_options={'startRows': 5, 'startCols': 2}).table_options
self.assertEqual(block_1_opts['startRows'], 5)
self.assertEqual(block_1_opts['startCols... | [
"def",
"test_table_options_others",
"(",
"self",
")",
":",
"block_1_opts",
"=",
"TableBlock",
"(",
"table_options",
"=",
"{",
"'startRows'",
":",
"5",
",",
"'startCols'",
":",
"2",
"}",
")",
".",
"table_options",
"self",
".",
"assertEqual",
"(",
"block_1_opts"... | [
367,
4
] | [
380,
59
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockForm.test_searchable_content | (self) |
Test searchable content is created correctly.
|
Test searchable content is created correctly.
| def test_searchable_content(self):
"""
Test searchable content is created correctly.
"""
block = TableBlock()
search_content = block.get_searchable_content(value=self.value)
self.assertIn('Galactica', search_content)
self.assertIn('Brenik', search_content) | [
"def",
"test_searchable_content",
"(",
"self",
")",
":",
"block",
"=",
"TableBlock",
"(",
")",
"search_content",
"=",
"block",
".",
"get_searchable_content",
"(",
"value",
"=",
"self",
".",
"value",
")",
"self",
".",
"assertIn",
"(",
"'Galactica'",
",",
"sea... | [
399,
4
] | [
406,
47
] | python | en | ['en', 'error', 'th'] | False |
TestTableBlockPageEdit.test_page_edit_page_view | (self) |
Test that edit page loads with saved table data and correct init function.
|
Test that edit page loads with saved table data and correct init function.
| def test_page_edit_page_view(self):
"""
Test that edit page loads with saved table data and correct init function.
"""
response = self.client.get(reverse('wagtailadmin_pages:edit', args=(self.table_block_page.id,)))
# check page + field renders
self.assertContains(respons... | [
"def",
"test_page_edit_page_view",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"reverse",
"(",
"'wagtailadmin_pages:edit'",
",",
"args",
"=",
"(",
"self",
".",
"table_block_page",
".",
"id",
",",
")",
")",
")",
"# check ... | [
432,
4
] | [
445,
50
] | python | en | ['en', 'error', 'th'] | False |
FallbackStorage._get | (self, *args, **kwargs) |
Gets a single list of messages from all storage backends.
|
Gets a single list of messages from all storage backends.
| def _get(self, *args, **kwargs):
"""
Gets a single list of messages from all storage backends.
"""
all_messages = []
for storage in self.storages:
messages, all_retrieved = storage._get()
# If the backend hasn't been used, no more retrieval is necessary.
... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"all_messages",
"=",
"[",
"]",
"for",
"storage",
"in",
"self",
".",
"storages",
":",
"messages",
",",
"all_retrieved",
"=",
"storage",
".",
"_get",
"(",
")",
"# If the b... | [
18,
4
] | [
35,
42
] | python | en | ['en', 'error', 'th'] | False |
FallbackStorage._store | (self, messages, response, *args, **kwargs) |
Stores the messages, returning any unstored messages after trying all
backends.
For each storage backend, any messages not stored are passed on to the
next backend.
|
Stores the messages, returning any unstored messages after trying all
backends. | def _store(self, messages, response, *args, **kwargs):
"""
Stores the messages, returning any unstored messages after trying all
backends.
For each storage backend, any messages not stored are passed on to the
next backend.
"""
for storage in self.storages:
... | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"storage",
"in",
"self",
".",
"storages",
":",
"if",
"messages",
":",
"messages",
"=",
"storage",
".",
"_store",
"(",
"message... | [
37,
4
] | [
54,
23
] | python | en | ['en', 'error', 'th'] | False |
format_response | (incoming_msg: WsRpcMessage, response_data: Dict[str, Any]) |
Formats the response into standard format.
|
Formats the response into standard format.
| def format_response(incoming_msg: WsRpcMessage, response_data: Dict[str, Any]) -> str:
"""
Formats the response into standard format.
"""
response = {
"command": incoming_msg["command"],
"ack": True,
"data": response_data,
"request_id": incoming_msg["request_id"],
... | [
"def",
"format_response",
"(",
"incoming_msg",
":",
"WsRpcMessage",
",",
"response_data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"response",
"=",
"{",
"\"command\"",
":",
"incoming_msg",
"[",
"\"command\"",
"]",
",",
"\"ack\"",
":... | [
29,
0
] | [
43,
19
] | python | en | ['en', 'error', 'th'] | False |
make_headers | (
keep_alive=None,
accept_encoding=None,
user_agent=None,
basic_auth=None,
proxy_basic_auth=None,
disable_cache=None,
) |
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as p... |
Shortcuts for generating request headers. | def make_headers(
keep_alive=None,
accept_encoding=None,
user_agent=None,
basic_auth=None,
proxy_basic_auth=None,
disable_cache=None,
):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_enc... | [
"def",
"make_headers",
"(",
"keep_alive",
"=",
"None",
",",
"accept_encoding",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"basic_auth",
"=",
"None",
",",
"proxy_basic_auth",
"=",
"None",
",",
"disable_cache",
"=",
"None",
",",
")",
":",
"headers",
"... | [
25,
0
] | [
94,
18
] | python | en | ['en', 'error', 'th'] | False |
set_file_position | (body, pos) |
If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use.
|
If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use.
| def set_file_position(body, pos):
"""
If a position is provided, move file to that point.
Otherwise, we'll attempt to record a position for future use.
"""
if pos is not None:
rewind_body(body, pos)
elif getattr(body, "tell", None) is not None:
try:
pos = body.tell()
... | [
"def",
"set_file_position",
"(",
"body",
",",
"pos",
")",
":",
"if",
"pos",
"is",
"not",
"None",
":",
"rewind_body",
"(",
"body",
",",
"pos",
")",
"elif",
"getattr",
"(",
"body",
",",
"\"tell\"",
",",
"None",
")",
"is",
"not",
"None",
":",
"try",
"... | [
97,
0
] | [
112,
14
] | python | en | ['en', 'error', 'th'] | False |
rewind_body | (body, body_pos) |
Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file.
|
Attempt to rewind body to a certain position.
Primarily used for request redirects and retries. | def rewind_body(body, body_pos):
"""
Attempt to rewind body to a certain position.
Primarily used for request redirects and retries.
:param body:
File-like object that supports seek.
:param int pos:
Position to seek to in file.
"""
body_seek = getattr(body, "seek", None)
... | [
"def",
"rewind_body",
"(",
"body",
",",
"body_pos",
")",
":",
"body_seek",
"=",
"getattr",
"(",
"body",
",",
"\"seek\"",
",",
"None",
")",
"if",
"body_seek",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"body_pos",
",",
"integer_types",
")",
":",
"try"... | [
115,
0
] | [
142,
9
] | python | en | ['en', 'error', 'th'] | False |
_byte_string | (s) | Cast a string or byte string to an ASCII byte string. | Cast a string or byte string to an ASCII byte string. | def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII') | [
"def",
"_byte_string",
"(",
"s",
")",
":",
"return",
"s",
".",
"encode",
"(",
"'ASCII'",
")"
] | [
12,
0
] | [
14,
28
] | python | en | ['en', 'en', 'en'] | True |
_std_string | (s) | Cast a string or byte string to an ASCII string. | Cast a string or byte string to an ASCII string. | def _std_string(s):
"""Cast a string or byte string to an ASCII string."""
return str(s.decode('ASCII')) | [
"def",
"_std_string",
"(",
"s",
")",
":",
"return",
"str",
"(",
"s",
".",
"decode",
"(",
"'ASCII'",
")",
")"
] | [
19,
0
] | [
21,
33
] | python | en | ['en', 'en', 'en'] | True |
_has_lo64 | (conn) | Return (bool, msg) about the lo64 support | Return (bool, msg) about the lo64 support | def _has_lo64(conn):
"""Return (bool, msg) about the lo64 support"""
if conn.server_version < 90300:
return (False, "server version %s doesn't support the lo64 API"
% conn.server_version)
if 'lo64' not in psycopg2.__version__:
return (False, "this psycopg build doesn't suppo... | [
"def",
"_has_lo64",
"(",
"conn",
")",
":",
"if",
"conn",
".",
"server_version",
"<",
"90300",
":",
"return",
"(",
"False",
",",
"\"server version %s doesn't support the lo64 API\"",
"%",
"conn",
".",
"server_version",
")",
"if",
"'lo64'",
"not",
"in",
"psycopg2"... | [
458,
0
] | [
467,
63
] | python | en | ['en', 'en', 'en'] | True |
model_performance | (pred,obs) |
Compute RMSE and R^2.
|
Compute RMSE and R^2.
| def model_performance(pred,obs):
"""
Compute RMSE and R^2.
"""
rmse = np.sqrt(np.mean((np.array(pred) - np.array(obs)) ** 2))
r2 = metrics.r2_score(np.array(obs),np.array(pred))
return rmse, r2 | [
"def",
"model_performance",
"(",
"pred",
",",
"obs",
")",
":",
"rmse",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"mean",
"(",
"(",
"np",
".",
"array",
"(",
"pred",
")",
"-",
"np",
".",
"array",
"(",
"obs",
")",
")",
"**",
"2",
")",
")",
"r2",
... | [
82,
0
] | [
90,
19
] | python | en | ['en', 'error', 'th'] | False |
pca | (X, n_components=1) |
PCA reduction of dimensions.
|
PCA reduction of dimensions.
| def pca(X, n_components=1):
"""
PCA reduction of dimensions.
"""
model = PCA(n_components=n_components, copy=True)
model.fit(X)
ev = sum(model.explained_variance_ratio_[:n_components])
print('Explained variance = ' + str(ev))
columns = ['pc' + str(i + 1) for i in range(n_c... | [
"def",
"pca",
"(",
"X",
",",
"n_components",
"=",
"1",
")",
":",
"model",
"=",
"PCA",
"(",
"n_components",
"=",
"n_components",
",",
"copy",
"=",
"True",
")",
"model",
".",
"fit",
"(",
"X",
")",
"ev",
"=",
"sum",
"(",
"model",
".",
"explained_varia... | [
94,
0
] | [
108,
50
] | python | en | ['en', 'error', 'th'] | False |
standard.standardize_target | (self, df, target) |
Standardize target vector to zero mean and unit variance.
|
Standardize target vector to zero mean and unit variance.
| def standardize_target(self, df, target):
"""
Standardize target vector to zero mean and unit variance.
"""
if len(df) < 2:
return df
unstandard_vector = df[target].values
self.unstandardized = unstandard_vector
mean, std = unstandard_vector.... | [
"def",
"standardize_target",
"(",
"self",
",",
"df",
",",
"target",
")",
":",
"if",
"len",
"(",
"df",
")",
"<",
"2",
":",
"return",
"df",
"unstandard_vector",
"=",
"df",
"[",
"target",
"]",
".",
"values",
"self",
".",
"unstandardized",
"=",
"unstandard... | [
25,
4
] | [
48,
21
] | python | en | ['en', 'error', 'th'] | False |
standard.unstandardize_target | (self, df, target) |
Retrun target data batck to unstandardized form
via saved mean and standard deviation.
|
Retrun target data batck to unstandardized form
via saved mean and standard deviation.
| def unstandardize_target(self, df, target):
"""
Retrun target data batck to unstandardized form
via saved mean and standard deviation.
"""
if len(df) < 2:
return df
if len(df) == len(self.unstandardized):
new_df = df.copy().drop(t... | [
"def",
"unstandardize_target",
"(",
"self",
",",
"df",
",",
"target",
")",
":",
"if",
"len",
"(",
"df",
")",
"<",
"2",
":",
"return",
"df",
"if",
"len",
"(",
"df",
")",
"==",
"len",
"(",
"self",
".",
"unstandardized",
")",
":",
"new_df",
"=",
"df... | [
50,
4
] | [
70,
21
] | python | en | ['en', 'error', 'th'] | False |
standard.unstandardize | (self, array) |
Unstandardize an array of values.
|
Unstandardize an array of values.
| def unstandardize(self, array):
"""
Unstandardize an array of values.
"""
return (array * self.std) + self.mean | [
"def",
"unstandardize",
"(",
"self",
",",
"array",
")",
":",
"return",
"(",
"array",
"*",
"self",
".",
"std",
")",
"+",
"self",
".",
"mean"
] | [
72,
4
] | [
77,
45
] | python | en | ['en', 'error', 'th'] | False |
ImageTransform.resize | (self, size) |
Change the image size, stretching the transform to make it fit the new size.
|
Change the image size, stretching the transform to make it fit the new size.
| def resize(self, size):
"""
Change the image size, stretching the transform to make it fit the new size.
"""
self._check_size(size)
clone = self.clone()
clone.scale = (
clone.scale[0] * size[0] / self.size[0],
clone.scale[1] * size[1] / self.size[1... | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"_check_size",
"(",
"size",
")",
"clone",
"=",
"self",
".",
"clone",
"(",
")",
"clone",
".",
"scale",
"=",
"(",
"clone",
".",
"scale",
"[",
"0",
"]",
"*",
"size",
"[",
"0",
"]",
... | [
51,
4
] | [
62,
20
] | python | en | ['en', 'error', 'th'] | False |
ImageTransform.crop | (self, rect) |
Crop the image to the specified rect.
|
Crop the image to the specified rect.
| def crop(self, rect):
"""
Crop the image to the specified rect.
"""
self._check_size(tuple(rect.size))
# Transform the image so the top left of the rect is at (0, 0), then set the size
clone = self.clone()
clone.offset = (
clone.offset[0] - rect.left ... | [
"def",
"crop",
"(",
"self",
",",
"rect",
")",
":",
"self",
".",
"_check_size",
"(",
"tuple",
"(",
"rect",
".",
"size",
")",
")",
"# Transform the image so the top left of the rect is at (0, 0), then set the size",
"clone",
"=",
"self",
".",
"clone",
"(",
")",
"c... | [
64,
4
] | [
77,
20
] | python | en | ['en', 'error', 'th'] | False |
ImageTransform.transform_vector | (self, vector) |
Transforms the given vector into the coordinate space of the final image.
Use this to find out where a point on the source image would end up in the
final image after cropping/resizing has been performed.
Returns a new vector.
|
Transforms the given vector into the coordinate space of the final image. | def transform_vector(self, vector):
"""
Transforms the given vector into the coordinate space of the final image.
Use this to find out where a point on the source image would end up in the
final image after cropping/resizing has been performed.
Returns a new vector.
"""... | [
"def",
"transform_vector",
"(",
"self",
",",
"vector",
")",
":",
"return",
"Vector",
"(",
"(",
"vector",
".",
"x",
"+",
"self",
".",
"offset",
"[",
"0",
"]",
")",
"*",
"self",
".",
"scale",
"[",
"0",
"]",
",",
"(",
"vector",
".",
"y",
"+",
"sel... | [
79,
4
] | [
91,
9
] | python | en | ['en', 'error', 'th'] | False |
ImageTransform.untransform_vector | (self, vector) |
Transforms the given vector back to the coordinate space of the source image.
This performs the inverse of `transform_vector`. Use this to find where a point
in the final cropped/resized image originated from in the source image.
Returns a new vector.
|
Transforms the given vector back to the coordinate space of the source image. | def untransform_vector(self, vector):
"""
Transforms the given vector back to the coordinate space of the source image.
This performs the inverse of `transform_vector`. Use this to find where a point
in the final cropped/resized image originated from in the source image.
Return... | [
"def",
"untransform_vector",
"(",
"self",
",",
"vector",
")",
":",
"return",
"Vector",
"(",
"vector",
".",
"x",
"/",
"self",
".",
"scale",
"[",
"0",
"]",
"-",
"self",
".",
"offset",
"[",
"0",
"]",
",",
"vector",
".",
"y",
"/",
"self",
".",
"scale... | [
93,
4
] | [
105,
9
] | python | en | ['en', 'error', 'th'] | False |
ImageTransform.get_rect | (self) |
Returns a Rect representing the region of the original image to be cropped.
|
Returns a Rect representing the region of the original image to be cropped.
| def get_rect(self):
"""
Returns a Rect representing the region of the original image to be cropped.
"""
return Rect(
-self.offset[0],
-self.offset[1],
-self.offset[0] + self.size[0] / self.scale[0],
-self.offset[1] + self.size[1] / self.sca... | [
"def",
"get_rect",
"(",
"self",
")",
":",
"return",
"Rect",
"(",
"-",
"self",
".",
"offset",
"[",
"0",
"]",
",",
"-",
"self",
".",
"offset",
"[",
"1",
"]",
",",
"-",
"self",
".",
"offset",
"[",
"0",
"]",
"+",
"self",
".",
"size",
"[",
"0",
... | [
107,
4
] | [
116,
9
] | python | en | ['en', 'error', 'th'] | False |
create_genesis_or_zero_coin_checker | (genesis_coin_id: bytes32) |
Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
|
Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
| def create_genesis_or_zero_coin_checker(genesis_coin_id: bytes32) -> Program:
"""
Given a specific genesis coin id, create a `genesis_coin_mod` that allows
both that coin id to issue a cc, or anyone to create a cc with amount 0.
"""
genesis_coin_mod = MOD
return genesis_coin_mod.curry(genesis_co... | [
"def",
"create_genesis_or_zero_coin_checker",
"(",
"genesis_coin_id",
":",
"bytes32",
")",
"->",
"Program",
":",
"genesis_coin_mod",
"=",
"MOD",
"return",
"genesis_coin_mod",
".",
"curry",
"(",
"genesis_coin_id",
")"
] | [
10,
0
] | [
16,
50
] | python | en | ['en', 'error', 'th'] | False |
genesis_coin_id_for_genesis_coin_checker | (
genesis_coin_checker: Program,
) |
Given a `genesis_coin_checker` program, pull out the genesis coin id.
|
Given a `genesis_coin_checker` program, pull out the genesis coin id.
| def genesis_coin_id_for_genesis_coin_checker(
genesis_coin_checker: Program,
) -> Optional[bytes32]:
"""
Given a `genesis_coin_checker` program, pull out the genesis coin id.
"""
r = genesis_coin_checker.uncurry()
if r is None:
return r
f, args = r
if f != MOD:
return Non... | [
"def",
"genesis_coin_id_for_genesis_coin_checker",
"(",
"genesis_coin_checker",
":",
"Program",
",",
")",
"->",
"Optional",
"[",
"bytes32",
"]",
":",
"r",
"=",
"genesis_coin_checker",
".",
"uncurry",
"(",
")",
"if",
"r",
"is",
"None",
":",
"return",
"r",
"f",
... | [
19,
0
] | [
31,
33
] | python | en | ['en', 'error', 'th'] | False |
calculate_frequencies | (file_contents) |
# ALTERNATIVE CODE
newFile = ""
for index, char in enumerate(file_contents):
if (char.isalpha() == True or char.isspace()):
newFile += char
newFile = newFile.split()
wordCloudFile = []
for word in newFile:
if ((word.lower() not in uninteresting_words) and (word... |
# ALTERNATIVE CODE
newFile = ""
for index, char in enumerate(file_contents):
if (char.isalpha() == True or char.isspace()):
newFile += char | def calculate_frequencies(file_contents):
# Here is a list of punctuations and uninteresting words you can use to process your text
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", "we", "our", "o... | [
"def",
"calculate_frequencies",
"(",
"file_contents",
")",
":",
"# Here is a list of punctuations and uninteresting words you can use to process your text",
"punctuations",
"=",
"'''!()-[]{};:'\"\\,<>./?@#$%^&*_~'''",
"uninteresting_words",
"=",
"[",
"\"the\"",
",",
"\"a\"",
",",
"... | [
73,
0
] | [
128,
27
] | python | en | ['en', 'error', 'th'] | False |
upload_docs._build_multipart | (cls, data) |
Build up the MIME payload for the POST data
|
Build up the MIME payload for the POST data
| def _build_multipart(cls, data):
"""
Build up the MIME payload for the POST data
"""
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = b'\n--' + boundary.encode('ascii')
end_boundary = sep_boundary + b'--'
end_items = end_boundary, b"... | [
"def",
"_build_multipart",
"(",
"cls",
",",
"data",
")",
":",
"boundary",
"=",
"'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'",
"sep_boundary",
"=",
"b'\\n--'",
"+",
"boundary",
".",
"encode",
"(",
"'ascii'",
")",
"end_boundary",
"=",
"sep_boundary",
"+",
"b... | [
123,
4
] | [
139,
49
] | python | en | ['en', 'error', 'th'] | False |
AppveyorHookTests.test_appveyor_build_success_message | (self) |
Tests if appveyor build success notification is handled correctly
|
Tests if appveyor build success notification is handled correctly
| def test_appveyor_build_success_message(self) -> None:
"""
Tests if appveyor build success notification is handled correctly
"""
expected_topic = "Hubot-DSC-Resource"
expected_message = """
[Build Hubot-DSC-Resource 2.0.59 completed](https://ci.appveyor.com/project/joebloggs/hubo... | [
"def",
"test_appveyor_build_success_message",
"(",
"self",
")",
"->",
"None",
":",
"expected_topic",
"=",
"\"Hubot-DSC-Resource\"",
"expected_message",
"=",
"\"\"\"\n[Build Hubot-DSC-Resource 2.0.59 completed](https://ci.appveyor.com/project/joebloggs/hubot-dsc-resource/build/2.0.59):\n* *... | [
8,
4
] | [
20,
86
] | python | en | ['en', 'error', 'th'] | False |
AppveyorHookTests.test_appveyor_build_failure_message | (self) |
Tests if appveyor build failure notification is handled correctly
|
Tests if appveyor build failure notification is handled correctly
| def test_appveyor_build_failure_message(self) -> None:
"""
Tests if appveyor build failure notification is handled correctly
"""
expected_topic = "Hubot-DSC-Resource"
expected_message = """
[Build Hubot-DSC-Resource 2.0.59 failed](https://ci.appveyor.com/project/joebloggs/hubot-d... | [
"def",
"test_appveyor_build_failure_message",
"(",
"self",
")",
"->",
"None",
":",
"expected_topic",
"=",
"\"Hubot-DSC-Resource\"",
"expected_message",
"=",
"\"\"\"\n[Build Hubot-DSC-Resource 2.0.59 failed](https://ci.appveyor.com/project/joebloggs/hubot-dsc-resource/build/2.0.59):\n* **Co... | [
22,
4
] | [
34,
86
] | python | en | ['en', 'error', 'th'] | False |
DistanceRatioExperiment.__init__ | (self, N, vectors, coverage_ratio=0.2) |
Performs exact nearest neighbour search on the data set.
vectors can either be a numpy matrix with all the vectors
as columns OR a python array containing the individual
numpy vectors.
|
Performs exact nearest neighbour search on the data set. | def __init__(self, N, vectors, coverage_ratio=0.2):
"""
Performs exact nearest neighbour search on the data set.
vectors can either be a numpy matrix with all the vectors
as columns OR a python array containing the individual
numpy vectors.
"""
# We need a dict f... | [
"def",
"__init__",
"(",
"self",
",",
"N",
",",
"vectors",
",",
"coverage_ratio",
"=",
"0.2",
")",
":",
"# We need a dict from vector string representation to index",
"self",
".",
"vector_dict",
"=",
"{",
"}",
"self",
".",
"N",
"=",
"N",
"self",
".",
"coverage_... | [
67,
4
] | [
124,
75
] | python | en | ['en', 'error', 'th'] | False |
DistanceRatioExperiment.perform_experiment | (self, engine_list) |
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
search_time is the average retrieval/search time... |
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list. | def perform_experiment(self, engine_list):
"""
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
... | [
"def",
"perform_experiment",
"(",
"self",
",",
"engine_list",
")",
":",
"# We will fill this array with measures for all the engines.",
"result",
"=",
"[",
"]",
"# For each engine, first index vectors and then retrieve neighbours",
"for",
"engine",
"in",
"engine_list",
":",
"pr... | [
126,
4
] | [
213,
21
] | python | en | ['en', 'error', 'th'] | False |
DistanceRatioExperiment.__vector_to_string | (self, vector) | Returns string representation of vector. | Returns string representation of vector. | def __vector_to_string(self, vector):
""" Returns string representation of vector. """
return numpy.array_str(vector) | [
"def",
"__vector_to_string",
"(",
"self",
",",
"vector",
")",
":",
"return",
"numpy",
".",
"array_str",
"(",
"vector",
")"
] | [
215,
4
] | [
217,
38
] | python | en | ['en', 'sv', 'en'] | True |
DistanceRatioExperiment.__index_of_vector | (self, vector) | Returns index of specified vector from test data set. | Returns index of specified vector from test data set. | def __index_of_vector(self, vector):
""" Returns index of specified vector from test data set. """
return self.vector_dict[self.__vector_to_string(vector)] | [
"def",
"__index_of_vector",
"(",
"self",
",",
"vector",
")",
":",
"return",
"self",
".",
"vector_dict",
"[",
"self",
".",
"__vector_to_string",
"(",
"vector",
")",
"]"
] | [
219,
4
] | [
221,
64
] | python | en | ['en', 'en', 'en'] | True |
objectify_response_json | (response) | return a PseudoNamespace() from requests.Response.json(). | return a PseudoNamespace() from requests.Response.json(). | def objectify_response_json(response):
"""return a PseudoNamespace() from requests.Response.json()."""
try:
json = response.json()
except ValueError:
json = dict()
# PseudoNamespace arg must be a dict, and json can be an array.
# TODO: Assess if list elements should be PseudoNamespa... | [
"def",
"objectify_response_json",
"(",
"response",
")",
":",
"try",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"json",
"=",
"dict",
"(",
")",
"# PseudoNamespace arg must be a dict, and json can be an array.",
"# TODO: Assess if l... | [
76,
0
] | [
87,
15
] | python | en | ['en', 'en', 'en'] | True |
Page.__item_class__ | (self) | Returns the class representing a single 'Page' item | Returns the class representing a single 'Page' item | def __item_class__(self):
"""Returns the class representing a single 'Page' item"""
return self.__class__ | [
"def",
"__item_class__",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__"
] | [
143,
4
] | [
145,
29
] | python | en | ['en', 'en', 'en'] | True |
Page.page_identity | (self, response, request_json=None) | Takes a `requests.Response` and
returns a new __item_class__ instance if the request method is not a get, or returns
a __class__ instance if the request path is different than the caller's `endpoint`.
| Takes a `requests.Response` and
returns a new __item_class__ instance if the request method is not a get, or returns
a __class__ instance if the request path is different than the caller's `endpoint`.
| def page_identity(self, response, request_json=None):
"""Takes a `requests.Response` and
returns a new __item_class__ instance if the request method is not a get, or returns
a __class__ instance if the request path is different than the caller's `endpoint`.
"""
request_path = ... | [
"def",
"page_identity",
"(",
"self",
",",
"response",
",",
"request_json",
"=",
"None",
")",
":",
"request_path",
"=",
"response",
".",
"request",
".",
"path_url",
"if",
"request_path",
"==",
"'/migrations_notran/'",
":",
"raise",
"exc",
".",
"IsMigrating",
"(... | [
156,
4
] | [
226,
44
] | python | en | ['en', 'en', 'en'] | True |
Page.update_identity | (self, obj) | Takes a `Page` and updates attributes to reflect its content | Takes a `Page` and updates attributes to reflect its content | def update_identity(self, obj):
"""Takes a `Page` and updates attributes to reflect its content"""
self.endpoint = obj.endpoint
self.json = obj.json
self.last_elapsed = obj.last_elapsed
self.r = obj.r
return self | [
"def",
"update_identity",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"endpoint",
"=",
"obj",
".",
"endpoint",
"self",
".",
"json",
"=",
"obj",
".",
"json",
"self",
".",
"last_elapsed",
"=",
"obj",
".",
"last_elapsed",
"self",
".",
"r",
"=",
"obj... | [
228,
4
] | [
234,
19
] | python | en | ['en', 'en', 'en'] | True |
Page.put | (self, json=None) | If a payload is supplied, PUT the payload. If not, submit our existing page JSON as our payload. | If a payload is supplied, PUT the payload. If not, submit our existing page JSON as our payload. | def put(self, json=None):
"""If a payload is supplied, PUT the payload. If not, submit our existing page JSON as our payload."""
json = self.json if json is None else json
r = self.connection.put(self.endpoint, json=json)
return self.page_identity(r, request_json=json) | [
"def",
"put",
"(",
"self",
",",
"json",
"=",
"None",
")",
":",
"json",
"=",
"self",
".",
"json",
"if",
"json",
"is",
"None",
"else",
"json",
"r",
"=",
"self",
".",
"connection",
".",
"put",
"(",
"self",
".",
"endpoint",
",",
"json",
"=",
"json",
... | [
273,
4
] | [
277,
55
] | python | en | ['en', 'en', 'en'] | True |
PageList.__item_class__ | (self) | Returns the class representing a single 'Page' item
With an inheritence of OrgListSubClass -> OrgList -> PageList -> Org -> Base -> Page, the following
will return the parent class of the current object (e.g. 'Org').
Obtaining a page type by registered endpoint is highly recommended over using ... | Returns the class representing a single 'Page' item
With an inheritence of OrgListSubClass -> OrgList -> PageList -> Org -> Base -> Page, the following
will return the parent class of the current object (e.g. 'Org'). | def __item_class__(self):
"""Returns the class representing a single 'Page' item
With an inheritence of OrgListSubClass -> OrgList -> PageList -> Org -> Base -> Page, the following
will return the parent class of the current object (e.g. 'Org').
Obtaining a page type by registered endpo... | [
"def",
"__item_class__",
"(",
"self",
")",
":",
"mro",
"=",
"inspect",
".",
"getmro",
"(",
"self",
".",
"__class__",
")",
"bl_index",
"=",
"mro",
".",
"index",
"(",
"PageList",
")",
"return",
"mro",
"[",
"bl_index",
"+",
"1",
"]"
] | [
332,
4
] | [
341,
32
] | python | en | ['en', 'en', 'en'] | True |
TentativePage.create_or_replace | (self, **query_parameters) | Create an object, and if any other item shares the name, delete that one first.
Generally, requires 'name' of object.
Exceptions:
- Users are looked up by username
- Teams need to be looked up by name + organization
| Create an object, and if any other item shares the name, delete that one first. | def create_or_replace(self, **query_parameters):
"""Create an object, and if any other item shares the name, delete that one first.
Generally, requires 'name' of object.
Exceptions:
- Users are looked up by username
- Teams need to be looked up by name + organization
... | [
"def",
"create_or_replace",
"(",
"self",
",",
"*",
"*",
"query_parameters",
")",
":",
"page",
"=",
"None",
"# look up users by username not name",
"if",
"'users'",
"in",
"self",
":",
"assert",
"query_parameters",
".",
"get",
"(",
"'username'",
")",
",",
"'For th... | [
387,
4
] | [
417,
46
] | python | en | ['en', 'en', 'en'] | True |
TentativePage.get_or_create | (self, **query_parameters) | Get an object by this name or id if it exists, otherwise create it.
Exceptions:
- Users are looked up by username
- Teams need to be looked up by name + organization
| Get an object by this name or id if it exists, otherwise create it. | def get_or_create(self, **query_parameters):
"""Get an object by this name or id if it exists, otherwise create it.
Exceptions:
- Users are looked up by username
- Teams need to be looked up by name + organization
"""
page = None
# look up users by username n... | [
"def",
"get_or_create",
"(",
"self",
",",
"*",
"*",
"query_parameters",
")",
":",
"page",
"=",
"None",
"# look up users by username not name",
"if",
"query_parameters",
".",
"get",
"(",
"'username'",
")",
"and",
"'users'",
"in",
"self",
":",
"page",
"=",
"self... | [
419,
4
] | [
446,
50
] | python | en | ['en', 'en', 'en'] | True |
_parents | (path) |
Given a path with elements separated by
posixpath.sep, generate all parents of that path.
>>> list(_parents('b/d'))
['b']
>>> list(_parents('/b/d/'))
['/b']
>>> list(_parents('b/d/f/'))
['b/d', 'b']
>>> list(_parents('b'))
[]
>>> list(_parents(''))
[]
|
Given a path with elements separated by
posixpath.sep, generate all parents of that path. | def _parents(path):
"""
Given a path with elements separated by
posixpath.sep, generate all parents of that path.
>>> list(_parents('b/d'))
['b']
>>> list(_parents('/b/d/'))
['/b']
>>> list(_parents('b/d/f/'))
['b/d', 'b']
>>> list(_parents('b'))
[]
>>> list(_parents('')... | [
"def",
"_parents",
"(",
"path",
")",
":",
"return",
"itertools",
".",
"islice",
"(",
"_ancestry",
"(",
"path",
")",
",",
"1",
",",
"None",
")"
] | [
14,
0
] | [
30,
53
] | python | en | ['en', 'error', 'th'] | False |
_ancestry | (path) |
Given a path with elements separated by
posixpath.sep, generate all elements of that path
>>> list(_ancestry('b/d'))
['b/d', 'b']
>>> list(_ancestry('/b/d/'))
['/b/d', '/b']
>>> list(_ancestry('b/d/f/'))
['b/d/f', 'b/d', 'b']
>>> list(_ancestry('b'))
['b']
>>> list(_ancestr... |
Given a path with elements separated by
posixpath.sep, generate all elements of that path | def _ancestry(path):
"""
Given a path with elements separated by
posixpath.sep, generate all elements of that path
>>> list(_ancestry('b/d'))
['b/d', 'b']
>>> list(_ancestry('/b/d/'))
['/b/d', '/b']
>>> list(_ancestry('b/d/f/'))
['b/d/f', 'b/d', 'b']
>>> list(_ancestry('b'))
... | [
"def",
"_ancestry",
"(",
"path",
")",
":",
"path",
"=",
"path",
".",
"rstrip",
"(",
"posixpath",
".",
"sep",
")",
"while",
"path",
"and",
"path",
"!=",
"posixpath",
".",
"sep",
":",
"yield",
"path",
"path",
",",
"tail",
"=",
"posixpath",
".",
"split"... | [
33,
0
] | [
52,
42
] | python | en | ['en', 'error', 'th'] | False |
_difference | (minuend, subtrahend) |
Return items in minuend not in subtrahend, retaining order
with O(1) lookup.
|
Return items in minuend not in subtrahend, retaining order
with O(1) lookup.
| def _difference(minuend, subtrahend):
"""
Return items in minuend not in subtrahend, retaining order
with O(1) lookup.
"""
return itertools.filterfalse(set(subtrahend).__contains__, minuend) | [
"def",
"_difference",
"(",
"minuend",
",",
"subtrahend",
")",
":",
"return",
"itertools",
".",
"filterfalse",
"(",
"set",
"(",
"subtrahend",
")",
".",
"__contains__",
",",
"minuend",
")"
] | [
59,
0
] | [
64,
71
] | python | en | ['en', 'error', 'th'] | False |
_pathlib_compat | (path) |
For path-like objects, convert to a filename for compatibility
on Python 3.6.1 and earlier.
|
For path-like objects, convert to a filename for compatibility
on Python 3.6.1 and earlier.
| def _pathlib_compat(path):
"""
For path-like objects, convert to a filename for compatibility
on Python 3.6.1 and earlier.
"""
try:
return path.__fspath__()
except AttributeError:
return str(path) | [
"def",
"_pathlib_compat",
"(",
"path",
")",
":",
"try",
":",
"return",
"path",
".",
"__fspath__",
"(",
")",
"except",
"AttributeError",
":",
"return",
"str",
"(",
"path",
")"
] | [
135,
0
] | [
143,
24
] | python | en | ['en', 'error', 'th'] | False |
CompleteDirs.resolve_dir | (self, name) |
If the name represents a directory, return that name
as a directory (with the trailing slash).
|
If the name represents a directory, return that name
as a directory (with the trailing slash).
| def resolve_dir(self, name):
"""
If the name represents a directory, return that name
as a directory (with the trailing slash).
"""
names = self._name_set()
dirname = name + '/'
dir_match = name not in names and dirname in names
return dirname if dir_match... | [
"def",
"resolve_dir",
"(",
"self",
",",
"name",
")",
":",
"names",
"=",
"self",
".",
"_name_set",
"(",
")",
"dirname",
"=",
"name",
"+",
"'/'",
"dir_match",
"=",
"name",
"not",
"in",
"names",
"and",
"dirname",
"in",
"names",
"return",
"dirname",
"if",
... | [
86,
4
] | [
94,
45
] | python | en | ['en', 'error', 'th'] | False |
CompleteDirs.make | (cls, source) |
Given a source (filename or zipfile), return an
appropriate CompleteDirs subclass.
|
Given a source (filename or zipfile), return an
appropriate CompleteDirs subclass.
| def make(cls, source):
"""
Given a source (filename or zipfile), return an
appropriate CompleteDirs subclass.
"""
if isinstance(source, CompleteDirs):
return source
if not isinstance(source, zipfile.ZipFile):
return cls(_pathlib_compat(source))
... | [
"def",
"make",
"(",
"cls",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"CompleteDirs",
")",
":",
"return",
"source",
"if",
"not",
"isinstance",
"(",
"source",
",",
"zipfile",
".",
"ZipFile",
")",
":",
"return",
"cls",
"(",
"_pathli... | [
97,
4
] | [
113,
21
] | python | en | ['en', 'error', 'th'] | False |
Path.__init__ | (self, root, at="") |
Construct a Path from a ZipFile or filename.
Note: When the source is an existing ZipFile object,
its type (__class__) will be mutated to a
specialized type. If the caller wishes to retain the
original type, the caller should either create a
separate ZipFile object or p... |
Construct a Path from a ZipFile or filename. | def __init__(self, root, at=""):
"""
Construct a Path from a ZipFile or filename.
Note: When the source is an existing ZipFile object,
its type (__class__) will be mutated to a
specialized type. If the caller wishes to retain the
original type, the caller should either c... | [
"def",
"__init__",
"(",
"self",
",",
"root",
",",
"at",
"=",
"\"\"",
")",
":",
"self",
".",
"root",
"=",
"FastLookup",
".",
"make",
"(",
"root",
")",
"self",
".",
"at",
"=",
"at"
] | [
226,
4
] | [
237,
20
] | python | en | ['en', 'error', 'th'] | False |
Path.open | (self, mode='r', *args, pwd=None, **kwargs) |
Open this entry as text or binary following the semantics
of ``pathlib.Path.open()`` by passing arguments through
to io.TextIOWrapper().
|
Open this entry as text or binary following the semantics
of ``pathlib.Path.open()`` by passing arguments through
to io.TextIOWrapper().
| def open(self, mode='r', *args, pwd=None, **kwargs):
"""
Open this entry as text or binary following the semantics
of ``pathlib.Path.open()`` by passing arguments through
to io.TextIOWrapper().
"""
if self.is_dir():
raise IsADirectoryError(self)
zip_mo... | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"*",
"args",
",",
"pwd",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_dir",
"(",
")",
":",
"raise",
"IsADirectoryError",
"(",
"self",
")",
"zip_mode",
"=",
"mode"... | [
239,
4
] | [
255,
56
] | python | en | ['en', 'error', 'th'] | False |
NormalizingFlowEstimator.fit | (self, X, Y, random_seed=None, verbose=True, eval_set=None, **kwargs) |
Fit the model with to the provided data
:param X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
:param Y: numpy array of y targets - shape: (n_samples, n_dim_y)
:param eval_set: (tuple) eval/test dataset - tuple (X_test, Y_test)
:param verbose: (boolean) contro... |
Fit the model with to the provided data | def fit(self, X, Y, random_seed=None, verbose=True, eval_set=None, **kwargs):
"""
Fit the model with to the provided data
:param X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
:param Y: numpy array of y targets - shape: (n_samples, n_dim_y)
:param eval_set: (t... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"Y",
",",
"random_seed",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"eval_set",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",... | [
101,
4
] | [
138,
26
] | python | en | ['en', 'error', 'th'] | False |
NormalizingFlowEstimator.reset_fit | (self) |
Resets all tensorflow objects and enables this model to be fitted anew
|
Resets all tensorflow objects and enables this model to be fitted anew
| def reset_fit(self):
"""
Resets all tensorflow objects and enables this model to be fitted anew
"""
tf.reset_default_graph()
self._build_model()
self.fitted = False | [
"def",
"reset_fit",
"(",
"self",
")",
":",
"tf",
".",
"reset_default_graph",
"(",
")",
"self",
".",
"_build_model",
"(",
")",
"self",
".",
"fitted",
"=",
"False"
] | [
140,
4
] | [
146,
27
] | python | en | ['en', 'error', 'th'] | False |
NormalizingFlowEstimator._build_model | (self) |
implementation of the flow model
|
implementation of the flow model
| def _build_model(self):
"""
implementation of the flow model
"""
with tf.variable_scope(self.name):
# adds placeholders, data normalization and data noise to graph as desired. Also sets up a placeholder
# for dropout
self.layer_in_x, self.layer_in_y = ... | [
"def",
"_build_model",
"(",
"self",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"self",
".",
"name",
")",
":",
"# adds placeholders, data normalization and data noise to graph as desired. Also sets up a placeholder",
"# for dropout",
"self",
".",
"layer_in_x",
",",
... | [
170,
4
] | [
253,
82
] | python | en | ['en', 'error', 'th'] | False |
Collector.add | (self, objs, source=None, nullable=False, reverse_dependency=False) |
Adds 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it,
and 'nullable' should be set to True if the relation can be null.
Returns a list of all objects that were not already collected.
|
Adds 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it,
and 'nullable' should be set to True if the relation can be null. | def add(self, objs, source=None, nullable=False, reverse_dependency=False):
"""
Adds 'objs' to the collection of objects to be deleted. If the call is
the result of a cascade, 'source' should be the model that caused it,
and 'nullable' should be set to True if the relation can be null.
... | [
"def",
"add",
"(",
"self",
",",
"objs",
",",
"source",
"=",
"None",
",",
"nullable",
"=",
"False",
",",
"reverse_dependency",
"=",
"False",
")",
":",
"if",
"not",
"objs",
":",
"return",
"[",
"]",
"new_objs",
"=",
"[",
"]",
"model",
"=",
"objs",
"["... | [
80,
4
] | [
105,
23
] | python | en | ['en', 'error', 'th'] | False |
Collector.add_field_update | (self, field, value, objs) |
Schedules a field update. 'objs' must be a homogeneous iterable
collection of model instances (e.g. a QuerySet).
|
Schedules a field update. 'objs' must be a homogeneous iterable
collection of model instances (e.g. a QuerySet).
| def add_field_update(self, field, value, objs):
"""
Schedules a field update. 'objs' must be a homogeneous iterable
collection of model instances (e.g. a QuerySet).
"""
if not objs:
return
model = objs[0].__class__
self.field_updates.setdefault(
... | [
"def",
"add_field_update",
"(",
"self",
",",
"field",
",",
"value",
",",
"objs",
")",
":",
"if",
"not",
"objs",
":",
"return",
"model",
"=",
"objs",
"[",
"0",
"]",
".",
"__class__",
"self",
".",
"field_updates",
".",
"setdefault",
"(",
"model",
",",
... | [
107,
4
] | [
117,
47
] | python | en | ['en', 'error', 'th'] | False |
Collector.can_fast_delete | (self, objs, from_field=None) |
Determines if the objects in the given queryset-like can be
fast-deleted. This can be done if there are no cascades, no
parents and no signal listeners for the object class.
The 'from_field' tells where we are coming from - we need this to
determine if the objects are in fact t... |
Determines if the objects in the given queryset-like can be
fast-deleted. This can be done if there are no cascades, no
parents and no signal listeners for the object class. | def can_fast_delete(self, objs, from_field=None):
"""
Determines if the objects in the given queryset-like can be
fast-deleted. This can be done if there are no cascades, no
parents and no signal listeners for the object class.
The 'from_field' tells where we are coming from - w... | [
"def",
"can_fast_delete",
"(",
"self",
",",
"objs",
",",
"from_field",
"=",
"None",
")",
":",
"if",
"from_field",
"and",
"from_field",
".",
"remote_field",
".",
"on_delete",
"is",
"not",
"CASCADE",
":",
"return",
"False",
"if",
"not",
"(",
"hasattr",
"(",
... | [
119,
4
] | [
153,
19
] | python | en | ['en', 'error', 'th'] | False |
Collector.get_del_batches | (self, objs, field) |
Returns the objs in suitably sized batches for the used connection.
|
Returns the objs in suitably sized batches for the used connection.
| def get_del_batches(self, objs, field):
"""
Returns the objs in suitably sized batches for the used connection.
"""
conn_batch_size = max(
connections[self.using].ops.bulk_batch_size([field.name], objs), 1)
if len(objs) > conn_batch_size:
return [objs[i:i ... | [
"def",
"get_del_batches",
"(",
"self",
",",
"objs",
",",
"field",
")",
":",
"conn_batch_size",
"=",
"max",
"(",
"connections",
"[",
"self",
".",
"using",
"]",
".",
"ops",
".",
"bulk_batch_size",
"(",
"[",
"field",
".",
"name",
"]",
",",
"objs",
")",
... | [
155,
4
] | [
165,
25
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.