Unnamed: 0
int64
0
2.93k
code
stringlengths
101
62.2k
docs
stringlengths
51
10.7k
doc_len
int64
4
1.74k
words
int64
4
4.82k
lang
stringclasses
1 value
prompt
stringlengths
320
71.2k
1,300
def monthdays2calendar(self, year, month): days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ]
Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero.
27
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def monthdays2calendar(self, year, month): days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ] ``` ###A...
1,301
async def predict_with_route(self, route_path, *args, **kwargs): if route_path not in self.dags: raise RayServeException(f"{route_path} does not exist in dags routes") return await self.dags[route_path].remote(*args, **kwargs)
Perform inference directly without HTTP for multi dags.
8
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def predict_with_route(self, route_path, *args, **kwargs): if route_path not in self.dags: raise RayServeException(f"{route_path} does not exist in dags ro...
1,302
def should_recover(self): return ( self.num_failures < self.max_failures or self.max_failures < 0 or ( self.num_failures == self.max_failures and self.num_restore_failures < int(os.environ.get("TUNE_RESTORE_RETRY_NUM", ...
Returns whether the trial qualifies for retrying. This is if the trial has not failed more than max_failures. Note this may return true even when there is no checkpoint, either because `self.checkpoint_freq` is `0` or because the trial failed before a checkpoint has been made.
45
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def should_recover(self): return ( self.num_failures < self.max_failures or self.max_failures < 0 or ( self.num_failures ...
1,303
def test_change_root_page_locale_on_locale_deletion(self): # change 'real' pages first Page.objects.filter(depth__gt=1).update( locale=Locale.objects.get(language_code="fr") ) self.assertEqual(Page.get_first_root_node().locale.language_code, "en") Locale.obje...
On deleting the locale used for the root page (but no 'real' pages), the root page should be reassigned to a new locale (the default one, if possible)
28
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_change_root_page_locale_on_locale_deletion(self): # change 'real' pages first Page.objects.filter(depth__gt=1).update( locale=Locale.objects.get...
1,304
def _proc_pax(self, tarfile): # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental information for either # the following file (extended) or all following files # (global). if self.type == XGLTYPE: ...
Process an extended or global header as described in POSIX.1-2008.
10
468
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _proc_pax(self, tarfile): # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental informati...
1,305
def get_global_params(): GlobalParams = namedtuple('GlobalParams', [ 'drop_connect_rate', 'width_coefficient', 'depth_coefficient', 'depth_divisor', 'image_size' ]) global_params = GlobalParams( drop_connect_rate=0.3, width_coefficient=1.2...
The fllowing are efficientnetb3's arch superparams, but to fit for scene text recognition task, the resolution(image_size) here is changed from 300 to 64.
23
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_global_params(): GlobalParams = namedtuple('GlobalParams', [ 'drop_connect_rate', 'width_coefficient', 'depth_coefficient', 'depth_divisor', ...
1,306
def _create_closed(cls, vertices): v = _to_unmasked_float_array(vertices) return cls(np.concatenate([v, v[:1]]), closed=True)
Create a closed polygonal path going through *vertices*. Unlike ``Path(..., closed=True)``, *vertices* should **not** end with an entry for the CLOSEPATH; this entry is added by `._create_closed`.
27
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _create_closed(cls, vertices): v = _to_unmasked_float_array(vertices) return cls(np.concatenate([v, v[:1]]), closed=True) ``` ###Assistant : ...
1,307
def test_predict_proba(loss, global_random_seed): n_samples = 20 y_true, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, y_bound=(-100, 100), raw_bound=(-5, 5), seed=global_random_seed, ) if hasattr(loss, "predict_proba"): ...
Test that predict_proba and gradient_proba work as expected.
8
93
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_predict_proba(loss, global_random_seed): n_samples = 20 y_true, raw_prediction = random_y_true_raw_prediction( loss=loss, n_samples=n_samples, y...
1,308
def get_late_shipments(scorecard): return get_total_shipments(scorecard) - get_on_time_shipments(scorecard)
Gets the number of late shipments (counting each item) in the period (based on Purchase Receipts vs POs)
18
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_late_shipments(scorecard): return get_total_shipments(scorecard) - get_on_time_shipments(scorecard) ``` ###Assistant : Gets the number of late shipments (counting ea...
1,309
def eval_loss(self, targets, predictions): eval_loss = 0 for of_name, of_obj in self.output_features.items(): of_eval_loss = of_obj.eval_loss(targets[of_name], predictions[of_name]) eval_loss += of_obj.loss["weight"] * of_eval_loss additional_loss = 0 ad...
Computes all evaluation losses for the model given targets and predictions. Args: targets: A dictionary of target names to target tensors. predictions: A dictionary of output names to output tensors. Returns: A tuple of loss values for eval losses and additional los...
42
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def eval_loss(self, targets, predictions): eval_loss = 0 for of_name, of_obj in self.output_features.items(): of_eval_loss = of_obj.eval_loss(targets[of_...
1,310
def partition_query(self, query, limit, offset): return ( ( f"SELECT * FROM ({query}) AS _ ORDER BY(SELECT NULL)" + f" OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY" ) if self._dialect_is_microsoft_sql() else f"SELECT *...
Get a query that partitions the original `query`. Parameters ---------- query : str The SQL query to get a partition. limit : int The size of the partition. offset : int Where the partition begins. Returns ------- ...
38
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def partition_query(self, query, limit, offset): return ( ( f"SELECT * FROM ({query}) AS _ ORDER BY(SELECT NULL)" + f" OFFSET {of...
1,311
def test_parameter_ends_with__in__or__isnull(self): # When it ends with '__in' ----------------------------------------- modeladmin = DecadeFilterBookAdminParameterEndsWith__In(Book, site) request = self.request_factory.get("/", {"decade__in": "the 90s"}) request.user = self.alf...
A SimpleListFilter's parameter name is not mistaken for a model field if it ends with '__isnull' or '__in' (#17091).
19
122
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_parameter_ends_with__in__or__isnull(self): # When it ends with '__in' ----------------------------------------- modeladmin = DecadeFilterBookAdminParameterE...
1,312
def v4_int_to_packed(address): try: return address.to_bytes(4, 'big') except OverflowError: raise ValueError("Address negative or too large for IPv4")
Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an ...
49
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def v4_int_to_packed(address): try: return address.to_bytes(4, 'big') except OverflowError: raise ValueError("Address negative or too large for IPv4") ...
1,313
def test_delete_alias_not_allowed(self) -> None: self._create_alias(self.admin_user) self.get_failure( self.handler.delete_association( create_requester(self.test_user), self.room_alias ), synapse.api.errors.AuthError, )
A user that doesn't meet the expected guidelines cannot delete an alias.
12
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_delete_alias_not_allowed(self) -> None: self._create_alias(self.admin_user) self.get_failure( self.handler.delete_association( c...
1,314
def trigintegrate(f, x, conds='piecewise'): pat, a, n, m = _pat_sincos(x) f = f.rewrite('sincos') M = f.match(pat) if M is None: return n, m = M[n], M[m] if n.is_zero and m.is_zero: return x zz = x if n.is_zero else S.Zero a = M[a] if n.is_odd or m.is_odd: ...
Integrate f = Mul(trig) over x. Examples ======== >>> from sympy import sin, cos, tan, sec >>> from sympy.integrals.trigonometry import trigintegrate >>> from sympy.abc import x >>> trigintegrate(sin(x)*cos(x), x) sin(x)**2/2 >>> trigintegrate(sin(x)**2, x) x/2 - sin(x)*cos(...
62
909
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def trigintegrate(f, x, conds='piecewise'): pat, a, n, m = _pat_sincos(x) f = f.rewrite('sincos') M = f.match(pat) if M is None: return n, m = M[n], M[m] ...
1,315
def get_pywin32_module_file_attribute(module_name): from PyInstaller.utils.win32 import winutils module = winutils.import_pywin32_module(module_name) return module.__file__
Get the absolute path of the PyWin32 DLL specific to the PyWin32 module with the passed name. On import, each PyWin32 module: * Imports a DLL specific to that module. * Overwrites the values of all module attributes with values specific to that DLL. This includes that module's `__file__` attrib...
103
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_pywin32_module_file_attribute(module_name): from PyInstaller.utils.win32 import winutils module = winutils.import_pywin32_module(module_name) return module.__file__ ...
1,316
def render_warning(self, message): context = {"error": message} return render_to_response("sentry/pipeline-provider-error.html", context, self.request)
For situations when we want to display an error without triggering an issue
13
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def render_warning(self, message): context = {"error": message} return render_to_response("sentry/pipeline-provider-error.html", context, self.request) ``` ...
1,317
def test_context_filter_not_labels(self) -> None: event_id = self._send_labelled_messages_in_room() channel = self.make_request( "GET", "/rooms/%s/context/%s?filter=%s" % (self.room_id, event_id, json.dumps(self.FILTER_NOT_LABELS)), access_token=...
Test that we can filter by the absence of a label on a /context request.
15
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_context_filter_not_labels(self) -> None: event_id = self._send_labelled_messages_in_room() channel = self.make_request( "GET", "/ro...
1,318
def _consistent_PT(u, v, graph_params, state_params): G1, G2 = graph_params.G1, graph_params.G2 mapping, reverse_mapping = state_params.mapping, state_params.reverse_mapping for neighbor in G1[u]: if neighbor in mapping: if G1.number_of_edges(u, neighbor) != G2.number_of_edges( ...
Checks the consistency of extending the mapping using the current node pair. Parameters ---------- u, v: Graph node The two candidate nodes being examined. graph_params: namedtuple Contains all the Graph-related parameters: G1,G2: NetworkX Graph or MultiGraph instances. ...
162
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _consistent_PT(u, v, graph_params, state_params): G1, G2 = graph_params.G1, graph_params.G2 mapping, reverse_mapping = state_params.mapping, state_params.reverse_mapping ...
1,319
def get_variant_values_for(items): attribute_map = {} for attr in frappe.db.sql( % ", ".join(["%s"] * len(items)), tuple(items), as_dict=1, ): attribute_map.setdefault(attr["parent"], {}) attribute_map[attr["parent"]].update({attr["attribute"]: attr["attribute_value"]}) return attribute_map
Returns variant values for items.select parent, attribute, attribute_value from `tabItem Variant Attribute` where parent in (%s)
16
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_variant_values_for(items): attribute_map = {} for attr in frappe.db.sql( % ", ".join(["%s"] * len(items)), tuple(items), as_dict=1, ): attribute_map.setdefault(attr["...
1,320
def test_edit_post_locked_by_self(self): # Lock the snippet self.lock_snippet(self.user) # Try to edit the snippet response = self.client.post( self.get_url("edit"), {"text": "Edited while locked"}, follow=True, ) self.refresh...
A user can edit a snippet that is locked by themselves.
11
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_edit_post_locked_by_self(self): # Lock the snippet self.lock_snippet(self.user) # Try to edit the snippet response = self.client.post( ...
1,321
def update_metrics(self, targets, predictions): for of_name, of_obj in self.output_features.items(): of_obj.update_metrics(targets[of_name], predictions[of_name]) eval_loss, additional_losses = self.eval_loss(targets, predictions) self.eval_loss_metric.update(eval_loss) ...
Updates the model's metrics given targets and predictions.
8
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update_metrics(self, targets, predictions): for of_name, of_obj in self.output_features.items(): of_obj.update_metrics(targets[of_name], predictions[of_name]...
1,322
def tick_right(self): label = True if 'label1On' in self._major_tick_kw: label = (self._major_tick_kw['label1On'] or self._major_tick_kw['label2On']) self.set_ticks_position('right') # if labels were turned off before this was called # le...
Move ticks and ticklabels (if present) to the right of the Axes.
12
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tick_right(self): label = True if 'label1On' in self._major_tick_kw: label = (self._major_tick_kw['label1On'] or self._major_tic...
1,323
def test_show_message_twice(view, info1, info2, count): view.show_message(info1) view.show_message(info2) assert len(view._messages) == count
Show the exact same message twice -> only one should be shown.
12
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_show_message_twice(view, info1, info2, count): view.show_message(info1) view.show_message(info2) assert len(view._messages) == count ``` ###Assistant ...
1,324
def __call__(self, bboxes1, bboxes2, mode='iou', is_aligned=False): bboxes1 = get_box_tensor(bboxes1) bboxes2 = get_box_tensor(bboxes2) assert bboxes1.size(-1) in [0, 4, 5] assert bboxes2.size(-1) in [0, 4, 5] if bboxes2.size(-1) == 5: bboxes2 = bboxes2[..., ...
Calculate IoU between 2D bboxes. Args: bboxes1 (Tensor or :obj:`BaseBoxes`): bboxes have shape (m, 4) in <x1, y1, x2, y2> format, or shape (m, 5) in <x1, y1, x2, y2, score> format. bboxes2 (Tensor or :obj:`BaseBoxes`): bboxes have shape (m, 4) ...
115
94
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __call__(self, bboxes1, bboxes2, mode='iou', is_aligned=False): bboxes1 = get_box_tensor(bboxes1) bboxes2 = get_box_tensor(bboxes2) assert bboxes1.size(-...
1,325
def binning(self) -> List[List[str]]: return self._binning_linear_threshold(multiplier=100)
Create bins to split linearly from the lowest to the highest sample value Returns ------- list List of bins of filenames
21
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def binning(self) -> List[List[str]]: return self._binning_linear_threshold(multiplier=100) ``` ###Assistant : Create bins to split linearly from the lowest t...
1,326
def connect(self, publish_port, connect_callback=None, disconnect_callback=None): raise NotImplementedError
Create a network connection to the the PublishServer or broker.
10
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def connect(self, publish_port, connect_callback=None, disconnect_callback=None): raise NotImplementedError ``` ###Assistant : Create a network connect...
1,327
def contains(self, g): if not isinstance(g, FreeGroupElement): return False elif self != g.group: return False else: return True
Tests if Free Group element ``g`` belong to self, ``G``. In mathematical terms any linear combination of generators of a Free Group is contained in it. Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> f.c...
45
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def contains(self, g): if not isinstance(g, FreeGroupElement): return False elif self != g.group: return False else: retu...
1,328
def get_pledged_security_qty(loan): current_pledges = {} unpledges = frappe._dict( frappe.db.sql( , (loan), ) ) pledges = frappe._dict( frappe.db.sql( , (loan), ) ) for security, qty in pledges.items(): current_pledges.setdefault(security, qty) current_pledges[security] -= unpledges.ge...
SELECT u.loan_security, sum(u.qty) as qty FROM `tabLoan Security Unpledge` up, `tabUnpledge` u WHERE up.loan = %s AND u.parent = up.name AND up.status = 'Approved' GROUP BY u.loan_security SELECT p.loan_security, sum(p.qty) as qty FROM `tabLoan Security Pledge` lp, `tabPledge`p WHERE lp.loan = %s ...
53
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_pledged_security_qty(loan): current_pledges = {} unpledges = frappe._dict( frappe.db.sql( , (loan), ) ) pledges = frappe._dict( frappe.db.sql( , (loan), ) ...
1,329
def get_select(self): select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += ...
Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_...
90
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_select(self): select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items...
1,330
def set_module_collection_mode(self, name, mode): if name is None: name = self.__name__ if mode is None: self._module_collection_mode.pop(name) else: self._module_collection_mode[name] = mode
" Set the package/module collection mode for the specified module name. If `name` is `None`, the hooked module/package name is used. Valid values for `mode` are: `'pyc'`, `'py'`, and `None`.
30
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_module_collection_mode(self, name, mode): if name is None: name = self.__name__ if mode is None: self._module_collection_mode.pop(nam...
1,331
def write_file (filename, contents): f = open(filename, "w") try: for line in contents: f.write(line + "\n") finally: f.close()
Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it.
19
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def write_file (filename, contents): f = open(filename, "w") try: for line in contents: f.write(line + "\n") finally: f.close() ``` ...
1,332
async def test_flow_run_policy_is_backwards_compatible(self): empty_new_policy = schemas.core.FlowRunPolicy() # should not raise an error self.OldFlowRunPolicy(**empty_new_policy.dict())
In version 2.1.1 and prior, the FlowRunPolicy schema required two properties, `max_retries` and `retry_delay_seconds`. These properties are deprecated. This test ensures old clients can load new FlowRunPolicySchemas. It can be removed when the corresponding properties are removed. ...
37
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_flow_run_policy_is_backwards_compatible(self): empty_new_policy = schemas.core.FlowRunPolicy() # should not raise an error self.OldFlowRunPo...
1,333
def test_help_text_examples_are_contextualized(): rendered_inline = render(spacing_invalid_value("padding", "inline")) assert "widget.styles.padding" in rendered_inline rendered_css = render(spacing_invalid_value("padding", "css")) assert "padding:" in rendered_css
Ensure that if the user is using CSS, they see CSS-specific examples and if they're using inline styles they see inline-specific examples.
22
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_help_text_examples_are_contextualized(): rendered_inline = render(spacing_invalid_value("padding", "inline")) assert "widget.styles.padding" in rendered_inline ren...
1,334
def test_reverse_proxy(tctx, keep_host_header): server = Placeholder(Server) tctx.options.mode = "reverse:http://localhost:8000" tctx.options.connection_strategy = "lazy" tctx.options.keep_host_header = keep_host_header assert ( Playbook(modes.ReverseProxy(tctx), hooks=False) >>...
Test mitmproxy in reverse proxy mode. - make sure that we connect to the right host - make sure that we respect keep_host_header - make sure that we include non-standard ports in the host header (#4280)
36
80
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_reverse_proxy(tctx, keep_host_header): server = Placeholder(Server) tctx.options.mode = "reverse:http://localhost:8000" tctx.options.connection_strategy = "lazy" ...
1,335
def _check_filter_horizontal(self, obj): if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be( "a list or tuple", option="filter_horizontal", obj=obj, id="admin.E018" ) else: return list( chain.from_iterable(...
Check that filter_horizontal is a sequence of field names.
9
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _check_filter_horizontal(self, obj): if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be( "a list or tuple", option="filt...
1,336
def poly_intersection(poly_det, poly_gt): assert isinstance(poly_det, plg.Polygon) assert isinstance(poly_gt, plg.Polygon) poly_inter = poly_det & poly_gt if len(poly_inter) == 0: return 0, poly_inter return poly_inter.area(), poly_inter
Calculate the intersection area between two polygon. Args: poly_det (Polygon): A polygon predicted by detector. poly_gt (Polygon): A gt polygon. Returns: intersection_area (float): The intersection area between two polygons.
29
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def poly_intersection(poly_det, poly_gt): assert isinstance(poly_det, plg.Polygon) assert isinstance(poly_gt, plg.Polygon) poly_inter = poly_det & poly_gt if len(poly_i...
1,337
def size(self) -> int: return sum(len(x.data) for x in [*self.answers, *self.authorities, *self.additionals])
Returns the cumulative data size of all resource record sections.
10
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def size(self) -> int: return sum(len(x.data) for x in [*self.answers, *self.authorities, *self.additionals]) ``` ###Assistant : Returns the cumulative data siz...
1,338
async def get_job_submission_info(self): jobs = {} fetched_jobs = await self._job_info_client.get_all_jobs() for ( job_submission_id, job_info, ) in fetched_jobs.items(): if job_info is not None: entry = { ...
Info for Ray job submission. Here a job can have 0 or many drivers.
14
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def get_job_submission_info(self): jobs = {} fetched_jobs = await self._job_info_client.get_all_jobs() for ( job_submission_id, ...
1,339
def _gen_sieve_array(M, factor_base): sieve_array = [0]*(2*M + 1) for factor in factor_base: if factor.soln1 is None: #The prime does not divides a continue for idx in range((M + factor.soln1) % factor.prime, 2*M, factor.prime): sieve_array[idx] += factor.log_p ...
Sieve Stage of the Quadratic Sieve. For every prime in the factor_base that does not divide the coefficient `a` we add log_p over the sieve_array such that ``-M <= soln1 + i*p <= M`` and ``-M <= soln2 + i*p <= M`` where `i` is an integer. When p = 2 then log_p is only added using ``-M <= soln1 + i*p <...
74
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _gen_sieve_array(M, factor_base): sieve_array = [0]*(2*M + 1) for factor in factor_base: if factor.soln1 is None: #The prime does not divides a continue ...
1,340
def rescue_docarray(): try: import docarray as docarray __docarray_version__ = docarray.__version__ except AttributeError: # Being here means docarray is not installed correctly, attempt to reinstall it # as recommended by pip https://pip.pypa.io/en/latest/user_guide/#usin...
Upgrading from 2.x to 3.x is broken (https://github.com/jina-ai/jina/issues/4194) This function checks if docarray is broken and if so attempts to rescue it
22
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def rescue_docarray(): try: import docarray as docarray __docarray_version__ = docarray.__version__ except AttributeError: # Being here means docarray ...
1,341
def transform(self, X): msg = ( "%(name)s is not fitted. Call fit to set the parameters before" " calling transform" ) check_is_fitted(self, msg=msg) X = self._validate_data(X, accept_sparse="csr", reset=False) check_non_negative(X, "X in Additiv...
Apply approximate feature map to X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- X_new :...
66
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def transform(self, X): msg = ( "%(name)s is not fitted. Call fit to set the parameters before" " calling transform" ) check_is_fitte...
1,342
def get_repository_root(cls, location): # type: (str) -> Optional[str] if cls.is_repository_directory(location): return location return None
Return the "root" (top-level) directory controlled by the vcs, or `None` if the directory is not in any. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. This can do more than is_repository_directory() alone. For example, the Git...
50
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_repository_root(cls, location): # type: (str) -> Optional[str] if cls.is_repository_directory(location): return location return None ...
1,343
def test_it_should_not_read_quotes_stream_if_it_does_not_exist_in_client(oauth_config, configured_catalog): source = SourceHubspot() all_records = list(source.read(logger, config=oauth_config, catalog=configured_catalog, state=None)) records = [record for record in all_records if record.type == Type.R...
If 'quotes' stream is not in the client, it should skip it.
12
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_it_should_not_read_quotes_stream_if_it_does_not_exist_in_client(oauth_config, configured_catalog): source = SourceHubspot() all_records = list(source.read(logger, conf...
1,344
def get_conda_env_dir(env_name): conda_prefix = os.environ.get("CONDA_PREFIX") if conda_prefix is None: # The caller is neither in a conda env or in (base) env. This is rare # because by default, new terminals start in (base), but we can still # support this case. conda_exe...
Find and validate the conda directory for a given conda environment. For example, given the environment name `tf1`, this function checks the existence of the corresponding conda directory, e.g. `/Users/scaly/anaconda3/envs/tf1`, and returns it.
33
226
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_conda_env_dir(env_name): conda_prefix = os.environ.get("CONDA_PREFIX") if conda_prefix is None: # The caller is neither in a conda env or in (base) env. This is...
1,345
async def test_switch_change_outlet_state(hass, utcnow): helper = await setup_test_component(hass, create_switch_service) await hass.services.async_call( "switch", "turn_on", {"entity_id": "switch.testdevice"}, blocking=True ) helper.async_assert_service_values( ServicesTypes.OUTLE...
Test that we can turn a HomeKit outlet on and off again.
12
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_switch_change_outlet_state(hass, utcnow): helper = await setup_test_component(hass, create_switch_service) await hass.services.async_call( "switch", "tur...
1,346
def _update_label_position(self, renderer): if not self._autolabelpos: return # get bounding boxes for this axis and any siblings # that have been set by `fig.align_xlabels()` bboxes, bboxes2 = self._get_tick_boxes_siblings(renderer=renderer) x, y = self.la...
Update the label position based on the bounding box enclosing all the ticklabels and axis spine
16
111
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _update_label_position(self, renderer): if not self._autolabelpos: return # get bounding boxes for this axis and any siblings # that have be...
1,347
def poly_union(poly_det, poly_gt): assert isinstance(poly_det, plg.Polygon) assert isinstance(poly_gt, plg.Polygon) area_det = poly_det.area() area_gt = poly_gt.area() area_inters, _ = poly_intersection(poly_det, poly_gt) return area_det + area_gt - area_inters
Calculate the union area between two polygon. Args: poly_det (Polygon): A polygon predicted by detector. poly_gt (Polygon): A gt polygon. Returns: union_area (float): The union area between two polygons.
29
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def poly_union(poly_det, poly_gt): assert isinstance(poly_det, plg.Polygon) assert isinstance(poly_gt, plg.Polygon) area_det = poly_det.area() area_gt = poly_gt.area() ...
1,348
def test_whitelist_idna_result(self) -> None: config: JsonDict = { "federation_certificate_verification_whitelist": [ "example.com", "*.xn--eckwd4c7c.xn--zckzah", ] } t = TestConfig() t.tls.read_config(config, config_dir_pa...
The federation certificate whitelist will match on IDNA encoded names.
10
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_whitelist_idna_result(self) -> None: config: JsonDict = { "federation_certificate_verification_whitelist": [ "example.com", ...
1,349
def simple_test_rpn(self, x, img_metas): rpn_outs = self(x) proposal_list = self.get_results(*rpn_outs, img_metas=img_metas) return proposal_list
Test without augmentation, only for ``RPNHead`` and its variants, e.g., ``GARPNHead``, etc. Args: x (tuple[Tensor]): Features from the upstream network, each is a 4D-tensor. img_metas (list[dict]): Meta info of each image. Returns: list[Tenso...
51
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def simple_test_rpn(self, x, img_metas): rpn_outs = self(x) proposal_list = self.get_results(*rpn_outs, img_metas=img_metas) return proposal_list ``...
1,350
def _get_tick_boxes_siblings(self, renderer): # Get the Grouper keeping track of x or y label groups for this figure. axis_names = [ name for name, axis in self.axes._get_axis_map().items() if name in self.figure._align_label_groups and axis is self] if len(axis_...
Get the bounding boxes for this `.axis` and its siblings as set by `.Figure.align_xlabels` or `.Figure.align_ylabels`. By default it just gets bboxes for self.
24
85
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_tick_boxes_siblings(self, renderer): # Get the Grouper keeping track of x or y label groups for this figure. axis_names = [ name for name, axis ...
1,351
def default(method): method._is_default = True # pylint: disable=protected-access return method
Decorates a method to detect overrides in subclasses.
8
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def default(method): method._is_default = True # pylint: disable=protected-access return method ``` ###Assistant : Decorates a method to detect overrides in subcl...
1,352
def test_help_tooltip(self): st.camera_input("the label", help="help_label") c = self.get_delta_from_queue().new_element.camera_input self.assertEqual(c.help, "help_label")
Test that it can be called using a string for type parameter.
12
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_help_tooltip(self): st.camera_input("the label", help="help_label") c = self.get_delta_from_queue().new_element.camera_input self.assertEqual(c.hel...
1,353
async def test_multiple_event_images(hass, auth): subscriber = await async_setup_camera(hass, DEVICE_TRAITS, auth=auth) assert len(hass.states.async_all()) == 1 assert hass.states.get("camera.my_camera") event_timestamp = utcnow() await subscriber.async_receive_event( make_motion_event...
Test fallback for an event event image that has been cleaned up on expiration.
14
96
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_multiple_event_images(hass, auth): subscriber = await async_setup_camera(hass, DEVICE_TRAITS, auth=auth) assert len(hass.states.async_all()) == 1 assert hass....
1,354
def test_delete_same_room_twice(self) -> None: body = {"new_room_user_id": self.admin_user} # first call to delete room # and do not wait for finish the task first_channel = self.make_request( "DELETE", self.url.encode("ascii"), content=body...
Test that the call for delete a room at second time gives an exception.
14
87
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_delete_same_room_twice(self) -> None: body = {"new_room_user_id": self.admin_user} # first call to delete room # and do not wait for finish the ta...
1,355
async def _async_refresh_device_detail_by_ids(self, device_ids_list): for device_id in device_ids_list: try: await self._async_refresh_device_detail_by_id(device_id) except asyncio.TimeoutError: _LOGGER.warning( "Timed out call...
Refresh each device in sequence. This used to be a gather but it was less reliable with august's recent api changes. The august api has been timing out for some devices so we want the ones that it isn't timing out for to keep working.
45
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def _async_refresh_device_detail_by_ids(self, device_ids_list): for device_id in device_ids_list: try: await self._async_refresh_device_det...
1,356
def masks_to_boxes(masks): if masks.size == 0: return np.zeros((0, 4)) h, w = masks.shape[-2:] y = np.arange(0, h, dtype=np.float32) x = np.arange(0, w, dtype=np.float32) # see https://github.com/pytorch/pytorch/issues/50276 y, x = np.meshgrid(y, x, indexing="ij") x_mask = ma...
Compute the bounding boxes around the provided panoptic segmentation masks. The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. Returns a [N, 4] tensor, with the boxes in corner (xyxy) format.
44
86
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def masks_to_boxes(masks): if masks.size == 0: return np.zeros((0, 4)) h, w = masks.shape[-2:] y = np.arange(0, h, dtype=np.float32) x = np.arange(0, w, dtype=...
1,357
def _roots_with_zeros(p, num_leading_zeros): # Avoid lapack errors when p is all zero p = _where(len(p) == num_leading_zeros, 1.0, p) # Roll any leading zeros to the end & compute the roots roots = _roots_no_zeros(roll(p, -num_leading_zeros)) # Sort zero roots to the end. roots = lax.sort_key_val(roots == 0...
\ Unlike the numpy version of this function, the JAX version returns the roots in a complex array regardless of the values of the roots. Additionally, the jax version of this function adds the ``strip_zeros`` function which must be set to False for the function to be compatible with JIT and other JAX transformations. W...
167
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _roots_with_zeros(p, num_leading_zeros): # Avoid lapack errors when p is all zero p = _where(len(p) == num_leading_zeros, 1.0, p) # Roll any leading zeros to the end & compute the ...
1,358
def port_monitoring(self) -> int: if GATEWAY_NAME in self._deployment_nodes: return self[GATEWAY_NAME].args.port_monitoring else: return self._common_kwargs.get( 'port_monitoring', __default_port_monitoring__ )
Return if the monitoring is enabled .. # noqa: DAR201
10
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def port_monitoring(self) -> int: if GATEWAY_NAME in self._deployment_nodes: return self[GATEWAY_NAME].args.port_monitoring else: return self...
1,359
def autodiscover_modules(*args, **kwargs): from django.apps import apps register_to = kwargs.get("register_to") for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: ...
Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to acc...
49
117
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def autodiscover_modules(*args, **kwargs): from django.apps import apps register_to = kwargs.get("register_to") for app_config in apps.get_app_configs(): for module...
1,360
def ensure_future(coro_or_future, *, loop=None): return _ensure_future(coro_or_future, loop=loop)
Wrap a coroutine or an awaitable in a future. If the argument is a Future, it is returned directly.
19
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ensure_future(coro_or_future, *, loop=None): return _ensure_future(coro_or_future, loop=loop) ``` ###Assistant : Wrap a coroutine or an awaitable in a future. ...
1,361
def getpalette(self, rawmode="RGB"): self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette if rawmode is None: rawmode = mode return list(self.im.getpalette(mode, rawmode))
Returns the image palette as a list. :param rawmode: The mode in which to return the palette. ``None`` will return the palette in its current mode. :returns: A list of color values [r, g, b, ...], or None if the image has no palette.
44
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getpalette(self, rawmode="RGB"): self.load() try: mode = self.im.getpalettemode() except ValueError: return None # no palette ...
1,362
def last_executor(self): if len(self.proto_wo_data.routes) > 0: return self.proto_wo_data.routes[-1].executor
Returns the name of the last Executor that has processed this Request :return: the name of the last Executor that processed this Request
23
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def last_executor(self): if len(self.proto_wo_data.routes) > 0: return self.proto_wo_data.routes[-1].executor ``` ###Assistant : Returns th...
1,363
def custom_generator_multi_io_temporal(self, sample_weights=None): batch_size = 3 num_samples = 3 iteration = 0 while True: batch_index = iteration * batch_size % num_samples iteration += 1 start = batch_index end = start + batch_s...
Generator for getting data for temporal multi io model. Args: sample_weights: List of sample_weights. Yields: Tuple of inputs, label, sample weights data.
22
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def custom_generator_multi_io_temporal(self, sample_weights=None): batch_size = 3 num_samples = 3 iteration = 0 while True: batch_index =...
1,364
def _just_docs(self): try: for child in self.ast.body: if not isinstance(child, ast.Assign): # allow string constant expressions (these are docstrings) if isinstance(child, ast.Expr) and isinstance(child.value, ast.Constant) and isinst...
Module can contain just docs and from __future__ boilerplate
9
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _just_docs(self): try: for child in self.ast.body: if not isinstance(child, ast.Assign): # allow string constant expressi...
1,365
def response_validator(self) -> RequestValidator: self.check_reload() assert self._response_validator is not None return self._response_validator
Reload the OpenAPI file if it has been modified after the last time it was read, and then return the openapi_core validator object. Similar to preceding functions. Used for proper access to OpenAPI objects.
34
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def response_validator(self) -> RequestValidator: self.check_reload() assert self._response_validator is not None return self._response_validator `...
1,366
def roots(p, *, strip_zeros=True): # ported from https://github.com/numpy/numpy/blob/v1.17.0/numpy/lib/polynomial.py#L168-L251 p = atleast_1d(p) if p.ndim != 1: raise ValueError("Input must be a rank-1 array.") # strip_zeros=False is unsafe because leading zeros aren't removed if not strip_zeros: if ...
\ Unlike NumPy's implementation of polyfit, :py:func:`jax.numpy.polyfit` will not warn on rank reduction, which indicates an ill conditioned matrix Also, it works best on rcond <= 10e-3 values.
28
116
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def roots(p, *, strip_zeros=True): # ported from https://github.com/numpy/numpy/blob/v1.17.0/numpy/lib/polynomial.py#L168-L251 p = atleast_1d(p) if p.ndim != 1: raise ValueError("I...
1,367
def _storage_path(self, local_path): rel_local_path = os.path.relpath(local_path, self.logdir) return os.path.join(self.remote_checkpoint_dir, rel_local_path)
Converts a `local_path` to be based off of `self.remote_checkpoint_dir`.
9
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _storage_path(self, local_path): rel_local_path = os.path.relpath(local_path, self.logdir) return os.path.join(self.remote_checkpoint_dir, rel_local_path) ...
1,368
def get_time_since_last_update(self) -> float: return time.time() - self.last_update_time
How much time has passed since the last call to update.
11
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_time_since_last_update(self) -> float: return time.time() - self.last_update_time ``` ###Assistant : How much time has passed since the last call to upd...
1,369
def train_fixbn(self, mode=True, freeze_bn=True, freeze_bn_affine=False): r super(DeepLabv3_plus, self).train(mode) if freeze_bn: print("Freezing Mean/Var of BatchNorm2D.") if freeze_bn_affine: print("Freezing Weight/Bias of BatchNorm2D.") if freez...
Sets the module in training mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`, etc. Returns: Module:...
38
192
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def train_fixbn(self, mode=True, freeze_bn=True, freeze_bn_affine=False): r super(DeepLabv3_plus, self).train(mode) if freeze_bn: print("Freezing Mean/Var...
1,370
def assert_params_all_zeros(module) -> bool: weight_data = module.weight.data is_weight_zero = weight_data.allclose( weight_data.new_zeros(weight_data.size())) if hasattr(module, 'bias') and module.bias is not None: bias_data = module.bias.data is_bias_zero = bias_data.allclose...
Check if the parameters of the module is all zeros. Args: module (nn.Module): The module to be checked. Returns: bool: Whether the parameters of the module is all zeros.
29
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def assert_params_all_zeros(module) -> bool: weight_data = module.weight.data is_weight_zero = weight_data.allclose( weight_data.new_zeros(weight_data.size())) if h...
1,371
def cleanup_state(self): # type: () -> None for f in self.cleanup_functions: if not callable(f): continue try: if not f(self.socket, self.configuration): log_automotive.info( "Cleanup function %s...
Executes all collected cleanup functions from a traversed path :return: None
11
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cleanup_state(self): # type: () -> None for f in self.cleanup_functions: if not callable(f): continue try: ...
1,372
def test_model_with_two_tabbed_panels_only(self): Publisher.settings_panels = [FieldPanel("name")] Publisher.promote_panels = [FieldPanel("headquartered_in")] warning_1 = checks.Warning( "Publisher.promote_panels will have no effect on modeladmin editing", hint=, ...
Ensure that Publisher uses `panels` instead of `promote_panels`\ or set up an `edit_handler` if you want a tabbed editing interface. There are no default tabs on non-Page models so there will be no\ Promote tab for the promote_panels to render in.Ensure that Publisher uses `panels` instead of `settings_panels`\ or set...
81
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_model_with_two_tabbed_panels_only(self): Publisher.settings_panels = [FieldPanel("name")] Publisher.promote_panels = [FieldPanel("headquartered_in")] warnin...
1,373
def get_builtin_layer(class_name): if not hasattr(LOCAL, "ALL_OBJECTS"): populate_deserializable_objects() return LOCAL.ALL_OBJECTS.get(class_name)
Returns class if `class_name` is registered, else returns None.
9
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_builtin_layer(class_name): if not hasattr(LOCAL, "ALL_OBJECTS"): populate_deserializable_objects() return LOCAL.ALL_OBJECTS.get(class_name) ``` ###...
1,374
def abelian_invariants(self): if self.is_trivial: return [] gns = self.generators inv = [] G = self H = G.derived_subgroup() Hgens = H.generators for p in primefactors(G.order()): ranks = [] while True: ...
Returns the abelian invariants for the given group. Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to the direct product of finitely many nontrivial cyclic groups of prime-power order. Explanation =========== The prime-powers that occur as...
212
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def abelian_invariants(self): if self.is_trivial: return [] gns = self.generators inv = [] G = self H = G.derived_subgroup() ...
1,375
def clone_graph_nodes(inputs, outputs): nodes_to_clone = find_nodes_by_inputs_and_outputs(inputs, outputs) cloned_inputs = [] cloned_outputs = [] # We not only need to create copies of Nodes (mimic the calls), also need to # clone keras_tensors to avoid the override of _keras_history attached o...
Clone the `Node` between the inputs and output tensors. This function is used to create a new functional model from any intermediate keras tensors. The clone of the nodes mimic the behavior of reconstructing the functional graph network by re-executing all the __call__ methods. The cloned nodes will be...
100
292
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clone_graph_nodes(inputs, outputs): nodes_to_clone = find_nodes_by_inputs_and_outputs(inputs, outputs) cloned_inputs = [] cloned_outputs = [] # We not only need to c...
1,376
def parallel_axis(self, point, frame=None): # circular import issue from sympy.physics.mechanics.functions import inertia_of_point_mass if frame is None: frame = self.frame return self.central_inertia.express(frame) + inertia_of_point_mass( self.mass, sel...
Returns the inertia dyadic of the body with respect to another point. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. frame : sympy.physics.vector.ReferenceFrame The reference frame used to construc...
53
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parallel_axis(self, point, frame=None): # circular import issue from sympy.physics.mechanics.functions import inertia_of_point_mass if frame is None: ...
1,377
def test_class_weight_does_not_contains_more_classses(): tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20}) # Does not raise tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1])
Check that class_weight can contain more labels than in y. Non-regression test for #22413
14
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_class_weight_does_not_contains_more_classses(): tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20}) # Does not raise tree.fit([[0, 0, 1], [1, 0, 1], [...
1,378
def parse(self, state): # type: (ParserState) -> str if state.mode == ParserMode.PARSE: path = AnyParser().parse(state) if not os.path.isfile(path): raise ParserError(f'Not a file: {path}') else: path = '' with state.delimit(PAT...
Parse the input from the given state and return the result.
11
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse(self, state): # type: (ParserState) -> str if state.mode == ParserMode.PARSE: path = AnyParser().parse(state) if not os.path.isfile(path)...
1,379
def layout(self) -> Layout: # self.log("I", self._inline_styles) # self.log("C", self._css_styles) # self.log("S", self.styles) assert self.styles.layout return self.styles.layout # @layout.setter # def layout(self, new_value: Layout) -> None: # # ...
Convenience property for accessing ``self.styles.layout``. Returns: The Layout associated with this view Convenience property setter for setting ``view.styles.layout``. # Args: # new_value: # Returns: # None #
27
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def layout(self) -> Layout: # self.log("I", self._inline_styles) # self.log("C", self._css_styles) # self.log("S", self.styles) assert self.styles.la...
1,380
def timeout_message(self, message): future = self.send_future_map.pop(message, None) # In a race condition the message might have been sent by the time # we're timing it out. Make sure the future is not None if future is not None: del self.send_timeout_map[message] ...
Handle a message timeout by removing it from the sending queue and informing the caller :raises: SaltReqTimeoutError
17
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def timeout_message(self, message): future = self.send_future_map.pop(message, None) # In a race condition the message might have been sent by the time # we'...
1,381
def test_not_all_records(self, requests_mock, authenticator, config, responses): expected_output = [ {"id": 1, "updated_at": "2018-01-02T00:00:00Z"}, {"id": 2, "updated_at": "2018-02-02T00:00:00Z"}, {"id": 2, "updated_at": "2018-02-02T00:00:00Z"}, # duplicate ...
TEST 1 - not all records are retrieved During test1 the tickets_stream changes the state of parameters on page: 2, by updating the params: `params["order_by"] = "updated_at"` `params["updated_since"] = last_record` continues to fetch records from the source, using new c...
130
152
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_not_all_records(self, requests_mock, authenticator, config, responses): expected_output = [ {"id": 1, "updated_at": "2018-01-02T00:00:00Z"}, ...
1,382
def run_from_argv(self, argv): self.test_runner = get_command_line_option(argv, "--testrunner") super().run_from_argv(argv)
Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments.
23
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def run_from_argv(self, argv): self.test_runner = get_command_line_option(argv, "--testrunner") super().run_from_argv(argv) ``` ###Assistant : ...
1,383
def test_new_processing_issue(self, mock_func): notification = NewProcessingIssuesActivityNotification( Activity( project=self.project, user=self.user, type=ActivityType.NEW_PROCESSING_ISSUES, data={ "issue...
Test that a Slack message is sent with the expected payload when an issue is held back in reprocessing
19
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_new_processing_issue(self, mock_func): notification = NewProcessingIssuesActivityNotification( Activity( project=self.project, ...
1,384
def load_array(data_arrays, batch_size, is_train=True): dataset = data.TensorDataset(*data_arrays) return data.DataLoader(dataset, batch_size, shuffle=is_train)
Construct a PyTorch data iterator. Defined in :numref:`sec_linear_concise`
8
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_array(data_arrays, batch_size, is_train=True): dataset = data.TensorDataset(*data_arrays) return data.DataLoader(dataset, batch_size, shuffle=is_train) ``` ...
1,385
def is_permanent_redirect(self): return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, )
True if this Response one of the permanent versions of redirect.
11
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_permanent_redirect(self): return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, ...
1,386
def _estimate_step_duration(self, current, now): if current: # there are a few special scenarios here: # 1) somebody is calling the progress bar without ever supplying # step 1 # 2) somebody is calling the progress bar and supplies step one ...
Estimate the duration of a single step. Given the step number `current` and the corresponding time `now` this function returns an estimate for how long a single step takes. If this is called before one step has been completed (i.e. `current == 0`) then zero is given as an estimate. The ...
92
102
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _estimate_step_duration(self, current, now): if current: # there are a few special scenarios here: # 1) somebody is calling the progress bar with...
1,387
def _propagate_index_objs(self, axis=None): self._filter_empties() if axis is None or axis == 0: cum_row_lengths = np.cumsum([0] + self._row_lengths) if axis is None or axis == 1: cum_col_widths = np.cumsum([0] + self._column_widths) if axis is None:
Synchronize labels by applying the index object for specific `axis` to the `self._partitions` lazily. Adds `set_axis` function to call-queue of each partition from `self._partitions` to apply new axis. Parameters ---------- axis : int, default: None The axi...
47
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _propagate_index_objs(self, axis=None): self._filter_empties() if axis is None or axis == 0: cum_row_lengths = np.cumsum([0] + self._row_lengths) ...
1,388
def test_query_devices_remote_no_sync(self) -> None: remote_user_id = "@test:other" local_user_id = "@test:test" remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY" remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ" self.hs.get_feder...
Tests that querying keys for a remote user that we don't share a room with returns the cross signing keys correctly.
21
114
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_query_devices_remote_no_sync(self) -> None: remote_user_id = "@test:other" local_user_id = "@test:test" remote_master_key = "85T7JXPFBAySB/jwby4S3...
1,389
def _matches_get_other_nodes(dictionary, nodes, node_ind): ind_node = nodes[node_ind] return [ind for ind in dictionary if nodes[ind] == ind_node]
Find other wildcards that may have already been matched.
9
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _matches_get_other_nodes(dictionary, nodes, node_ind): ind_node = nodes[node_ind] return [ind for ind in dictionary if nodes[ind] == ind_node] ``` #...
1,390
def save_pretrained(self, save_directory): for attribute_name in self.attributes: attribute = getattr(self, attribute_name) # Include the processor class in the attribute config so this processor can then be reloaded with the # `AutoProcessor` API. if has...
Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it can be reloaded using the [`~ProcessorMixin.from_pretrained`] method. <Tip> This class method is simply calling [`~feature_extraction_utils.FeatureExtractionMixin.save_pretra...
74
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save_pretrained(self, save_directory): for attribute_name in self.attributes: attribute = getattr(self, attribute_name) # Include the processor c...
1,391
def _user_has_module_perms(user, app_label): for backend in auth.get_backends(): if not hasattr(backend, "has_module_perms"): continue try: if backend.has_module_perms(user, app_label): return True except PermissionDenied: return False...
Backend can raise `PermissionDenied` to short-circuit permission checking.
8
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _user_has_module_perms(user, app_label): for backend in auth.get_backends(): if not hasattr(backend, "has_module_perms"): continue try: i...
1,392
def get_default_address(out, name): shipping_addresses = frappe.db.sql( , (name), as_dict=1, ) if shipping_addresses: for out.shipping_address in shipping_addresses: if out.shipping_address.is_shipping_address: return out.shipping_address out.shipping_address = shipping_addresses[0] return out....
SELECT parent, (SELECT is_shipping_address FROM tabAddress a WHERE a.name=dl.parent) AS is_shipping_address FROM `tabDynamic Link` dl WHERE dl.link_doctype="Customer" AND dl.link_name=%s AND dl.parenttype = "Address"
23
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_default_address(out, name): shipping_addresses = frappe.db.sql( , (name), as_dict=1, ) if shipping_addresses: for out.shipping_address in shipping_addresses: if out.sh...
1,393
def force_list(elements=None, to_tuple=False): ctor = list if to_tuple is True: ctor = tuple return ctor() if elements is None else ctor(elements) \ if type(elements) in [list, set, tuple] else ctor([elements])
Makes sure `elements` is returned as a list, whether `elements` is a single item, already a list, or a tuple. Args: elements (Optional[any]): The inputs as single item, list, or tuple to be converted into a list/tuple. If None, returns empty list/tuple. to_tuple (bool): Whether...
71
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def force_list(elements=None, to_tuple=False): ctor = list if to_tuple is True: ctor = tuple return ctor() if elements is None else ctor(elements) \ if type(...
1,394
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): if order == 3: K = steps // 3 + 1 if steps % 3 == 0: orders = [3, ] * (K - 2) + [2, 1] elif steps % 3 == 1: orders = [3, ] * (K - 1) +...
Get the order of each step for sampling by the singlestep DPM-Solver. We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast". Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is: - I...
309
159
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): if order == 3: K = steps // 3 + 1 if steps % 3 =...
1,395
def _aligned_zeros(shape, dtype=float, order="C", align=None): dtype = np.dtype(dtype) if dtype == np.dtype(object): # Can't do this, fall back to standard allocation (which # should always be sufficiently aligned) if align is not None: raise ValueError("object array ali...
Allocate a new ndarray with aligned memory. The ndarray is guaranteed *not* aligned to twice the requested alignment. Eg, if align=4, guarantees it is not aligned to 8. If align=None uses dtype.alignment.
32
129
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _aligned_zeros(shape, dtype=float, order="C", align=None): dtype = np.dtype(dtype) if dtype == np.dtype(object): # Can't do this, fall back to standard allocation (w...
1,396
def smart_resize(x, size, interpolation='bilinear'): if len(size) != 2: raise ValueError('Expected `size` to be a tuple of 2 integers, ' f'but got: {size}.') img = tf.convert_to_tensor(x) if img.shape.rank is not None: if img.shape.rank < 3 or img.shape.rank > 4: raise ValueE...
Resize images to a target size without aspect ratio distortion. TensorFlow image datasets typically yield images that have each a different size. However, these images need to be batched before they can be processed by Keras layers. To be batched, images need to share the same height and width. You could si...
348
228
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def smart_resize(x, size, interpolation='bilinear'): if len(size) != 2: raise ValueError('Expected `size` to be a tuple of 2 integers, ' f'but got: {size}.') ...
1,397
def gather(tensor): if AcceleratorState().distributed_type == DistributedType.TPU: return _tpu_gather(tensor, name="accelerate.utils.gather") elif AcceleratorState().distributed_type in [DistributedType.DEEPSPEED, DistributedType.MULTI_GPU]: return _gpu_gather(tensor) elif AcceleratorSt...
Recursively gather tensor in a nested list/tuple/dictionary of tensors from all devices. Args: tensor (nested list/tuple/dictionary of :obj:`torch.Tensor`): The data to gather. Returns: The same data structure as :obj:`tensor` with all tensors sent to the proper device.
37
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def gather(tensor): if AcceleratorState().distributed_type == DistributedType.TPU: return _tpu_gather(tensor, name="accelerate.utils.gather") elif AcceleratorState().dis...
1,398
def speed_metrics(split, start_time, num_samples=None, num_steps=None): runtime = time.time() - start_time result = {f"{split}_runtime": round(runtime, 4)} if num_samples is not None: samples_per_second = num_samples / runtime result[f"{split}_samples_per_second"] = round(samples_per_se...
Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test.....
57
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def speed_metrics(split, start_time, num_samples=None, num_steps=None): runtime = time.time() - start_time result = {f"{split}_runtime": round(runtime, 4)} if num_samples is...
1,399
def parse_date_fields(year_col, month_col, day_col) -> npt.NDArray[np.object_]: warnings.warn( , # noqa: E501 FutureWarning, stacklevel=find_stack_level(), ) year_col = _maybe_cast(year_col) month_col = _maybe_cast(month_col) day_col = _maybe_cast(day_col) return p...
Parse columns with years, months and days into a single date column. .. deprecated:: 1.2 Use pd.to_datetime({"year": year_col, "month": month_col, "day": day_col}) instead to get a Pandas Series. Use ser = pd.to_datetime({"year": year_col, "month": month_col, "day": day_col}) and ...
49
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse_date_fields(year_col, month_col, day_col) -> npt.NDArray[np.object_]: warnings.warn( , # noqa: E501 FutureWarning, stacklevel=find_stack_level(), ...