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,800 | async def test_missing_tones_list(hass):
siren = MockSirenEntity(SirenEntityFeature.TONES, ["a", "b"])
siren.hass = hass
with pytest.raises(ValueError):
process_turn_on_params(siren, {"tone": "test"})
| Test ValueError when setting a tone that is missing from available_tones list. | 12 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_missing_tones_list(hass):
siren = MockSirenEntity(SirenEntityFeature.TONES, ["a", "b"])
siren.hass = hass
with pytest.raises(ValueError):
process_turn... |
2,801 | def task_failed_deps(args):
dag = get_dag(args.subdir, args.dag_id)
task = dag.get_task(task_id=args.task_id)
ti = _get_ti(task, args.execution_date_or_run_id, args.map_index)
dep_context = DepContext(deps=SCHEDULER_QUEUED_DEPS)
failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_con... |
Returns the unmet dependencies for a task instance from the perspective of the
scheduler (i.e. why a task instance doesn't get scheduled and then queued by the
scheduler, and then run by an executor).
>>> airflow tasks failed-deps tutorial sleep 2015-01-01
Task instance dependencies not met:
Da... | 73 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def task_failed_deps(args):
dag = get_dag(args.subdir, args.dag_id)
task = dag.get_task(task_id=args.task_id)
ti = _get_ti(task, args.execution_date_or_run_id, args.map_inde... |
2,802 | def load(self, rawdata):
if isinstance(rawdata, str):
self.__parse_string(rawdata)
else:
# self.update() wouldn't call our custom __setitem__
for key, value in rawdata.items():
self[key] = value
return
| Load cookies from a string (presumably HTTP_COOKIE) or
from a dictionary. Loading cookies from a dictionary 'd'
is equivalent to calling:
map(Cookie.__setitem__, d.keys(), d.values())
| 24 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load(self, rawdata):
if isinstance(rawdata, str):
self.__parse_string(rawdata)
else:
# self.update() wouldn't call our custom __setitem__... |
2,803 | def _reset_major_tick_kw(self, keep_tick_and_label_visibility=False):
backup = {name: value for name, value in self._major_tick_kw.items()
if name in ['tick1On', 'tick2On', 'label1On', 'label2On']}
self._major_tick_kw.clear()
if keep_tick_and_label_visibility:
... |
Reset major tick params to defaults.
Shared subplots pre-configure tick and label visibility. To keep this
beyond an Axis.clear() operation, we may
*keep_tick_and_label_visibility*.
| 23 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reset_major_tick_kw(self, keep_tick_and_label_visibility=False):
backup = {name: value for name, value in self._major_tick_kw.items()
if name in ['tic... |
2,804 | def test_class_variable_to_instance(self):
logger = self.logger
self.assertEqual(logger._to_exclude, logger._exclude_results)
self.assertEqual(logger._to_system, logger._system_results)
self.assertEqual(logger._to_other, logger._other_results)
self.assertEqual(logger._to... | Test that class variables get properly assigned to instance
variables.
| 10 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_class_variable_to_instance(self):
logger = self.logger
self.assertEqual(logger._to_exclude, logger._exclude_results)
self.assertEqual(logger._to_sys... |
2,805 | def detect_all(byte_str, ignore_threshold=False):
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError(
f"Expected object of type bytes or bytearray, got: {type(byte_str)}"
)
byte_str = bytearray(byte_str)
detec... |
Detect all the possible encodings of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
:param ignore_threshold: Include encodings that are below
``UniversalDetector.MINIMUM_THRESHOLD``
... | 35 | 120 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def detect_all(byte_str, ignore_threshold=False):
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError(
f"... |
2,806 | def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
if names is None: # simple value lookup
return cls.__new__(cls, value)
# otherwise, functional API: we're creating a new Enum type
return cls._create_(
value,
... |
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
(i.e. Color = Enum('Color', names='RED GREEN BLUE')).
When used for the fun... | 167 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1):
if names is None: # simple value lookup
return cls.__new__(cls, value)
... |
2,807 | def edges2dot(edges, shapes=None, attr=None):
if not shapes:
shapes = dict()
if not attr:
attr = dict()
dot_string = "digraph G {\n"
for pair in attr.items():
dot_string += f"{pair[0]} = {pair[1]};\n"
for edge in edges:
for shape in shapes.items():
... |
:param edges: the set (or list) of edges of a directed graph.
:return dot_string: a representation of 'edges' as a string in the DOT
graph language, which can be converted to an image by the 'dot' program
from the Graphviz package, or nltk.parse.dependencygraph.dot2img(dot_string).
:param... | 94 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def edges2dot(edges, shapes=None, attr=None):
if not shapes:
shapes = dict()
if not attr:
attr = dict()
dot_string = "digraph G {\n"
for pair in attr.i... |
2,808 | def _draw_line_numbers(self):
if not self.line_numbers:
return
for p in range(self.maxlineno):
n = p + self.line_number_start
if (n % self.line_number_step) == 0:
self._draw_linenumber(p, n)
|
Create drawables for the line numbers.
| 6 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _draw_line_numbers(self):
if not self.line_numbers:
return
for p in range(self.maxlineno):
n = p + self.line_number_start
if ... |
2,809 | def export(ctx, directory):
directory_path = Path(directory)
if directory_path.absolute == Path.cwd().absolute:
console.print(
,
style="red bold",
end="",
)
proceed = input().lower() == "y"
else:
proceed = True
if proceed:
if no... | You are reading the config from the same directory you are exporting to.
This means that the exported config will overwrite the config for this directory.
Are you sure you want to continue? (y/n) | 34 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def export(ctx, directory):
directory_path = Path(directory)
if directory_path.absolute == Path.cwd().absolute:
console.print(
,
style="red bold",
... |
2,810 | def update_keymap(self, name, key):
if name not in self._tools:
raise KeyError(f'{name!r} not in Tools')
self._remove_keys(name)
if isinstance(key, str):
key = [key]
for k in key:
if k in self._keys:
_api.warn_external(
... |
Set the keymap to associate with the specified tool.
Parameters
----------
name : str
Name of the Tool.
key : str or list of str
Keys to associate with the tool.
| 31 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update_keymap(self, name, key):
if name not in self._tools:
raise KeyError(f'{name!r} not in Tools')
self._remove_keys(name)
if isinstance(ke... |
2,811 | def named_parameters(self, *args, **kwargs):
arch = kwargs.pop('arch', False)
for name, p in super().named_parameters(*args, **kwargs):
if any(name == par_name for par_name in self._arch_parameter_names):
if arch:
yield name, p
else:
... | Named parameters excluding architecture parameters. | 5 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def named_parameters(self, *args, **kwargs):
arch = kwargs.pop('arch', False)
for name, p in super().named_parameters(*args, **kwargs):
if any(name == pa... |
2,812 | def unzip3(xyzs):
# Note: we deliberately don't use zip(*xyzs) because it is lazily evaluated,
# is too permissive about inputs, and does not guarantee a length-3 output.
xs = []
ys = []
zs = []
for x, y, z in xyzs:
xs.append(x)
ys.append(y)
zs.append(z)
return tuple(xs), tuple(ys), tuple(z... | Unzip sequence of length-3 tuples into three tuples. | 8 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unzip3(xyzs):
# Note: we deliberately don't use zip(*xyzs) because it is lazily evaluated,
# is too permissive about inputs, and does not guarantee a length-3 output.
xs = []
... |
2,813 | def test_json_get_subscribers_for_guest_user(self) -> None:
guest_user = self.example_user("polonius")
never_subscribed = gather_subscriptions_helper(guest_user, True).never_subscribed
# A guest user can only see never subscribed streams that are web-public.
# For Polonius, the... |
Guest users should have access to subscribers of web-public streams, even
if they aren't subscribed or have never subscribed to that stream.
| 22 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_json_get_subscribers_for_guest_user(self) -> None:
guest_user = self.example_user("polonius")
never_subscribed = gather_subscriptions_helper(guest_user, Tru... |
2,814 | def _reconnect(self):
if not self._isconnected():
try:
self._connect()
except http_client.socket.error as e:
# Attempt to reconnect if the connection was refused
if e.errno == 61 or e.errno == 10061:
# errno 61 ... | Connect if disconnected.
Retry self.maxtries times with delays
| 8 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reconnect(self):
if not self._isconnected():
try:
self._connect()
except http_client.socket.error as e:
# Attemp... |
2,815 | def list_master(saltenv=None, prefix=""):
if not saltenv:
saltenv = __opts__["saltenv"] or "base"
return _client().file_list(saltenv, prefix)
|
.. versionchanged:: 3005
``saltenv`` will use value from config if not explicitly set
List all of the files stored on the master
CLI Example:
.. code-block:: bash
salt '*' cp.list_master
| 30 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def list_master(saltenv=None, prefix=""):
if not saltenv:
saltenv = __opts__["saltenv"] or "base"
return _client().file_list(saltenv, prefix)
```
###Assist... |
2,816 | def test_bert_hf_tokenizer_parity(tmpdir, pretrained_model_name_or_path):
from ludwig.utils.tokenizers import get_hf_tokenizer, HFTokenizer
inputs = "Hello, ``I'm'' ónë of 1,205,000 sentences!"
hf_tokenizer = HFTokenizer(pretrained_model_name_or_path)
torchtext_tokenizer = get_hf_tokenizer(pretrai... | Tests the BERTTokenizer implementation.
Asserts both tokens and token IDs are the same by initializing the BERTTokenizer as a standalone tokenizer and as a
HF tokenizer.
| 26 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_bert_hf_tokenizer_parity(tmpdir, pretrained_model_name_or_path):
from ludwig.utils.tokenizers import get_hf_tokenizer, HFTokenizer
inputs = "Hello, ``I'm'' ónë of 1,20... |
2,817 | def get_pe_matching_query(amount_condition, account_from_to, transaction):
# get matching payment entries query
if transaction.deposit > 0:
currency_field = "paid_to_account_currency as currency"
else:
currency_field = "paid_from_account_currency as currency"
return f
|
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,
{currency_field}
F... | 68 | 27 | 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
if transaction.deposit > 0:
currency_field = "paid_to_account_currency as ... |
2,818 | def _check_list_display_links(self, obj):
from django.contrib.admin.options import ModelAdmin
if obj.list_display_links is None:
return []
elif not isinstance(obj.list_display_links, (list, tuple)):
return must_be(
"a list, a tuple, or None",
... | Check that list_display_links is a unique subset of list_display. | 9 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_list_display_links(self, obj):
from django.contrib.admin.options import ModelAdmin
if obj.list_display_links is None:
return []
elif ... |
2,819 | def min_mireds(self) -> int:
min_mireds = self.cluster.get("color_temp_physical_min", self.MIN_MIREDS)
if min_mireds == 0:
self.warning(
"[Min mireds is 0, setting to %s] Please open an issue on the quirks repo to have this device corrected",
self.MIN... | Return the coldest color_temp that this channel supports. | 8 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def min_mireds(self) -> int:
min_mireds = self.cluster.get("color_temp_physical_min", self.MIN_MIREDS)
if min_mireds == 0:
self.warning(
... |
2,820 | def pop_screen(self) -> Screen:
screen_stack = self._screen_stack
if len(screen_stack) <= 1:
raise ScreenStackError(
"Can't pop screen; there must be at least one screen on the stack"
)
screen = screen_stack.pop()
screen.post_message_no_wa... | Pop the current screen from the stack, and switch to the previous screen.
Returns:
Screen: The screen that was replaced.
| 20 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pop_screen(self) -> Screen:
screen_stack = self._screen_stack
if len(screen_stack) <= 1:
raise ScreenStackError(
"Can't pop screen; t... |
2,821 | def test_notify_interested_services_ephemeral(self):
interested_service = self._mkservice(is_interested=True)
services = [interested_service]
self.mock_store.get_app_services.return_value = services
self.mock_store.get_type_stream_id_for_appservice.return_value = make_awaitable(... |
Test sending ephemeral events to the appservice handler are scheduled
to be pushed out to interested appservices, and that the stream ID is
updated accordingly.
| 25 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_notify_interested_services_ephemeral(self):
interested_service = self._mkservice(is_interested=True)
services = [interested_service]
self.mock_store... |
2,822 | def convert(self, value):
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
value = ConvertingDict(value)
value.configurator = self
elif not isinstance(value, ConvertingList) and isinstance(value, list):
value = Con... |
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
| 33 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def convert(self, value):
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
value = ConvertingDict(value)
value.c... |
2,823 | def test_parse_transition(duration, parsed_duration):
css = f
stylesheet = Stylesheet()
stylesheet.parse(css)
rule = stylesheet.rules[0].styles
assert len(stylesheet.rules) == 1
assert len(stylesheet.rules[0].errors) == 0
assert rule.transitions == {
"offset": Transition(duration=p... | #some-widget {{
transition: offset {duration} in_out_cubic;
}}
| 7 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_parse_transition(duration, parsed_duration):
css = f
stylesheet = Stylesheet()
stylesheet.parse(css)
rule = stylesheet.rules[0].styles
assert len(stylesheet.ru... |
2,824 | def test_meta_charset(self) -> None:
encodings = _get_html_media_encodings(
b,
"text/html",
)
self.assertEqual(list(encodings), ["ascii", "utf-8", "cp1252"])
# A less well-formed version.
encodings = _get_html_media_encodings(
b,
... | A character encoding is found via the meta tag.
<html>
<head><meta charset="ascii">
</head>
</html>
<html>
<head>< meta charset = ascii>
</head>
</html>
| 22 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_meta_charset(self) -> None:
encodings = _get_html_media_encodings(
b,
"text/html",
)
self.assertEqual(list(encodings), ["asc... |
2,825 | def _build_amps_list(self, amp_value, processlist):
ret = []
try:
# Search in both cmdline and name (for kernel thread, see #1261)
for p in processlist:
if (re.search(amp_value.regex(), p['name']) is not None) or (
p['cmdline'] is not ... | Return the AMPS process list according to the amp_value
Search application monitored processes by a regular expression
| 17 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _build_amps_list(self, amp_value, processlist):
ret = []
try:
# Search in both cmdline and name (for kernel thread, see #1261)
for p in p... |
2,826 | def call(self, inputs, *args, **kwargs): # pylint: disable=unused-argument
return inputs
| This is where the layer's logic lives.
The `call()` method may not create state (except in its first invocation,
wrapping the creation of variables or other resources in `tf.init_scope()`).
It is recommended to create state in `__init__()`, or the `build()` method
that is called automat... | 319 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call(self, inputs, *args, **kwargs): # pylint: disable=unused-argument
return inputs
```
###Assistant : This is where the layer's logic lives.
The... |
2,827 | def test_use_predictor_with_view(self, mock_handler):
# set integration data
df = pd.DataFrame([
{'a': 1, 'b': 'one'},
{'a': 2, 'b': 'two'},
{'a': 1, 'b': 'three'},
])
self.set_handler(mock_handler, name='pg', tables={'tasks': df})
view_name ... |
select task_model.p
from views.{view_name}
join mindsdb.task_model
where {view_name}.a = 2
| 10 | 144 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_use_predictor_with_view(self, mock_handler):
# set integration data
df = pd.DataFrame([
{'a': 1, 'b': 'one'},
{'a': 2, 'b': 'two'},
... |
2,828 | def test_vr_connector_shift_by_one(self):
view_rq_dict = {
"state": ViewRequirement("obs"),
"next_state": ViewRequirement(
"obs", shift=1, used_for_compute_actions=False
),
"prev_state": ViewRequirement("obs", shift=-1),
}
... | Test that the ViewRequirementConnector can handle shift by one correctly and
can ignore future referencing view_requirements to respect causality | 19 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_vr_connector_shift_by_one(self):
view_rq_dict = {
"state": ViewRequirement("obs"),
"next_state": ViewRequirement(
"obs", shi... |
2,829 | def adapt_error(cls, e):
return e._replace(message=e.message.format(*e.vars))[:4]
error = namedtuple("error", "lineno col message type vars")
Error = partial(partial, error, message="", type=SentryCheck, vars=())
S001 = Error(
message="S001: Avoid using the {} mock call as it is "
"confusing... | Adapts the extended error namedtuple to be compatible with Flake8. | 10 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def adapt_error(cls, e):
return e._replace(message=e.message.format(*e.vars))[:4]
error = namedtuple("error", "lineno col message type vars")
Error = partial(partial, erro... |
2,830 | def on_train_begin(self, logs=None):
logs = self._process_logs(logs)
for callback in self.callbacks:
callback.on_train_begin(logs)
| Calls the `on_train_begin` methods of its callbacks.
Args:
logs: Dict. Currently, no data is passed via this argument
for this method, but that may change in the future.
| 28 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def on_train_begin(self, logs=None):
logs = self._process_logs(logs)
for callback in self.callbacks:
callback.on_train_begin(logs)
```
###As... |
2,831 | def test_decorate_validated_function():
decorated_function = deprecated()(_func)
with pytest.warns(FutureWarning, match="Function _func is deprecated"):
decorated_function(1, 2, c=3)
# outer decorator does not interfer with validation
with pytest.warns(FutureWarning, match="Function _func... | Check that validate_params functions can be decorated | 7 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_decorate_validated_function():
decorated_function = deprecated()(_func)
with pytest.warns(FutureWarning, match="Function _func is deprecated"):
decorated_funct... |
2,832 | def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
axes.set_xscale(xscale), axes.set_yscale(yscale)
axes.set_xlim(xlim), axes.set_ylim(ylim)
if legend:
axes.legend(legend)
axes.grid()
| Set the axes for matplotlib.
Defined in :numref:`sec_calculus` | 8 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
axes.set_xscale(xscale), axes.set_yscale(yscale)
axe... |
2,833 | def register(self, addon):
api_changes = {
# mitmproxy 6 -> mitmproxy 7
"clientconnect": "client_connected",
"clientdisconnect": "client_disconnected",
"serverconnect": "server_connect and server_connected",
"serverdisconnect": "server_disconn... |
Register an addon, call its load event, and then register all its
sub-addons. This should be used by addons that dynamically manage
addons.
If the calling addon is already running, it should follow with
running and configure events. Must be called within a c... | 45 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def register(self, addon):
api_changes = {
# mitmproxy 6 -> mitmproxy 7
"clientconnect": "client_connected",
"clientdisconnect": "client_... |
2,834 | def get_context_data(self, **kwargs):
from tickets.models import Ticket
from tickets.const import TICKET_DETAIL_URL
ticket_id = self.request.session.get("auth_ticket_id")
if not ticket_id:
ticket = None
else:
ticket = Ticket.all().filter(pk=ticket_id).firs... | Wait for <b>{}</b> confirm, You also can copy link to her/him <br/>
Don't close this page | 16 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_context_data(self, **kwargs):
from tickets.models import Ticket
from tickets.const import TICKET_DETAIL_URL
ticket_id = self.request.session.get("auth_ticket_... |
2,835 | def tf_shard_checkpoint(weights, max_shard_size="10GB"):
max_shard_size = convert_file_size_to_int(max_shard_size)
sharded_state_dicts = []
current_block = []
current_block_size = 0
total_size = 0
for item in weights:
weight_size = item.numpy().size * dtype_byte_size(item.dtype)
... |
Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a
given size.
The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no
optimization made to make each sub-checkpoint as close as pos... | 158 | 137 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tf_shard_checkpoint(weights, max_shard_size="10GB"):
max_shard_size = convert_file_size_to_int(max_shard_size)
sharded_state_dicts = []
current_block = []
current_b... |
2,836 | def scale(self, x=1, y=1, pt=None):
if pt:
pt = Point(pt, dim=2)
return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
fx, fy = self.functions
return self.func((fx*x, fy*y), self.limits)
| Override GeometryEntity.scale since Curve is not made up of Points.
Returns
=======
Curve :
returns scaled curve.
Examples
========
>>> from sympy import Curve
>>> from sympy.abc import x
>>> Curve((x, x), (x, 0, 1)).scale(2)
Curve(... | 40 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def scale(self, x=1, y=1, pt=None):
if pt:
pt = Point(pt, dim=2)
return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
fx, fy = ... |
2,837 | def orient_body_fixed(self, parent, angles, rotation_order):
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not isinstance(v, Vector):
amounts[i] = sympify(v)
approved_orders = ('123', '231', '312', '132', '213', '32... | Rotates this reference frame relative to the parent reference frame
by right hand rotating through three successive body fixed simple axis
rotations. Each subsequent axis of rotation is about the "body fixed"
unit vectors of a new intermediate reference frame. This type of
rotation is al... | 365 | 217 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def orient_body_fixed(self, parent, angles, rotation_order):
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not... |
2,838 | def get_applicable_block_lists(employee=None, company=None, all_lists=False):
block_lists = []
if not employee:
employee = frappe.db.get_value("Employee", {"user_id": frappe.session.user})
if not employee:
return []
if not company:
company = frappe.db.get_value("Employee", employee, "company")
def add_b... | select name from `tabLeave Block List`
where applies_to_all_departments=1 and company=%s | 10 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_applicable_block_lists(employee=None, company=None, all_lists=False):
block_lists = []
if not employee:
employee = frappe.db.get_value("Employee", {"user_id": frappe.session.use... |
2,839 | def _setup_connection(self):
# noqa
cur = self.connection.cursor()
if ('store',) not in list(cur.execute("SELECT name FROM sqlite_master WHERE type='table';")):
cur.execute(
)
self.internal_registry.commit()
| Checks that a key-value table exists, otherwise creates it. create table store (key text, value text) | 16 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _setup_connection(self):
# noqa
cur = self.connection.cursor()
if ('store',) not in list(cur.execute("SELECT name FROM sqlite_master WHERE type='table';")):
... |
2,840 | def cull(dsk, keys):
if not isinstance(keys, (list, set)):
keys = [keys]
seen = set()
dependencies = dict()
out = {}
work = list(set(flatten(keys)))
while work:
new_work = []
for k in work:
dependencies_k = get_dependencies(dsk, k, as_list=True) # fuse... | Return new dask with only the tasks required to calculate keys.
In other words, remove unnecessary tasks from dask.
``keys`` may be a single key or list of keys.
Examples
--------
>>> def inc(x):
... return x + 1
>>> def add(x, y):
... return x + y
>>> d = {'x': 1, 'y': (... | 109 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cull(dsk, keys):
if not isinstance(keys, (list, set)):
keys = [keys]
seen = set()
dependencies = dict()
out = {}
work = list(set(flatten(keys)))
wh... |
2,841 | def fill_leverage_tiers(self) -> None:
leverage_tiers = self.load_leverage_tiers()
for pair, tiers in leverage_tiers.items():
tiers = []
for tier in tiers:
tiers.append(self.parse_leverage_tier(tier))
self._leverage_tiers[pair] = tiers
|
Assigns property _leverage_tiers to a dictionary of information about the leverage
allowed on each pair
| 15 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fill_leverage_tiers(self) -> None:
leverage_tiers = self.load_leverage_tiers()
for pair, tiers in leverage_tiers.items():
tiers = []
for ... |
2,842 | def kronecker_product(*matrices):
if not matrices:
raise TypeError("Empty Kronecker product is undefined")
validate(*matrices)
if len(matrices) == 1:
return matrices[0]
else:
return KroneckerProduct(*matrices).doit()
|
The Kronecker product of two or more arguments.
This computes the explicit Kronecker product for subclasses of
``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic
``KroneckerProduct`` object is returned.
Examples
========
For ``MatrixSymbol`` arguments a ``KroneckerProduct`` ob... | 212 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def kronecker_product(*matrices):
if not matrices:
raise TypeError("Empty Kronecker product is undefined")
validate(*matrices)
if len(matrices) == 1:
return ... |
2,843 | def _get_obj_does_not_exist_redirect(self, request, opts, object_id):
msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % {
"name": opts.verbose_name,
"key": unquote(object_id),
}
self.message_user(request, msg, messages.WARNING)
... |
Create a message informing the user that the object doesn't exist
and return a redirect to the admin index page.
| 20 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_obj_does_not_exist_redirect(self, request, opts, object_id):
msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % {
"name": op... |
2,844 | def compare_total(self, other, context=None):
other = _convert_other(other, raiseit=True)
# if one is negative and the other is positive, it's easy
if self._sign and not other._sign:
return _NegativeOne
if not self._sign and other._sign:
return _One
... | Compares self to other using the abstract representations.
This is not like the standard compare, which use their numerical
value. Note that a total ordering is defined for all possible abstract
representations.
| 32 | 183 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compare_total(self, other, context=None):
other = _convert_other(other, raiseit=True)
# if one is negative and the other is positive, it's easy
if self.... |
2,845 | def detect_current_mode(cls) -> _FaultTolerantMode:
env_value = os.getenv("PL_FAULT_TOLERANT_TRAINING", "0").lower()
# the int values are kept for backwards compatibility, but long-term we want to keep only the strings
if env_value in ("0", "disabled"):
return _FaultTolerant... | This classmethod detects if `Fault Tolerant` is activated and maps its value to `_FaultTolerantMode`. | 14 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def detect_current_mode(cls) -> _FaultTolerantMode:
env_value = os.getenv("PL_FAULT_TOLERANT_TRAINING", "0").lower()
# the int values are kept for backwards compatib... |
2,846 | def apply_channel_shift(x, intensity, channel_axis=0):
x = np.rollaxis(x, channel_axis, 0)
min_x, max_x = np.min(x), np.max(x)
channel_images = [
np.clip(x_channel + intensity, min_x, max_x) for x_channel in x
]
x = np.stack(channel_images, axis=0)
x = np.rollaxis(x, 0, channel_axis... | Performs a channel shift.
Args:
x: Input tensor. Must be 3D.
intensity: Transformation intensity.
channel_axis: Index of axis for channels in the input tensor.
Returns:
Numpy image tensor.
| 28 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply_channel_shift(x, intensity, channel_axis=0):
x = np.rollaxis(x, channel_axis, 0)
min_x, max_x = np.min(x), np.max(x)
channel_images = [
np.clip(x_channel +... |
2,847 | def _nested_gather(self, tensors, name=None):
if tensors is None:
return
if self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return tensors
# Copied from Accelerate. |
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
| 20 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _nested_gather(self, tensors, name=None):
if tensors is None:
return
if self.args.local_rank != -1:
tensors = distributed_concat(tensors)... |
2,848 | def test_glm_regression_unpenalized(solver, fit_intercept, glm_dataset):
model, X, y, coef, _, _, _ = glm_dataset
n_samples, n_features = X.shape
alpha = 0 # unpenalized
params = dict(
alpha=alpha,
fit_intercept=fit_intercept,
# solver=solver, # only lbfgs available
... | Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
Note: This checks the minimum norm solution for wide X, i.e.
n_samples < n_features:
min ||w||_2 subject to w = argmin deviance(X, y, w)
| 46 | 269 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_glm_regression_unpenalized(solver, fit_intercept, glm_dataset):
model, X, y, coef, _, _, _ = glm_dataset
n_samples, n_features = X.shape
alpha = 0 # unpenalized
... |
2,849 | def _node_redundancy(G, v):
n = len(G[v])
overlap = sum(
1 for (u, w) in combinations(G[v], 2) if (G[u].keys() & G[w].keys()) - {v}
)
return (2 * overlap) / (n * (n - 1))
| Returns the redundancy of the node `v` in the bipartite graph `G`.
If `G` is a graph with `n` nodes, the redundancy of a node is the ratio
of the "overlap" of `v` to the maximum possible overlap of `v`
according to its degree. The overlap of `v` is the number of pairs of
neighbors that have mutual neig... | 72 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _node_redundancy(G, v):
n = len(G[v])
overlap = sum(
1 for (u, w) in combinations(G[v], 2) if (G[u].keys() & G[w].keys()) - {v}
)
return (2 * overlap) / (n *... |
2,850 | def solve(self):
count_reaction_loads = 0
for node in self._nodes:
if node in list(self._supports):
if self._supports[node[0]]=='pinned':
count_reaction_loads += 2
elif self._supports[node[0]]=='roller':
count_r... |
This method solves for all reaction forces of all supports and all internal forces
of all the members in the truss, provided the Truss is solvable.
A Truss is solvable if the following condition is met,
2n >= r + m
Where n is the number of nodes, r is the number of reaction f... | 218 | 199 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def solve(self):
count_reaction_loads = 0
for node in self._nodes:
if node in list(self._supports):
if self._supports[node[0]]=='pinned':... |
2,851 | def gf_edf_zassenhaus(f, n, p, K):
factors = [f]
if gf_degree(f) <= n:
return factors
N = gf_degree(f) // n
if p != 2:
b = gf_frobenius_monomial_base(f, p, K)
t = [K.one, K.zero]
while len(factors) < N:
if p == 2:
h = r = t
for i in range(... |
Cantor-Zassenhaus: Probabilistic Equal Degree Factorization
Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and
an integer ``n``, such that ``n`` divides ``deg(f)``, returns all
irreducible factors ``f_1,...,f_d`` of ``f``, each of degree ``n``.
EDF procedure gives complete factorizatio... | 96 | 127 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def gf_edf_zassenhaus(f, n, p, K):
factors = [f]
if gf_degree(f) <= n:
return factors
N = gf_degree(f) // n
if p != 2:
b = gf_frobenius_monomial_base(f... |
2,852 | def _tracemin_fiedler(L, X, normalized, tol, method):
import numpy as np
import scipy as sp
import scipy.linalg # call as sp.linalg
import scipy.linalg.blas # call as sp.linalg.blas
import scipy.sparse # call as sp.sparse
n = X.shape[0]
if normalized:
# Form the normalized ... | Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
The Fiedler vector of a connected undirected graph is the eigenvector
corresponding to the second smallest eigenvalue of the Laplacian matrix
of the graph. This function starts with the Laplacian L, not the Graph.
Parameters
---... | 172 | 89 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _tracemin_fiedler(L, X, normalized, tol, method):
import numpy as np
import scipy as sp
import scipy.linalg # call as sp.linalg
import scipy.linalg.blas # call as ... |
2,853 | def test_complex_pipeline_with_shared_prompt_model_and_prompt_template_yaml(tmp_path):
with open(tmp_path / "tmp_config_with_prompt_template.yml", "w") as tmp_file:
tmp_file.write(
f
)
pipeline = Pipeline.load_from_yaml(path=tmp_path / "tmp_config_with_prompt_template.yml")
resul... |
version: ignore
components:
- name: pmodel
type: PromptModel
params:
model_name_or_path: google/flan-t5-small
model_kwargs:
torch_dtype: torch.bfloat16
- name: question_generation_template
... | 72 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_complex_pipeline_with_shared_prompt_model_and_prompt_template_yaml(tmp_path):
with open(tmp_path / "tmp_config_with_prompt_template.yml", "w") as tmp_file:
tmp_file.writ... |
2,854 | def _download_model(self):
self.logger.info("Downloading model: '%s' from: %s", self._model_name, self._url_download)
for attempt in range(self._retries):
try:
downloaded_size = self._url_partial_size
req = urllib.request.Request(self._url_download)
... | Download the model zip from github to the cache folder. | 10 | 109 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _download_model(self):
self.logger.info("Downloading model: '%s' from: %s", self._model_name, self._url_download)
for attempt in range(self._retries):
... |
2,855 | def fit_transform(self, X, y=None):
self._validate_params()
self._fit_transform(X)
return self.embedding_
| Compute the embedding vectors for data X and transform X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training set.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
X_new : a... | 45 | 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()
self._fit_transform(X)
return self.embedding_
```
###Assistant : Compute the embeddi... |
2,856 | def test_song_from_data_dump():
# Loads from str
song = Song.from_data_dump(
)
assert song.name == "Ropes"
assert song.artists == ["Dirty Palm", "Chandler Jewels"]
assert song.album_name == "Ropes"
assert song.album_artist == "Dirty Palm"
assert song.genres == ["gaming ed... |
Tests if Song.from_data_dump() works correctly.
{
"name": "Ropes",
"artists": ["Dirty Palm", "Chandler Jewels"],
"album_name": "Ropes",
"album_artist": "Dirty Palm",
"genres": ["gaming edm", "melbourne bounce international"],
"dis... | 59 | 84 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_song_from_data_dump():
# Loads from str
song = Song.from_data_dump(
)
assert song.name == "Ropes"
assert song.artists == ["Dirty Palm", "Chandler... |
2,857 | def test_run(self) -> Tuple[Dict, Dict]:
print(" | > Synthesizing test sentences.")
test_audios = {}
test_figures = {}
test_sentences = self.config.test_sentences
for idx, s_info in enumerate(test_sentences):
try:
aux_inputs = self.get_aux_inp... | Generic test run for `tts` models used by `Trainer`.
You can override this for a different behaviour.
Returns:
Tuple[Dict, Dict]: Test figures and audios to be projected to Tensorboard.
| 29 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_run(self) -> Tuple[Dict, Dict]:
print(" | > Synthesizing test sentences.")
test_audios = {}
test_figures = {}
test_sentences = self.config.t... |
2,858 | def read_dict(self, dictionary, source='<dict>'):
elements_added = set()
for section, keys in dictionary.items():
section = str(section)
try:
self.add_section(section)
except (DuplicateSectionError, ValueError):
if self._strict... | Read configuration from a dictionary.
Keys are section names, values are dictionaries with keys and values
that should be present in the section. If the used dictionary type
preserves order, sections and their keys will be added in order.
All types held in the dictionary are converted ... | 72 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read_dict(self, dictionary, source='<dict>'):
elements_added = set()
for section, keys in dictionary.items():
section = str(section)
try:... |
2,859 | def send(self, load, tries=3, timeout=60, raw=False):
_try = 1
while True:
try:
if self.crypt == "clear":
log.trace("ReqChannel send clear load=%r", load)
ret = yield self._uncrypted_transfer(load, timeout=timeout)
... |
Send a request, return a future which will complete when we send the message
:param dict load: A load to send across the wire
:param int tries: The number of times to make before failure
:param int timeout: The number of seconds on a response before failing
| 47 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def send(self, load, tries=3, timeout=60, raw=False):
_try = 1
while True:
try:
if self.crypt == "clear":
log.trace("... |
2,860 | def get_fields_from_path(model, path):
pieces = path.split(LOOKUP_SEP)
fields = []
for piece in pieces:
if fields:
parent = get_model_from_relation(fields[-1])
else:
parent = model
fields.append(parent._meta.get_field(piece))
return fields
| Return list of Fields given path relative to model.
e.g. (ModelX, "user__groups__name") -> [
<django.db.models.fields.related.ForeignKey object at 0x...>,
<django.db.models.fields.related.ManyToManyField object at 0x...>,
<django.db.models.fields.CharField object at 0x...>,
]
| 27 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_fields_from_path(model, path):
pieces = path.split(LOOKUP_SEP)
fields = []
for piece in pieces:
if fields:
parent = get_model_from_relation(field... |
2,861 | def find_config_files(self):
files = []
check_environ()
# Where to look for the system-wide Distutils config file
sys_dir = os.path.dirname(sys.modules['distutils'].__file__)
# Look for the system config file
sys_file = os.path.join(sys_dir, "distutils.cfg")
... | Find as many configuration files as should be processed for this
platform, and return a list of filenames in the order in which they
should be parsed. The filenames returned are guaranteed to exist
(modulo nasty race conditions).
There are three possible config files: distutils.cfg in ... | 93 | 92 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_config_files(self):
files = []
check_environ()
# Where to look for the system-wide Distutils config file
sys_dir = os.path.dirname(sys.modu... |
2,862 | def get_save_image_name(org_im_path, output_dir, num):
# name prefix of orginal image
org_im_name = os.path.split(org_im_path)[-1]
im_prefix = os.path.splitext(org_im_name)[0]
ext = '.png'
# save image path
save_im_path = os.path.join(output_dir, im_prefix + ext)
if os.path.exists(save_... |
Get save image name from source image path.
| 8 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_save_image_name(org_im_path, output_dir, num):
# name prefix of orginal image
org_im_name = os.path.split(org_im_path)[-1]
im_prefix = os.path.splitext(org_im_name)[... |
2,863 | def rgb_to_hsv(arr):
arr = np.asarray(arr)
# check length of the last dimension, should be _some_ sort of rgb
if arr.shape[-1] != 3:
raise ValueError("Last dimension of input array must be 3; "
"shape {} was found.".format(arr.shape))
in_shape = arr.shape
arr ... |
Convert float RGB values (in the range [0, 1]), in a numpy array to HSV
values.
Parameters
----------
arr : (..., 3) array-like
All values must be in the range [0, 1]
Returns
-------
(..., 3) ndarray
Colors converted to HSV values in range [0, 1]
| 46 | 175 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rgb_to_hsv(arr):
arr = np.asarray(arr)
# check length of the last dimension, should be _some_ sort of rgb
if arr.shape[-1] != 3:
raise ValueError("Last dimensio... |
2,864 | def test_scheduler_verify_pool_full(self, dag_maker, configs):
with conf_vars(configs):
with dag_maker(dag_id='test_scheduler_verify_pool_full'):
BashOperator(
task_id='dummy',
pool='test_scheduler_verify_pool_full',
... |
Test task instances not queued when pool is full
| 9 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_scheduler_verify_pool_full(self, dag_maker, configs):
with conf_vars(configs):
with dag_maker(dag_id='test_scheduler_verify_pool_full'):
... |
2,865 | def ms_word():
# TODO : Take location input from the user
try:
speak("Enter the document's location - ")
location = input("Enter the document's location - ")
file_loc = doubleslash(location)
doc = docx.Document(file_loc)
fullText = []
... | [Print and speak out a ms_word docx file as specified in the path]
| 13 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ms_word():
# TODO : Take location input from the user
try:
speak("Enter the document's location - ")
location = input("Enter the document's location... |
2,866 | def tree_data(G, root, attrs=None, ident="id", children="children"):
if G.number_of_nodes() != G.number_of_edges() + 1:
raise TypeError("G is not a tree.")
if not G.is_directed():
raise TypeError("G is not directed.")
if not nx.is_weakly_connected(G):
raise TypeError("G is not w... | Returns data in tree format that is suitable for JSON serialization
and use in Javascript documents.
Parameters
----------
G : NetworkX graph
G must be an oriented tree
root : node
The root of the tree
attrs : dict
A dictionary that contains two keys 'id' and 'children'.... | 235 | 151 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tree_data(G, root, attrs=None, ident="id", children="children"):
if G.number_of_nodes() != G.number_of_edges() + 1:
raise TypeError("G is not a tree.")
if not G.is_d... |
2,867 | def test_mutating_input_arrays_y_and_z(fig_test, fig_ref):
ax1 = fig_test.add_subplot(111, projection='3d')
x = [1, 2, 3]
y = [0.0, 0.0, 0.0]
z = [0.0, 0.0, 0.0]
ax1.plot(x, y, z, 'o-')
ax1.set_ylim([0, 4])
ax1.set_zlim([0, 4])
fig_test.draw_without_rendering()
# mutate y,z to... |
Test to see if the `z` axis does not get mutated
after a call to `Axes3D.plot`
test cases came from GH#8990
| 21 | 87 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_mutating_input_arrays_y_and_z(fig_test, fig_ref):
ax1 = fig_test.add_subplot(111, projection='3d')
x = [1, 2, 3]
y = [0.0, 0.0, 0.0]
z = [0.0, 0.0, 0.0]
ax1... |
2,868 | def test_search_with_hyphen(self):
book = models.Book.objects.create(
title="Harry Potter and the Half-Blood Prince",
publication_date=date(2009, 7, 15),
number_of_pages=607,
)
index = self.backend.get_index_for_model(models.Book)
index.add_i... |
This tests that punctuation characters are treated the same
way in both indexing and querying.
See: https://github.com/wagtail/wagtail/issues/937
| 17 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_search_with_hyphen(self):
book = models.Book.objects.create(
title="Harry Potter and the Half-Blood Prince",
publication_date=date(2009, 7, ... |
2,869 | def resolve(self, s):
name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += '.' + frag
try:
found = getattr(found, frag)
... |
Resolve strings to objects using standard import and attribute
syntax.
| 10 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resolve(self, s):
name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in nam... |
2,870 | def heldout_score(clf, X_test, y_test):
score = np.zeros((n_estimators,), dtype=np.float64)
for i, y_pred in enumerate(clf.staged_decision_function(X_test)):
score[i] = binomial_deviance(y_test, y_pred.ravel())
return score
| compute deviance scores on ``X_test`` and ``y_test``. | 7 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def heldout_score(clf, X_test, y_test):
score = np.zeros((n_estimators,), dtype=np.float64)
for i, y_pred in enumerate(clf.staged_decision_function(X_test)):
score[i] = ... |
2,871 | def test_product_types_query_ids_not_exists(user_api_client, category):
query = NOT_EXISTS_IDS_COLLECTIONS_QUERY
variables = {"filter": {"ids": ["fTEJRuFHU6fd2RU=", "2XwnQNNhwCdEjhP="]}}
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response, ignore_errors=True)... |
query($filters: ProductTypeFilterInput) {
productTypes(first: 10, filter: $filters) {
edges {
node {
name
}
}
}
}
| 17 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_product_types_query_ids_not_exists(user_api_client, category):
query = NOT_EXISTS_IDS_COLLECTIONS_QUERY
variables = {"filter": {"ids": ["fTEJRuFHU6fd2RU=", "2XwnQNNhwCdEjhP=... |
2,872 | def _generate_examples(self, filepath):
for idx, line in enumerate(open(filepath, "r", encoding="utf-8")):
if idx == 0:
continue # skip header
line = line.strip()
split_line = line.split("\t")
# Examples not marked with a three out of fiv... | Generate hans examples.
Args:
filepath: a string
Yields:
dictionaries containing "premise", "hypothesis" and "label" strings
| 15 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _generate_examples(self, filepath):
for idx, line in enumerate(open(filepath, "r", encoding="utf-8")):
if idx == 0:
continue # skip header
... |
2,873 | def _light_internal_color_mode(self) -> str:
if (color_mode := self.color_mode) is None:
# Backwards compatibility for color_mode added in 2021.4
# Add warning in 2021.6, remove in 2021.10
supported = self._light_internal_supported_color_modes
if ColorMo... | Return the color mode of the light with backwards compatibility. | 10 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _light_internal_color_mode(self) -> str:
if (color_mode := self.color_mode) is None:
# Backwards compatibility for color_mode added in 2021.4
# A... |
2,874 | def kde(self, bw_method=None, ind=None, **kwargs):
return self(kind="kde", bw_method=bw_method, ind=ind, **kwargs)
density = kde
|
Generate Kernel Density Estimate plot using Gaussian kernels.
In statistics, `kernel density estimation`_ (KDE) is a non-parametric
way to estimate the probability density function (PDF) of a random
variable. This function uses Gaussian kernels and includes automatic
bandwidth ... | 399 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def kde(self, bw_method=None, ind=None, **kwargs):
return self(kind="kde", bw_method=bw_method, ind=ind, **kwargs)
density = kde
```
###Assistant :
... |
2,875 | def subscription_invoice_requested_webhook(subscription_webhook):
return subscription_webhook(
INVOICE_REQUESTED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.INVOICE_REQUESTED
)
INVOICE_DELETED_SUBSCRIPTION_QUERY =
@pytest.fixture |
subscription{
event{
...on InvoiceDeleted{
invoice{
id
}
}
}
}
| 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def subscription_invoice_requested_webhook(subscription_webhook):
return subscription_webhook(
INVOICE_REQUESTED_SUBSCRIPTION_QUERY, WebhookEventAsyncType.INVOICE_REQUESTED
)... |
2,876 | def test_prompt_from_examples_valid() -> None:
template =
input_variables = ["question"]
example_separator = "\n\n"
prefix =
suffix =
examples = [
,
,
]
prompt_from_examples = PromptTemplate.from_examples(
examples,
suffix,
input_variables,... | Test prompt can be successfully constructed from examples.Test Prompt:
Question: who are you?
Answer: foo
Question: what are you?
Answer: bar
Question: {question}
Answer:Test Prompt:Question: {question}\nAnswer:Question: who are you?\nAnswer: fooQuestion: what are you?\nAnswer: bar | 34 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_prompt_from_examples_valid() -> None:
template =
input_variables = ["question"]
example_separator = "\n\n"
prefix =
suffix =
examples = [
,
... |
2,877 | def compatible_platforms(provided, required):
if provided is None or required is None or provided == required:
# easy case
return True
# Mac OS X special cases
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
# is ... | Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
| 33 | 163 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compatible_platforms(provided, required):
if provided is None or required is None or provided == required:
# easy case
return True
# Mac OS X special cases
... |
2,878 | def find_negative_cycle(G, source, weight="weight"):
weight = _weight_function(G, weight)
pred = {source: []}
v = _inner_bellman_ford(G, [source], weight, pred=pred)
if v is None:
raise nx.NetworkXError("No negative cycles detected.")
# negative cycle detected... find it
neg_cycle... | Returns a cycle with negative total weight if it exists.
Bellman-Ford is used to find shortest_paths. That algorithm
stops if there exists a negative cycle. This algorithm
picks up from there and returns the found negative cycle.
The cycle consists of a list of nodes in the cycle order. The last
n... | 285 | 125 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_negative_cycle(G, source, weight="weight"):
weight = _weight_function(G, weight)
pred = {source: []}
v = _inner_bellman_ford(G, [source], weight, pred=pred)
if... |
2,879 | def expand(image, border=0, fill=0):
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
color = _color(fill, image.mode)
if image.mode == "P" and image.palette:
palette = ImagePalette.ImagePalette(palette=image.getpalett... |
Add border to the image
:param image: The image to expand.
:param border: Border width, in pixels.
:param fill: Pixel fill value (a color value). Default is 0 (black).
:return: An image.
| 32 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def expand(image, border=0, fill=0):
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
color = _color... |
2,880 | def test_digest_enabled(self, digests, mock_func):
backend = RedisBackend()
digests.digest = backend.digest
digests.enabled.return_value = True
rule = Rule.objects.create(project=self.project, label="my rule")
ProjectOwnership.objects.create(project_id=self.project.id, ... |
Test that with digests enabled, but Slack notification settings
(and not email settings), we send a Slack notification
| 18 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_digest_enabled(self, digests, mock_func):
backend = RedisBackend()
digests.digest = backend.digest
digests.enabled.return_value = True
rule... |
2,881 | def pole_zero_numerical_data(system):
_check_system(system)
system = system.doit() # Get the equivalent TransferFunction object.
num_poly = Poly(system.num, system.var).all_coeffs()
den_poly = Poly(system.den, system.var).all_coeffs()
num_poly = np.array(num_poly, dtype=np.complex128)
de... |
Returns the numerical data of poles and zeros of the system.
It is internally used by ``pole_zero_plot`` to get the data
for plotting poles and zeros. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
=======... | 187 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pole_zero_numerical_data(system):
_check_system(system)
system = system.doit() # Get the equivalent TransferFunction object.
num_poly = Poly(system.num, system.var).al... |
2,882 | def get_versions():
commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']
return tuple([_find_exe_version(cmd) for cmd in commands])
| Try to find out the versions of gcc, ld and dllwrap.
If not possible it returns None for it.
| 19 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_versions():
commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']
return tuple([_find_exe_version(cmd) for cmd in commands])
```
###Assistant : Try... |
2,883 | def __virtual__():
if salt.utils.napalm.virtual(__opts__, __virtualname__, __file__):
return __virtualname__
else:
err_msg = "NAPALM is not installed."
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
|
This beacon can only work when running under a regular or a proxy minion, managed through napalm.
| 17 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __virtual__():
if salt.utils.napalm.virtual(__opts__, __virtualname__, __file__):
return __virtualname__
else:
err_msg = "NAPALM is not installed."
l... |
2,884 | def parse_prompt_attention(text):
res = []
round_brackets = []
square_brackets = []
round_bracket_multiplier = 1.1
square_bracket_multiplier = 1 / 1.1
|
Parses a string with attention tokens and returns a list of pairs: text and its assoicated weight.
Accepted tokens are:
(abc) - increases attention to abc by a multiplier of 1.1
(abc:3.12) - increases attention to abc by a multiplier of 3.12
[abc] - decreases attention to abc by a multiplier ... | 145 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parse_prompt_attention(text):
res = []
round_brackets = []
square_brackets = []
round_bracket_multiplier = 1.1
square_bracket_multiplier = 1 / 1.1
```... |
2,885 | def get_dependencies(self, candidate):
# type: (Candidate) -> list[Candidate]
r
# FIXME: If there's several galaxy servers set, there may be a
# FIXME: situation when the metadata of the same collection
# FIXME: differs. So how do we resolve this case? Priority?
# FIXME: ... | Get direct dependencies of a candidate.
:returns: A collection of requirements that `candidate` \
specifies as its dependencies.
| 18 | 178 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_dependencies(self, candidate):
# type: (Candidate) -> list[Candidate]
r
# FIXME: If there's several galaxy servers set, there may be a
# FIXME: situat... |
2,886 | def test_set_displayname(self) -> None:
# Modify user
channel = self.make_request(
"PUT",
self.url_other_user,
access_token=self.admin_user_tok,
content={"displayname": "foobar"},
)
self.assertEqual(HTTPStatus.OK, channel.code, m... |
Test setting the displayname of another user.
| 7 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_set_displayname(self) -> None:
# Modify user
channel = self.make_request(
"PUT",
self.url_other_user,
access_token=self... |
2,887 | def on_ssl_errors(self, reply, qt_errors):
errors = certificateerror.CertificateErrorWrapper(reply, qt_errors)
log.network.debug("Certificate errors: {!r}".format(errors))
try:
host_tpl: Optional[urlutils.HostTupleType] = urlutils.host_tuple(
reply.url())
... | Decide if SSL errors should be ignored or not.
This slot is called on SSL/TLS errors by the self.sslErrors signal.
Args:
reply: The QNetworkReply that is encountering the errors.
qt_errors: A list of errors.
| 34 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def on_ssl_errors(self, reply, qt_errors):
errors = certificateerror.CertificateErrorWrapper(reply, qt_errors)
log.network.debug("Certificate errors: {!r}".format(er... |
2,888 | def render_pep440(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += f"{pieces['distance']}.g{pieces['short']}"
if pieces["dirty"]:
rendered... | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
| 37 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def render_pep440(pieces):
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(p... |
2,889 | async def test_aset_many(self):
self.assertEqual(await cache.aset_many({"a": 1, "b": 2}), [])
self.assertEqual(
await cache.aset_many({"a": 1, "b": 2}, timeout=2, version="1"),
[],
)
| aset_many() does nothing for the dummy cache backend. | 8 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_aset_many(self):
self.assertEqual(await cache.aset_many({"a": 1, "b": 2}), [])
self.assertEqual(
await cache.aset_many({"a": 1, "b": 2}, t... |
2,890 | def _user_input(self, input_str):
os.environ["COMP_WORDS"] = input_str
idx = len(input_str.split(" ")) - 1 # Index of the last word
comp_cword = idx + 1 if input_str.endswith(" ") else idx
os.environ["COMP_CWORD"] = str(comp_cword)
sys.argv = input_str.split()
|
Set the environment and the list of command line arguments.
This sets the bash variables $COMP_WORDS and $COMP_CWORD. The former is
an array consisting of the individual words in the current command
line, the latter is the index of the current cursor position, so in
case a word... | 80 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _user_input(self, input_str):
os.environ["COMP_WORDS"] = input_str
idx = len(input_str.split(" ")) - 1 # Index of the last word
comp_cword = idx + 1 if ... |
2,891 | def _check_conflicts() -> None:
# Node-related conflicts
# When using the Node server, we must always connect to 8501 (this is
# hard-coded in JS). Otherwise, the browser would decide what port to
# connect to based on window.location.port, which in dev is going to
# be (3000)
# Import logger ... |
Warning: the config option 'server.enableCORS=false' is not compatible with 'server.enableXsrfProtection=true'.
As a result, 'server.enableCORS' is being overridden to 'true'.
More information:
In order to protect against CSRF attacks, we send a cookie with each request.
To do so, we must specify allowable origins, w... | 61 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_conflicts() -> None:
# Node-related conflicts
# When using the Node server, we must always connect to 8501 (this is
# hard-coded in JS). Otherwise, the browser would ... |
2,892 | def num_columns(self) -> Dict[str, int]:
self._check_values_type()
return {k: dataset.num_columns for k, dataset in self.items()}
| Number of columns in each split of the dataset.
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes")
>>> ds.num_columns
{'test': 2, 'train': 2, 'validation': 2}
```
| 29 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def num_columns(self) -> Dict[str, int]:
self._check_values_type()
return {k: dataset.num_columns for k, dataset in self.items()}
```
###Assistant : Num... |
2,893 | def _sample_with_replacement_map_partitions(population, k):
stream = iter(population)
e = next(stream)
reservoir, stream_length = [e for _ in range(k)], 1
w = [rnd.random() for _ in range(k)]
nxt = [_geometric(wi) for wi in w]
min_nxt = min(nxt)
for i, e in enumerate(stream, 1):
... |
Reservoir sampling with replacement, the main idea is to use k reservoirs of size 1
See Section Applications in http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
| 20 | 72 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _sample_with_replacement_map_partitions(population, k):
stream = iter(population)
e = next(stream)
reservoir, stream_length = [e for _ in range(k)], 1
w = [rnd.ran... |
2,894 | def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {})
if name in member_map:
raise AttributeError('cannot reassign member %r' % (name, ))
super().__setattr__(name, value)
|
Block attempts to reassign Enum members.
A simple assignment to the class namespace only changes one of the
several possible ways to get an Enum member from the Enum class,
resulting in an inconsistent Enumeration.
| 35 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __setattr__(cls, name, value):
member_map = cls.__dict__.get('_member_map_', {})
if name in member_map:
raise AttributeError('cannot reassign member ... |
2,895 | def read_file(self, f, source=None):
if source is None:
try:
source = f.name
except AttributeError:
source = '<???>'
self._read(f, source)
| Like read() but the argument must be a file-like object.
The `f' argument must be iterable, returning one line at a time.
Optional second argument is the `source' specifying the name of the
file being read. If not given, it is taken from f.name. If `f' has no
`name' attribute, `<???>' i... | 53 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read_file(self, f, source=None):
if source is None:
try:
source = f.name
except AttributeError:
source = '<???>'
... |
2,896 | def get_newsletters() -> pd.DataFrame:
urls = [
"https://defiweekly.substack.com/archive",
"https://newsletter.thedefiant.io/archive",
"https://thedailygwei.substack.com/archive",
"https://todayindefi.substack.com/archive",
"https://newsletter.banklesshq.com/archive",
... | Scrape all substack newsletters from url list.
[Source: substack.com]
Returns
-------
pd.DataFrame
DataFrame with recent news from most popular DeFi related newsletters.
| 22 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_newsletters() -> pd.DataFrame:
urls = [
"https://defiweekly.substack.com/archive",
"https://newsletter.thedefiant.io/archive",
"https://thedailygwei... |
2,897 | def _object2proto(self) -> GetEnumAttributeAction_PB:
return GetEnumAttributeAction_PB(
path=self.path,
id_at_location=serialize(self.id_at_location),
address=serialize(self.address),
msg_id=serialize(self.id),
)
| Returns a protobuf serialization of self.
As a requirement of all objects which inherit from Serializable,
this method transforms the current object into the corresponding
Protobuf object so that it can be further serialized.
:return: returns a protobuf object
:rtype: GetOrSetPro... | 68 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _object2proto(self) -> GetEnumAttributeAction_PB:
return GetEnumAttributeAction_PB(
path=self.path,
id_at_location=serialize(self.id_at_location... |
2,898 | async def test_becomes_delivered_not_shown_notification(hass):
package = Package(
tracking_number="456",
destination_country=206,
friendly_name="friendly name 1",
info_text="info text 1",
location="location 1",
timestamp="2020-08-10 10:32",
origin_country... | Ensure notification is triggered when package becomes delivered. | 8 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_becomes_delivered_not_shown_notification(hass):
package = Package(
tracking_number="456",
destination_country=206,
friendly_name="friendly nam... |
2,899 | def fit(self, X, y=None, sample_weight=None):
X = self._validate_data(X, accept_sparse=["csc"])
if issparse(X):
# Pre-sort indices to avoid that each individual tree of the
# ensemble sorts the indices.
X.sort_indices()
rnd = check_random_state(self.... |
Fit estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Use ``dtype=np.float32`` for maximum
efficiency. Sparse matrices are also supported, use sparse
``csc_matrix`` for maximum effici... | 66 | 230 | 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, sample_weight=None):
X = self._validate_data(X, accept_sparse=["csc"])
if issparse(X):
# Pre-sort indices to avoid that each ind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.