seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | bigcode/self-oss-instruct-sc2-concepts |
def _AddNGrad(op, grad):
"""Copies the gradient to all inputs."""
# Not broadcasting.
return [grad] * len(op.inputs) | bigcode/self-oss-instruct-sc2-concepts |
def oneof(*args):
"""Returns true iff one of the parameters is true.
Args:
*args: arguments to check
Returns:
bool: true iff one of the parameters is true.
"""
return len([x for x in args if x]) == 1 | bigcode/self-oss-instruct-sc2-concepts |
import warnings
from typing import Optional
from typing import Union
from typing import Type
from typing import cast
def _is_unexpected_warning(
actual_warning: warnings.WarningMessage,
expected_warning: Optional[Union[Type[Warning], bool]],
) -> bool:
"""Check if the actual warning issued is unexpected."""
if actual_warning and not expected_warning:
return True
expected_warning = cast(Type[Warning], expected_warning)
return bool(not issubclass(actual_warning.category, expected_warning)) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_pose_loss(gt_pose, pred_pose, vis, loss_type):
"""
gt_pose: [B, J*2]
pred_pose: [B, J*2]
vis: [B, J]
Loss: L2 (MSE), or L1
"""
vis = torch.repeat_interleave(vis, 2, dim=-1) # [B, 1122...JJ]
if loss_type == "L2":
loss = torch.sum((gt_pose - pred_pose) ** 2 * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
elif loss_type == "L1":
loss = torch.sum(torch.abs(gt_pose - pred_pose) * vis, dim=-1) / torch.sum(vis, dim=-1) # [B]
else:
assert False, "Unknown loss type"
return loss | bigcode/self-oss-instruct-sc2-concepts |
def wrap_cdata(s: str) -> str:
"""Wraps a string into CDATA sections"""
s = str(s).replace("]]>", "]]]]><![CDATA[>")
return "<![CDATA[" + s + "]]>" | bigcode/self-oss-instruct-sc2-concepts |
def get_spacing_groups(font):
"""
Return a dictionary containing the ``left`` and ``right`` spacing groups in the font.
"""
_groups = {}
_groups['left'] = {}
_groups['right'] = {}
for _group in list(font.groups.keys()):
if _group[:1] == '_':
if _group[1:5] == 'left':
_groups['left'][_group] = font.groups[_group]
if _group[1:6] == 'right':
_groups['right'][_group] = font.groups[_group]
return _groups | bigcode/self-oss-instruct-sc2-concepts |
def _get_gate_span(qregs, instruction):
"""Get the list of qubits drawing this gate would cover"""
min_index = len(qregs)
max_index = 0
for qreg in instruction.qargs:
index = qregs.index(qreg)
if index < min_index:
min_index = index
if index > max_index:
max_index = index
if instruction.cargs:
return qregs[min_index:]
return qregs[min_index:max_index + 1] | bigcode/self-oss-instruct-sc2-concepts |
def get_AP_parameters(exp):
"""
This function is connect with'Advanced Parameter' button.
Parameters
------
exp: the Ui_Experiment object
Return
------
AP_parameters: list contains all the advanced parameters
"""
conv_fact = float(exp.experiment_conversion_factor.text())
set_gain = float(exp.experiment_setpoint_gain.text())
set_offset = float(exp.experiment_setpoint_offset.text())
sr = float(exp.experiment_shunt_resistor.text())
ts = float(exp.experiment_time_step.text())
avg_num = int(exp.experiment_averag_number.text())
AP_parameters = [conv_fact, set_gain, set_offset, sr, ts,avg_num]
return AP_parameters | bigcode/self-oss-instruct-sc2-concepts |
import requests
def read_data_json(typename, api, body):
"""
read_data_json directly accesses the C3.ai COVID-19 Data Lake APIs using the requests library,
and returns the response as a JSON, raising an error if the call fails for any reason.
------
typename: The type you want to access, i.e. 'OutbreakLocation', 'LineListRecord', 'BiblioEntry', etc.
api: The API you want to access, either 'fetch' or 'evalmetrics'.
body: The spec you want to pass. For examples, see the API documentation.
"""
response = requests.post(
"https://api.c3.ai/covid/api/1/" + typename + "/" + api,
json=body,
headers={
'Accept': 'application/json',
'Content-Type': 'application/json'
}
)
# if request failed, show exception
if response.status_code != 200:
raise Exception(response.json()["message"])
return response.json() | bigcode/self-oss-instruct-sc2-concepts |
def matrix_from_vectors(op, v):
"""
Given vector v, build matrix
[[op(v1, v1), ..., op(v1, vn)],
...
[op(v2, v1), ..., op(vn, vn)]].
Note that if op is commutative, this is redundant: the matrix will be equal to its transpose.
The matrix is represented as a list of lists.
"""
return [[op(vi, vj) for vj in v] for vi in v] | bigcode/self-oss-instruct-sc2-concepts |
def create_user(connection, body, username, fields=None):
"""Create a new user. The response includes the user ID, which other
endpoints use as a request parameter to specify the user to perform an
action on.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
body: JSON formatted user data;
{
"username": "string",
"fullName": "string",
"description": "string",
"password": "string",
"enabled": true,
"passwordModifiable": true,
"passwordExpirationDate": "2020-06-15T13:26:09.616Z",
"requireNewPassword": true,
"standardAuth": true,
"ldapdn": "string",
"trustId": "string",
"memberships": [
"string"
]
}
username(str): username of a user, used in error message
fields(list, optional): Comma separated top-level field whitelist. This
allows client to selectively retrieve part of the response model.
Returns:
HTTP response object returned by the MicroStrategy REST server.
"""
return connection.session.post(
url=f'{connection.base_url}/api/users',
params={'fields': fields},
json=body,
) | bigcode/self-oss-instruct-sc2-concepts |
def plus_all(tem, sum):
"""
:param tem:int, the temperature user entered.
:param sum:int, the sum of temperatures user entered.
This function plus all temperatures user entered.
"""
return sum+tem | bigcode/self-oss-instruct-sc2-concepts |
def check_input(saved_input):
"""Checks for yes and no awnsers from the user."""
if saved_input.lower() == "!yes":
return True
if saved_input.lower() == "!no":
return False | bigcode/self-oss-instruct-sc2-concepts |
def _get_fk_relations_helper(unvisited_tables, visited_tables,
fk_relations_map):
"""Returns a ForeignKeyRelation connecting to an unvisited table, or None."""
for table_to_visit in unvisited_tables:
for table in visited_tables:
if (table, table_to_visit) in fk_relations_map:
fk_relation = fk_relations_map[(table, table_to_visit)]
unvisited_tables.remove(table_to_visit)
visited_tables.append(table_to_visit)
return fk_relation
return None | bigcode/self-oss-instruct-sc2-concepts |
import math
def phaseNearTargetPhase(phase,phase_trgt):
"""
Adds or subtracts 2*math.pi to get the phase near the target phase.
"""
pi2 = 2*math.pi
delta = pi2*int((phase_trgt - phase)/(pi2))
phase += delta
if(phase_trgt - phase > math.pi):
phase += pi2
return phase
if(phase_trgt - phase < -math.pi):
phase -= pi2
return phase | bigcode/self-oss-instruct-sc2-concepts |
def coding_problem_28(word_list, max_line_length):
"""
Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of
strings which represents each line, fully justified. More specifically, you should have as many words as possible
in each line. There should be at least one space between each word. Pad extra spaces when necessary so that each
line has exactly length k. Spaces should be distributed as equally as possible, with the extra spaces, if any,
distributed starting from the left. If you can only fit one word on a line, then you should pad the right-hand side
with spaces. Each word is guaranteed not to be longer than k.
Example:
>>> coding_problem_28(["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"], 16)
['the quick brown', 'fox jumps over', 'the lazy dog']
"""
lines = []
while word_list:
if len(word_list) == 1: # right-align ending word
lines.append('{:>{mll}}'.format(word_list[0], mll=max_line_length))
break
words = []
while len(' '.join(words + word_list[:1])) <= max_line_length and word_list:
words += word_list[:1]
word_list = word_list[1:]
total_spaces = max_line_length - sum(map(len, words))
gaps = len(words) - 1
gap_len = total_spaces // gaps
first_gap_add = total_spaces - gap_len * gaps
lines.append(words[0] + ' ' * (gap_len + first_gap_add) + (' ' * gap_len).join(words[1:]))
return lines | bigcode/self-oss-instruct-sc2-concepts |
def truncate(value):
"""
Takes a float and truncates it to two decimal points.
"""
return float('{0:.2f}'.format(value)) | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.