content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_task_info():
"""Get task info from Rosetta Code
Returns: List of Tuple(task name, task url)
"""
url = "http://www.rosettacode.org/wiki/Category:Programming_Tasks"
soup = get_soup(url)
task_tags = soup.find("div", class_="mw-category").find_all("a")
task_urls = [] # list of task ... | 66,600 |
def sample_action(policy, state):
"""
Samples a policy for an action given the current state.
"""
choices = np.arange(0, policy.shape[1])
probabilities = policy[state]
return np.random.choice(choices, p=probabilities) | 66,601 |
def _plot_clusters(estimator, fdata, *, chart=None, fig=None, axes=None,
n_rows=None, n_cols=None,
labels, sample_labels, cluster_colors, cluster_labels,
center_colors, center_labels, center_width, colormap):
"""Implementation of the plot of the FDataGrid sam... | 66,602 |
def plot(canvas, word, grid, answers):
"""
called by handle_plot() function
draws a box around the word if it is a correct solution
"""
# pulls data from answers dictionary
(iscol, isrev, word_len, x_start, y_start) = answers[word]
(x1, y1, square_dim) = find_coord(x_start, y_start, sgs.WIN... | 66,603 |
def split_flow_into_segments(flow):
"""Splits the flow into multiple segments where a segment is
defined by: data only from endpoint A (request) followed by data only from
endpoint B (response). New data from endpoint A initiates a new segment.
Returns: list of TcpFlow instances with each instance repre... | 66,604 |
def sigD(jax=True, dtype=np.float32):
"""
Pauli 'down' matrix.
PARAMETERS
----------
jax (bool, default True): Toggles whether a Jax or np array is returned.
dtype: the data type of the return value.
"""
vals = [[0, 0],
[1, 0]]
D = np.array(vals, dtype=dtype)
if jax:... | 66,605 |
def test_writing_plot(tmpdir):
"""Testing that we can create write a plot to disk."""
fig = Figure(jinja_env=env, template="line.html_template", title="Simple plot")
plot = fig.add_plot("Energies")
x_axis = plot.add_axis("x", label="Time (ps)")
y_axis = plot.add_axis("y", label="Energy (kcal/mol)"... | 66,606 |
def do_check_package_status(package_id, host_ip):
"""
检查包状态
Args:
package_id:
host_ip:
Returns:
"""
time.sleep(5)
package = AppPkgMapper.get(app_package_id=package_id, host_ip=host_ip)
if package is None:
logger.debug("package record %s not found", package_id)
... | 66,607 |
def is_clockwise(points):
"""
Check if the points given forms a clockwise polygon
:return: True if the points forms a clockwise polygon
"""
a = 0
i, j = 0, 0
for i in range(len(points)):
j = i + 1
if j == len(points): j = 0
a += points[i][X]*points[j][Y] -... | 66,608 |
def upload_chunk_feather(*, data: DataFrame, container: str, dir_path: str,
filename: str) -> NoReturn:
"""
Requires keyword arguments.
Parameters
----------
data: DataFrame
container: str
Storage container name.
dir_path: str
Storage directory pat... | 66,609 |
def filter_stats(stats):
"""Remove individual-level data in the statistics"""
logger.info("Filtering out individual level data in the statistics")
# sex: all
stats.loc[
stats.loc[:, "nindivs_all"].isin(INDIV_LEVELS),
ALL_COLS + FEMALE_COLS + MALE_COLS
] = None
# sex: female
... | 66,610 |
def kl_divergence(p, q):
"""Standard KL divergence."""
return stats.entropy(p, q) | 66,611 |
def calculate_unaberrated_contrast_and_normalization(instrument, design=None, return_coro_simulator=True, save_coro_floor=False, save_psfs=False, outpath=''):
"""
Calculate the direct PSF peak and unaberrated coronagraph floor of an instrument.
:param instrument: string, 'LUVOIR', 'HiCAT', 'RST' or 'JWST'
... | 66,612 |
def validate_category(value):
"""Validator for Node#category. Makes sure that the value is one of the
categories defined in CATEGORY_MAP.
"""
if value not in Node.CATEGORY_MAP.keys():
raise ValidationValueError('Invalid value for category.')
return True | 66,613 |
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read t... | 66,614 |
def dideryServerService(self):
"""
Service server given by valet
Ioinit attributes:
valet is a Valet instance
Context: recur
Example:
do didery server service
"""
if self.valet.value:
self.valet.value.serviceAll() | 66,615 |
def drop_unevaluated_comp(df):
"""Drop unevaluated compounds from a dataframe."""
df = df[df.index.get_level_values(
level=metadata.TREATMENT_GROUP) != metadata.NEGATIVE_CONTROL]
df = df[df.index.get_level_values(level=metadata.MOA) != metadata.UNKNOWN]
return df | 66,616 |
def target_frame():
"""Input target frame."""
return 'IAU_ENCELADUS' | 66,617 |
def associate_node_id(tr, node=""):
"""
Returns a dictionary with key 'id' and value as the ID associated
with the node string.
"""
return {"id": tr.get_uml_id(name=node)} | 66,618 |
def example_data():
"""Create some sample data for testing."""
# van = City(name="Vancouver")
chambar = Restaurant(name="Chambar",
location="568 Beatty St, Vancouver, BC V6B 2L3",
phone="(604) 879-7119",
latitude=49.2810018,
... | 66,619 |
def record(app, db, s3_location):
"""Create a record."""
record = {
'title': 'fuu'
}
record = Record.create(record)
record.commit()
db.session.commit()
return record | 66,620 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Flipr from a config entry."""
hass.data.setdefault(DOMAIN, {})
coordinator = FliprDataUpdateCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id] = coord... | 66,621 |
def build_api_query(req: ExternalAPIRequest) -> str:
""" build_api_query takes a ExternalAPIRequest object and returns a URL with query params """
# if the query options weren't specified, return the url without
# adding to it.
if not req.q:
return req.url
base_url = req.url
if not ba... | 66,622 |
def SET(query):
""" Decorator that marks a method as a SET query handler for some
variable in the genotype-phenotype interface. The decorator
receives as argument the name of the query. For instace, this
decorator is applied to the Synapses.set_weights method as
@SET("synapses:weights").
... | 66,623 |
def setup(bot: Bot) -> None:
"""Set up the ping cog."""
bot.add_cog(Ping(bot)) | 66,624 |
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "Filter UniRef EC list\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"-i","--input",
help="the UniRef EC triplet file [m... | 66,625 |
def pax(src, pkgdir, verbose=0, dry_run=0, TOOL='/bin/pax'):
"""
Create a pax gzipped cpio archive of the given src directory and store it
to the given pkg directory
returns size of archive
"""
dest = os.path.realpath(os.path.join(pkgdir, 'Contents', 'Archive.pax.gz'))
mkpath(os.path.dirnam... | 66,626 |
def get_last_close_str(
fmt=ae_consts.COMMON_DATE_FORMAT):
"""get_last_close_str
Get the Last Trading Close Date as a string
with default formatting ae_consts.COMMON_DATE_FORMAT
(YYYY-MM-DD)
:param fmt: optional output format (default
ae_consts.COMMON_DATE_FORMAT)
"""
retur... | 66,627 |
def load_grad_z(grad_z_dir=Path("./grad_z/"), train_dataset_size=-1):
"""Loads all grad_z data required to calculate the influence function and
returns it.
Arguments:
grad_z_dir: Path, folder containing files storing the grad_z values
train_dataset_size: int, number of total samples in data... | 66,628 |
def feed_json(directory=None, name=None, obj=None):
"""
feed json file at directory with obj
=================================================================
"""
if name is None:
raise ValueError("Name can't be None")
set_dir(directory)
with open(name, 'r') as f:
data = json... | 66,629 |
def extract_games(world_folder):
""" Locate the games in a world folder. """
envs = []
for filename in os.listdir(world_folder):
if filename.endswith(".ulx"):
envs.append(world_folder + "/" + filename)
return envs | 66,630 |
def try_int(options, key, default):
"""Expects a int."""
flatten(options, key, default)
if options[key] != default:
options[key] = int(options[key]) | 66,631 |
def clause_words(clause_tree):
""" Returns the constants in a clause. These will be everything that is not a keyword. """
if clause_tree == []:
return []
elif clause_tree[0] == 'func':
assert(len(clause_tree) == 3)
if clause_tree[2] == []:
return [clause_tree[1]]
else:
return [clause_... | 66,632 |
def list(on):
"""list the command's man page."""
command_list = find_commands_on_specified_platform(on)
click.echo('\n'.join(command_list)) | 66,633 |
def _reusables():
"""Return the reusables object.
We use this wrapper because so that functions which use the reusables variable
can be pickled.
"""
return reusables | 66,634 |
def algo_ration(balls: Balls) -> int:
"""
Algorithmus: Binäre-Suche mit optimiertem Teilverhältnis mit der ersten Kugel,
dann mit Einzelschritten suchen.
Teilverhältnis -> Mittlere Anzahl: 0.10 -> 13.43 ; 0.19 -> 10.94 ;
0.20 -> 10.94 ; 0.21 -> 10.96 ; 0.30 -> 12.30
:param balls: Die Kugeln für ... | 66,635 |
def D50(Stk50, RhoP, Q, C, Eta, W):
"""
Returns the cut point diameter D50
Parameters
----------
Stk50 : float
Stokes number for 50% collection efficiency = 0.23
RhoP : float
particle density (g/cm3)
Q : float
volumetric flow rate (cm3/s)
... | 66,636 |
def rank_transform(arr: np.ndarray, centered=True) -> np.ndarray:
"""
Transform a 1-dim ndarray with arbitrary scalar values to an array with equally spaced rank values.
This is a nonlinear transform.
:param arr: input array
:param centered: if the transform should by centered around zero
:retu... | 66,637 |
def getMagic(fileName):
"""Get file magic."""
mime = magic.Magic(mime=True)
mimeType = mime.from_file(fileName)
return mimeType | 66,638 |
def features(args):
"""
Applys the trained Word2Vec model to translate
the token vectors into feature vectors.
Parameters
----------
args : dict
Configuration dict, typically loaded from YAML file
"""
with timer("Generating Feature Vectors"):
pf.finalize_feature_vectors... | 66,639 |
def inspect_out(*args, **kwargs):
"""Deprecated: Please use inspect_hex()"""
warnings.warn("inspect_out() is deprecated; use inspect_hex().", DeprecationWarning)
return inspect_hex(*args, **kwargs) | 66,640 |
def get_slurm_queue():
"""Get a list of jobs currently in the Slurm queue. """
pattern = ('(?P<job_id>\d+)+\s+(?P<name>[-\w\d_\.]+)\s+(?P<user>[\w\d]+)\s+(?P<group>\w+)'
'\s+(?P<account>[-\w]+)\s+(?P<partition>[-\w]+)\s+(?P<time_limit>[-\d\:]+)\s+'
'(?P<time_left>[-\d\:]+)\s+(?P<s... | 66,641 |
def DirDocNode(arg_dir, the_dir):
"""
This creates a non-clickable node. The text is taken from __doc__ if it exists,
otherwise the file name is 'beautifuled'.
"""
full_module = arg_dir + "." + the_dir
try:
imported_mod = importlib.import_module(full_module)
except ImportError:
... | 66,642 |
def ReadAll(buf):
"""Reads all the chunks from the input buffer (until the end).
Args:
buf: An input buffer to read the chunks from.
Yields:
Chunks of bytes stored in the buffer.
Raises:
ValueError: If the buffer contains an incorrect sequence of bytes.
"""
while True:
chunk = Read(buf)
... | 66,643 |
def is_move_slide_locked(start_hex: tuple, ending_hex: tuple, board_piece_locations: set[tuple]) -> bool:
"""
A move is 'slide locked' if a piece on a physical board cannot be slid from its current hex to an adjacent, empty
hex without having to pick up the moving piece. This function expects start_hex and ... | 66,644 |
def face_detect():
"""
{
"faceimage":"img(base64 or url)"
}
:return: {
"similar":1.0,
"code":"00000",
"errorinfo":"message",
"result":true
}
"""
try:
face_base64 = request.json
face_detect_result = FaceUtils.detect_face(face_base64['faceimage']... | 66,645 |
def uninstall():
"""
Uninstall the Azure Monitor Linux Agent.
This is a somewhat soft uninstall. It is not a purge.
Note: uninstall operation times out from WAAgent at 5 minutes
"""
find_package_manager("Uninstall")
if PackageManager == "dpkg":
OneAgentUninstallCommand = "dpkg -P azu... | 66,646 |
def match_riccati(eq, f, x):
"""
A function that matches and returns the coefficients
if an equation is a Riccati ODE
Parameters
==========
eq: Equation to be matched
f: Dependent variable
x: Independent variable
Returns
=======
match: True if equation is a Riccati ODE, F... | 66,647 |
def find_nonAscii(text):
""" Return the first appearance of a non-ASCII character (in a `Match` object), or `None`. """
regex = re.compile(r'([^\x00-\x7F])+')
return re.search(regex, text) | 66,648 |
def linear_search(arr, x):
"""
Performs a linear search
:param arr: Iterable of elements
:param x: Element to search for
:return: Index if element found else None
"""
l = len(arr)
for i in range(l):
if arr[i] == x:
return i
return None | 66,649 |
def _filter(data, scopedData, scopedLogic):
"""
Filter 'scopedData' using the specified 'scopedLogic' argument.
'scopedData' argument can be:
- a manually specified data array;
- a JsonLogic rule returning a data array;
- a JsonLogic 'var' operation returning part of the data object
... | 66,650 |
def write_file(filename, data, encoding=__ENCODING_UTF8):
"""
write text into file
:param filename: file path to save
:param data: text data
:param encoding: file encoding
:return: None
"""
with open(filename, 'w', encoding=encoding) as f:
f.write(data) | 66,651 |
def _parse_age_specific_distribution(df, parameter, parameter_function, age_bins, full_factorial):
"""Age-specific parameter sampling from a numpy distribution
Create a column in the DataFrame for each age bin, and sample from
the specified distribution.
Modifies the input DataFrame in place.
"""
... | 66,652 |
def generic_tarfile_verify(filepath, method):
"""
Verify that a tar/tgz/tbz/txz file is valid and working.
:param filepath: Filename.
:type filepath: str
:param method: Tarfile read method.
:type method: str
"""
if smart_is_tarfile(filepath):
with tarfile.open(filepath, method)... | 66,653 |
def helicsFederateInfoSetCoreType(fi: 'helics_federate_info', coretype: 'int') -> "void":
"""
"""
return _helics.helicsFederateInfoSetCoreType(fi, coretype) | 66,654 |
def score_hmm_unit_id_shuffle(bst, hmm, n_shuffles=250, normalize=False):
"""Docstring goes here.
Returns
-------
scores : array of size (n_events,)
shuffled : array of size (n_shuffles, n_events)
"""
scores = score_hmm_logprob(bst=bst,
hmm=hmm,
... | 66,655 |
def get_service_rel_tech_decr_by(tech_decreased_share, service_tech_by_p):
"""Iterate technologies with future less service demand (replaced tech)
and get relative share of service in base year
Parameters
----------
tech_decreased_share : dict
Technologies with decreased service
service... | 66,656 |
def cmd_run(client, args):
"""Runs the application container.
Parameters
----------
client : docker.client.DockerClient
The Docker API client.
args : argparse.Namespace
A Namespace object populated with the values of the command line arguments.
Returns
-------
docker.Co... | 66,657 |
def step(grouped_seqs, stop_short=False):
""" Generates tuples of lists of rows for every matching keys
"""
Empty = object()
NoMore = object()
EmptyVal = []
keys = [Empty] * len(grouped_seqs)
vals = [EmptyVal] * len(grouped_seqs)
def update(i, gs):
try:
... | 66,658 |
def get_opencor_algorithm(requested_alg, config=None):
""" Get a possibly alternative algorithm that OpenCOR should execute
Args:
requested_alg (:obj:`Algorithm`): requested algorithm
config (:obj:`Config`, optional): configuration
Returns:
:obj:`Algorithm`: possibly alternative al... | 66,659 |
def test_s3_import__no_pipeline_capabilities(mocker):
"""Test S3 import failure when project has no
pipeline capabilities.
"""
runner = CliRunner()
mocked_login = mocker.patch.object(APIClient, "login", return_value=None)
mocked_import_s3_projects = mocker.patch.object(
APIClient,
... | 66,660 |
def wassertein_distance(u_x: Tensor, s_x: Tensor, u_y: Tensor, s_y: Tensor,
is_target: bool = True, num_iter: int = 10):
"""
Computer Wassertein distance between two multivariate normal distribution X Y
the covariance matrix of Y is assumed to be unit matrix if is_target is True
... | 66,661 |
def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]:
"""Prepares masked tokens inputs/labels for masked language modeling:
80% MASK, 10% random, 10% original."""
if tokenizer.mask_token is None:
raise ValueError(
"This tokeniz... | 66,662 |
def to_json(p):
"""Returns a JSON-compatible dict of a plugin that can be serialized and
sent to clients.
"""
name = (p['vimorg_name'] or p['github_repo_name'] or
p['github_vim_scripts_repo_name'])
author = (p['vimorg_author'].strip() or p['github_author'].strip())
plugin_manager_us... | 66,663 |
def sms_in(request):
"""
sender - the number of the person sending the sms
receiver - the number the sms was sent to
msgdata - the message
"""
sender = request.GET.get("sender", None)
receiver = request.GET.get("receiver", None)
msgdata = request.GET.get("msgdata", None)
if sender is... | 66,664 |
def test_DIGRAC():
"""
Testing DIGRAC
"""
num_nodes = 100
num_features = 3
num_classes = 3
X, A, F, _, edge_index, edge_weight = \
create_mock_data(num_nodes, num_features, num_classes)
A = scipy_sparse_to_torch_sparse(A).to(device)
prob_imbalance_loss = Prob_Imbalance_Loss... | 66,665 |
def my_qq_plot(y_pre, y_tar, title):
"""
Plot qq - plot.
:param y_pre: Prediction
:param y_tar: Target
:param title: Title of the plot
:return:
"""
plt.figure()
plt.scatter(y_tar, y_pre, label="prediction", color="b", marker="x")
plt.plot(range(3), range(3), label="target", color... | 66,666 |
def bytes_to_str(data):
"""bytes to string, used after data transform by internet."""
if isinstance(data, bytes):
return data if sys.version_info.major == 2 else data.decode("ascii")
if isinstance(data, dict):
return dict(map(bytes_to_str, data.items()))
if isinstance(data, tuple):
... | 66,667 |
def test_false_negative():
"""Test false negative function."""
from my_ml.utils.scoring import false_negative
y: np.ndarray = np.array([0, 0, 1, 1, 0, 1])
y_preds: np.ndarray = np.array([1, 0, 0, 0, 1, 0])
tp: float = false_negative(y, y_preds)
assert np.isclose(tp, 3, rtol=.001) | 66,668 |
def best_model_based_selector(train_features, test_features, train_similarity_target, test_similarity_target, regressor):
""" Function used to select the best model based selector """
model_based_score = 0
scaling_factors = ["0.25*mean", "0.5*mean", "median", "1.25*mean", "1.5*mean"]
# scaling_factors = ["0.5*mean"... | 66,669 |
def ex12():
"""
Example 12
Example with state
file name: Example12.py
Copyright Log Opt Co., Ltd.
"""
m1 = Model()
n = 9 #number of activities
state = m1.addState("state")
state.addValue( time=0, value=0 )
state.addValue( time=7, value=0 )
state.addValue( time=14, valu... | 66,670 |
def GetAllCmdOutput(args, cwd=None, quiet=False):
"""Open a subprocess to execute a program and returns its output.
Args:
args: A string or a sequence of program arguments. The program to execute is
the string or the first item in the args sequence.
cwd: If not None, the subprocess's current director... | 66,671 |
def resultados_portafolio(p,w,C):
"""
Dados unos pesos de colocacion para un
portafolio y teniendose los rendimientos y
covarianzas historicas, se obtiene el
rendimiento y volatilidad del portafolio
`p`: matriz con rendimientos historicos del
portafolio
`w`:... | 66,672 |
def arg_parser() -> dict:
"""Parse CLI arguments.
Returns:
dict: parsed arguments in dictionary
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("words", nargs="+", type=str, help="Sentence that will be translated")
return parser.parse_args().__dict__ | 66,673 |
def pml_prompt():
"""
Reads user input given the PML prompt.
"""
return raw_input("pml:> ") | 66,674 |
def out_labels(G, q):
"""Returns a list of each of the labels appearing on the edges
starting at `q` in `G`.
Parameters
----------
G : labeled graph
q : vertex in `G`
Examples
--------
>>> G = nx.MultiDiGraph()
>>> G.add_edge(1, 2, label="a")
>>> G.add_edge(1, 3, label="a")... | 66,675 |
def get_project_root(name, context='local'):
"""find out where a repository lives
context can be 'local' or 'remote' or a repo type ('sf', 'bb', 'git')
"""
is_private = name in private_repos
is_private_value = name in private_repos.values()
if is_private_value:
value = name
for ... | 66,676 |
def relpath(path, start=os.curdir):
"""Return a relative version of a path
flaming - copied from the python 2.7 source for os.path.relpath()
because python 2.5 doesn't have this by default"""
if not path:
raise ValueError("no path specified")
start_list = [x for x in os.path.abspath(sta... | 66,677 |
def IKinBody(Blist, M, T, thetalist0, eomg, ev):
"""Computes inverse kinematics in the body frame for an open chain robot
:param Blist: The joint screw axes in the end-effector frame when the
manipulator is at the home position, in the format of a
matrix with axes as the colu... | 66,678 |
def create_parent_child_relation(parent, child, relation_type, volume):
"""Create parent child relations."""
rr = RecordRelationsParentChild()
click.echo('Creating relations: {0} - {1}'.format(parent['pid'],
child['pid']))
rr.add(
parent=pare... | 66,679 |
def paper1c(sc=1.2):
"""
paper1c - Define params to make pretty 1col fig publication
"""
rescale = sc/1.2
fontSize = rescale*10.
rc('figure', figsize=(3.*sc,2.3*sc))
rc('figure.subplot', left=0.15, right=0.97, bottom=0.18, top=0.95)
rc('lines', linewidth=0.5*rescale)
rc('axes', line... | 66,680 |
def _read_uint8(stream: BinaryIO) -> int:
"""Read an unsigned 8-bit integer from the given byte stream."""
return helpers.read_int(stream, 1, signed=False) | 66,681 |
def config_homepath(homepath, logpath=False, cachepath=False):
"""
Fix path for ini file.
:param homepath: Path to ini file.
:type homepath: str
:param logpath: True if processing log folder, False if not. Default is False.
:type logpath: bool
:param cachepath: True if processing cache fo... | 66,682 |
def orthonormal_initializer(output_size, input_size, debug=False):
"""adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py
Parameters
----------
output_size : int
input_size : int
debug : bool
Whether to skip this initializer
Returns
-------
... | 66,683 |
def get_items(access_token, env, realm_id):
"""
Uses access token to get Item data for Invoice API
"""
half_url = f"{env}/v3/company/{realm_id}/query"
api_parameters = {"query": "select * from Item", "minorversion": "38"}
api_headers = {"Accept": "application/json",
"Authoriz... | 66,684 |
def preload_powers(session):
""" All possible powers in Powerplay. """
session.add_all([
Power(id=0, text="None", eddn='None', abbrev="NON"),
Power(id=1, text="Aisling Duval", eddn='Aisling Duval', abbrev="AIS", home_system_name='Cubeo'),
Power(id=2, text="Archon Delaine", eddn='Archon D... | 66,685 |
def exercise_1(prefix="tst_model_remove_alternative_conformations_1"):
""" Make sure that CA in SER3 gets to the right position. """
inp = iotbx.pdb.input(lines=tst_pdb_str, source_info=None)
model = mmtbx.model.manager(
model_input = inp)
model.remove_alternative_conformations(always_keep_one_conformer=F... | 66,686 |
def create_dummy_tensors_single():
"""
Binary: 1 actual, 1 predicted (tp: 1, fp: 0, fn: 0)
"""
label = torch.tensor([1])
pred = torch.tensor([1])
return (label, pred) | 66,687 |
def uniqueroots(nodes): #(1)
"""Returns a list of the nodes in `nodes` that are not
children of any node in `nodes`."""
result = []
def handle_node(n): #(2)
"""If any of the ancestors of n are in realroots,
just return, otherwise, append n to realroots.
"""
for an... | 66,688 |
async def test_find_system_by_invalid_name(galaxy_fx):
"""
Test that an invalid system will return None.
"""
invalid = await galaxy_fx.find_system_by_name("Fualun")
assert invalid is None | 66,689 |
def autodoc_skip(app, what, name, obj, skip, options):
"""
Hook to tell autodoc to include or exclude certain fields (see :event:`autodoc-skip-member`).
Sadly, it doesn't give a reference to the parent object,
so only the ``name`` can be used for referencing.
:param app: The Sphinx application obj... | 66,690 |
async def get_interval_data(meta_ids: str,
start: str,
end: str):
"""
获取某时间段内的统计数据和
:param meta_ids: 请求的 meta_ids, 以英文 , 分隔的字符串
:param day: 开始时间,例如 2020-12-01
:param end: 结束时间,例如 2020-12-01
:param db: 数据库连接,不需要传
:return:
"""
... | 66,691 |
def convert_tf_config_to_jax_bert(config):
"""Convert TF BERT model config to be compatible with JAX BERT model.
Args:
config: dictionary of TF model configurations
Returns:
dictionary of param names and values compatible with JAX BERT model
"""
unnecessary_keys = ['initializer_range', 'backward_com... | 66,692 |
async def test_storage_is_removed(hass, hass_storage):
"""Test entity map storage removal is idempotent."""
await setup_platform(hass)
entity_map = hass.data[ENTITY_MAP]
hkid = '00:00:00:00:00:01'
entity_map.async_create_or_update_map(
hkid,
1,
[],
)
assert hkid in ... | 66,693 |
def create_shapers(aces_ctl_directory,
lut_directory,
lut_resolution_1d,
cleanup):
"""
Creates sets of shaper colorspaces covering the *Log 2* and *Dolby PQ*
transfer functions and dynamic ranges suitable of use with the 48 nit,
1000 nit, 2000 ... | 66,694 |
def find_sequences_before(context, strip):
"""
Returns a list of sequences that are before the strip in the current context
"""
return [s for s in context.sequences if s.frame_final_end <= strip.frame_final_start] | 66,695 |
def assert_user_props(user_props, expand):
"""
Assert the output object of the zhmc_user module
"""
assert isinstance(user_props, dict) # Dict of User properties
# Assert presence of normal properties in the output
for prop_name in zhmc_user.ZHMC_USER_PROPERTIES:
prop_name_hmc = prop_n... | 66,696 |
def unpack_line_key(key):
"""Retrieve a model instance and options dict from a unique key created by
create_line_key. """
bits = key.split(KEY_SEPARATOR)
instance = unpack_instance_key(*bits[:-1])
options = json.loads(bits[-1])
return (instance, options) | 66,697 |
def profile_stgs(request):
""" Display the users current settings and allow them to be modified """
user = request.user
prof = get_object_or_404(Profile, user=user)
if request.POST:
form = SettingsForm(request.POST)
if form.is_valid():
user.email = form.cleaned_data['ema... | 66,698 |
def pipe(*args, **kwargs):
"""A source that fetches the result of a given YQL query.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'query'. May
contain... | 66,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.