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
900
def box2corners(box): B = box.shape[0] x, y, w, h, alpha = paddle.split(box, 5, axis=-1) x4 = paddle.to_tensor( [0.5, 0.5, -0.5, -0.5], dtype=paddle.float32).reshape( (1, 1, 4)) # (1,1,4) x4 = x4 * w # (B, N, 4) y4 = paddle.to_tensor( [-0.5, 0.5, 0.5, -0.5], dtype=...
convert box coordinate to corners Args: box (Tensor): (B, N, 5) with (x, y, w, h, alpha) angle is in [0, 90) Returns: corners (Tensor): (B, N, 4, 2) with (x1, y1, x2, y2, x3, y3, x4, y4)
38
128
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def box2corners(box): B = box.shape[0] x, y, w, h, alpha = paddle.split(box, 5, axis=-1) x4 = paddle.to_tensor( [0.5, 0.5, -0.5, -0.5], dtype=paddle.float32).reshape...
901
def get_crash_rate_alert_metrics_aggregation_value(self, subscription_update): rows = subscription_update["values"]["data"] if BaseMetricsEntitySubscription.is_crash_rate_format_v2(rows): version = "v2" result = self._get_crash_rate_alert_metrics_aggregation_value_v2(sub...
Handle both update formats. Once all subscriptions have been updated to v2, we can remove v1 and replace this function with current v2.
23
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_crash_rate_alert_metrics_aggregation_value(self, subscription_update): rows = subscription_update["values"]["data"] if BaseMetricsEntitySubscription.is_crash...
902
def strict_promotion_if_dtypes_match(dtypes): if all(dtype == dtypes[0] for dtype in dtypes): return jax.numpy_dtype_promotion('strict') return jax.numpy_dtype_promotion('standard')
Context manager to enable strict promotion if all dtypes match, and enable standard dtype promotion otherwise.
16
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def strict_promotion_if_dtypes_match(dtypes): if all(dtype == dtypes[0] for dtype in dtypes): return jax.numpy_dtype_promotion('strict') return jax.numpy_dtype_promotion('standard...
903
def test_stroptions_deprecated_subset(): with pytest.raises(ValueError, match="deprecated options must be a subset"): StrOptions({"a", "b", "c"}, deprecated={"a", "d"})
Check that the deprecated parameter must be a subset of options.
11
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_stroptions_deprecated_subset(): with pytest.raises(ValueError, match="deprecated options must be a subset"): StrOptions({"a", "b", "c"}, deprecated={"a", "d"}) ...
904
def _validate_target_and_loss(self, y, loss): # `self.loss` references the loss added via `compile` call. If users have # provided such, the target must be provided; otherwise it's a user error. # Note that `self.loss` does not include losses added via `add_loss`, and it # is a...
Raises error if target or loss is not found. This method verifies that the target and loss are properly populated when applicable, or raises errors. Args: y: the target for training. loss: the total loss tensor including loss added via `compile` and `add_loss`. ...
43
148
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _validate_target_and_loss(self, y, loss): # `self.loss` references the loss added via `compile` call. If users have # provided such, the target must be provided...
905
def _validate_datetimelike_monotonic(self): # GH 46061 if self._on.hasnans: self._raise_monotonic_error("values must not have NaT") for group_indices in self._grouper.indices.values(): group_on = self._on.take(group_indices) if not ( g...
Validate that each group in self._on is monotonic
8
52
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _validate_datetimelike_monotonic(self): # GH 46061 if self._on.hasnans: self._raise_monotonic_error("values must not have NaT") for group_ind...
906
def framework_info(filename): is_framework = STRICT_FRAMEWORK_RE.match(filename) if not is_framework: return None return is_framework.groupdict()
A framework name can take one of the following four forms: Location/Name.framework/Versions/SomeVersion/Name_Suffix Location/Name.framework/Versions/SomeVersion/Name Location/Name.framework/Name_Suffix Location/Name.framework/Name returns None if not found, or a mapping equival...
46
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def framework_info(filename): is_framework = STRICT_FRAMEWORK_RE.match(filename) if not is_framework: return None return is_framework.groupdict() ``` ##...
907
def contained_in(filename, directory): filename = os.path.normcase(os.path.abspath(filename)) directory = os.path.normcase(os.path.abspath(directory)) return os.path.commonprefix([filename, directory]) == directory
Test if a file is located within the given directory.
10
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def contained_in(filename, directory): filename = os.path.normcase(os.path.abspath(filename)) directory = os.path.normcase(os.path.abspath(directory)) return os.path.commonp...
908
def glu(x, axis=-1): a, b = tf.split(x, 2, axis=axis) return a * tf.math.sigmoid(b) if version.parse(tf.version.VERSION) >= version.parse("2.4"):
Gated Linear Unit. Implementation as defined in the original paper (see https://arxiv.org/abs/1612.08083), where the input `x` is split in two halves across a dimension (`axis`), A and B, returning A * sigmoid(B). Args: `x`: float Tensor to perform activation `axis`: dimension across which...
63
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def glu(x, axis=-1): a, b = tf.split(x, 2, axis=axis) return a * tf.math.sigmoid(b) if version.parse(tf.version.VERSION) >= version.parse("2.4"): ``` ###Assistant...
909
def matplot(self, plot, opts=None, env=None, win=None): opts = {} if opts is None else opts _title2str(opts) _assert_opts(opts) # write plot to SVG buffer: buffer = StringIO() plot.savefig(buffer, format="svg") buffer.seek(0) svg = buffer.read() ...
This function draws a Matplotlib `plot`. The function supports one plot-specific option: `resizable`. When set to `True` the plot is resized with the pane. You need `beautifulsoup4` and `lxml` packages installed to use this option.
35
149
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def matplot(self, plot, opts=None, env=None, win=None): opts = {} if opts is None else opts _title2str(opts) _assert_opts(opts) # write plot to SVG ...
910
def acl_clone(consul_url=None, token=None, **kwargs): ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error("No Consul URL found.") ret["message"] = "No Consul URL found." ret["res"] = False return r...
Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d2...
42
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def acl_clone(consul_url=None, token=None, **kwargs): ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.err...
911
def slice_indexer(self, start=None, end=None, step=None, kind=lib.no_default): self._deprecated_arg(kind, "kind", "slice_indexer") # For historical reasons DatetimeIndex supports slices between two # instances of datetime.time as if it were applying a slice mask to # an array o...
Return indexer for specified label slice. Index.slice_indexer, customized to handle time slicing. In addition to functionality provided by Index.slice_indexer, does the following: - if both `start` and `end` are instances of `datetime.time`, it invokes `indexer_betwe...
52
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def slice_indexer(self, start=None, end=None, step=None, kind=lib.no_default): self._deprecated_arg(kind, "kind", "slice_indexer") # For historical reasons Datetime...
912
def fix_old_dry_orders(engine): with engine.begin() as connection: connection.execute( text( ) ) connection.execute( text( ) )
update orders set ft_is_open = 0 where ft_is_open = 1 and (ft_trade_id, order_id) not in ( select id, stoploss_order_id from trades where stoploss_order_id is not null ) and ft_order_side = 'stoploss' and order_id like ...
70
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fix_old_dry_orders(engine): with engine.begin() as connection: connection.execute( text( ) ) connection.execute( ...
913
def build_data_frame(self, data, flags=None, stream_id=1, padding_len=0): flags = set(flags) if flags is not None else set() f = DataFrame(stream_id) f.data = data f.flags = flags if padding_len: flags.add("PADDED") f.pad_length = padding_len ...
Builds a single data frame out of a chunk of data.
11
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def build_data_frame(self, data, flags=None, stream_id=1, padding_len=0): flags = set(flags) if flags is not None else set() f = DataFrame(stream_id) f.data ...
914
def set_dryrun_parser(parser=None): if not parser: parser = set_base_parser() parser.add_argument( 'host', type=str, help='The full host address of the Gateway, e.g. grpc://localhost:12345', ) parser.add_argument( '--timeout', type=int, defa...
Set the parser for `dryrun` :param parser: an existing parser to build upon :return: the parser Timeout in millisecond of one check -1 for waiting forever
26
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_dryrun_parser(parser=None): if not parser: parser = set_base_parser() parser.add_argument( 'host', type=str, help='The full host address...
915
def wheel_dist_info_dir(source, name): # type: (ZipFile, str) -> str # Zip file path separators must be / subdirs = {p.split("/", 1)[0] for p in source.namelist()} info_dirs = [s for s in subdirs if s.endswith(".dist-info")] if not info_dirs: raise UnsupportedWheel(".dist-info directo...
Returns the name of the contained .dist-info directory. Raises AssertionError or UnsupportedWheel if not found, >1 found, or it doesn't match the provided name.
24
83
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wheel_dist_info_dir(source, name): # type: (ZipFile, str) -> str # Zip file path separators must be / subdirs = {p.split("/", 1)[0] for p in source.namelist()} info...
916
def in1d(ar1, ar2, assume_unique=False, invert=False): # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # Ensure that iteration through object arrays yields size-1 arrays if ar2.dtype == object: ar2 = ar2.r...
Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. We recommend using :func:`isin` instead of `in1d` for new code. Parameters ---------- ar1 :...
303
367
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def in1d(ar1, ar2, assume_unique=False, invert=False): # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar...
917
def out_degree_centrality(G): if len(G) <= 1: return {n: 1 for n in G} s = 1.0 / (len(G) - 1.0) centrality = {n: d * s for n, d in G.out_degree()} return centrality
Compute the out-degree centrality for nodes. The out-degree centrality for a node v is the fraction of nodes its outgoing edges are connected to. Parameters ---------- G : graph A NetworkX graph Returns ------- nodes : dictionary Dictionary of nodes with out-degree cen...
136
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def out_degree_centrality(G): if len(G) <= 1: return {n: 1 for n in G} s = 1.0 / (len(G) - 1.0) centrality = {n: d * s for n, d in G.out_degree()} return centra...
918
def _read_html(self, file_url): with open(file_url.replace("file://", "").replace(" ", "")) as f: return f.read() if matplotlylib:
Read and return the HTML contents from a file_url in the form e.g. file:///Users/chriddyp/Repos/plotly.py/plotly-temp.html
14
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _read_html(self, file_url): with open(file_url.replace("file://", "").replace(" ", "")) as f: return f.read() if matplotlylib: ``` ###Assis...
919
def set_omp_num_threads_if_unset() -> bool: num_threads_from_env = os.environ.get("OMP_NUM_THREADS") if num_threads_from_env is not None: # No ops if it's set return False # If unset, try setting the correct CPU count assigned. runtime_ctx = ray.get_runtime_context() if runtime...
Set the OMP_NUM_THREADS to default to num cpus assigned to the worker This function sets the environment variable OMP_NUM_THREADS for the worker, if the env is not previously set and it's running in worker (WORKER_MODE). Returns True if OMP_NUM_THREADS is set in this function.
44
129
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_omp_num_threads_if_unset() -> bool: num_threads_from_env = os.environ.get("OMP_NUM_THREADS") if num_threads_from_env is not None: # No ops if it's set re...
920
async def test_binary_device_classes(hass, hk_driver): entity_id = "binary_sensor.demo" aid = 1 for device_class, (service, char, _) in BINARY_SENSOR_SERVICE_MAP.items(): hass.states.async_set(entity_id, STATE_OFF, {ATTR_DEVICE_CLASS: device_class}) await hass.async_block_till_done() ...
Test if services and characteristics are assigned correctly.
8
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def test_binary_device_classes(hass, hk_driver): entity_id = "binary_sensor.demo" aid = 1 for device_class, (service, char, _) in BINARY_SENSOR_SERVICE_MAP.items(): ...
921
def Internaldate2tuple(resp): mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.gro...
Parse an IMAP4 INTERNALDATE string. Return corresponding local time. The return value is a time.struct_time tuple or None if the string has wrong format.
24
76
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def Internaldate2tuple(resp): mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.g...
922
def test_delete_get(self): # Send request response = self.client.get( reverse("wagtaildocs:delete_multiple", args=(self.doc.id,)) ) # Check response self.assertEqual(response.status_code, 405)
This tests that a GET request to the delete view returns a 405 "METHOD NOT ALLOWED" response
17
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_delete_get(self): # Send request response = self.client.get( reverse("wagtaildocs:delete_multiple", args=(self.doc.id,)) ) # Ch...
923
def test_stream_admin_remove_others_from_public_stream(self) -> None: result = self.attempt_unsubscribe_of_principal( query_count=15, target_users=[self.example_user("cordelia")], is_realm_admin=False, is_stream_admin=True, is_subbed=True, ...
You can remove others from public streams you're a stream administrator of.
12
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_stream_admin_remove_others_from_public_stream(self) -> None: result = self.attempt_unsubscribe_of_principal( query_count=15, target_users=[s...
924
def _mosaic_combine(self, loc, center_position_xy, img_shape_wh): assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') if loc == 'top_left': # index0 to top left part of image x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ ...
Calculate global coordinate of mosaic image and local coordinate of cropped sub-image. Args: loc (str): Index for the sub-image, loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right'). center_position_xy (Sequence[float]): Mixing center for 4 images, ...
67
201
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _mosaic_combine(self, loc, center_position_xy, img_shape_wh): assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') if loc == 'top_left': ...
925
def permute(self, perm, orientation='rows', direction='forward'): r from sympy.combinatorics import Permutation # allow british variants and `columns` if direction == 'forwards': direction = 'forward' if direction == 'backwards': direction = 'backward' ...
Permute the rows or columns of a matrix by the given list of swaps. Parameters ========== perm : Permutation, list, or list of lists A representation for the permutation. If it is ``Permutation``, it is used directly with some resizing with respect ...
395
164
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def permute(self, perm, orientation='rows', direction='forward'): r from sympy.combinatorics import Permutation # allow british variants and `columns` if dir...
926
def apply(self, func, *args, **kwargs): func(self, *args, **kwargs) return self
Pass the grid to a user-supplied function and return self. The `func` must accept an object of this type for its first positional argument. Additional arguments are passed through. The return value of `func` is ignored; this method returns self. See the `pipe` method if you wan...
53
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def apply(self, func, *args, **kwargs): func(self, *args, **kwargs) return self ``` ###Assistant : Pass the grid to a user-supplied function an...
927
def copy_m2m_relationships(obj1, obj2, fields, kwargs=None): for field_name in fields: if hasattr(obj1, field_name): try: field_obj = obj1._meta.get_field(field_name) except FieldDoesNotExist: continue if isinstance(field_obj, ManyToMa...
In-place operation. Given two saved objects, copies related objects from obj1 to obj2 to field of same name, if field occurs in `fields`
23
110
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def copy_m2m_relationships(obj1, obj2, fields, kwargs=None): for field_name in fields: if hasattr(obj1, field_name): try: field_obj = obj1._meta....
928
def load_from_pipeline(pipeline): try: import transformers except ImportError: raise ImportError( "transformers not installed. Please try `pip install transformers`" ) if not isinstance(pipeline, transformers.Pipeline): raise ValueError("pipeline must be a tr...
Gets the appropriate Interface kwargs for a given Hugging Face transformers.Pipeline. pipeline (transformers.Pipeline): the transformers.Pipeline from which to create an interface Returns: (dict): a dictionary of kwargs that can be used to construct an Interface object
36
440
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_from_pipeline(pipeline): try: import transformers except ImportError: raise ImportError( "transformers not installed. Please try `pip instal...
929
def calculate_bounds_for_mechanism(value_array, min_val_array, max_val_array): # TODO: Double check whether the iDPGaussianMechanism class squares its squared_l2_norm values!! worst_case_l2_norm = np.sqrt(np.sum(np.square(max_val_array - min_val_array))) * np.ones_like(value_array) l2_norm = np.s...
Calculates the squared L2 norm values needed to create a Mechanism, and calculate privacy budget + spend If you calculate the privacy budget spend with the worst case bound, you can show this number to the D.S. If you calculate it with the regular value (the value computed below when public_only = False, you cannot...
66
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def calculate_bounds_for_mechanism(value_array, min_val_array, max_val_array): # TODO: Double check whether the iDPGaussianMechanism class squares its squared_l2_norm values!!...
930
def get_po_entries(conditions): return frappe.db.sql( .format( conditions=conditions ), as_dict=1, ) # nosec
SELECT child.name, child.parent, child.cost_center, child.project, child.warehouse, child.material_request, child.material_request_item, child.item_code, child.stock_uom, child.qty, child.amount, child.base_amount, child.schedule_date, parent.transaction_date, parent.supp...
44
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_po_entries(conditions): return frappe.db.sql( .format( conditions=conditions ), as_dict=1, ) # nosec ``` ###Assistant : SELECT child.name, child.par...
931
def get_year(self): year = self.year if year is None: try: year = self.kwargs["year"] except KeyError: try: year = self.request.GET["year"] except KeyError: raise Http404(_("No year s...
Return the year for which this view should display data.
10
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_year(self): year = self.year if year is None: try: year = self.kwargs["year"] except KeyError: try: ...
932
def test_overwrite_storage_path(self): call_command("document_retagger", "--storage_path", "--overwrite") d_first, d_second, d_unrelated, d_auto = self.get_updated_docs() self.assertEqual(d_first.storage_path, self.sp2) self.assertEqual(d_auto.storage_path, self.sp1) se...
GIVEN: - 2 storage paths with documents which match them - 1 document which matches but has a storage path WHEN: - document retagger is called with overwrite THEN: - Matching document's storage paths updated - Non-matching documents ha...
47
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_overwrite_storage_path(self): call_command("document_retagger", "--storage_path", "--overwrite") d_first, d_second, d_unrelated, d_auto = self.get_updated_d...
933
def invert(self): return DataFrameDefault.register(pandas.DataFrame.__invert__)(self)
Apply bitwise inversion for each element of the QueryCompiler. Returns ------- BaseQueryCompiler New QueryCompiler containing bitwise inversion for each value.
20
4
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def invert(self): return DataFrameDefault.register(pandas.DataFrame.__invert__)(self) ``` ###Assistant : Apply bitwise inversion for each element of th...
934
def test_center_head_loss(self): s = 256 img_metas = [{'batch_input_shape': (s, s, 3)}] test_cfg = dict(topK=100, max_per_img=100) centernet_head = CenterNetHead( num_classes=4, in_channels=1, feat_channels=4, test_cfg=test_cfg) feat = [torch.rand(1, 1, s, s...
Tests center head loss when truth is empty and non-empty.
10
183
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_center_head_loss(self): s = 256 img_metas = [{'batch_input_shape': (s, s, 3)}] test_cfg = dict(topK=100, max_per_img=100) centernet_head = C...
935
def from_package(package): spec = wrap_spec(package) reader = spec.loader.get_resource_reader(spec.name) return reader.files() @contextlib.contextmanager
Return a Traversable object for the given package.
8
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_package(package): spec = wrap_spec(package) reader = spec.loader.get_resource_reader(spec.name) return reader.files() @contextlib.contextmanager ``` #...
936
def _is_refund_ongoing(payment): return ( payment.transactions.filter( kind=TransactionKind.REFUND_ONGOING, is_success=True ).exists() if payment else False )
Return True if refund is ongoing for given payment.
9
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _is_refund_ongoing(payment): return ( payment.transactions.filter( kind=TransactionKind.REFUND_ONGOING, is_success=True ).exists() if payment...
937
def installed(name, updates=None): if isinstance(updates, str): updates = [updates] if not updates: updates = name ret = {"name": name, "changes": {}, "result": True, "comment": ""} wua = salt.utils.win_update.WindowsUpdateAgent() # Search for updates install_list = wua....
Ensure Microsoft Updates are installed. Updates will be downloaded if needed. Args: name (str): The identifier of a single update to install. updates (list): A list of identifiers for updates to be installed. Overrides ``name``. Default is None. ....
161
215
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def installed(name, updates=None): if isinstance(updates, str): updates = [updates] if not updates: updates = name ret = {"name": name, "changes": {}, "res...
938
def _getKivyInformation(self): setup_codes = r info = self.queryRuntimeInformationMultiple( info_name="kivy_info", setup_codes=setup_codes, values=( ("libs_loaded", "kivy.core.image.libs_loaded"), ("window_impl", "kivy.core.window.windo...
import kivy.core.image import kivy.core.text # Prevent Window from being created at compile time. kivy.core.core_select_lib=(lambda *args, **kwargs: None) import kivy.core.window # Kivy has packages designed to provide these on Windows try: from kivy_deps.sdl2 import dep_bins as sdl2_dep_bins except ImportError: ...
53
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _getKivyInformation(self): setup_codes = r info = self.queryRuntimeInformationMultiple( info_name="kivy_info", setup_codes=setup_codes, ...
939
def __iter__(self) -> Iterator: return iter(self._info_axis) # can we get a better explanation of this?
Iterate over info axis. Returns ------- iterator Info axis as iterator.
11
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __iter__(self) -> Iterator: return iter(self._info_axis) # can we get a better explanation of this? ``` ###Assistant : Iterate over info axis. ...
940
def cast(self, target_schema, *args, **kwargs): table = table_cast(self.table, target_schema, *args, **kwargs) blocks = [] for subtables in self.blocks: new_tables = [] fields = list(target_schema) for subtable in subtables: subfields ...
Cast table values to another schema Args: target_schema (:obj:`Schema`): Schema to cast to, the names and order of fields must match safe (:obj:`bool`, defaults to :obj:`True`): Check for overflows or other unsafe conversions Returns: ...
35
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cast(self, target_schema, *args, **kwargs): table = table_cast(self.table, target_schema, *args, **kwargs) blocks = [] for subtables in self.blocks: ...
941
def softmax(p, axis=None, temperature=1): if axis is None: axis = p.ndim - 1 if temperature == 0.: # NOTE: in case of multiple equal maxima, returns uniform distribution. p = p == np.max(p, axis=axis, keepdims=True) else: # oldp = p logp = np.log(p) logp /= temperature logp -= logp....
Apply the softmax transform to an array of categorical distributions. Args: p: an array of categorical probability vectors, possibly unnormalized. axis: the axis that spans the categories (default: -1). temperature: if not 1, transform the distribution by dividing the log probabilities and renorm...
80
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def softmax(p, axis=None, temperature=1): if axis is None: axis = p.ndim - 1 if temperature == 0.: # NOTE: in case of multiple equal maxima, returns uniform distribution. ...
942
def _populate_static_information(self) -> None: self.info["ludwig_version"] = LUDWIG_VERSION self.info["start_disk_usage"] = shutil.disk_usage(os.path.expanduser("~")).used # CPU information cpu_info = get_my_cpu_info() self.info["cpu_architecture"] = cpu_info["arch"] ...
Populate the report with static software and hardware information.
9
77
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _populate_static_information(self) -> None: self.info["ludwig_version"] = LUDWIG_VERSION self.info["start_disk_usage"] = shutil.disk_usage(os.path.expanduser("~"...
943
def assertCanNotCreateAt(self, parent_model, child_model, msg=None): if self._testCanCreateAt(parent_model, child_model): msg = self._formatMessage( msg, "Can create a %s.%s under a %s.%s" % ( child_model._meta.app_label, ...
Assert a particular child Page type can not be created under a parent Page type. ``parent_model`` and ``child_model`` should be the Page classes being tested.
25
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def assertCanNotCreateAt(self, parent_model, child_model, msg=None): if self._testCanCreateAt(parent_model, child_model): msg = self._formatMessage( ...
944
def get_feature_objects(self) -> Mapping[Project, Feature]: cls = self._manager._get_feature_class(self.feature_name) return {obj: cls(self.feature_name, obj) for obj in self.objects}
Iterate over individual Feature objects. This is a fallback mode for applying a FeatureHandler that doesn't support checking the entire batch at once.
23
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_feature_objects(self) -> Mapping[Project, Feature]: cls = self._manager._get_feature_class(self.feature_name) return {obj: cls(self.feature_name, obj) for o...
945
def require_ffmpeg(test_case): import subprocess try: subprocess.check_output(["ffmpeg", "-h"], stderr=subprocess.DEVNULL) return test_case except Exception: return unittest.skip("test requires ffmpeg")(test_case)
Decorator marking a test that requires FFmpeg. These tests are skipped when FFmpeg isn't installed.
15
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def require_ffmpeg(test_case): import subprocess try: subprocess.check_output(["ffmpeg", "-h"], stderr=subprocess.DEVNULL) return test_case except Exception...
946
def generate_random_string(): import random import string return "".join(random.choices(string.ascii_uppercase + string.digits, k=8)) random_string = generate_random_string() # [START create_queue] create_queue = CloudTasksQueueCreateOperator( location=LOCATION, ...
Generate random string for queue and task names. Queue name cannot be repeated in preceding 7 days and task name in the last 1 hour.
25
221
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_random_string(): import random import string return "".join(random.choices(string.ascii_uppercase + string.digits, k=8)) random_string = g...
947
def make_gradient_clipvalue_fn(clipvalue): if clipvalue is None: return lambda grads_and_vars: grads_and_vars
Creates a gradient transformation function for clipping by value.
9
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def make_gradient_clipvalue_fn(clipvalue): if clipvalue is None: return lambda grads_and_vars: grads_and_vars ``` ###Assistant : Creates a gradient transformati...
948
def odd_ext(x, n, axis=-1): if n < 1: return x if n > x.shape[axis] - 1: raise ValueError( f"The extension length n ({n}) is too big. " f"It must not exceed x.shape[axis]-1, which is {x.shape[axis] - 1}.") left_end = lax.slice_in_dim(x, 0, 1, axis=axis) left_ext = jnp.flip(lax.slice_i...
Extends `x` along with `axis` by odd-extension. This function was previously a part of "scipy.signal.signaltools" but is no longer exposed. Args: x : input array n : the number of points to be added to the both end axis: the axis to be extended
44
83
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def odd_ext(x, n, axis=-1): if n < 1: return x if n > x.shape[axis] - 1: raise ValueError( f"The extension length n ({n}) is too big. " f"It must not exceed x....
949
def filter_on_submodules(all_modules, submodule): filtered_modules = [ mod for mod in all_modules if PACKAGE + submodule in mod.__name__ ] return filtered_modules
Filters all the modules based on the module flag. The module flag has to be relative to the core package imported. For example, if `submodule=keras.layers` then, this function will return all the modules in the submodule. Args: all_modules: All the modules in the core package. submodule: Submodule to ...
60
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def filter_on_submodules(all_modules, submodule): filtered_modules = [ mod for mod in all_modules if PACKAGE + submodule in mod.__name__ ] return filtered_modules `...
950
def get_pe_matching_query(amount_condition, account_from_to, transaction): # get matching payment entries query from_date = frappe.db.get_single_value("Bank Reconciliation Tool", "bank_statement_from_date") to_date = frappe.db.get_single_value("Bank Reconciliation Tool", "bank_statement_to_date") from_reference_dat...
SELECT (CASE WHEN reference_no=%(reference_no)s THEN 1 ELSE 0 END + CASE WHEN (party_type = %(party_type)s AND party = %(party)s ) THEN 1 ELSE 0 END + 1 ) AS rank, 'Payment Entry' as doctype, name, paid_amount, reference_no, reference_date, party, party_type, posting_date, {curre...
80
124
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_pe_matching_query(amount_condition, account_from_to, transaction): # get matching payment entries query from_date = frappe.db.get_single_value("Bank Reconciliation Tool", "bank_sta...
951
def closed(self) -> IntervalInclusiveType: warnings.warn( "Attribute `closed` is deprecated in favor of `inclusive`.", FutureWarning, stacklevel=find_stack_level(inspect.currentframe()), ) return self.dtype.inclusive _interval_shared_docs["set_cl...
String describing the inclusive side the intervals. Either ``left``, ``right``, ``both`` or ``neither`. Return an identical %(klass)s closed on the specified side. .. deprecated:: 1.5.0 Parameters ---------- closed : {'left', 'right', 'both', 'neither...
51
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def closed(self) -> IntervalInclusiveType: warnings.warn( "Attribute `closed` is deprecated in favor of `inclusive`.", FutureWarning, sta...
952
def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import cos, sin re, im = self.args[0].as_real_imag() if deep: re = re.expand(deep, **hints) im = im.expand(deep, **hints) cos, sin = cos(im), sin(im) return ...
Returns this function as a 2-tuple representing a complex number. Examples ======== >>> from sympy import I, exp >>> from sympy.abc import x >>> exp(x).as_real_imag() (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x))) >>> exp(1).as_real_imag() (E, 0...
44
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.trigonometric import cos, sin re, im = self.args[0].as_real_imag() if deep: ...
953
async def _get_conversation_ids_to_process(self) -> Set[Text]: conversation_ids_in_tracker_store = ( await self._get_conversation_ids_in_tracker() ) if not self.requested_conversation_ids: return conversation_ids_in_tracker_store self._validate_all_requ...
Get conversation IDs that are good for processing. Finds the intersection of events that are contained in the tracker store with those events requested as a command-line argument. Returns: Conversation IDs that are both requested and contained in the tracker store. If n...
56
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def _get_conversation_ids_to_process(self) -> Set[Text]: conversation_ids_in_tracker_store = ( await self._get_conversation_ids_in_tracker() ) ...
954
def call(self, inputs, training=None, mask=None): raise NotImplementedError( "Unimplemented `tf.keras.Model.call()`: if you " "intend to create a `Model` with the Functional " "API, please provide `inputs` and `outputs` " "arguments. Otherwise, subclass `...
Calls the model on new inputs and returns the outputs as tensors. In this case `call()` just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs). Note: This method should not be called directly. It is only meant to be ...
150
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call(self, inputs, training=None, mask=None): raise NotImplementedError( "Unimplemented `tf.keras.Model.call()`: if you " "intend to create a `Mo...
955
def _read(cls, path_or_buf, **kwargs): path_or_buf = cls.get_path_or_buffer(path_or_buf) if isinstance(path_or_buf, str): if not cls.file_exists(path_or_buf): return cls.single_worker_read(path_or_buf, **kwargs) path_or_buf = cls.get_path(path_or_buf) ...
Read data from `path_or_buf` according to the passed `read_json` `kwargs` parameters. Parameters ---------- path_or_buf : str, path object or file-like object `path_or_buf` parameter of `read_json` function. **kwargs : dict Parameters of `read_json` func...
44
157
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _read(cls, path_or_buf, **kwargs): path_or_buf = cls.get_path_or_buffer(path_or_buf) if isinstance(path_or_buf, str): if not cls.file_exists(path_or_...
956
def stop_ambient_camera_rotation(self, about="theta"): about: str = about.lower() try: if config.renderer == RendererType.CAIRO: trackers = { "theta": self.camera.theta_tracker, "phi": self.camera.phi_tracker, ...
This method stops all ambient camera rotation.
7
40
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def stop_ambient_camera_rotation(self, about="theta"): about: str = about.lower() try: if config.renderer == RendererType.CAIRO: trackers...
957
def _get_bundled_aggregations(self) -> JsonDict: # Fetch the bundled aggregations of the event. channel = self.make_request( "GET", f"/_matrix/client/unstable/rooms/{self.room}/event/{self.parent_id}", access_token=self.user_token, ) self.asse...
Requests /event on the parent ID and returns the m.relations field (from unsigned), if it exists.
16
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_bundled_aggregations(self) -> JsonDict: # Fetch the bundled aggregations of the event. channel = self.make_request( "GET", f"/_matri...
958
def get_memos(self) -> Dict[bytes32, List[bytes]]: memos: Dict[bytes32, List[bytes]] = {} for coin_spend in self.coin_spends: result = Program.from_bytes(bytes(coin_spend.puzzle_reveal)).run( Program.from_bytes(bytes(coin_spend.solution)) ) fo...
Retrieves the memos for additions in this spend_bundle, which are formatted as a list in the 3rd parameter of CREATE_COIN. If there are no memos, the addition coin_id is not included. If they are not formatted as a list of bytes, they are not included. This is expensive to call, it should not b...
59
153
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_memos(self) -> Dict[bytes32, List[bytes]]: memos: Dict[bytes32, List[bytes]] = {} for coin_spend in self.coin_spends: result = Program.from_bytes...
959
def _clean_url_path_part(part): # type: (str) -> str # We unquote prior to quoting to make sure nothing is double quoted. return urllib.parse.quote(urllib.parse.unquote(part))
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
13
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _clean_url_path_part(part): # type: (str) -> str # We unquote prior to quoting to make sure nothing is double quoted. return urllib.parse.quote(urllib.parse.unquote(part...
960
def CheckAltTokens(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # curre...
Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
40
114
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def CheckAltTokens(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort...
961
def register_ray(): try: from ray.util.joblib.ray_backend import RayBackend register_parallel_backend("ray", RayBackend) except ImportError: msg = ( "To use the ray backend you must install ray." "Try running 'pip install ray'." "See https://docs...
Register Ray Backend to be called with parallel_backend("ray").
8
39
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def register_ray(): try: from ray.util.joblib.ray_backend import RayBackend register_parallel_backend("ray", RayBackend) except ImportError: msg = ( ...
962
def get_group_permissions(self, user_obj, obj=None): return self._get_permissions(user_obj, obj, "group")
Return a set of permission strings the user `user_obj` has from the groups they belong.
15
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_group_permissions(self, user_obj, obj=None): return self._get_permissions(user_obj, obj, "group") ``` ###Assistant : Return a set of permission...
963
def get_evaluation_sets(self) -> List[dict]: return self.evaluation_set_client.get_evaluation_sets()
Returns a list of uploaded evaluation sets to deepset cloud. :return: list of evaluation sets as dicts These contain ("name", "evaluation_set_id", "created_at", "matched_labels", "total_labels") as fields.
26
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_evaluation_sets(self) -> List[dict]: return self.evaluation_set_client.get_evaluation_sets() ``` ###Assistant : Returns a list of uploaded eval...
964
def allowlist_svg(dirty_xml): from lxml.html import clean allow_tags = [ 'xml', 'svg', 'circle', 'ellipse', 'line', 'path', 'polygon', 'polyline', 'rect' ] cleaner = clean.Cleaner( ...
Filter out malicious/harmful content from SVG files by defining allowed tags
11
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def allowlist_svg(dirty_xml): from lxml.html import clean allow_tags = [ 'xml', 'svg', 'circle', 'ellipse', 'line', ...
965
def _sort_filelist(self) -> None: for filename, image, alignments in self._iterator(): self.score_image(filename, image, alignments) self.sort() logger.debug("sorted list: %s", [r[0] if isinstance(r, (tuple, list)) else r for r in self._result])
Call the sort method's logic to populate the :attr:`_results` attribute. Put logic for scoring an individual frame in in :attr:`score_image` of the child Returns ------- list The sorted file. A list of tuples with the filename in the first position and score in ...
46
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _sort_filelist(self) -> None: for filename, image, alignments in self._iterator(): self.score_image(filename, image, alignments) self.sort() ...
966
def finalize_variable_values(self, var_list): if self.use_ema: # If the optimizer uses EMA, then when finalizing, we replace the model # variable value with its moving average stored inside optimizer. self._overwrite_model_variables_with_average_value(var_list)
Set the final value of model's trainable variables. Sometimes there are some extra steps before ending the variable updates, such as overriding the model variables with its average value. Args: var_list: list of model variables.
35
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def finalize_variable_values(self, var_list): if self.use_ema: # If the optimizer uses EMA, then when finalizing, we replace the model # variable val...
967
async def wait_floating_requests_end(self): while self.total_num_floating_tasks_alive > 0: await asyncio.sleep(0)
Await this coroutine to make sure that all the floating tasks that the request handler may bring are properly consumed
20
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def wait_floating_requests_end(self): while self.total_num_floating_tasks_alive > 0: await asyncio.sleep(0) ``` ###Assistant : Await ...
968
def _lu_impl(A, pivot=True, get_infos=False, out=None): # type: (Tensor, bool, bool, Any) -> Tuple[Tensor, Tensor, Tensor] r # If get_infos is True, then we don't need to check for errors and vice versa return torch._lu_with_info(A, pivot=pivot, check_errors=(not get_infos)) if TYPE_CHECKING: _List...
Computes the LU factorization of a matrix or batches of matrices :attr:`A`. Returns a tuple containing the LU factorization and pivots of :attr:`A`. Pivoting is done if :attr:`pivot` is set to ``True``. .. note:: * The returned permutation matrix for every matrix in the batch is repr...
497
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _lu_impl(A, pivot=True, get_infos=False, out=None): # type: (Tensor, bool, bool, Any) -> Tuple[Tensor, Tensor, Tensor] r # If get_infos is True, then we don't need to check f...
969
def test_new_configs_appservice_worker(self) -> None: appservice_worker_config = self._make_worker_config( worker_app="synapse.app.generic_worker", worker_name="worker1" ) self.assertTrue( appservice_worker_config._should_this_worker_perform_duty( ...
Tests new config options. This is for the worker's config.
10
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_new_configs_appservice_worker(self) -> None: appservice_worker_config = self._make_worker_config( worker_app="synapse.app.generic_worker", worker_name="...
970
def E_nl(n, Z=1): n, Z = S(n), S(Z) if n.is_integer and (n < 1): raise ValueError("'n' must be positive integer") return -Z**2/(2*n**2)
Returns the energy of the state (n, l) in Hartree atomic units. The energy does not depend on "l". Parameters ========== n : integer Principal Quantum Number which is an integer with possible values as 1, 2, 3, 4,... Z : Atomic number (1 for Hydrogen, 2 for Helium, .....
80
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def E_nl(n, Z=1): n, Z = S(n), S(Z) if n.is_integer and (n < 1): raise ValueError("'n' must be positive integer") return -Z**2/(2*n**2) ``` ###Assistan...
971
def test_model_checkpoint_no_extraneous_invocations(tmpdir): model = LogInTwoMethods() num_epochs = 4 model_checkpoint = ModelCheckpointTestInvocations(monitor="early_stop_on", expected_count=num_epochs, save_top_k=-1) trainer = Trainer( strategy="ddp_spawn", accelerator="cpu", ...
Test to ensure that the model callback saves the checkpoints only once in distributed mode.
15
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_model_checkpoint_no_extraneous_invocations(tmpdir): model = LogInTwoMethods() num_epochs = 4 model_checkpoint = ModelCheckpointTestInvocations(monitor="early_stop_o...
972
def find_module(self, fullname, path): warnings.warn("MetaPathFinder.find_module() is deprecated since Python " "3.4 in favor of MetaPathFinder.find_spec() and is " "slated for removal in Python 3.12", DeprecationWarning, ...
Return a loader for the module. If no module is found, return None. The fullname is a str and the path is a list of strings or None. This method is deprecated since Python 3.4 in favor of finder.find_spec(). If find_spec() exists then backwards-compatible functionality is prov...
50
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_module(self, fullname, path): warnings.warn("MetaPathFinder.find_module() is deprecated since Python " "3.4 in favor of MetaPathFinder.find_sp...
973
def _generate_individual(self, parameter_id): pos = -1 for i in range(len(self.population)): if self.population[i].result is None: pos = i break if pos != -1: indiv = copy.deepcopy(self.population[pos]) self.populatio...
This function will generate the config for a trial. If at the first generation, randomly generates individuals to satisfy self.population_size. Otherwise, random choose a pair of individuals and compare their fitnesses. The worst of the pair will be removed. Copy the best of the pair an...
70
103
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _generate_individual(self, parameter_id): pos = -1 for i in range(len(self.population)): if self.population[i].result is None: pos =...
974
async def connect(self): connection = {"client_id": self.client_id, "websocket": self.websocket} logging.info(f"Connecting WebSocket: {connection}") await self.websocket.accept() WSProgressHandler.instances.append(self)
Called when a new client connects to the websocket.
9
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def connect(self): connection = {"client_id": self.client_id, "websocket": self.websocket} logging.info(f"Connecting WebSocket: {connection}") await s...
975
def prepare_test_img(self, idx): img_info = self.data_infos[idx] results = dict(img_info=img_info) if self.proposals is not None: results['proposals'] = self.proposals[idx] self.pre_pipeline(results) return self.pipeline(results)
Get testing data after pipeline. Args: idx (int): Index of data. Returns: dict: Testing data after pipeline with new keys introduced by \ pipeline.
24
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def prepare_test_img(self, idx): img_info = self.data_infos[idx] results = dict(img_info=img_info) if self.proposals is not None: results['propo...
976
def get_data(filters): data = [] conditions = get_conditions(filters) salary_slips = frappe.db.sql( % (conditions), as_dict=1, ) component_type_dict = frappe._dict( frappe.db.sql( ) ) if not len(component_type_dict): return [] entry = frappe.db.sql( % (conditions, ", ".join(["%s"] * l...
select sal.name from `tabSalary Slip` sal where docstatus = 1 %s select name, component_type from `tabSalary Component` where component_type in ('Provident Fund', 'Additional Provident Fund', 'Provident Fund Loan') select sal.name, sal.employee, sal.employee_name, ded.salary_component, ded.amount from `tabSal...
63
107
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_data(filters): data = [] conditions = get_conditions(filters) salary_slips = frappe.db.sql( % (conditions), as_dict=1, ) component_type_dict = frappe._dict( frappe.d...
977
def as_dict(self) -> dict[str, Any]: return { "extended_dict": self.as_extended_dict(), "short_dict": self.as_short_dict(), }
Return an dictionary version of this ActionTrace for saving.
9
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def as_dict(self) -> dict[str, Any]: return { "extended_dict": self.as_extended_dict(), "short_dict": self.as_short_dict(), } ``` ...
978
def deserialize(config, custom_objects=None, **kwargs): # loss_scale_optimizer has a direct dependency of optimizer, import here # rather than top to avoid the cyclic dependency. from keras.mixed_precision import ( loss_scale_optimizer, ) use_legacy_optimizer = kwargs.pop("use_legacy_o...
Inverse of the `serialize` function. Args: config: Optimizer configuration dictionary. custom_objects: Optional dictionary mapping names (strings) to custom objects (classes and functions) to be considered during deserialization. Returns: A Keras Optimizer insta...
32
218
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deserialize(config, custom_objects=None, **kwargs): # loss_scale_optimizer has a direct dependency of optimizer, import here # rather than top to avoid the cyclic dependency...
979
def multiply(self, a, b): a = _convert_other(a, raiseit=True) r = a.__mul__(b, context=self) if r is NotImplemented: raise TypeError("Unable to convert %s to Decimal" % b) else: return r
multiply multiplies two operands. If either operand is a special value then the general rules apply. Otherwise, the operands are multiplied together ('long multiplication'), resulting in a number which may be as long as the sum of the lengths of the two operands. >>> ExtendedCo...
75
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def multiply(self, a, b): a = _convert_other(a, raiseit=True) r = a.__mul__(b, context=self) if r is NotImplemented: raise TypeError("Unable to c...
980
def test_run_cleanup_skip_archive(self, cleanup_table_mock, kwargs, should_skip): run_cleanup( clean_before_timestamp=None, table_names=['log'], dry_run=None, verbose=None, confirm=False, **kwargs, ) assert cleanup_...
test that delete confirmation input is called when appropriate
9
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_run_cleanup_skip_archive(self, cleanup_table_mock, kwargs, should_skip): run_cleanup( clean_before_timestamp=None, table_names=['log'], ...
981
def process(self) -> None: if not self.is_downloaded(): self.download() self.process_downloaded_dataset()
Process the dataset into a dataframe and save it at self.processed_dataset_path.
11
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def process(self) -> None: if not self.is_downloaded(): self.download() self.process_downloaded_dataset() ``` ###Assistant : Process the dat...
982
def test_healthy_only_works_for_list_of_functions(self): actors = [Actor.remote(i) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # Mark first and second actor as unhealthy. manager.set_actor_state(1, False) manager.set_actor_state(2, False)
Test healthy only mode works when a list of funcs are provided.
12
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_healthy_only_works_for_list_of_functions(self): actors = [Actor.remote(i) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # M...
983
def test_unassignment(self, mock_func): notification = UnassignedActivityNotification( Activity( project=self.project, group=self.group, user=self.user, type=ActivityType.ASSIGNED, data={"assignee": ""}, ...
Test that a Slack message is sent with the expected payload when an issue is unassigned
16
42
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unassignment(self, mock_func): notification = UnassignedActivityNotification( Activity( project=self.project, group=self...
984
def print_help(self): has_ticker_start = "[unvl]" if not self.ticker else "" has_ticker_end = "[/unvl]" if not self.ticker else "" help_text = f console.print(text=help_text, menu="Stocks - Insider Trading")
Print help[cmds] view view available presets set set one of the available presets[/cmds] [param]PRESET: [/param]{self.preset}[cmds] filter filter insiders based on preset [src][Open Insider][/src] load load a specific stock ticker for analysis[/cmds] {has_ticker_st...
176
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def print_help(self): has_ticker_start = "[unvl]" if not self.ticker else "" has_ticker_end = "[/unvl]" if not self.ticker else "" help_text = f con...
985
def test_project_config_dynamic_sampling_is_none(default_project): default_project.update_option("sentry:dynamic_sampling", None) with Feature({"organizations:server-side-sampling": True}): cfg = get_project_config(default_project) cfg = cfg.to_dict() dynamic_sampling = get_path(cfg, "con...
Tests test check inc-237 that dynamic sampling is None, so it's pass when we have fix and fails when we dont
21
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_project_config_dynamic_sampling_is_none(default_project): default_project.update_option("sentry:dynamic_sampling", None) with Feature({"organizations:server-side-sampl...
986
def seek(self, offset, whence=io.SEEK_SET): self._check_can_seek() return self._buffer.seek(offset, whence)
Change the file position. The new position is specified by offset, relative to the position indicated by whence. Values for whence are: 0: start of stream (default); offset must not be negative 1: current stream position 2: end of stream; offset must not be positive...
66
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def seek(self, offset, whence=io.SEEK_SET): self._check_can_seek() return self._buffer.seek(offset, whence) ``` ###Assistant : Change the file position....
987
def savepoint(self): if not self._savepoint_allowed(): return thread_ident = _thread.get_ident() tid = str(thread_ident).replace("-", "") self.savepoint_state += 1 sid = "s%s_x%d" % (tid, self.savepoint_state) self.validate_thread_sharing() ...
Create a savepoint inside the current transaction. Return an identifier for the savepoint that will be used for the subsequent rollback or commit. Do nothing if savepoints are not supported.
30
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def savepoint(self): if not self._savepoint_allowed(): return thread_ident = _thread.get_ident() tid = str(thread_ident).replace("-", "") ...
988
def get_unclaimed_expese_claims(filters): cond = "1=1" if filters.get("employee"): cond = "ec.employee = %(employee)s" return frappe.db.sql( .format( cond=cond ), filters, as_list=1, )
select ec.employee, ec.employee_name, ec.name, ec.total_sanctioned_amount, ec.total_amount_reimbursed, sum(gle.credit_in_account_currency - gle.debit_in_account_currency) as outstanding_amt from `tabExpense Claim` ec, `tabGL Entry` gle where gle.against_voucher_type = "Expense Claim" and gle.against_...
49
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_unclaimed_expese_claims(filters): cond = "1=1" if filters.get("employee"): cond = "ec.employee = %(employee)s" return frappe.db.sql( .format( cond=cond ), filters, a...
989
def site_config_dir(self) -> str: # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False path = os.environ.get("XDG_CONFIG_DIRS", "") if not path.strip(): path = "/etc/xdg" return self._with_multi_path(path)
:return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS path separator), e.g. ``/etc/xdg/$appname/$version``
34
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def site_config_dir(self) -> str: # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False path = os.environ.get("XDG_CONFIG_DIRS", "") if not pa...
990
def fit_transform(self, X, y=None): self._validate_params() return self._fit_transform(X, compute_sources=True)
Fit the model and recover the sources from X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present fo...
66
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit_transform(self, X, y=None): self._validate_params() return self._fit_transform(X, compute_sources=True) ``` ###Assistant : Fit the model and re...
991
def __fetch_randomly_sampled_transactions(self, project, query, sample_size, query_time_range): sampling_factor = self.__generate_transactions_sampling_factor( project=project, query=query, sample_size=sample_size, query_time_range=query_time_range, ...
Fetches a random sample of transactions of size `sample_size` in the last period defined by `stats_period`. The random sample is fetched by generating a random number by for every row, and then doing a modulo operation on it, and if that number is divisible by the sampling factor then i...
82
92
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __fetch_randomly_sampled_transactions(self, project, query, sample_size, query_time_range): sampling_factor = self.__generate_transactions_sampling_factor( p...
992
def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False): conditions = [] if isinstance(filters, str): filters = json.loads(filters) #Get searchfields from meta and use in Item Link field query meta = frappe.get_meta("Item", cached=True) searchfields = meta.get_search_fields() # the...
select tabItem.name, tabItem.item_name, tabItem.item_group, if(length(tabItem.description) > 40, \ concat(substr(tabItem.description, 1, 40), "..."), description) as description {columns} from tabItem where tabItem.docstatus < 2 and tabItem.disabled=0 and tabItem.has_variants=0 and (tabItem.end_o...
69
235
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def item_query(doctype, txt, searchfield, start, page_len, filters, as_dict=False): conditions = [] if isinstance(filters, str): filters = json.loads(filters) #Get searchfields from m...
993
def apply_and_enforce(*args, **kwargs): func = kwargs.pop("_func") expected_ndim = kwargs.pop("expected_ndim") out = func(*args, **kwargs) if getattr(out, "ndim", 0) != expected_ndim: out_ndim = getattr(out, "ndim", 0) raise ValueError( f"Dimension mismatch: expected out...
Apply a function, and enforce the output.ndim to match expected_ndim Ensures the output has the expected dimensionality.
17
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def apply_and_enforce(*args, **kwargs): func = kwargs.pop("_func") expected_ndim = kwargs.pop("expected_ndim") out = func(*args, **kwargs) if getattr(out, "ndim", 0) != ...
994
def _sanitize_non_ordered(data) -> None: if isinstance(data, (set, frozenset)): raise TypeError(f"'{type(data).__name__}' type is unordered")
Raise only for unordered sets, e.g., not for dict_keys
9
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _sanitize_non_ordered(data) -> None: if isinstance(data, (set, frozenset)): raise TypeError(f"'{type(data).__name__}' type is unordered") ``` ###Assistant ...
995
def dis(x=None, *, file=None, depth=None): if x is None: distb(file=file) return # Extract functions from methods. if hasattr(x, '__func__'): x = x.__func__ # Extract compiled code objects from... if hasattr(x, '__code__'): # ...a function, or x = x.__code__ ...
Disassemble classes, methods, functions, and other compiled objects. With no argument, disassemble the last traceback. Compiled objects currently include generator objects, async generator objects, and coroutine objects, all of which store their code object in a special attribute.
38
145
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dis(x=None, *, file=None, depth=None): if x is None: distb(file=file) return # Extract functions from methods. if hasattr(x, '__func__'): x = x._...
996
def bernoulli_poly(n, x=None, polys=False): r return named_poly(n, dup_bernoulli, QQ, "Bernoulli polynomial", (x,), polys)
Generates the Bernoulli polynomial `\operatorname{B}_n(x)`. `\operatorname{B}_n(x)` is the unique polynomial satisfying .. math :: \int_{x}^{x+1} \operatorname{B}_n(t) \,dt = x^n. Based on this, we have for nonnegative integer `s` and integer `a` and `b` .. math :: \sum_{k=a}^{b} k^s = \frac{\op...
168
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bernoulli_poly(n, x=None, polys=False): r return named_poly(n, dup_bernoulli, QQ, "Bernoulli polynomial", (x,), polys) ``` ###Assistant : Generates the Bernoulli po...
997
def after_log(logger, log_level, sec_format="%0.3f"): log_tpl = ( "Finished call to '%s' after " + str(sec_format) + "(s), " "this was the %s time calling it." )
After call strategy that logs to some logger the finished attempt.
11
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def after_log(logger, log_level, sec_format="%0.3f"): log_tpl = ( "Finished call to '%s' after " + str(sec_format) + "(s), " "this was the %s time calling it." )...
998
def _compat_get_offset(meth): sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(), lambda self, bbox, renderer: locals()]
Decorator for the get_offset method of OffsetBox and subclasses, that allows supporting both the new signature (self, bbox, renderer) and the old signature (self, width, height, xdescent, ydescent, renderer).
29
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _compat_get_offset(meth): sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(), lambda self, bbox, renderer: locals()] ``` ###Assi...
999
def sixtofour(self): if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address.
26
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sixtofour(self): if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) ``` ###Assistant : Retur...