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
2,900
def get_sympy_dir(): this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) return os.path.normcase(sympy_dir)
Returns the root SymPy directory and set the global value indicating whether the system is case sensitive or not.
19
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_sympy_dir(): this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) retur...
2,901
def CheckCaffeRandom(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum()...
Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set u...
84
99
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def CheckCaffeRandom(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons ...
2,902
def test_mapped_dag(self, dag_id, executor_name, session): # This test needs a real executor to run, so that the `make_list` task can write out the TaskMap from airflow.executors.executor_loader import ExecutorLoader self.dagbag.process_file(str(TEST_DAGS_FOLDER / f'{dag_id}.py')) ...
End-to-end test of a simple mapped dag. We test with multiple executors as they have different "execution environments" -- for instance DebugExecutor runs a lot more in the same process than other Executors.
33
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_mapped_dag(self, dag_id, executor_name, session): # This test needs a real executor to run, so that the `make_list` task can write out the TaskMap from airf...
2,903
async def test_emergency_ssl_certificate_when_invalid(hass, tmpdir, caplog): cert_path, key_path = await hass.async_add_executor_job( _setup_broken_ssl_pem_files, tmpdir ) hass.config.safe_mode = True assert ( await async_setup_component( hass, "http", ...
Test http can startup with an emergency self signed cert when the current one is broken.
16
69
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_emergency_ssl_certificate_when_invalid(hass, tmpdir, caplog): cert_path, key_path = await hass.async_add_executor_job( _setup_broken_ssl_pem_files, tmpdir ...
2,904
def get_safe_request_meta(self, request): if not hasattr(request, "META"): return {} return {k: self.cleanse_setting(k, v) for k, v in request.META.items()}
Return a dictionary of request.META with sensitive values redacted.
9
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_safe_request_meta(self, request): if not hasattr(request, "META"): return {} return {k: self.cleanse_setting(k, v) for k, v in request.META.items...
2,905
def cuda(self, *args, **kwargs) -> nn.Module: return self.data_preprocessor.cuda(*args, **kwargs)
Overrides this method to set the :attr:`device` Returns: nn.Module: The model itself.
12
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cuda(self, *args, **kwargs) -> nn.Module: return self.data_preprocessor.cuda(*args, **kwargs) ``` ###Assistant : Overrides this method to set the :attr:`de...
2,906
def get_cache_attr_name(cls): return "_{}.{}".format(cls._meta.app_label, cls._meta.model_name).lower()
Returns the name of the attribute that should be used to store a reference to the fetched/created object on a request.
21
5
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_cache_attr_name(cls): return "_{}.{}".format(cls._meta.app_label, cls._meta.model_name).lower() ``` ###Assistant : Returns the name of the attr...
2,907
def get_instance(cls, info, **data): object_id = data.get("id") object_sku = data.get("sku") attributes = data.get("attributes") if attributes: # Prefetches needed by AttributeAssignmentMixin and # associate_attribute_values_to_instance qs =...
Prefetch related fields that are needed to process the mutation. If we are updating an instance and want to update its attributes, # prefetch them.
25
77
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_instance(cls, info, **data): object_id = data.get("id") object_sku = data.get("sku") attributes = data.get("attributes") if attributes: ...
2,908
def _can_use_libjoin(self) -> bool: if type(self) is Index: # excludes EAs return isinstance(self.dtype, np.dtype) return not is_interval_dtype(self.dtype) # -------------------------------------------------------------------- # Uncategorized Methods
Whether we can use the fastpaths implement in _libs.join
9
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _can_use_libjoin(self) -> bool: if type(self) is Index: # excludes EAs return isinstance(self.dtype, np.dtype) return not is_interval_dty...
2,909
def sub_syllables(self, from_i, to_j): if not isinstance(from_i, int) or not isinstance(to_j, int): raise ValueError("both arguments should be integers") group = self.group if to_j <= from_i: return group.identity else: r = tuple(self.array_fo...
`sub_syllables` returns the subword of the associative word `self` that consists of syllables from positions `from_to` to `to_j`, where `from_to` and `to_j` must be positive integers and indexing is done with origin 0. Examples ======== >>> from sympy.combinato...
59
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sub_syllables(self, from_i, to_j): if not isinstance(from_i, int) or not isinstance(to_j, int): raise ValueError("both arguments should be integers") ...
2,910
def seterr(all=None, divide=None, over=None, under=None, invalid=None): pyvals = umath.geterrobj() old = geterr() if divide is None: divide = all or old['divide'] if over is None: over = all or old['over'] if under is None: under = all or old['under'] if invalid is...
Set how floating-point errors are handled. Note that operations on integer scalar types (such as `int16`) are handled like floating point, and are affected by these settings. Parameters ---------- all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional Set treatment for al...
336
72
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def seterr(all=None, divide=None, over=None, under=None, invalid=None): pyvals = umath.geterrobj() old = geterr() if divide is None: divide = all or old['divide'] ...
2,911
def _create_drawables(self, tokensource): lineno = charno = maxcharno = 0 maxlinelength = linelength = 0 for ttype, value in tokensource: while ttype not in self.styles: ttype = ttype.parent style = self.styles[ttype] # TODO: make sure...
Create drawables for the token content.
6
144
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _create_drawables(self, tokensource): lineno = charno = maxcharno = 0 maxlinelength = linelength = 0 for ttype, value in tokensource: while t...
2,912
def __monotonic_time_coarse() -> float: return time.clock_gettime(CLOCK_MONOTONIC_COARSE) monotonic_time_coarse = time.monotonic with suppress(Exception): if ( platform.system() == "Linux" and abs(time.monotonic() - __monotonic_time_coarse()) < 1 ): monotonic_time_coarse = __m...
Return a monotonic time in seconds. This is the coarse version of time_monotonic, which is faster but less accurate. Since many arm64 and 32-bit platforms don't support VDSO with time.monotonic because of errata, we can't rely on the kernel to provide a fast monotonic time. https://lore.kernel.or...
46
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __monotonic_time_coarse() -> float: return time.clock_gettime(CLOCK_MONOTONIC_COARSE) monotonic_time_coarse = time.monotonic with suppress(Exception): if ( platfor...
2,913
def prepare_image_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: image_inputs = [] for i in range(feature_extract_tester.bat...
This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, or a list of PyTorch tensors if one specifies torchify=True.
28
129
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def prepare_image_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False): assert not (numpify and torchify), "You cannot specify both numpy and PyTor...
2,914
def _update_step_xla(self, gradient, variable, key): return self._update_step(gradient, variable)
A wrapper of `update_step` to enable XLA acceleration. Due to `tf.function` tracing mechanism, for (gradient, variable) pairs of the same shape and dtype, the execution graph always invoke the first pair it has seen. Thus, we need a `key` argument to make each (gradient, variable) pair ...
93
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _update_step_xla(self, gradient, variable, key): return self._update_step(gradient, variable) ``` ###Assistant : A wrapper of `update_step` to enable XLA ac...
2,915
async def log_in(self, request): fingerprint = request["fingerprint"] if self.service.logged_in_fingerprint == fingerprint: return {"fingerprint": fingerprint} await self._stop_wallet() started = await self.service._start(fingerprint) if started is True: ...
Logs in the wallet with a specific key.
8
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def log_in(self, request): fingerprint = request["fingerprint"] if self.service.logged_in_fingerprint == fingerprint: return {"fingerprint": finge...
2,916
def test_bitbucket2_on_push_commits_multiple_committers_with_others(self) -> None: commit_info = "* first commit ([84b96adc644](https://bitbucket.org/kolaszek/repository-name/commits/84b96adc644a30fd6465b3d196369d880762afed))\n" expected_message = f self.check_webhook( "push_multiple...
Tomasz [pushed](https://bitbucket.org/kolaszek/repository-name/branch/master) 10 commits to branch master. Commits by Tomasz (4), James (3), Brendon (2) and others (1).\n\n{commit_info*9}* first commit ([84b96adc644](https://bitbucket.org/kolaszek/repository-name/commits/84b96adc644a30fd6465b3d196369d880762afed))
21
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_bitbucket2_on_push_commits_multiple_committers_with_others(self) -> None: commit_info = "* first commit ([84b96adc644](https://bitbucket.org/kolaszek/repository-name/commits...
2,917
def drawControl(self, element, opt, p, widget=None): if element not in [QStyle.ControlElement.CE_TabBarTab, QStyle.ControlElement.CE_TabBarTabShape, QStyle.ControlElement.CE_TabBarTabLabel]: # Let the real style draw it. self._style.drawControl(element...
Override drawControl to draw odd tabs in a different color. Draws the given element with the provided painter with the style options specified by option. Args: element: ControlElement opt: QStyleOption p: QPainter widget: QWidget
34
122
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def drawControl(self, element, opt, p, widget=None): if element not in [QStyle.ControlElement.CE_TabBarTab, QStyle.ControlElement.CE_TabBarTabShape, ...
2,918
def _get_mask(length, max_length): length = length.unsqueeze(-1) B = paddle.shape(length)[0] grid = paddle.arange(0, max_length).unsqueeze(0).tile([B, 1]) zero_mask = paddle.zeros([B, max_length], dtype='float32') inf_mask = paddle.full([B, max_length], '-inf', dtype='float32') diag_mask = ...
Generate a square mask for the sequence. The masked positions are filled with float('-inf'). Unmasked positions are filled with float(0.0).
20
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_mask(length, max_length): length = length.unsqueeze(-1) B = paddle.shape(length)[0] grid = paddle.arange(0, max_length).unsqueeze(0).tile([B, 1]) zero_mask = pa...
2,919
def test_config_options_removed_on_reparse(self): global_config_path = "/mock/home/folder/.streamlit/config.toml" makedirs_patch = patch("streamlit.config.os.makedirs") makedirs_patch.return_value = True pathexists_patch = patch("streamlit.config.os.path.exists") pathex...
Test that config options that are removed in a file are also removed from our _config_options dict. [theme] base = "dark" font = "sans serif" [theme] base = "dark"
29
52
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_config_options_removed_on_reparse(self): global_config_path = "/mock/home/folder/.streamlit/config.toml" makedirs_patch = patch("streamlit.config.os.makedi...
2,920
def __getitem__(self, key): getitem = self._data.__getitem__ if is_integer(key) or is_float(key): # GH#44051 exclude bool, which would return a 2d ndarray key = com.cast_scalar_indexer(key, warn_float=True) return getitem(key) if isinstance(key, sli...
Override numpy.ndarray's __getitem__ method to work as desired. This function adds lists and Series as valid boolean indexers (ndarrays only supports ndarray with dtype=bool). If resulting ndim != 1, plain ndarray is returned instead of corresponding `Index` subclass. ...
38
178
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __getitem__(self, key): getitem = self._data.__getitem__ if is_integer(key) or is_float(key): # GH#44051 exclude bool, which would return a 2d ndarr...
2,921
def get_data(conditions, filters): data = frappe.db.sql( .format( conditions=conditions ), filters, as_dict=1, ) return data
SELECT so.transaction_date as date, soi.delivery_date as delivery_date, so.name as sales_order, so.status, so.customer, soi.item_code, DATEDIFF(CURDATE(), soi.delivery_date) as delay_days, IF(so.status in ('Completed','To Bill'), 0, (SELECT delay_days)) as delay, soi.qty, soi.delivered_qty, (...
146
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_data(conditions, filters): data = frappe.db.sql( .format( conditions=conditions ), filters, as_dict=1, ) return data ``` ###Assistant : SELECT so.t...
2,922
def getcoroutinelocals(coroutine): frame = getattr(coroutine, "cr_frame", None) if frame is not None: return frame.f_locals else: return {} ############################################################################### ### Function Signature Object (PEP 362) #########################...
Get the mapping of coroutine local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.
27
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getcoroutinelocals(coroutine): frame = getattr(coroutine, "cr_frame", None) if frame is not None: return frame.f_locals else: return {} ###############...
2,923
def _forward_over_back_hessian(f, params, use_pfor, dtype=None): return _vectorize_parameters( functools.partial(_hvp, f, params), params, use_pfor=use_pfor, dtype=dtype, )
Computes the full Hessian matrix for the scalar-valued f(*params). Args: f: A function taking `params` and returning a scalar. params: A possibly nested structure of tensors. use_pfor: If true, uses `tf.vectorized_map` calls instead of looping. dtype: Required if `use_pfor=False`. A possibl...
105
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _forward_over_back_hessian(f, params, use_pfor, dtype=None): return _vectorize_parameters( functools.partial(_hvp, f, params), params, use_pfor=use_pfor,...
2,924
def predict_proba(self, X): check_is_fitted(self) # TODO(1.3): Remove "log" if self.loss in ("log_loss", "log"): return self._predict_proba_lr(X) elif self.loss == "modified_huber": binary = len(self.classes_) == 2 scores = self.decision_fun...
Probability estimates. This method is only available for log loss and modified Huber loss. Multiclass probability estimates are derived from binary (one-vs.-rest) estimates by simple normalization, as recommended by Zadrozny and Elkan. Binary probability estimates for loss="mo...
138
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict_proba(self, X): check_is_fitted(self) # TODO(1.3): Remove "log" if self.loss in ("log_loss", "log"): return self._predict_proba_lr(X...
2,925
def fetch_jwks(jwks_url) -> Optional[dict]: response = None try: response = requests.get(jwks_url, timeout=REQUEST_TIMEOUT) response.raise_for_status() jwks = response.json() except requests.exceptions.RequestException: logger.exception("Unable to fetch jwks from %s", jw...
Fetch JSON Web Key Sets from a provider. Fetched keys will be stored in the cache to the reduced amount of possible requests. :raises AuthenticationError
25
86
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fetch_jwks(jwks_url) -> Optional[dict]: response = None try: response = requests.get(jwks_url, timeout=REQUEST_TIMEOUT) response.raise_for_status() j...