text
stringlengths 15
7.82k
| ids
listlengths 1
7
|
---|---|
def METHOD_NAME(cls, *args, **kwargs):
if cls._args_schema is not None:
return cls._args_schema
cls._args_schema = super().METHOD_NAME(*args, **kwargs)
# define Arg Group ""
_args_schema = cls._args_schema
_args_schema.fabric_name = AAZStrArg(
options=["--fabric-name"],
help="Fabric name.",
required=True,
)
_args_schema.resource_group = AAZResourceGroupNameArg(
required=True,
)
_args_schema.vault_name = AAZStrArg(
options=["--vault-name"],
help="The name of the recovery services vault.",
required=True,
)
return cls._args_schema | [
56,
134,
135
] |
def METHOD_NAME(iface: Interface) -> VNA:
# serial_port.timeout = TIMEOUT
return NAME2DEVICE[iface.comment](iface) | [
19,
-1
] |
def METHOD_NAME():
print(__doc__) | [
558
] |
def METHOD_NAME(self, x, y):
locs = np.vstack((x, y)).T
distances = cdist(locs, locs)
return np.mean(distances) | [
314,
1886
] |
def METHOD_NAME():
item = _get_resource_json("image_data_legacy.json")
item["id"] = ""
actual_images_data = smk.get_record_data(item)
assert actual_images_data is None | [
9,
19,
3669,
3116,
610,
98,
41
] |
def METHOD_NAME():
roles = {}
extensions = ["markdown.extensions.nl2br"]
for name in glob("apps/volunteer/role_descriptions/*.md"):
role_id = name.split("/")[-1].replace(".md", "")
content = open(name, "r").read()
roles[role_id] = Markup(markdown.markdown(content, extensions=extensions))
return roles | [
275,
1018,
1303
] |
def METHOD_NAME(self):
error = .001
t = carla.Transform(
carla.Location(x=0.0, y=0.0, z=-1.0),
carla.Rotation(pitch=90.0, yaw=0.0, roll=0.0))
point_list = [carla.Location(x=0.0, y=0.0, z=2.0),
carla.Location(x=0.0, y=10.0, z=1.0),
carla.Location(x=0.0, y=18.0, z=2.0)
]
t.transform(point_list)
solution_list = [carla.Location(-2.0, 0.0, -1.0),
carla.Location(-1.0, 10.0, -1.0),
carla.Location(-2.0, 18.0, -1.0)
]
for i in range(len(point_list)):
self.assertTrue(abs(point_list[i].x - solution_list[i].x) <= error)
self.assertTrue(abs(point_list[i].y - solution_list[i].y) <= error)
self.assertTrue(abs(point_list[i].z - solution_list[i].z) <= error) | [
9,
245,
2271,
61,
2518,
708
] |
def METHOD_NAME(
throttle_class, request_factory, view
):
request = request_factory.get("/")
throttle = throttle_class()
assert throttle.get_cache_key(view.initialize_request(request), view) is not None | [
9,
3431,
1585,
2790,
610,
3171,
596
] |
def METHOD_NAME(self, task=None, language=None, no_timestamps=True):
return self.tokenizer.METHOD_NAME(task=task, language=language, no_timestamps=no_timestamps) | [
19,
3642,
2995,
308
] |
def METHOD_NAME(question, answers):
fields = []
is_correct = []
for num in range(1, 5):
fields.append(f"option_{cstr(num)}")
fields.append(f"is_correct_{cstr(num)}")
question_details = frappe.db.get_value(
"LMS Quiz Question", question, fields, as_dict=1
)
for num in range(1, 5):
if question_details[f"option_{num}"] in answers:
is_correct.append(question_details[f"is_correct_{num}"])
else:
is_correct.append(0)
return is_correct | [
250,
4220,
9099
] |
def METHOD_NAME(db_type, monkeypatch):
uri = f"{db_type}://hostname/database"
monkeypatch.setenv(MLFLOW_TRACKING_URI.name, uri)
monkeypatch.delenv("MLFLOW_SQLALCHEMYSTORE_POOLCLASS", raising=False)
with mock.patch("sqlalchemy.create_engine") as mock_create_engine, mock.patch(
"mlflow.store.db.utils._initialize_tables"
), mock.patch(
"mlflow.store.model_registry.sqlalchemy_store.SqlAlchemyStore."
"_verify_registry_tables_exist"
):
store = _get_store()
assert isinstance(store, SqlAlchemyStore)
assert store.db_uri == uri
mock_create_engine.assert_called_once_with(uri, pool_pre_ping=True) | [
9,
19,
1308,
4267,
1308
] |
def METHOD_NAME(self) -> None: ... | [
537,
459
] |
def METHOD_NAME(self):
self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError, AirStatus.from_dict, None) | [
9,
280,
553,
216,
1646,
10308,
293
] |
def METHOD_NAME():
assert np.round(Pareto(b=2.).cdf(x=1.1), 3) == 0.174 | [
9,
6277
] |
def METHOD_NAME(self) -> None:
assert m.parser.get_default("progress") is False | [
9,
3064
] |
def METHOD_NAME( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, number=None, order_id
):
order = cls.get_node_or_error(info, order_id, only_type=Order, field="orderId")
cls.check_channel_permissions(info, [order.channel_id])
cls.clean_order(order)
manager = get_plugin_manager_promise(info.context).get()
if not is_event_active_for_any_plugin("invoice_request", manager.all_plugins):
raise ValidationError(
{
"orderId": ValidationError(
"No app or plugin is configured to handle invoice requests.",
code=InvoiceErrorCode.NO_INVOICE_PLUGIN.value,
)
}
)
shallow_invoice = models.Invoice.objects.create(
order=order,
number=number,
)
invoice = manager.invoice_request(
order=order, invoice=shallow_invoice, number=number
)
app = get_app_promise(info.context).get()
if invoice and invoice.status == JobStatus.SUCCESS:
order_events.invoice_generated_event(
order=order,
user=info.context.user,
app=app,
invoice_number=invoice.number,
)
else:
order_events.invoice_requested_event(
user=info.context.user, app=app, order=order
)
events.invoice_requested_event(
user=info.context.user,
app=app,
order=order,
number=number,
)
return InvoiceRequest(invoice=invoice, order=order) | [
407,
87
] |
async def METHOD_NAME() -> AsyncIterator[bytes]:
for _ in range(10):
yield b"some_data" | [
370
] |
def METHOD_NAME(next_link=None):
if not next_link:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
extension_type_name=extension_type_name,
template_url=self.list.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
request = build_list_request(
subscription_id=self._config.subscription_id,
location=location,
extension_type_name=extension_type_name,
template_url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request | [
123,
377
] |
METHOD_NAME(self): | [
19,
3081,
1881
] |
def METHOD_NAME(self):
"""expand src package"""
osc.core.set_link_rev('http://localhost', 'osctest', 'simple', expand=True) | [
9,
-1
] |
def METHOD_NAME(self):
"""Test exception is raised for negative probabilities."""
probs = [[1.1, -0.1], [0, 1]]
self.assertRaises(NoiseError, lambda: ReadoutError(probs))
probs = [[0, 1], [1.1, -0.1]]
self.assertRaises(NoiseError, lambda: ReadoutError(probs)) | [
9,
3318,
2927,
442
] |
def METHOD_NAME(file):
path = file.short_path
if path.startswith("../"):
return _strip_external(path)
return _strip_internal(path, file) | [
17471,
157
] |
def METHOD_NAME(worker_id, num_workers, rank, seed):
"""Worker init func for dataloader.
The seed of each worker equals to num_worker * rank + worker_id + user_seed
Args:
worker_id (int): Worker id.
num_workers (int): Number of workers.
rank (int): The rank of current process.
seed (int): The random seed to use.
"""
worker_seed = num_workers * rank + worker_id + seed
np.random.seed(worker_seed)
random.seed(worker_seed) | [
1794,
176,
667
] |
def METHOD_NAME(self, extensions):
super(NamedExtensionManager, self).METHOD_NAME(extensions)
if self._name_order:
self.extensions = [self[n] for n in self._names
if n not in self._missing_names] | [
176,
1294
] |
def METHOD_NAME(ds_meadow: Dataset, table_names: List[str]) -> pd.DataFrame:
"""Combine meadow tables."""
dfs = []
for table_name in table_names:
tb_meadow = ds_meadow[table_name].reset_index()
df = pd.DataFrame(tb_meadow)
# assign sex
if table_name.startswith("both_"):
df = df.assign(sex="all")
elif table_name.startswith("female_"):
df = df.assign(sex="female")
elif table_name.startswith("male_"):
df = df.assign(sex="male")
else:
raise ValueError(f"Unknown sex for table {table_name}!")
dfs.append(df)
df = pd.concat(dfs, ignore_index=True)
return cast(pd.DataFrame, df) | [
2003,
14092,
2253
] |
def METHOD_NAME(self) -> str:
"""
The ID of the deployment.
"""
return pulumi.get(self, "id") | [
147
] |
def METHOD_NAME(self, s):
"""Clear screen.
"""
os.system("cls") | [
3847
] |
def METHOD_NAME():
# Simple class to make outer.
class dummy:
def __init__(self, name):
self.name = name
class field_dummy:
def __init__(self, name, ftype):
self.fieldtype = ftype
self.name = name
lenfield = field_dummy('lenfield', LengthFieldType(u16))
for arrtype, s, b in [[DynamicArrayType(dummy("test1"), "test_arr", byte,
lenfield),
"00010203",
bytes([0, 1, 2, 3])],
[DynamicArrayType(dummy("test2"), "test_arr", u16,
lenfield),
"[0,1,2,256]",
bytes([0, 0, 0, 1, 0, 2, 1, 0])],
[DynamicArrayType(dummy("test3"), "test_arr", short_channel_id,
lenfield),
"[1x2x3,4x5x6,7x8x9,10x11x12]",
bytes([0, 0, 1, 0, 0, 2, 0, 3]
+ [0, 0, 4, 0, 0, 5, 0, 6]
+ [0, 0, 7, 0, 0, 8, 0, 9]
+ [0, 0, 10, 0, 0, 11, 0, 12])]]:
lenfield.fieldtype.add_length_for(field_dummy(s, arrtype))
v, _ = arrtype.val_from_str(s)
otherfields = {s: v}
assert arrtype.val_to_str(v, otherfields) == s
v2 = arrtype.read(io.BytesIO(b), otherfields)
assert v2 == v
buf = io.BytesIO()
arrtype.write(buf, v, None)
assert buf.getvalue() == b
lenfield.fieldtype.len_for = [] | [
9,
2111,
877
] |
def METHOD_NAME(pyramid_request):
pyramid_request.GET = MultiDict(pyramid_request.GET)
pyramid_request.GET["foo"] = "bar"
url = pretend.stub()
pyramid_request.current_route_path = pretend.call_recorder(lambda _query: url)
url_maker = paginate.paginate_url_factory(pyramid_request)
assert url_maker(5) is url
assert pyramid_request.current_route_path.calls == [
pretend.call(_query=[("foo", "bar"), ("page", 5)])
] | [
9,
11465,
274
] |
def METHOD_NAME(self):
return self._command_args or [] | [
462,
335
] |
def METHOD_NAME(self):
"""Mock SoftwareManager"""
self.sm_patcher = patch(
"avocado.plugins.runners.package.SoftwareManager", autospec=True
)
self.mock_sm = self.sm_patcher.start()
self.addCleanup(self.sm_patcher.stop) | [
0,
1
] |
def METHOD_NAME(self, layout, in_menu=None):
# I think it is more appropriate place for coding layout of 3d panel
if not in_menu:
row = layout.row(align=True)
menu = row.operator('node.popup_3d_menu', text=f'Show "{self.label or self.name}"', icon=self.bl_icon)
menu.tree_name = self.id_data.name
menu.node_name = self.name
else:
col = layout.column(align=True)
row = col.row(align=True)
row.label(text=self.label or self.name)
row.prop(self, 'multiple_selection', toggle=True, text='',
icon='SNAP_ON' if self.multiple_selection else 'SNAP_OFF')
for i, val in enumerate(self.string_values):
col.prop(self, "user_list", toggle=True, index=i, text=val.name) | [
1100,
1409,
-1
] |
def METHOD_NAME(self, cookie: Cookie, request: Request) -> bool: ... # undocumented | [
1413,
1217,
16572
] |
def METHOD_NAME(self, record, shift, args, replay_path, image_path, port):
logger = logging.getLogger('replay')
vm = self.get_vm()
vm.set_console()
if record:
logger.info('recording the execution...')
mode = 'record'
else:
logger.info('replaying the execution...')
mode = 'replay'
vm.add_args('-gdb', 'tcp::%d' % port, '-S')
vm.add_args('-icount', 'shift=%s,rr=%s,rrfile=%s,rrsnapshot=init' %
(shift, mode, replay_path),
'-net', 'none')
vm.add_args('-drive', 'file=%s,if=none' % image_path)
if args:
vm.add_args(*args)
vm.launch()
return vm | [
22,
944
] |
def METHOD_NAME(context):
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often.
"""
app = wx.GetApp()
if app is not None:
assert wx.Thread_IsMain()
elr = EventLoopRunner()
# As this time is made shorter, keyboard response improves, but idle
# CPU load goes up. 10 ms seems like a good compromise.
elr.Run(time=10, # CHANGE time here to control polling interval
input_is_ready=context.input_is_ready)
return 0 | [
5013,
5014
] |
def METHOD_NAME(self):
return self.sslobj.METHOD_NAME() | [
4483
] |
def METHOD_NAME(args, model, device, train_loader, optimizer, epoch):
model.METHOD_NAME()
t_list = []
for batch_idx, (data, target) in enumerate(train_loader):
t = time.perf_counter()
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print(
f"Train Epoch: {epoch} [{batch_idx * len(data)}/{len(train_loader.dataset)} "
f"({100.0 * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}"
)
if args.dry_run:
break
t_list.append(time.perf_counter() - t)
print("average time", sum(t_list) / len(t_list)) | [
849
] |
def METHOD_NAME(self, phys_address: int) -> int:
out_buf = self.read_physical_mem(phys_address, 2)
value = unpack('=H', out_buf)[0]
self.logger.log_hal(f'[mem] word at PA = 0x{phys_address:016X}: 0x{value:04X}')
return value | [
203,
4935,
1279,
2236
] |
def METHOD_NAME(
self, checker: ICredentialsChecker, *credentialInterfaces: Type[Interface]
) -> None:
if not credentialInterfaces:
credentialInterfaces = checker.credentialInterfaces
for credentialInterface in credentialInterfaces:
self.checkers[credentialInterface] = checker | [
372,
7598
] |
def METHOD_NAME(
self,
fp: str | bytes | Path | _Writeable,
format: str | None = ...,
*,
save_all: bool = ...,
bitmap_format: Literal["bmp", "png"] = ...,
**params: Any,
) -> None: ... | [
73
] |
def METHOD_NAME(__a: Any, __b: Any) -> Any: ... | [
14829
] |
def METHOD_NAME(self, graph, feat):
r"""Compute Graph Isomorphism Network layer.
Parameters
----------
graph : DGLGraph
The graph.
feat : tf.Tensor or pair of tf.Tensor
If a tf.Tensor is given, the input feature of shape :math:`(N, D_{in})` where
:math:`D_{in}` is size of input feature, :math:`N` is the number of nodes.
If a pair of tf.Tensor is given, the pair must contain two tensors of shape
:math:`(N_{in}, D_{in})` and :math:`(N_{out}, D_{in})`.
If ``apply_func`` is not None, :math:`D_{in}` should
fit the input dimensionality requirement of ``apply_func``.
Returns
-------
tf.Tensor
The output feature of shape :math:`(N, D_{out})` where
:math:`D_{out}` is the output dimensionality of ``apply_func``.
If ``apply_func`` is None, :math:`D_{out}` should be the same
as input dimensionality.
"""
with graph.local_scope():
feat_src, feat_dst = expand_as_pair(feat, graph)
graph.srcdata["h"] = feat_src
graph.update_all(fn.copy_u("h", "m"), self._reducer("m", "neigh"))
rst = (1 + self.eps) * feat_dst + graph.dstdata["neigh"]
if self.apply_func is not None:
rst = self.apply_func(rst)
return rst | [
128
] |
def METHOD_NAME(uri):
return create_engine(uri).dialect.name | [
19,
463,
7735
] |
def METHOD_NAME(next_link=None):
if not next_link:
request = build_get_request(
resource_group_name=resource_group_name,
move_collection_name=move_collection_name,
subscription_id=self._config.subscription_id,
dependency_level=dependency_level,
orderby=orderby,
filter=filter,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request | [
123,
377
] |
def METHOD_NAME(self) -> None:
if len(self.__undo_stack) > 0 and not self.__undo_stack[-1].is_undo_valid:
self.clear() | [
187
] |
def METHOD_NAME(self):
return self.focus_obj, self.index | [
19,
264
] |
def METHOD_NAME(self):
state = self.get_state()
return state == ALBAZoomMotorAutoBrightness.READY | [
137,
1338
] |
def METHOD_NAME(self) -> Mapping[str, Any]:
"""Parameters of the trial.""" | [
386
] |
def METHOD_NAME(self, metric_id):
return os.path.isdir(self._build_measure_path(metric_id)) | [
220,
12605
] |
def METHOD_NAME(self, *args, **kwargs):
return self.optim.METHOD_NAME(*args, **kwargs) | [
238,
49,
846
] |
def METHOD_NAME(error: Any) -> bool:
def _check_single_item(error_: dbt_results.RunResult) -> bool:
return error_.status == dbt_results.RunStatus.Error and "The source and target schemas on this incremental model are out of sync" in error_.message
if isinstance(error, dbt_results.RunResult):
return _check_single_item(error)
elif isinstance(error, dbt_results.RunExecutionResult):
return any(_check_single_item(r) for r in error.results)
return False | [
137,
3542,
135,
1737,
47,
164,
168
] |
def METHOD_NAME(self, output, outputChannelIndex):
inputID, inputChannelIndex = self.getInputIDChannelIndex(output, outputChannelIndex)
return ACMInput(inputID) | [
19,
362
] |
def METHOD_NAME(self, state_name): | [
3287
] |
def METHOD_NAME():
names = [
name for name in os.listdir(__stage_scripts_dir)
if os.path.isdir(os.path.join(__stage_scripts_dir, name))
]
names.sort()
print('\n'.join(names))
sys.exit(0) | [
3164,
245
] |
def METHOD_NAME(request):
return get_response(request) | [
3174
] |
def METHOD_NAME(self, *args, **kwargs):
self.run_and_statis(quant=False, max_examples=150) | [
9
] |
def METHOD_NAME():
# parse the command line, exit with UNKNOWN if it fails
try:
args = parse_args()
except SystemExit:
sys.exit(3)
with open(args.INPUT_FILE, 'rb') as file:
data = json.load(file)
if args.AUTO:
for row in data['panels']:
if row['type'] == 'row':
row_title = row['title']
uid = row_title.lower().replace(' ', '-').replace('/', '').replace('---', '-').replace('_', '-')
windows = bool('windows' in uid)
if uid == 'default':
out_filename = 'assets/grafana/{}{}.json'.format(uid, args.FILENAME_POSTFIX)
else:
out_filename = 'check-plugins/{}/{}{}.json'.format(uid.replace("-windows", ""), uid, args.FILENAME_POSTFIX)
new_panels = get_panels(row['panels'])
# re-read the json, as orig_data should not be a reference to data, and copy.deepcopy() is slower than json.load().
with open(args.INPUT_FILE, 'rb') as file:
orig_data = json.load(file)
new_dashboard = generate_new_dashboards(orig_data, new_panels, row_title, uid)
save_dashboard_to_file(new_dashboard, out_filename)
if args.GENERATE_ICINGAWEB2_INI:
panel_ids = [str(panel['id']) for panel in new_dashboard['panels']]
repeatable = any([panel.get('repeat') for panel in new_dashboard['panels']])
if uid == 'default':
out_filename = 'assets/grafana/{}{}.json'.format(uid, args.FILENAME_POSTFIX)
else:
out_filename = 'check-plugins/{}/icingaweb2-module-grafana/{}.ini'.format(uid.replace("-windows", ""), uid)
generate_icingaweb_ini(out_filename, row_title, uid, panel_ids, repeatable, windows)
sys.exit()
all_panels = get_panels(data['panels'])
all_panels_desc = [(panel['id'], '{} ({})'.format(panel['title'], panel['type'])) for panel in all_panels]
print('Which panels(s) would you like to combine?')
print('- ' * 40)
all_panels_desc = sorted(all_panels_desc, key=lambda item: item[1])
for index, text in enumerate(all_panels_desc):
print('{}: {}'.format(index, text[1]))
print('- ' * 40)
try:
selection = input('Select the appropriate numbers separated by commas: ').strip(',').split(',')
selection = [int(item.strip()) for item in selection]
new_title = input('Choose the title for the new dashboard: ').strip()
new_uid = input('Choose the uid for the new dashboard: ').strip()
out_filename = input('Choose the filename: ').strip()
except KeyboardInterrupt:
sys.exit()
except ValueError:
print('Failed to parse selection.')
sys.exit(3)
new_panel_ids = [all_panels_desc[index][0] for index in selection]
new_panels = [panel for panel in get_panels(data['panels']) if panel['id'] in new_panel_ids]
new_dashboard = generate_new_dashboards(data, new_panels, new_title, new_uid)
save_dashboard_to_file(new_dashboard, out_filename) | [
57
] |
def METHOD_NAME(colorer, s, i):
return colorer.match_mark_previous(s, i, kind="label", pattern=":",
at_whitespace_end=True,
exclude_match=True) | [
2336,
15707
] |
def METHOD_NAME(self):
"""Only keep files that are images, or that are named 'gcp_list.txt'"""
_, file_extension = path.splitext(self.name)
return file_extension.lower() in VALID_IMAGE_EXTENSIONS or self.name == 'gcp_list.txt' | [
137,
1205
] |
def METHOD_NAME(benchmark, n, log, numba):
x = make_data(size=n)
if log:
def cost(x, z, mu, sigma, slope):
return -np.sum(log_mixture(x, z, mu, sigma, slope))
else:
def cost(x, z, mu, sigma, slope):
return -np.sum(np.log(mixture(x, z, mu, sigma, slope)))
if numba:
cost = nb.njit(cost)
cost(x, *ARGS) # jit warm-up
m = Minuit(lambda *args: cost(x, *args), *ARGS)
m.errordef = Minuit.LIKELIHOOD
m.limits[0, 1] = (0, 1)
m.limits[2, 3] = (0, 10)
def run():
m.reset()
return m.migrad()
m = benchmark(run)
assert m.valid
# ignore slope
assert_allclose(m.values[:-1], ARGS[:-1], atol=2 / n**0.5) | [
9,
15729
] |
def METHOD_NAME(input: Store, axis: int) -> Store:
"""
Sum values along the chosen axis
Parameters
----------
input : Store
Input to sum
axis : int
Axis along which the summation should be done
Returns
-------
Store
Summation result
"""
sanitized = _sanitize_axis(axis, input.ndim)
# Compute the output shape by removing the axis being summed over
res_shape = tuple(
ext for dim, ext in enumerate(input.shape) if dim != sanitized
)
result = context.create_store(input.type, res_shape)
np.asarray(result).fill(0)
# Broadcast the output along the contracting dimension
promoted = result.promote(axis, input.shape[axis])
assert promoted.shape == input.shape
task = context.create_auto_task(OpCode.SUM_OVER_AXIS)
task.add_input(input)
task.add_reduction(promoted, ty.ReductionOp.ADD)
task.add_alignment(input, promoted)
task.execute()
return result | [
912,
3217,
2227
] |
def METHOD_NAME(self) -> contractOrderStackData:
return self.data.db_contract_order_stack | [
1267,
1522,
1501,
365
] |
def METHOD_NAME():
"""A credential shouldn't request a new token when it has a cached one with sufficient validity remaining"""
credential = MockCredential(cached_token=AccessToken(CACHED_TOKEN, time.time() + DEFAULT_REFRESH_OFFSET + 1))
token = credential.get_token(SCOPE)
credential.acquire_token_silently.assert_called_once_with(SCOPE, claims=None, tenant_id=None)
assert credential.request_token.call_count == 0
assert token.token == CACHED_TOKEN | [
9,
175,
466,
261,
1920,
1092
] |
def METHOD_NAME(factory_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
trigger_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTriggerResult:
"""
Gets a trigger.
:param str factory_name: The factory name.
:param str resource_group_name: The resource group name.
:param str trigger_name: The trigger name.
"""
__args__ = dict()
__args__['factoryName'] = factory_name
__args__['resourceGroupName'] = resource_group_name
__args__['triggerName'] = trigger_name
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('azure-native:datafactory/v20180601:getTrigger', __args__, opts=opts, typ=GetTriggerResult).value
return AwaitableGetTriggerResult(
etag=pulumi.get(__ret__, 'etag'),
id=pulumi.get(__ret__, 'id'),
name=pulumi.get(__ret__, 'name'),
properties=pulumi.get(__ret__, 'properties'),
type=pulumi.get(__ret__, 'type')) | [
19,
2117
] |
def METHOD_NAME(self):
return ServeModelInfoResult(infos=vars(self._pipeline.model.config)) | [
578,
100
] |
def METHOD_NAME(samples: int = ...) -> QtGui.QSurfaceFormat: ... | [
8737,
881,
275
] |
def METHOD_NAME(self):
return "MgmtErrorFormat" | [
168,
275
] |
def METHOD_NAME(self):
self.run_location_tests([
["Catfish", False, []],
["Catfish", False, [], ['Progressive Glove', 'Flippers']],
["Catfish", False, [], ['Progressive Glove', 'Magic Mirror']],
["Catfish", False, [], ['Progressive Glove', 'Moon Pearl']],
["Catfish", True, ['Beat Agahnim 1', 'Magic Mirror', 'Progressive Glove']],
["Catfish", True, ['Beat Agahnim 1', 'Moon Pearl', 'Magic Mirror', 'Flippers']],
["Catfish", True, ['Progressive Glove', 'Hammer']],
["Catfish", True, ['Progressive Glove', 'Flippers']],
["Catfish", True, ['Progressive Glove', 'Progressive Glove', 'Magic Mirror', 'Moon Pearl']],
["Pyramid", False, []],
["Pyramid", True, ['Beat Agahnim 1', 'Magic Mirror']],
["Pyramid", True, ['Hammer']],
["Pyramid", True, ['Flippers']],
["Pyramid", True, ['Progressive Glove', 'Progressive Glove', 'Magic Mirror', 'Moon Pearl']],
["Pyramid Fairy - Left", False, []],
["Pyramid Fairy - Left", False, [], ['Magic Mirror']],
["Pyramid Fairy - Left", False, [], ['Crystal 5']],
["Pyramid Fairy - Left", False, [], ['Crystal 6']],
["Pyramid Fairy - Left", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Hammer', 'Progressive Glove', 'Moon Pearl']],
["Pyramid Fairy - Left", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Progressive Glove', 'Progressive Glove', 'Moon Pearl']],
["Pyramid Fairy - Left", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Beat Agahnim 1']],
["Pyramid Fairy - Right", False, []],
["Pyramid Fairy - Right", False, [], ['Magic Mirror']],
["Pyramid Fairy - Right", False, [], ['Crystal 5']],
["Pyramid Fairy - Right", False, [], ['Crystal 6']],
["Pyramid Fairy - Right", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Hammer', 'Progressive Glove', 'Moon Pearl']],
["Pyramid Fairy - Right", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Progressive Glove', 'Progressive Glove', 'Moon Pearl']],
["Pyramid Fairy - Right", True, ['Crystal 5', 'Crystal 6', 'Magic Mirror', 'Beat Agahnim 1']],
]) | [
9,
6627,
14745
] |
def METHOD_NAME(self, *args, **kwargs):
return brew.conv(
self,
*args,
use_cudnn=self.use_cudnn,
order=self.order,
cudnn_exhaustive_search=self.cudnn_exhaustive_search,
ws_nbytes_limit=self.ws_nbytes_limit,
**kwargs
) | [
1306
] |
def METHOD_NAME(fileid, rootdir=None, #*,
normalize=False,
strictpathsep=None,
_pathsep=PATH_SEP,
**kwargs
):
"""Return a pathsep-separated file ID ("./"-prefixed) for the given value.
The file ID may be absolute. If so and "rootdir" is
provided then make the file ID relative. If absolute but "rootdir"
is not provided then leave it absolute.
"""
if not fileid or fileid == '.':
return fileid
# We default to "/" (forward slash) as the final path sep, since
# that gives us a consistent, cross-platform result. (Windows does
# actually support "/" as a path separator.) Most notably, node IDs
# from pytest use "/" as the path separator by default.
_fileid = fileid.replace(_pathsep, '/')
relpath = _resolve_relpath(_fileid, rootdir,
_pathsep=_pathsep,
**kwargs
)
if relpath: # Note that we treat "" here as an absolute path.
_fileid = './' + relpath
if normalize:
if strictpathsep:
raise ValueError(
'cannot normalize *and* keep strict path separator')
_fileid = _str_to_lower(_fileid)
elif strictpathsep:
# We do not use _normcase since we want to preserve capitalization.
_fileid = _fileid.replace('/', _pathsep)
return _fileid | [
1112,
-1
] |
def METHOD_NAME(image, crop_height, crop_width):
"""Central crop image"""
image_height = image.shape[0]
image_width = image.shape[1]
offset_height = (image_height - crop_height) // 2
offset_width = (image_width - crop_width) // 2
return image[offset_height:offset_height +
crop_height, offset_width:offset_width + crop_width] | [
11727,
712
] |
def METHOD_NAME(self):
model = FlaxDistilBertModel.from_pretrained("distilbert-base-uncased")
input_ids = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
attention_mask = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
output = model(input_ids, attention_mask=attention_mask)[0]
expected_shape = (1, 11, 768)
self.assertEqual(output.shape, expected_shape)
expected_slice = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]])
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4)) | [
9,
1748,
654,
373,
4653,
1632
] |
async def METHOD_NAME(
app: web.Application, user_id: UserID, new_group: dict
) -> dict[str, Any]:
async with get_database_engine(app).acquire() as conn:
return await _db.METHOD_NAME(conn, user_id=user_id, new_group=new_group) | [
129,
21,
846
] |
def METHOD_NAME(self, tree):
coeffs = {}
self._getCoefficientsDict(tree, coeffs)
return coeffs | [
19,
1631
] |
def METHOD_NAME(source: Path, target: Path) -> None:
"""Wrapper around Path.symlink_to that pytest-skips OS Errors.
Useful e.g. for making tests not fail locally due to permission errors.
"""
try:
source.METHOD_NAME(target)
except OSError as exc:
pytest.skip(f"Skipping due to OS error while creating symlink: {exc!r}") | [
953,
24
] |
def METHOD_NAME(self, tab_position=None):
self._next_token()
self._assert_current_token_type_equals("TAB")
if tab_position is not None:
self._assert_current_token_position_equals(tab_position) | [
638,
243,
466,
137,
5678
] |
def METHOD_NAME():
""" Import environment lightning settings from world.rpr_data """
world = bpy.context.scene.world
env_data = world.get('rpr_data', None)
if not env_data:
return
env_data = env_data.to_dict()
environment = env_data.get('environment', None)
if not environment:
return
env_enabled = environment.get('enable', True)
world.rpr.enabled = env_enabled
ibl = environment.get('ibl', None)
if not ibl:
return
ibl_type = ibl.get('type', None)
if ibl_type is not None:
world.rpr.ibl_type = {0: 'COLOR', 1: 'IBL'}[ibl_type]
# Environment light
color = ibl.get('color', None)
if color:
world.rpr.ibl_color = color[:]
ibl_image = ibl.get('ibl_image', None)
if ibl_image:
world.rpr.ibl_image = ibl_image
intensity = ibl.get('intensity', None)
if intensity is not None:
world.rpr.ibl_intensity = intensity
# Rotation Gizmo
gizmo_object = environment.get('gizmo', None)
if gizmo_object:
world.rpr.gizmo = gizmo_object
gizmo_rotation = environment.get('gizmo_rotation', None)
if gizmo_rotation:
world.rpr.gizmo_rotation = gizmo_rotation
# TODO Import Environment Overrides
# TODO Import Sun & Sky | [
86,
988,
15550,
1027
] |
def METHOD_NAME(
self,
response_content: dict,
) -> dict:
"""Parse the actual text response from the objective model.
Args:
response_content: The raw response content from the objective model.
Returns:
The parsed response.
"""
function_name = response_content["function_call"]["name"]
function_arguments = json_loads(response_content["function_call"]["arguments"])
parsed_response = {
"motivation": function_arguments.pop("motivation"),
"self_criticism": function_arguments.pop("self_criticism"),
"reasoning": function_arguments.pop("reasoning"),
"next_ability": function_name,
"ability_arguments": function_arguments,
}
return parsed_response | [
214,
17,
459
] |
def METHOD_NAME(self):
return {
"Visual Studio": 15,
"gcc": 7,
"clang": 4,
"apple-clang": 10,
}.get(str(self.settings.compiler)) | [
1681,
1436,
281,
10565,
14205
] |
def METHOD_NAME(self):
"""Like digest(), but returns a string of hexadecimal digits instead.
"""
h = self._current()
return h.METHOD_NAME() | [
8992
] |
f METHOD_NAME(self): | [
697
] |
def METHOD_NAME(self, record):
"""Serialize a single record.
:param record: Record instance.
"""
style, locale = (
self.url_args_retriever()
if callable(self.url_args_retriever)
else self.url_args_retriever
)
# set defaults if params are not provided
style = style or self._default_style
locale = locale or self._default_locale
style_filepath = get_style_location(style)
return get_citation_string(
self.dump_obj(record), record["id"], style_filepath, locale
) | [
183,
279
] |
def METHOD_NAME(mpstate):
'''initialise module'''
return HorizonModule(mpstate) | [
176
] |
def METHOD_NAME(self):
# There is currently no way for participants to delete their own submission, but I'll add this
# behavior so it can be "switched on" easily later
self.client.login(username="participant", password="pass")
resp = self.client.post(reverse("competitions:submission_delete", kwargs={"pk": self.submission_1.pk}))
self.assertRedirects(resp, reverse("competitions:view", kwargs={"pk": self.competition.pk})) | [
9,
34,
1179,
4268,
24,
1434,
217
] |
async def METHOD_NAME(self, session):
read_saved_searches = await models.saved_searches.read_saved_searches(
session=session
)
assert len(read_saved_searches) == 0 | [
9,
203,
2973,
5217,
610,
35,
245
] |
def METHOD_NAME(quiz,scorer,use_relative_scores=False):
result = {}
for user_answer in quiz.quiz_answers:
result[user_answer.user_id] = calculate_quiz_answer_score(user_answer,scorer,use_relative_scores)
return {k: v for k, v in reversed(sorted(result.items(), key=lambda item: item[1]['score']))} | [
1593,
13463,
3295
] |
f METHOD_NAME(self): | [
9,
137,
401
] |
def METHOD_NAME(self):
action, inputs = self.parse_html_form("id='form-captcha'")
if inputs is None:
self.fail(self._("Captcha form not found"))
else:
recaptcha = ReCaptcha(self.pyfile)
captcha_key = recaptcha.detect_key()
if captcha_key:
self.captcha = recaptcha
response = recaptcha.challenge(captcha_key)
inputs["g-recaptcha-response"] = response
else:
hcaptcha = HCaptcha(self.pyfile)
captcha_key = hcaptcha.detect_key()
if captcha_key:
self.captcha = hcaptcha
response = hcaptcha.challenge(captcha_key)
inputs["g-recaptcha-response"] = inputs["h-captcha-response"] = response
if captcha_key:
self.data = self.load(self.free_url, post=inputs, ref=self.free_url)
else:
self.fail(self._("Could not detect captcha type")) | [
283,
2244
] |
def METHOD_NAME(self):
"""
Set up tests
"""
super().METHOD_NAME()
self.ccx = ccx = CustomCourseForEdX(
course_id=self.course.id,
display_name='Test CCX',
coach=self.coach
)
ccx.save()
self.ccx_locator = CCXLocator.from_course_locator(self.course.id, ccx.id) | [
0,
1
] |
def METHOD_NAME(text, parser=None, base_url=None, forbid_dtd=False, forbid_entities=True): # pylint: disable=missing-function-docstring
if parser is None:
parser = getDefaultParser()
rootelement = _etree.METHOD_NAME(text, parser, base_url=base_url)
elementtree = rootelement.getroottree()
check_docinfo(elementtree, forbid_dtd, forbid_entities)
return rootelement | [
9890
] |
def METHOD_NAME(self, widget):
return GuiUtils.Communicate() | [
767
] |
def METHOD_NAME(self):
x = self.create_data_double_batch()
kernel = self.create_kernel(num_dims=x.size(-1), batch_shape=torch.Size([3, 2]))
res1 = kernel(x).to_dense()[0, 1] # Result of first kernel on first batch of data
new_kernel = kernel[0, 1]
res2 = new_kernel(x[0, 1]).to_dense() # Should also be result of first kernel on first batch of data.
self.assertLess(torch.norm(res1 - res2) / res1.norm(), 1e-4)
# Test diagonal
kernel_diag = kernel(x, diag=True)
actual_diag = res1.diagonal(dim1=-1, dim2=-2)
self.assertLess(torch.norm(kernel_diag - actual_diag) / actual_diag.norm(), 1e-4) | [
9,
1885,
5181,
2152,
2277
] |
def METHOD_NAME(self):
userid = self.request.form.get('userid')
mtool = api.portal.get_tool('portal_membership')
regtool = api.portal.get_tool('portal_registration')
acl_users = api.portal.get_tool('acl_users')
member = mtool.getMemberById(userid)
current_roles = member.getRoles()
if 'Manager' in current_roles and not self.is_zope_manager:
raise Forbidden
pw = regtool.generatePassword()
acl_users.userFolderEditUser(
userid, pw, current_roles, member.getDomains(), REQUEST=self.context.REQUEST)
self.context.REQUEST.form['new_password'] = pw
regtool.mailPassword(userid, self.context.REQUEST) | [
353,
-1
] |
f METHOD_NAME(self, key_template_name): | [
9,
2196,
443
] |
def METHOD_NAME(self, basepaths):
"""
Returns a list of paths where all known (valid) module classes have
been added to each of the given base paths.
"""
valid_module_classes = build_option('valid_module_classes')
paths = []
for path in basepaths:
for moduleclass in valid_module_classes:
paths.extend([os.path.join(path, moduleclass)])
return paths | [
8689,
3336
] |
def METHOD_NAME(self):
reduced = Dataset({'Age':self.age, 'Weight':self.weight, 'Height':self.height},
kdims=self.kdims[1:], vdims=self.vdims)
self.assertEqual(self.table.reduce(['Gender'], np.mean).sort(), reduced.sort()) | [
9,
126,
332,
15090
] |
def METHOD_NAME(bld):
obj = bld.program(features = 'cxx',
source = 'imgpo.cpp',
includes = '. .. ../../',
target = 'imgpo',
uselib = bld.env.LIBRARIES,
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'parego.cpp',
includes = '.. ../.. ../../../',
target = 'parego',
uselib = bld.env.LIBRARIES + ' SFERES',
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'multi.cpp',
includes = '.. ../.. ../../../',
target = 'multi_ehvi',
uselib = bld.env.LIBRARIES + ' SFERES',
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'multi.cpp',
includes = '.. ../.. ../../../',
target = 'multi_parego',
uselib = bld.env.LIBRARIES + ' SFERES',
defines = 'PAREGO',
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'multi.cpp',
includes = '.. ../.. ../../../',
target = 'multi_nsbo',
uselib = bld.env.LIBRARIES + ' SFERES',
defines = 'NSBO',
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'cbo.cpp',
includes = '.. ../.. ../../../',
target = 'cbo',
uselib = bld.env.LIBRARIES + ' SFERES',
use = 'limbo') | [
56
] |
def METHOD_NAME(self):
"""Test that avg memory level 1 data is correctly marginalized."""
memory = np.array([1.0j, 1.0, 0.5 + 0.5j], dtype=complex)
result = marginal_memory(memory, [0, 1])
expected = np.array([1.0j, 1.0], dtype=complex)
np.testing.assert_array_equal(result, expected) | [
9,
1645,
33,
1170,
1654
] |
def METHOD_NAME(self, enforcement_rules_config: dict[str, Any]) -> None:
rules = enforcement_rules_config['rules']
default_rule = next(r for r in rules if r['mainRule'] is True)
other_rules = [r for r in rules if r != default_rule]
logging.debug(f'Default enforcement rule: {json.dumps(default_rule, indent=2)}')
logging.debug(f'Other enforcement rules ({len(other_rules)} total): {json.dumps(other_rules, indent=2)}')
matched_rules = []
for rule in other_rules:
if any(repo for repo in rule['repositories'] if self.bc_integration.repo_matches(repo['accountName'])):
matched_rules.append(rule)
if len(matched_rules) > 1:
logging.warning(f'Found {len(matched_rules)} enforcement rules for the specified repo. This likely means '
f'that one rule was created for the VCS repo, and another rule for the CLI repo. You '
f'should update the configurations in the platform to ensure that the following repos '
f'are all in the same rule group:')
exact_match_rule = None
for rule in matched_rules:
for repo in rule['repositories']:
repo_name = repo['accountName']
if self.bc_integration.repo_matches(repo_name):
logging.warning(f'- {repo_name}')
if repo_name == self.bc_integration.repo_id:
if exact_match_rule:
logging.debug('Found multiple rules that exactly match --repo-id - likely the same '
'name across multiple VCSes. Using the first one.')
else:
exact_match_rule = rule
if not exact_match_rule:
logging.debug('Did not find any rules with a repo name that exactly matched --repo-id; taking the '
'first one.')
self.enforcement_rule = exact_match_rule or matched_rules[0]
elif len(matched_rules) == 0:
logging.info('Did not find any enforcement rules for the specified repo; using the default rule')
self.enforcement_rule = default_rule
else:
logging.info('Found exactly one matching enforcement rule for the specified repo')
self.enforcement_rule = matched_rules[0]
logging.debug(
'Selected the following enforcement rule (it will not be applied unless --use-enforcement-rules is specified):')
logging.debug(json.dumps(self.enforcement_rule, indent=2))
for code_category_type in [e.value for e in CodeCategoryType]:
config = RepoConfigIntegration._get_code_category_object(self.enforcement_rule['codeCategories'],
code_category_type)
if config:
self.code_category_configs[code_category_type] = config | [
0,
11969,
1634
] |
def METHOD_NAME(self):
# declare no dependencies --> run asap, but do not block other steps
rm_pr_label_step = PipelineStep(
name='rm_pr_label',
raw_dict={},
is_synthetic=True,
notification_policy=StepNotificationPolicy.NO_NOTIFICATION,
pull_request_notification_policy=PullRequestNotificationPolicy.NO_NOTIFICATION,
injecting_trait_name=self.name,
script_type=ScriptType.PYTHON3
)
rm_pr_label_step.set_timeout(duration_string='5m')
yield rm_pr_label_step | [
1592,
1910
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.