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,100
def _imaginary_unit_as_coefficient(arg): if getattr(arg, 'is_real', True): return None else: return arg.as_coefficient(S.ImaginaryUnit) @sympify_method_args
Helper to extract symbolic coefficient for imaginary unit
8
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _imaginary_unit_as_coefficient(arg): if getattr(arg, 'is_real', True): return None else: return arg.as_coefficient(S.ImaginaryUnit) @sympify_method_args ...
2,101
def from_config(cls, config, custom_objects=None): if "learning_rate" in config: if isinstance(config["learning_rate"], dict): config["learning_rate"] = learning_rate_schedule.deserialize( config["learning_rate"], custom_objects=custom_objects ...
Creates an optimizer from its config. This method is the reverse of `get_config`, capable of instantiating the same optimizer from the config dictionary. Args: config: A Python dictionary, typically the output of get_config. custom_objects: A Python dictionary mapping n...
53
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_config(cls, config, custom_objects=None): if "learning_rate" in config: if isinstance(config["learning_rate"], dict): config["learning_r...
2,102
def test_generate_pdf_from_mail(self): mail = self.parser.get_parsed(os.path.join(self.SAMPLE_FILES, "html.eml")) pdf_path = os.path.join(self.parser.tempdir, "html.eml.pdf") with open(pdf_path, "wb") as file: file.write(self.parser.generate_pdf_from_mail(mail)) c...
GIVEN: - Fresh start WHEN: - pdf generation from simple eml file is requested THEN: - gotenberg is called and the resulting file is returned and look as expected.
29
81
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_generate_pdf_from_mail(self): mail = self.parser.get_parsed(os.path.join(self.SAMPLE_FILES, "html.eml")) pdf_path = os.path.join(self.parser.tempdir, "html...
2,103
def new(self, degree=0, color=None): (center_x, center_y, angle, inner_radius, outer_radius, outer_color, pointer_color, origin_color, line_width) = self.all pointer_color = color or pointer_color if self.figure != []: for figure in self.figu...
Draw new pointer by angle, erase old pointer if exist degree defined as clockwise from negative x-axis.
17
100
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def new(self, degree=0, color=None): (center_x, center_y, angle, inner_radius, outer_radius, outer_color, pointer_color, origin_color, line_width) = sel...
2,104
def postprocess(paths, images, data_out, score_thresh, label_names, output_dir, handle_id, visualization=True): results = data_out.copy_to_cpu() lod = data_out.lod()[0] check_dir(output_dir) if paths: assert type(paths) is list, "type(paths) is not list." if handle_id < len(paths)...
postprocess the lod_tensor produced by Executor.run Args: paths (list[str]): The paths of images. images (list(numpy.ndarray)): images data, shape of each is [H, W, C] data_out (lod_tensor): data output of predictor. output_dir (str): The path to store output images. vi...
181
172
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def postprocess(paths, images, data_out, score_thresh, label_names, output_dir, handle_id, visualization=True): results = data_out.copy_to_cpu() lod = data_out.lod()[0] che...
2,105
def series_with_multilevel_index() -> Series: arrays = [ ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], ["one", "two", "one", "two", "one", "two", "one", "two"], ] tuples = zip(*arrays) index = MultiIndex.from_tuples(tuples) data = np.random.randn(8) ser = Series(...
Fixture with a Series with a 2-level MultiIndex.
8
59
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def series_with_multilevel_index() -> Series: arrays = [ ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], ["one", "two", "one", "two", "one", "two", "one", ...
2,106
def _async_stop(self) -> None: if self._async_unsub_state_changed: self._async_unsub_state_changed() self._async_unsub_state_changed = None
Unregister the group from Home Assistant. This method must be run in the event loop.
15
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _async_stop(self) -> None: if self._async_unsub_state_changed: self._async_unsub_state_changed() self._async_unsub_state_changed = None ...
2,107
def test_database_connection_url(generate_test_database_connection_url): url = generate_test_database_connection_url if url is None: yield None else: # TODO: https://github.com/PrefectHQ/orion/issues/2045 # Also temporarily override the environment variable, so that child ...
Update the setting for the database connection url to the generated value from `generate_test_database_connection_url` This _must_ be separate from the generation of the test url because async fixtures are run in a separate context from the test suite.
38
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_database_connection_url(generate_test_database_connection_url): url = generate_test_database_connection_url if url is None: yield None else: # TODO:...
2,108
def define_by_run_func(trial) -> Optional[Dict[str, Any]]: # This param is not used in the objective function. activation = trial.suggest_categorical("activation", ["relu", "tanh"]) trial.suggest_float("width", 0, 20) trial.suggest_float("height", -100, 100) # Define-by-run allows for conditio...
Define-by-run function to create the search space. Ensure no actual computation takes place here. That should go into the trainable passed to ``Tuner`` (in this example, that's ``easy_objective``). For more information, see https://optuna.readthedocs.io/en/stable\ /tutorial/10_key_features/002_configu...
46
50
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def define_by_run_func(trial) -> Optional[Dict[str, Any]]: # This param is not used in the objective function. activation = trial.suggest_categorical("activation", ["relu", "tan...
2,109
def _compile_to_sklearn(self, expr): sklearn_pipeline_str = generate_pipeline_code( expr_to_tree(expr, self._pset), self.operators ) sklearn_pipeline = eval(sklearn_pipeline_str, self.operators_context) sklearn_pipeline.memory = self._memory if self.random_st...
Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline
23
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _compile_to_sklearn(self, expr): sklearn_pipeline_str = generate_pipeline_code( expr_to_tree(expr, self._pset), self.operators ) sklearn_pipe...
2,110
def equals(self, other, failing_expression=False): if self.shape != getattr(other, 'shape', None): return False rv = True for i in range(self.rows): for j in range(self.cols): ans = self[i, j].equals(other[i, j], failing_expression) ...
Applies ``equals`` to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is True) if it cannot be decided if the expressions are eq...
103
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def equals(self, other, failing_expression=False): if self.shape != getattr(other, 'shape', None): return False rv = True for i in range(self.ro...
2,111
def load(self, loader): loader.add_option( "block_list", Sequence[str], [], )
Block matching requests and return an empty response with the specified HTTP status. Option syntax is "/flow-filter/status-code", where flow-filter describes which requests this rule should be applied to and status-code is the HTTP status code to return for blocked reque...
65
8
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load(self, loader): loader.add_option( "block_list", Sequence[str], [], ) ``` ###Assistant : Block matching requests an...
2,112
def train(self, tagged_docs): m1 = [self.source_lang_vec.dv[item.tags].flatten() for item in tagged_docs] m2 = [self.target_lang_vec.dv[item.tags].flatten() for item in tagged_docs] self.translation_matrix = np.linalg.lstsq(m2, m1, -1)[0] return self.translation_matrix
Build the translation matrix to map from the source model's vectors to target model's vectors Parameters ---------- tagged_docs : list of :class:`~gensim.models.doc2vec.TaggedDocument`, Documents that will be used for training, both the source language document vector and ...
61
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def train(self, tagged_docs): m1 = [self.source_lang_vec.dv[item.tags].flatten() for item in tagged_docs] m2 = [self.target_lang_vec.dv[item.tags].flatten() for item...
2,113
def serialize(input, tree="etree", encoding=None, **serializer_opts): # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) s = HTMLSerializer(**serializer_opts) return s.render(walker(input), encoding)
Serializes the input token stream using the specified treewalker :arg input: the token stream to serialize :arg tree: the treewalker to use :arg encoding: the encoding to use :arg serializer_opts: any options to pass to the :py:class:`html5lib.serializer.HTMLSerializer` that gets created ...
66
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def serialize(input, tree="etree", encoding=None, **serializer_opts): # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) s = HTMLSerializer(**serializer_o...
2,114
def set_client_cli_parser(parser=None): if not parser: from jina.parsers.base import set_base_parser parser = set_base_parser() from jina.parsers.peapods.runtimes.remote import mixin_client_gateway_parser from jina.parsers.client import ( mixin_client_features_parser, ...
Set the parser for the cli client :param parser: an optional existing parser to build upon :return: the parser
19
28
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_client_cli_parser(parser=None): if not parser: from jina.parsers.base import set_base_parser parser = set_base_parser() from jina.parsers.peapods.runti...
2,115
def send_sale_toggle_notification(info, instance, catalogue): manager = info.context.plugins now = datetime.now(pytz.utc) start_date = instance.start_date end_date = instance.end_date if (start_date and start_date <= now) and (not end_date or not end_date <= now): ...
Send a notification about starting or ending sale if it hasn't been sent yet. Send the notification when the start date is before the current date and the sale is not already finished.
33
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def send_sale_toggle_notification(info, instance, catalogue): manager = info.context.plugins now = datetime.now(pytz.utc) start_date = instance.start_date ...
2,116
def bcoo_todense(data, indices, *, spinfo): return bcoo_todense_p.bind(jnp.asarray(data), jnp.asarray(indices), spinfo=spinfo) @bcoo_todense_p.def_impl
Convert batched sparse matrix to a dense matrix. Args: data : array of shape ``batch_dims + (nse,) + block_dims``. indices : array of shape ``batch_dims + (n_sparse, nse)`` spinfo : BCOOInfo. In particular, this includes the shape of the matrix, which is equal to ``batch_dims + sparse_dims + block_...
64
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def bcoo_todense(data, indices, *, spinfo): return bcoo_todense_p.bind(jnp.asarray(data), jnp.asarray(indices), spinfo=spinfo) @bcoo_todense_p.def_impl ``` ###Assistant : C...
2,117
def ignore_ray_errors(self) -> Iterator[ResultOrError]: return self._Iterator( [r for r in self.result_or_errors if not isinstance(r.get(), RayError)] )
Return an iterator over the results, skipping only Ray errors. Similar to ignore_errors, but only skips Errors raised from the Ray framework. This is useful for application that wants to handle errors from user code differently.
36
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ignore_ray_errors(self) -> Iterator[ResultOrError]: return self._Iterator( [r for r in self.result_or_errors if not isinstance(r.get(), RayError)] ) ...
2,118
def certificate_was_accepted(self) -> None: if not self.is_overridable(): return False if self._certificate_accepted is None: raise ValueError("No decision taken yet") return self._certificate_accepted @dataclasses.dataclass
Check whether the certificate was accepted by the user.
9
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def certificate_was_accepted(self) -> None: if not self.is_overridable(): return False if self._certificate_accepted is None: raise ValueErro...
2,119
def mask(self, row_indices, col_indices): return ( self.force_materialization() .list_of_partitions_to_combine[0] .mask(row_indices, col_indices) )
Create (synchronously) a mask that extracts the indices provided. Parameters ---------- row_indices : list-like, slice or label The row labels for the rows to extract. col_indices : list-like, slice or label The column labels for the columns to extract. ...
47
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mask(self, row_indices, col_indices): return ( self.force_materialization() .list_of_partitions_to_combine[0] .mask(row_indices, col_...
2,120
def left_integral3D(facets, index, expr, vertices, hp_param, degree): value = S.Zero facet = facets[index] x0 = vertices[facet[0]] facet_len = len(facet) for i, fac in enumerate(facet): side = (vertices[fac], vertices[facet[(i + 1) % facet_len]]) value += distance_to_side(x0, si...
Computes the left integral of Eq 10 in Chin et al. Explanation =========== For the 3D case, this is the sum of the integral values over constituting line segments of the face (which is accessed by facets[index]) multiplied by the distance between the first point of facet and that line segment. ...
177
46
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def left_integral3D(facets, index, expr, vertices, hp_param, degree): value = S.Zero facet = facets[index] x0 = vertices[facet[0]] facet_len = len(facet) for i, fac ...
2,121
def xdropout(self, inputs): mask = tf.cast( 1 - tf.compat.v1.distributions.Bernoulli(probs=1.0 - self.drop_prob).sample(sample_shape=shape_list(inputs)), tf.bool, ) scale = tf.convert_to_tensor(1.0 / (1 - self.drop_prob), dtype=tf.float32) if ...
Applies dropout to the inputs, as vanilla dropout, but also scales the remaining elements up by 1/drop_prob.
17
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def xdropout(self, inputs): mask = tf.cast( 1 - tf.compat.v1.distributions.Bernoulli(probs=1.0 - self.drop_prob).sample(sample_shape=shape_list(input...
2,122
def test_deltas_that_melt_dataframes(self): deltas = self._get_deltas_that_melt_dataframes() for delta in deltas: el = delta(DATAFRAME) el._legacy_add_rows(NEW_ROWS) df_proto = _get_data_frame(self.get_delta_from_queue()) # Test that the add_ro...
Some element types require that their dataframes are 'melted' (https://pandas.pydata.org/docs/reference/api/pandas.melt.html) before being sent to the frontend. Test that the melting occurs.
21
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_deltas_that_melt_dataframes(self): deltas = self._get_deltas_that_melt_dataframes() for delta in deltas: el = delta(DATAFRAME) el._...
2,123
def sensors_temperatures(): ret = collections.defaultdict(list) basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*') # CentOS has an intermediate /device directory: # https://github.com/giampaolo/psutil/issues/971 # https://github.com/nicolargo/glances/issues/1060 basenames.extend(glob....
Return hardware (CPU and others) temperatures as a dict including hardware name, label, current, max and critical temperatures. Implementation notes: - /sys/class/hwmon looks like the most recent interface to retrieve this info, and this implementation relies on it only (old distros will pr...
65
326
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sensors_temperatures(): ret = collections.defaultdict(list) basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*') # CentOS has an intermediate /device directory: ...
2,124
def preview_revision_for_task(request, page_id, task_id): page = get_object_or_404(Page, id=page_id) task = get_object_or_404(Task, id=task_id).specific try: task_state = TaskState.objects.get( page_revision__page=page, task=task, status=TaskState.STATUS_IN_PROGRESS ) e...
Preview the revision linked to the in-progress TaskState of a specified Task. This enables pages in moderation to be edited and new TaskStates linked to the new revisions created, with preview links remaining valid
34
68
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def preview_revision_for_task(request, page_id, task_id): page = get_object_or_404(Page, id=page_id) task = get_object_or_404(Task, id=task_id).specific try: task_s...
2,125
def push_async_callback(self, callback, /, *args, **kwds): _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped...
Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions.
10
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def push_async_callback(self, callback, /, *args, **kwds): _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so usi...
2,126
def scanString(self, instring, maxMatches=_MAX_INT, overlap=False): if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = _ustr(instring).expandtabs() instrlen = len(instring) ...
Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional ``maxMatches`` argument, to clip scanning after 'n' matches are found. If ``overlap`` is specified, then overlapping matches will be...
99
135
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def scanString(self, instring, maxMatches=_MAX_INT, overlap=False): if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.s...
2,127
def add_to_apply_calls(self, func, *args, length=None, width=None, **kwargs): return PandasOnDaskDataframePartition( self._data, call_queue=self.call_queue + [[func, args, kwargs]], length=length, width=width, )
Add a function to the call queue. Parameters ---------- func : callable Function to be added to the call queue. *args : iterable Additional positional arguments to be passed in `func`. length : distributed.Future or int, optional Leng...
87
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add_to_apply_calls(self, func, *args, length=None, width=None, **kwargs): return PandasOnDaskDataframePartition( self._data, call_queue=self.call...
2,128
def to_json_string(self) -> str: dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() # make sure private name "_processor_class" is correctly # saved as "processor_clas...
Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
23
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def to_json_string(self) -> str: dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dic...
2,129
def one_of_permissions_or_auth_filter_required(context, permissions): if not permissions: return True authorization_filters = [ p for p in permissions if isinstance(p, AuthorizationFilters) ] permissions = [p for p in permissions if not isinstance(p, AuthorizationFilters)] gra...
Determine whether user or app has rights to perform an action. The `context` parameter is the Context instance associated with the request.
22
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def one_of_permissions_or_auth_filter_required(context, permissions): if not permissions: return True authorization_filters = [ p for p in permissions if isinst...
2,130
def _dirmatch(path, matchwith): matchlen = len(matchwith) if (path.startswith(matchwith) and path[matchlen:matchlen + 1] in [os.sep, '']): return True return False
Check if path is within matchwith's tree. >>> _dirmatch('/home/foo/bar', '/home/foo/bar') True >>> _dirmatch('/home/foo/bar/', '/home/foo/bar') True >>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar') True >>> _dirmatch('/home/foo/bar2', '/home/foo/bar') False >>> _dirmatch('/home/fo...
27
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _dirmatch(path, matchwith): matchlen = len(matchwith) if (path.startswith(matchwith) and path[matchlen:matchlen + 1] in [os.sep, '']): return True return...
2,131
def deform_sampling(self, feat, offset): # it is an equivalent implementation of bilinear interpolation b, c, h, w = feat.shape weight = feat.new_ones(c, 1, 1, 1) y = deform_conv2d(feat, offset, weight, 1, 0, 1, c, c) return y
Sampling the feature x according to offset. Args: feat (Tensor): Feature offset (Tensor): Spatial offset for feature sampling
18
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deform_sampling(self, feat, offset): # it is an equivalent implementation of bilinear interpolation b, c, h, w = feat.shape weight = feat.new_ones(c, 1, ...
2,132
def page_identity(self, response, request_json=None): request_path = response.request.path_url if request_path == '/migrations_notran/': raise exc.IsMigrating('You have been redirected to the migration-in-progress page.') request_method = response.request.method.lower() ...
Takes a `requests.Response` and returns a new __item_class__ instance if the request method is not a get, or returns a __class__ instance if the request path is different than the caller's `endpoint`.
32
171
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def page_identity(self, response, request_json=None): request_path = response.request.path_url if request_path == '/migrations_notran/': raise exc.IsMigr...
2,133
def _installed_conda(self): if not self._is_conda: return None with Popen("conda list", shell=True, stdout=PIPE, stderr=PIPE) as conda: stdout, stderr = conda.communicate() if stderr: return "Could not get package list" installed = stdout.deco...
str: The list of installed Conda packages within Faceswap's scope.
10
33
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _installed_conda(self): if not self._is_conda: return None with Popen("conda list", shell=True, stdout=PIPE, stderr=PIPE) as conda: stdou...
2,134
def embedding(self, input_seq): seq_embeddings = self.item_embedding_layer(input_seq) seq_embeddings = seq_embeddings * (self.embedding_dim ** 0.5) # FIXME positional_seq = tf.expand_dims(tf.range(tf.shape(input_seq)[1]), 0) positional_seq = tf.tile(positional_seq, [tf...
Compute the sequence and positional embeddings. Args: input_seq (tf.Tensor): Input sequence Returns: tf.Tensor, tf.Tensor: - Sequence embeddings. - Positional embeddings.
20
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def embedding(self, input_seq): seq_embeddings = self.item_embedding_layer(input_seq) seq_embeddings = seq_embeddings * (self.embedding_dim ** 0.5) # FIXME...
2,135
def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False, newline=True): nocolor = msg if not log_only: has_newline = msg.endswith(u'\n') if has_newline: msg2 = msg[:-1] else: msg2 = msg ...
Display a message to the user Note: msg *must* be a unicode string to prevent UnicodeError tracebacks.
17
223
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False, newline=True): nocolor = msg if not log_only: has_newline = msg.en...
2,136
def get_queryset(self, request): queryset = SavedFilter.objects.all() user = request.user if user.is_superuser: return queryset if user.is_anonymous: return queryset.filter(shared=True) return queryset.filter( Q(shared=True) | Q(user=u...
Return only shared SavedFilters, or those owned by the current user, unless this is a superuser.
16
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_queryset(self, request): queryset = SavedFilter.objects.all() user = request.user if user.is_superuser: return queryset if user.i...
2,137
def list(self, request): report_list = [] report_content_type = ContentType.objects.get(app_label='extras', model='report') results = { r.name: r for r in JobResult.objects.filter( obj_type=report_content_type, status__in=JobResult...
Compile all reports and their related results (if any). Result data is deferred in the list view.
17
64
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def list(self, request): report_list = [] report_content_type = ContentType.objects.get(app_label='extras', model='report') results = { r.name: r...
2,138
def _usable(self, queryset, name, value): user = self.request.user if self.request else None if not user or user.is_anonymous: if value: return queryset.filter(enabled=True, shared=True) return queryset.filter(Q(enabled=False) | Q(shared=False)) i...
Return only SavedFilters that are both enabled and are shared (or belong to the current user).
16
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _usable(self, queryset, name, value): user = self.request.user if self.request else None if not user or user.is_anonymous: if value: ...
2,139
def get_current_enrollment(student, academic_year=None): current_academic_year = academic_year or frappe.defaults.get_defaults().academic_year program_enrollment_list = frappe.db.sql( , (student, current_academic_year), as_dict=1, ) if program_enrollment_list: return program_enrollment_list[0] else: ret...
select name as program_enrollment, student_name, program, student_batch_name as student_batch, student_category, academic_term, academic_year from `tabProgram Enrollment` where student = %s and academic_year = %s order by creation
26
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_current_enrollment(student, academic_year=None): current_academic_year = academic_year or frappe.defaults.get_defaults().academic_year program_enrollment_list = frappe.db.sql( , ...
2,140
def inception_resnet_block(x, scale, block_type, block_idx, activation="relu"): if block_type == "block35": branch_0 = conv2d_bn(x, 32, 1) branch_1 = conv2d_bn(x, 32, 1) branch_1 = conv2d_bn(branch_1, 32, 3) branch_2 = conv2d_bn(x, 32, 1) branch_2 = conv2d_bn(branch_2, 4...
Adds an Inception-ResNet block. This function builds 3 types of Inception-ResNet blocks mentioned in the paper, controlled by the `block_type` argument (which is the block name used in the official TF-slim implementation): - Inception-ResNet-A: `block_type='block35'` - Inception-ResNet-B: `block_ty...
193
180
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def inception_resnet_block(x, scale, block_type, block_idx, activation="relu"): if block_type == "block35": branch_0 = conv2d_bn(x, 32, 1) branch_1 = conv2d_bn(x, 32...
2,141
def _get_calculations(self): for selection in self._selections: if selection == "raw": continue logger.debug("Calculating: %s", selection) method = getattr(self, f"_calc_{selection}") raw_keys = [key for key in self._stats if key.startswit...
Perform the required calculations and populate :attr:`stats`.
7
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_calculations(self): for selection in self._selections: if selection == "raw": continue logger.debug("Calculating: %s", selec...
2,142
def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"): if solver_type not in ['dpm_solver', 'taylor']: raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) ns = self.noise_schedule ...
Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`. Args: x: A pytorch tensor. The initial value at time `s`. model_prev_list: A list of pytorch tensor. The previous computed model values. t_prev_list: A list of pytorch tensor. The previous times, ...
91
228
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"): if solver_type not in ['dpm_solver', 'taylor']: raise...
2,143
def global_enum(cls, update_str=False): if issubclass(cls, Flag): cls.__repr__ = global_flag_repr else: cls.__repr__ = global_enum_repr if not issubclass(cls, ReprEnum) or update_str: cls.__str__ = global_str sys.modules[cls.__module__].__dict__.update(cls.__members__) r...
decorator that makes the repr() of an enum member reference its module instead of its class; also exports all members to the enum's module's global namespace
26
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def global_enum(cls, update_str=False): if issubclass(cls, Flag): cls.__repr__ = global_flag_repr else: cls.__repr__ = global_enum_repr if not issubclass(cls...
2,144
def create_training_target(self, target, run_eagerly=False): if self.has_training_target(): raise ValueError( "The training_target field for the _TrainingEndpoint " "instance has already been populated" ) if run_eagerly: # When...
Create training_target instance and update the self.training_target. Note that the input target should just be a tensor or None, and corresponding training target will be created based on the output and loss_fn. Args: target: the target tensor for the current output. Could be...
67
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def create_training_target(self, target, run_eagerly=False): if self.has_training_target(): raise ValueError( "The training_target field for the ...
2,145
def test_set_task_instance_state(run_id, execution_date, session, dag_maker): start_date = datetime_tz(2020, 1, 1) with dag_maker("test_set_task_instance_state", start_date=start_date, session=session) as dag: task_1 = DummyOperator(task_id="task_1") task_2 = DummyOperator(task_id="task_2"...
Test that set_task_instance_state updates the TaskInstance state and clear downstream failed
11
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_set_task_instance_state(run_id, execution_date, session, dag_maker): start_date = datetime_tz(2020, 1, 1) with dag_maker("test_set_task_instance_state", start_date=sta...
2,146
async def async_step_link(self, user_input=None): errors = {} if user_input is not None: # Do not authenticate if the host is already configured self._async_abort_entries_match({CONF_HOST: self._host}) try: info = await authenticate( ...
Handle linking and authenticting with the roon server.
8
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_step_link(self, user_input=None): errors = {} if user_input is not None: # Do not authenticate if the host is already configured ...
2,147
def test_get_sid_string_none(): sid_obj = salt.utils.win_dacl.get_sid(None) assert isinstance(sid_obj, pywintypes.SIDType) assert salt.utils.win_dacl.get_sid_string(sid_obj) == "S-1-0-0"
Validate getting a null sid (S-1-0-0) when a null sid is passed
12
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_sid_string_none(): sid_obj = salt.utils.win_dacl.get_sid(None) assert isinstance(sid_obj, pywintypes.SIDType) assert salt.utils.win_dacl.get_sid_string(sid_obj)...
2,148
def read(self, filename, split='train'): label_list = self.get_labels() vocab_info = self.get_vocab()
Returns a dataset containing all the examples that can be read from the file path. If `self.lazy` is False, this eagerly reads all instances from `self._read()` and returns a `MapDataset`. If `self.lazy` is True, this returns an `IterDataset`, which internally relies on the ge...
112
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def read(self, filename, split='train'): label_list = self.get_labels() vocab_info = self.get_vocab() ``` ###Assistant : Returns a dataset con...
2,149
def test_no_rule_for_attr(self): tag = self.soup.b fn = attribute_rule({"snowman": "barbecue"}) fn(tag) self.assertEqual(str(tag), "<b>baz</b>")
Test that attribute_rule() drops attributes for which no rule has been defined.
12
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_no_rule_for_attr(self): tag = self.soup.b fn = attribute_rule({"snowman": "barbecue"}) fn(tag) self.assertEqual(str(tag), "<b>baz</b>") ...
2,150
def _inspect_generic_serialization(base_obj, depth, parent, failure_set): assert not inspect.isfunction(base_obj) functions = inspect.getmembers(base_obj, predicate=inspect.isfunction) found = False with _printer.indent(): for name, obj in functions: serializable, _ = inspect_se...
Adds the first-found non-serializable element to the failure_set.
8
103
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _inspect_generic_serialization(base_obj, depth, parent, failure_set): assert not inspect.isfunction(base_obj) functions = inspect.getmembers(base_obj, predicate=inspect.isfu...
2,151
def is_dihedral(self): r if self._is_dihedral is not None: return self._is_dihedral order = self.order() if order % 2 == 1: self._is_dihedral = False return False if order == 2: self._is_dihedral = True return True ...
Return ``True`` if the group is dihedral. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup ...
70
287
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def is_dihedral(self): r if self._is_dihedral is not None: return self._is_dihedral order = self.order() if order % 2 == 1: self._is...
2,152
def extend_rearport_cable_paths(instance, created, **kwargs): if created: rearport = instance.rear_port for cablepath in CablePath.objects.filter(_nodes__contains=rearport): cablepath.retrace()
When a new FrontPort is created, add it to any CablePaths which end at its corresponding RearPort.
17
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extend_rearport_cable_paths(instance, created, **kwargs): if created: rearport = instance.rear_port for cablepath in CablePath.objects.filter(_nodes__contains=re...
2,153
def _load_images_to_cache(self, image_files, frame_dims, thumbnail_size): logger.debug("Number image_files: %s, frame_dims: %s, thumbnail_size: %s", len(image_files), frame_dims, thumbnail_size) num_images = (frame_dims[0] // thumbnail_size) * (frame_dims[1] // thumbnail_si...
Load preview images to the image cache. Load new images and append to cache, filtering the cache the number of thumbnails that will fit inside the display panel. Parameters ---------- image_files: list A list of new image files that have been modified since the la...
86
281
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _load_images_to_cache(self, image_files, frame_dims, thumbnail_size): logger.debug("Number image_files: %s, frame_dims: %s, thumbnail_size: %s", len...
2,154
def target_profile(self) -> t.Optional[PosixProfile]: return t.cast(PosixProfile, self.profiles[0]) if self.profiles else None
The POSIX target profile, if it uses a different Python interpreter than the controller, otherwise None.
16
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def target_profile(self) -> t.Optional[PosixProfile]: return t.cast(PosixProfile, self.profiles[0]) if self.profiles else None ``` ###Assistant : The POSIX targ...
2,155
def preprocess_transactions(self): p_bar = tqdm(range(14), desc="Preprocessing transactions") try: # 0. If optional fields not in the transactions add missing optional_fields = [ "Sector", "Industry", "Country", ...
Method to preprocess, format and compute auxiliary fields. Preprocessing steps: 0. If optional fields not in the transactions add missing 1. Convert Date to datetime 2. Sort transactions by date 3. Capitalize Ticker and Type [of instrument...] 4. Tran...
116
512
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def preprocess_transactions(self): p_bar = tqdm(range(14), desc="Preprocessing transactions") try: # 0. If optional fields not in the transactions add...
2,156
def _var_key(var): # pylint: disable=protected-access # Get the distributed variable if it exists. if hasattr(var, "_distributed_container"): var = var._distributed_container() if getattr(var, "_in_graph_mode", False): return var._shared_name return var._unique_id
Key for representing a primary variable, for looking up slots. In graph mode the name is derived from the var shared name. In eager mode the name is derived from the var unique id. If distribution strategy exists, get the primary variable first. Args: var: the variable. Returns: the unique name of ...
54
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _var_key(var): # pylint: disable=protected-access # Get the distributed variable if it exists. if hasattr(var, "_distributed_container"): var = var._distributed_container()...
2,157
def test_stacking_classifier_base_regressor(): X_train, X_test, y_train, y_test = train_test_split( scale(X_iris), y_iris, stratify=y_iris, random_state=42 ) clf = StackingClassifier(estimators=[("ridge", Ridge())]) clf.fit(X_train, y_train) clf.predict(X_test) clf.predict_proba(X_t...
Check that a regressor can be used as the first layer in `StackingClassifier`.
13
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_stacking_classifier_base_regressor(): X_train, X_test, y_train, y_test = train_test_split( scale(X_iris), y_iris, stratify=y_iris, random_state=42 ) clf = S...
2,158
def _get_style_dict(self, gc, rgbFace): attrib = {} forced_alpha = gc.get_forced_alpha() if gc.get_hatch() is not None: attrib['fill'] = "url(#%s)" % self._get_hatch(gc, rgbFace) if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0 ...
Generate a style string from the GraphicsContext and rgbFace.
9
145
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_style_dict(self, gc, rgbFace): attrib = {} forced_alpha = gc.get_forced_alpha() if gc.get_hatch() is not None: attrib['fill'] = "url(#...
2,159
def test_union(self, mock_handler): self.set_handler(mock_handler, name='pg', tables={'tasks': self.df}) # --- use predictor --- predictor = { 'name': 'task_model', 'predict': 'p', 'dtypes': { 'p': dtype.float, 'a': dtype.inte...
SELECT a as a1, b as target FROM pg.tasks UNION {union} SELECT model.a as a2, model.p as target2 FROM pg.tasks as t JOIN mindsdb.task_model as model WHERE t.a=1
28
85
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_union(self, mock_handler): self.set_handler(mock_handler, name='pg', tables={'tasks': self.df}) # --- use predictor --- predictor = { 'name': '...
2,160
def test_run_cleanup_tables(self, clean_table_mock, table_names): base_kwargs = dict( clean_before_timestamp=None, dry_run=None, verbose=None, ) run_cleanup(**base_kwargs, table_names=table_names) assert clean_table_mock.call_count == len(tabl...
``_cleanup_table`` should be called for each table in subset if one is provided else should be called for all tables.
20
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_run_cleanup_tables(self, clean_table_mock, table_names): base_kwargs = dict( clean_before_timestamp=None, dry_run=None, verbose=...
2,161
def test_set_serialize_call_old_signature(self, get_import, session): serialize_watcher = MagicMock()
When XCom.serialize_value takes only param ``value``, other kwargs should be ignored.
11
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_set_serialize_call_old_signature(self, get_import, session): serialize_watcher = MagicMock() ``` ###Assistant : When XCom.serialize_value take...
2,162
def gmean(a, axis=0, dtype=None, weights=None): if not isinstance(a, np.ndarray): # if not an ndarray object attempt to convert it log_a = np.log(np.array(a, dtype=dtype)) elif dtype: # Must change the default dtype allowing array type if isinstance(a, np.ma.MaskedArray): ...
Compute the geometric mean along the specified axis. Return the geometric average of the array elements. That is: n-th root of (x1 * x2 * ... * xn) Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int or None, optional Axis a...
301
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def gmean(a, axis=0, dtype=None, weights=None): if not isinstance(a, np.ndarray): # if not an ndarray object attempt to convert it log_a = np.log(np.array(a, dtype=d...
2,163
def handle_m2m_field(self, obj, field): raise NotImplementedError( "subclasses of Serializer must provide a handle_m2m_field() method" )
Called to handle a ManyToManyField.
5
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def handle_m2m_field(self, obj, field): raise NotImplementedError( "subclasses of Serializer must provide a handle_m2m_field() method" ) ``` ...
2,164
def check_connection(self) -> StatusResponse: response = StatusResponse(False) need_to_close = self.is_connected is False try: connection = self.connect() with connection.cursor() as cur: cur.execute('SELECT * FROM SYS.M_DATABASE') r...
Check the connection of the SAP HANA database :return: success status and error message if error occurs
17
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_connection(self) -> StatusResponse: response = StatusResponse(False) need_to_close = self.is_connected is False try: connection = sel...
2,165
def extract(self, rowsList, colsList): r if not is_sequence(rowsList) or not is_sequence(colsList): raise TypeError("rowsList and colsList must be iterable") # ensure rowsList and colsList are lists of integers if rowsList and all(isinstance(i, bool) for i in rowsList): ...
Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range $-n \le i < n$ where $n$ is the number of rows or columns. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 3, range(12)) ...
156
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def extract(self, rowsList, colsList): r if not is_sequence(rowsList) or not is_sequence(colsList): raise TypeError("rowsList and colsList must be iterable") ...
2,166
def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs): doit_flags = { 'deep': False, 'meijerg': meijerg, 'conds': conds, 'risch': risch, 'heurisch': heurisch, 'manual': manual } integral = Integral(*ar...
integrate(f, var, ...) Explanation =========== Compute definite or indefinite integral of one or more variables using Risch-Norman algorithm and table lookup. This procedure is able to handle elementary algebraic and transcendental functions and also a huge class of special functions, includin...
865
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs): doit_flags = { 'deep': False, 'meijerg': meijerg, 'c...
2,167
def parsed_paths(self) -> List[str]: res_paths: List[str] = [] paths = self.parser.existing_paths for directory in paths: for filename in paths[directory]: res_paths.append(os.path.join(directory, filename)) return res_paths
Returns a list of file paths that have currently been parsed into the parser tree. The returned list may include paths with wildcard characters, for example: ['/etc/apache2/conf.d/*.load'] This is typically called on the root node of the ParserNode tree. :returns: list of file...
50
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parsed_paths(self) -> List[str]: res_paths: List[str] = [] paths = self.parser.existing_paths for directory in paths: for filename in paths...
2,168
def _check_guts_toc_mtime(attr_name, old_toc, new_toc, last_build, pyc=False): for dest_name, src_name, typecode in old_toc: if misc.mtime(src_name) > last_build: logger.info("Building because %s changed", src_name) return True elif pyc and typecode == 'PYMODULE': ...
Rebuild is required if mtimes of files listed in old TOC are newer than last_build. If pyc=True, check for .py files as well. Use this for calculated/analysed values read from cache.
31
45
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _check_guts_toc_mtime(attr_name, old_toc, new_toc, last_build, pyc=False): for dest_name, src_name, typecode in old_toc: if misc.mtime(src_name) > last_build: ...
2,169
def check_connection(self) -> StatusResponse: response = StatusResponse(False) need_to_close = self.is_connected is False try: connection = self.connect() with connection.cursor() as cur: cur.execute('SELECT 1 FROM (SELECT 1 AS "dual") AS "dual"...
Check the connection of the Teradata database :return: success status and error message if error occurs
16
65
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_connection(self) -> StatusResponse: response = StatusResponse(False) need_to_close = self.is_connected is False try: connection = sel...
2,170
def process_doc_file(code_file, add_new_line=True): with open(code_file, "r", encoding="utf-8", newline="\n") as f: code = f.read() # fmt: off splits = code.split("```") if len(splits) % 2 != 1: raise ValueError("The number of occurrences of ``` should be an even number.") spl...
Process given file. Args: code_file (`str` or `os.PathLike`): The file in which we want to style the docstring.
18
79
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def process_doc_file(code_file, add_new_line=True): with open(code_file, "r", encoding="utf-8", newline="\n") as f: code = f.read() # fmt: off splits = code.split("...
2,171
def finalize(self, batch): for face, landmarks in zip(batch["detected_faces"], batch["landmarks"]): if not isinstance(landmarks, np.ndarray): landmarks = np.array(landmarks) face._landmarks_xy = landmarks logger.trace("Item out: %s", {key: val.shape if ...
Finalize the output from Aligner This should be called as the final task of each `plugin`. Pairs the detected faces back up with their original frame before yielding each frame. Parameters ---------- batch : dict The final ``dict`` from the `plugin` process. It mu...
76
82
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def finalize(self, batch): for face, landmarks in zip(batch["detected_faces"], batch["landmarks"]): if not isinstance(landmarks, np.ndarray): la...
2,172
def find_dcerpc_interface(name): try: return next(x for x in DCE_RPC_INTERFACES.values() if x.name == name) except StopIteration: raise AttributeError("Unknown interface !") # --- NDR fields - [C706] chap 14
Find an interface object through the name in the IDL
10
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_dcerpc_interface(name): try: return next(x for x in DCE_RPC_INTERFACES.values() if x.name == name) except StopIteration: raise AttributeError("Unknown i...
2,173
def test_animatable(): animatable = AnimateTest() # Fake wall-clock time time = 100.0 # Object that does the animation animation = SimpleAnimation( animatable, "bar", time, 3.0, start_value=Animatable(20.0), end_value=Animatable(50.0), ...
Test SimpleAnimation works with the Animatable protocol
7
86
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_animatable(): animatable = AnimateTest() # Fake wall-clock time time = 100.0 # Object that does the animation animation = SimpleAnimation( animat...
2,174
def update(self, bbox, score, label, gt_box, gt_label, difficult=None): if difficult is None: difficult = np.zeros_like(gt_label) # record class gt count for gtl, diff in zip(gt_label, difficult): if self.evaluate_difficult or int(diff) == 0: sel...
Update metric statics from given prediction and ground truth infomations.
10
125
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def update(self, bbox, score, label, gt_box, gt_label, difficult=None): if difficult is None: difficult = np.zeros_like(gt_label) # record class gt coun...
2,175
def _get_permission_objects_for_actions(self, actions): permission_codenames = [ "%s_%s" % (action, self.model_name) for action in actions ] return Permission.objects.filter( content_type=self._content_type, codename__in=permission_codenames )
Get a queryset of the Permission objects for the given actions
11
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_permission_objects_for_actions(self, actions): permission_codenames = [ "%s_%s" % (action, self.model_name) for action in actions ] retu...
2,176
def createWindow(self, wintype): debug_type = debug.qenum_key(QWebEnginePage, wintype) background = config.val.tabs.background log.webview.debug("createWindow with type {}, background {}".format( debug_type, background)) if wintype == QWebEnginePage.WebWindowType.W...
Called by Qt when a page wants to create a new window. This function is called from the createWindow() method of the associated QWebEnginePage, each time the page wants to create a new window of the given type. This might be the result, for example, of a JavaScript request to open a doc...
106
99
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def createWindow(self, wintype): debug_type = debug.qenum_key(QWebEnginePage, wintype) background = config.val.tabs.background log.webview.debug("createWind...
2,177
def predict(self, X): raw_predictions = self.decision_function(X) encoded_labels = self._loss._raw_prediction_to_decision(raw_predictions) return self.classes_.take(encoded_labels, axis=0)
Predict class for X. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. Ret...
47
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def predict(self, X): raw_predictions = self.decision_function(X) encoded_labels = self._loss._raw_prediction_to_decision(raw_predictions) return self.classe...
2,178
def union_all(graphs, rename=()): R = None seen_nodes = set() # rename graph to obtain disjoint node labels
Returns the union of all graphs. The graphs must be disjoint, otherwise an exception is raised. Parameters ---------- graphs : iterable Iterable of NetworkX graphs rename : iterable , optional Node names of graphs can be changed by specifying the tuple rename=('G-','H-') (for...
146
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def union_all(graphs, rename=()): R = None seen_nodes = set() # rename graph to obtain disjoint node labels ``` ###Assistant : Returns the union of all graphs. ...
2,179
def test_unknown_category_that_are_negative(): rng = np.random.RandomState(42) n_samples = 1000 X = np.c_[rng.rand(n_samples), rng.randint(4, size=n_samples)] y = np.zeros(shape=n_samples) y[X[:, 1] % 2 == 0] = 1 hist = HistGradientBoostingRegressor( random_state=0, categor...
Check that unknown categories that are negative does not error. Non-regression test for #24274.
14
63
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_unknown_category_that_are_negative(): rng = np.random.RandomState(42) n_samples = 1000 X = np.c_[rng.rand(n_samples), rng.randint(4, size=n_samples)] y = np.zer...
2,180
def forward(self, x_input, mask, cache=None): if isinstance(x_input, tuple): x, pos_emb = x_input[0], x_input[1] else: x, pos_emb = x_input, None # whether to use macaron style if self.feed_forward_macaron is not None: residual = x ...
Compute encoded features. :param torch.Tensor x_input: encoded source features, w/o pos_emb tuple((batch, max_time_in, size), (1, max_time_in, size)) or (batch, max_time_in, size) :param torch.Tensor mask: mask for x (batch, max_time_in) :param torch.Tensor cache: cache for x (b...
43
225
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, x_input, mask, cache=None): if isinstance(x_input, tuple): x, pos_emb = x_input[0], x_input[1] else: x, pos_emb = x_input, ...
2,181
def test_prompt_invalid_template_format() -> None: template = "This is a {foo} test." input_variables = ["foo"] with pytest.raises(ValueError): Prompt( input_variables=input_variables, template=template, template_format="bar" )
Test initializing a prompt with invalid template format.
8
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_prompt_invalid_template_format() -> None: template = "This is a {foo} test." input_variables = ["foo"] with pytest.raises(ValueError): Prompt( i...
2,182
def test_medium_does_not_exist(self) -> None: # test for unknown medium url = "/_synapse/admin/v1/threepid/publickey/users/unknown-key" channel = self.make_request( "GET", url, access_token=self.admin_user_tok, ) self.assertEqual(404...
Tests that both a lookup for a medium that does not exist and a user that doesn't exist with that third party ID returns a 404
26
48
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_medium_does_not_exist(self) -> None: # test for unknown medium url = "/_synapse/admin/v1/threepid/publickey/users/unknown-key" channel = self.make_...
2,183
def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs): mismatches = [] if mismatches is None else mismatches if config is None: config = self.deepspeed_config for key, value in config.items(): if isinstance(value, ...
Process the DeepSpeed config with the values from the kwargs.
10
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs): mismatches = [] if mismatches is None else mismatches if conf...
2,184
def get_metrics_result(self): # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if isinstance(result, dict): return_metrics.update(result) else: return_metrics[metric.n...
Returns the model's metrics values as a dict. If any of the metric result is a dict (containing multiple metrics), each of them gets added to the top level returned dict of this method. Returns: A `dict` containing values of the metrics listed in `self.metrics`. Example: ...
50
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_metrics_result(self): # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if...
2,185
def refactor_docstring(self, input, filename): result = [] block = None block_lineno = None indent = None lineno = 0 for line in input.splitlines(keepends=True): lineno += 1 if line.lstrip().startswith(self.PS1): if block i...
Refactors a docstring, looking for doctests. This returns a modified version of the input string. It looks for doctests, which start with a ">>>" prompt, and may be continued with "..." prompts, as long as the "..." is indented the same as the ">>>". (Unfortunately we can't us...
65
95
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def refactor_docstring(self, input, filename): result = [] block = None block_lineno = None indent = None lineno = 0 for line in inpu...
2,186
def test_complex_reversed_dag(self, test_complex_taskgroup_dag, complex_dag_expected_edges): ( dag, group, ( group_dm1, group_dm2, group_dm3, dm_in1, dm_in2, dm_in3, ...
Tests the complex reversed dag with a TaskGroup and a Label
11
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_complex_reversed_dag(self, test_complex_taskgroup_dag, complex_dag_expected_edges): ( dag, group, ( group_dm1, ...
2,187
def postprocess_response(token_ids, tokenizer): eos_pos = len(token_ids) for i, tok_id in enumerate(token_ids): if tok_id == tokenizer.sep_token_id: eos_pos = i break token_ids = token_ids[:eos_pos] tokens = tokenizer.convert_ids_to_tokens(token_ids) tokens = tok...
Post-process the decoded sequence. Truncate from the first <eos>.
9
30
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def postprocess_response(token_ids, tokenizer): eos_pos = len(token_ids) for i, tok_id in enumerate(token_ids): if tok_id == tokenizer.sep_token_id: eos_pos ...
2,188
def clip_grad_norm_(self, parameters, max_norm, norm_type=2): if self.distributed_type == DistributedType.FSDP: self.unscale_gradients() parameters = [p for p in parameters] for model in self._models: if parameters == [p for p in model.parameters()]: ...
Should be used in place of `torch.nn.utils.clip_grad_norm_`. Returns: `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector). Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(gradient_accum...
69
66
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def clip_grad_norm_(self, parameters, max_norm, norm_type=2): if self.distributed_type == DistributedType.FSDP: self.unscale_gradients() parameters =...
2,189
def check_library_list(self, libraries): if not isinstance(libraries, list): raise DistutilsSetupError( "'libraries' option must be a list of tuples") for lib in libraries: if not isinstance(lib, tuple) and len(lib) != 2: raise Distutil...
Ensure that the list of libraries is valid. `library` is presumably provided as a command option 'libraries'. This method checks that it is a list of 2-tuples, where the tuples are (library_name, build_info_dict). Raise DistutilsSetupError if the structure is invalid anywhere; ...
44
108
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_library_list(self, libraries): if not isinstance(libraries, list): raise DistutilsSetupError( "'libraries' option must be a list of t...
2,190
def _process_new_state(cls, new_state, unprocessed, processed): if isinstance(new_state, str): # an existing state if new_state == '#pop': return -1 elif new_state in unprocessed: return (new_state,) elif new_state == '#pus...
Preprocess the state transition action of a token definition.
9
130
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _process_new_state(cls, new_state, unprocessed, processed): if isinstance(new_state, str): # an existing state if new_state == '#pop': ...
2,191
def test_ohe_infrequent_two_levels_user_cats(): X_train = np.array( [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object ).T ohe = OneHotEncoder( categories=[["c", "d", "a", "b"]], sparse=False, handle_unknown="infrequent_if_exist", max_categories=2, ...
Test that the order of the categories provided by a user is respected.
13
89
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_ohe_infrequent_two_levels_user_cats(): X_train = np.array( [["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object ).T ohe = OneHotEncoder( ...
2,192
def fit(self, X, y=None): self._validate_params() random_state = check_random_state(self.random_state) X = self._validate_data(X) self.mean_ = X.mean(axis=0) X = X - self.mean_ if self.n_components is None: n_components = X.shape[1] else: ...
Fit the model from data in X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present here for API con...
53
34
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit(self, X, y=None): self._validate_params() random_state = check_random_state(self.random_state) X = self._validate_data(X) self.mean_ = X.mea...
2,193
def test_create_profile(): invoke_and_assert( ["profile", "create", "foo"], expected_output=( f ), ) profiles = load_profiles() assert profiles["foo"] == Profile( name="foo", settings={}, source=PREFECT_PROFILES_PATH.value() )
Created profile 'foo'. Switch to your new profile with: prefect profile use 'foo' Or, to use it for a single command, include the `-p` option: prefect -p 'foo' config view
30
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_create_profile(): invoke_and_assert( ["profile", "create", "foo"], expected_output=( f ), ) profiles = load_profiles() assert pr...
2,194
def test_mixed_errorbar_polar_caps(): fig = plt.figure() ax = plt.subplot(111, projection='polar') # symmetric errorbars th_sym = [1, 2, 3] r_sym = [0.9]*3 ax.errorbar(th_sym, r_sym, xerr=0.35, yerr=0.2, fmt="o") # long errorbars th_long = [np.pi/2 + .1, np.pi + .1] r_long = [...
Mix several polar errorbar use cases in a single test figure. It is advisable to position individual points off the grid. If there are problems with reproducibility of this test, consider removing grid.
33
97
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_mixed_errorbar_polar_caps(): fig = plt.figure() ax = plt.subplot(111, projection='polar') # symmetric errorbars th_sym = [1, 2, 3] r_sym = [0.9]*3 ax.e...
2,195
def test_edgeql_for_01(self): self.assert_test_query( r, {(1, 1), (2, 2), (3, 3)}, )
FOR X IN {1,2,3} UNION ((SELECT X), (SELECT X));
9
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_edgeql_for_01(self): self.assert_test_query( r, {(1, 1), (2, 2), (3, 3)}, ) ``` ###Assistant : FOR X IN {1,2,3} UNI...
2,196
def on_clicked(self, index): if not index.isValid(): return item = self._model().data(index, downloads.ModelRole.item) if item.done and item.successful: item.open_file() item.remove()
Handle clicking of an item. Args: index: The QModelIndex of the clicked item.
13
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def on_clicked(self, index): if not index.isValid(): return item = self._model().data(index, downloads.ModelRole.item) if item.done and item.succ...
2,197
def _tie_weights(self): # To tie those two weights if they get disconnected (on TPU or when the bias is resized) self.bias = self.decoder.bias @add_start_docstrings( , XLM_ROBERTA_XL_START_DOCSTRING, )
XLM-RoBERTa-xlarge Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.
23
27
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _tie_weights(self): # To tie those two weights if they get disconnected (on TPU or when the bias is resized) self.bias = self.decoder.bias @add_start_docstrings( , ...
2,198
def matches_minor(self, other): return (self.major, self.minor) == (other.major, other.minor)
Check whether this version matches the other in (major, minor).
10
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def matches_minor(self, other): return (self.major, self.minor) == (other.major, other.minor) ``` ###Assistant : Check whether this version matches the other i...
2,199
def test_04_query_predictor_single_where_condition(self): time.sleep(120) # TODO query = f response = self.handler.native_query(query) self.assertTrue(response.type == RESPONSE_TYPE.TABLE) self.assertTrue(len(response.data_frame) == 1) self.assertTrue(response.data_frame...
SELECT target from {self.test_model_1} WHERE sqft=100
6
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_04_query_predictor_single_where_condition(self): time.sleep(120) # TODO query = f response = self.handler.native_query(query) self.assertTrue(respon...