text string | label_name string | labels int64 |
|---|---|---|
Changed from enrollments to enrollment
).prefetch_related('contents').order_by('-id')
@action(detail=True, methods=['get'])
def contents(self, request, pk=None):
"""Get all contents for a specific course"""
course = self.get_object()
contents = course.contents.all()
ser... | Python | 1 |
std::io::Result::Ok(()) });
/// ```
pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
self.inner.send_to(buf, path.as_ref()).await
}
/// Receives data from the connected address.
///
/// On success, returns the number of bytes received.
///
... | Rust | 0 |
[]], aggr=[[MIN(#person.age)]]\
\n TableScan: person projection=None",
);
}
#[test]
fn test_sum_aggregate() {
quick_test(
"SELECT SUM(age) from person",
"Projection: #SUM(person.age)\
\n Aggregate: groupBy=[[]], aggr=[[SUM(#person.age)]]\
... | Rust | 0 |
ef reset_hist(event):
"""Reset the histogram content."""
app.hist_content.text = app.histogram_plotter.reset()
app.return_to_normal_mode()
app.default_focus()
@error_handler
def edit_hist(event):
"""Edit the histogram."""
app.shift_focus(app.hist_content)
de... | Python | 1 |
#
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 Carsten Igel.
#
# This file is part of simplepycons
# (see https://github.com/carstencodes/simplepycons).
#
# This file is published using the MIT license.
# Refer to LICENSE for more information
#
""""""
# pylint: disable=C0302
# Justification: Code is generated
... | Python | 1 |
#This is a Grade Test Program
while True:
print("\n")
print(" Welcome to Grade Calculator")
print("=== === === === === === === ===")
print('\n')
print("------------------------------------------")
print("1. Total Grade Calculator : ")
print("2. Individual Grade Checker : ")
choice ... | Python | 1 |
--symbols', nargs='+',
default=['BTCUSDT', 'ETHUSDT', 'ADAUSDT', 'DOTUSDT', 'LINKUSDT'],
help='Symbols to collect/trade')
parser.add_argument('--intervals', nargs='+',
default=['1m', '5m', '15m', '1h'],
help='Intervals to co... | Python | 1 |
_ast = index_ast.right.take().unwrap();
output_ast(*index_num_ast, buf);
// その配列のサイズをスタックに積む
buf.output_push_num(index_ast.type_.size as u64);
// サイズ×index番号でオフセットを求めスタックに積む
write_operation(buf, "imul");
index_ast = *index_ast.left.unwrap();
indexing_times += 1;
... | Rust | 0 |
HRESOURCE) -> super::super::Foundation::BOOL;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub fn ClusAddClusterHealthFault(hcluster: *const _HCLUSTER, failure: *const CLUSTER_HEALTH_FAULT, param2: u32) -> u32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub fn... | Rust | 0 |
AccessPolicyResource {
#[serde(flatten)]
pub resource: Resource,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<AccessPolicyResourceProperties>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccessPolicyResourceProperties {
#[serde(rename = "princ... | Rust | 0 |
let evlp1 = [
evlp[0].pow(&[index.max_poly_size as u64]),
evlp[1].pow(&[index.max_poly_size as u64]),
];
let e = &evals
.iter()
.zip(evlp1.iter())
.map(|(es, &e1)| ProofEvaluations::<Fr<G>> {
l: DensePolynomial::eval_polynomial(... | Rust | 0 |
::MAX, 1, 2, 3, 4, 5, 6, 7]);
let c: [u32; 4] = convert_to_u32_m128i_from_lower4_u16_m128i(a).into();
assert_eq!(c, [u16::MAX as u32, 1, 2, 3]);
}
#[test]
fn test_convert_to_u64_m128i_from_lower2_u16_m128i() {
let a = m128i::from([u16::MAX, 1, 2, 3, 4, 5, 6, 7]);
let c: [u64; 2] = convert_to_u64_m128i_from_low... | Rust | 0 |
# Copyright (c) Saga Inc.
# Distributed under the terms of the GNU Affero General Public License v3.0 License.
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
class MessageType(str, Enum):
"""Types of app manager messages."""
MANAGE_APP = "manage-app"
CHECK... | Python | 1 |
184,
"Configured Grid Phases",
options={0: "Three Phase", 1: "Single Phase", 2: "Split Phase"},
),
)
#################
# Advanced Inverter Software Configuration Settings
#################
SENSORS += ( ### no idea why there is a "no work" option, but it's in the spec
SelectRWSensor(
... | Python | 1 |
assert_eq!(9.0, mesh.face_area(face_id));
}
#[test]
fn test_face_normal() {
let mesh = MeshBuilder::new().triangle().build().unwrap();
let face_id = mesh.face_iter().next().unwrap();
let computed_normal = mesh.face_normal(face_id);
assert_eq!(0.0, computed_normal.x);
... | Rust | 0 |
unt used to track the threads that currently have
/// outstanding run-down protection request being tracked by this object.
///
/// The reference count holds two parts, the actual count in the lower bits
/// and the flags bit in the most significant bit of the u64. The flags and
/// reference count ... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from facebook_business.adobjects.abstractobject import AbstractObject
"""
This class is auto-generated.
For any issues o... | Python | 1 |
def push(v, vl, vr, tree):
if vl + 1 == vr:
return
tree[2 * v + 1] = max(tree[v], tree[2 * v + 1])
tree[2 * v + 2] = max(tree[v], tree[2 * v + 2])
tree[v] = min(tree[2 * v + 1], tree[2 * v + 2])
def globalPush(v, vl, vr, tree):
if vl + 1 == vr:
return
push(v, vl, vr, tree)
... | Python | 1 |
wn_log_reader(&repository)?;
let output = match args[2].as_str() {
"csv" => to_csv(reader),
"json" => to_json(reader),
"postgres" => to_postgres(reader, "commits"),
x => return Err(format!("unknown output format '{}'", x)),
};
lines_to_stdout(output)
.map_err(|err| fo... | Rust | 0 |
# weights_only parameter was introduced in PyTorch 1.13.0
if major > 1 or (major == 1 and minor >= 13):
model.load_state_dict(torch.load(full_path, map_location=device, weights_only=True))
else:
model.load_state_dict(torch.load(full_path, map_location=device))
... | Python | 1 |
o one file."
)
)
parser.add_argument("file_path", type=str, help="Path to the markdown file.")
parser.add_argument(
"--translate-only",
action="store_true",
help="Only generate the JS translation.",
)
parser.add_argument(
"--consolidate-only",
action="... | Python | 1 |
["Error parsing option '", arg, "' with value '", value, "': ", &s, "\n"].concat()
})?;
}
}
Ok(())
}
/// Parse a positional argument.
///
/// arg: the argument supplied by the user
/// positional: a tuple containing slot to parse into and the name of the argument
#[doc(hid... | Rust | 0 |
_download))
.await
{
let error_msg = format!("cannot send broadcast subscribe message: {}", err);
error!("{}", error_msg);
Err(RsbtError::FailureReason(error_msg))?;
}
}
}
let sender = web::Data::new(rsbt_command_se... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Python | 1 |
:1 Ip A1:1 C444", WIDTH, HEIGHT, FPS)?;
let mut frame = Frame::default();
for frame_index in 0..frames_count {
canvas.fill(BACKGROUND);
state.render(&mut canvas, WIDTH);
canvas_as_frame(&canvas, &mut frame);
save_frame(&mut video_sink, &frame)?;
sound.fill(0.0);
... | Rust | 0 |
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::{Field, One, PrimeField, UniformRand, Zero};
use array_init::array_init;
use mina_curves::pasta::{fp::Fp as F, pallas::Affine as Other};
use rand::{rngs::StdRng, SeedableRng};
use super::framework::TestFramework;
// Tests add and double gates
#[test]
fn ec_test(... | Rust | 0 |
import ssl
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class APIServerConfig():
log_level: str = field(
default="debug", metadata={"help": "Logging level for the API server."}
)
host: str = field(
default="localhost",
metadata={"help": "Hostname... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
from torch.nn.modules import GroupNorm
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.models.backbones.res2net import Bottle2neck
from mmdet.models.backbones.resnet import BasicBlock, Bottleneck
from mmdet.models.backbones.resnext import Bottleneck as Bottl... | Python | 1 |
base classes
classes.append(obj())
return classes
def getSecCoolFluids():
"""
Returns a list of DigitalData objects, which
contain data for the fits. All objects here
implement the fitFluid() function, which can
be called to set the coefficients before writing
the JSON file... | Python | 1 |
) {
Some(it) => it,
None => return Vec::new(),
};
let krate = module.krate();
vec![krate.into()]
}
#[cfg(test)]
mod tests {
use test_utils::mark;
use crate::fixture::{self};
#[test]
fn test_resolve_parent_module() {
let (analysis, pos) = fixture::position(
... | Rust | 0 |
);
}
}
}
if self.state == ATTACK_STATE {
//back to previous state
if rl.is_mouse_button_pressed(MouseButton::MOUSE_RIGHT_BUTTON) {
self.nextstate = MENU_STATE;
self.state = self.nextstate;
}
... | Rust | 0 |
pub mod day2;
aoc_lib!{ year = 2021 }
// Generated by `scripts/generate.js`
pub type VkDriverId = super::super::vk::VkDriverId;
#[doc(hidden)]
pub type RawVkDriverId = super::super::vk::RawVkDriverId;//! [](https://opensource.org/li... | Rust | 0 |
from festim import FluxBC, k_B
import fenics as f
import sympy as sp
class DissociationFlux(FluxBC):
"""
FluxBC subclass for hydrogen dissociation flux.
-D(T) * grad(c) * n = Kd(T) * P
Args:
Kd_0 (float or sp.Expr): dissociation coefficient pre-exponential
factor (m-2 s-1 Pa-1)
... | Python | 1 |
":[{\"name\":\"beat\",\"type\":\"long\"}]}"}"#)
/// .create();
///
/// let _m = mock("GET", "/subjects/heartbeat-key/versions/latest")
/// .with_status(200)
/// .with_header("content-type", "application/vnd.schemaregistry.v1+json")
/// .with_body(r#"{"subject":"heartbeat-value","version":1,"id":4,"schem... | Rust | 0 |
from pydantic import BaseModel
from typing import Optional
class RecommendationRequest(BaseModel):
escape: Optional[int] = None
relaxation: Optional[int] = None
play: Optional[int] = None
strengthening_family_bonds: Optional[int] = None
prestige: Optional[int] = None
social_interaction: Optiona... | Python | 1 |
"""
=============================
Dynamic background correction
=============================
This example shows how to remove the dynamic background of an EBSD pattern using
:meth:`~kikuchipy.signals.EBSD.remove_dynamic_background`.
More details are given in the
:doc:`pattern processing tutorial </tutorials/pattern_... | Python | 1 |
nput.files[0]) {
alert('Please select an image first');
return;
}
const formData = new FormData();
formData.append('file', fileInput.files[0]);
docume... | Python | 1 |
pub use self::config::{
EvalConfig, EvaluatorChoice, ExecutionMode, Statistics, TimeFormat, TimeRepresentation, Verbosity,
};
pub use self::io_handler::OutputChannel;
pub(crate) use self::io_handler::{create_event_source, EventSource, EventSourceConfig, OutputHandler};
pub use self::csv_input::{CSVEventSource, C... | Rust | 0 |
("parameter `Pages` is deprecated", DeprecationWarning)
r"""证书列表总页数
注意:此字段可能返回 null,表示取不到有效值。
:rtype: int
"""
return self._Pages
@Pages.setter
def Pages(self, Pages):
warnings.warn("parameter `Pages` is deprecated", DeprecationWarning)
self._Pages = Pages
... | Python | 1 |
.take(length)
.read_to_end(&mut buf)
.unwrap_or_else(
|e| {
panic!("{}: {}", err_msg, e);
});
if read_bytes != buf.len() {
panic!("{}: {} bytes read but {} was expected", err_msg, read_bytes, length);
}
buf
}
struct... | Rust | 0 |
add_classic(
bincode::serialize(&command.into_shared()),
topics::SESSION_DISCONNECTED_TOPIC,
)
}
fn xadd_undo_move(&self, command: UndoMove) {
self.xadd_classic(bincode::serialize(&command), topics::UNDO_MOVE_TOPIC)
}
}
impl RedisXAddCommands {
pub fn create(cli... | Rust | 0 |
argsbx)
};
let ops = format!("{:36}", ops);
match op {
OP_MOVE => format!("{} | R({}) := R({})", ops, arga, argb),
OP_MOVEN => format!("{} | R({}) := R({}); followed by {} MOVE ops", ops, arga, argb, argc),
OP_LOADK => format!("{} | R({}) := Kst({})", ops, arga, argbx),
OP... | Rust | 0 |
"""This example lets you dynamically create static walls and dynamic balls
"""
__docformat__ = "reStructuredText"
import pygame
import pymunk
import pymunk.pygame_util
pm = pymunk
def main():
pygame.init()
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
running = True
... | Python | 1 |
Outcome::Passed, Timestamp::Unknown).await.expect("stop run");
run_reporter.finished().await.expect("finish run");
let (run_result, suite_results) = parse_json_in_output(dir.path());
assert_run_result(
dir.path(),
&run_result,
&ExpectedTestRun::new(directory:... | Rust | 0 |
filtered_projects = [p for p in filtered_projects if p.has_late_tasks]
elif selected_card == 2:
filtered_projects = [p for p in filtered_projects if
p.expected_due_date and datetime.now() > p.expected_due_date]
spotlight = [pc.render(project) for project in filtere... | Python | 1 |
from flask import Flask, request, render_template
import os
import random
import redis
import socket
import sys
import hvac
import json
app = Flask(__name__)
# Load configurations
app.config.from_pyfile('config_file.cfg')
button1 = app.config['VOTE1VALUE']
button2 = app.config['VOTE2VALUE']
title = ... | Python | 1 |
not os.path.exists(file_path):
# 백업 오디오 파일 사용 시도
backup_paths = [
Path(resource_path("resources/backup_audio.wav")),
Path(resource_path("resources/audio/backup_audio.wav")),
Path(resource_path("resources/sounds/backup_audio.wav... | Python | 1 |
pLabelInfo: *const VkDebugUtilsLabelEXT,
);
}
extern "C" {
pub fn vkCmdEndDebugUtilsLabelEXT(commandBuffer: VkCommandBuffer);
}
extern "C" {
pub fn vkCmdInsertDebugUtilsLabelEXT(
commandBuffer: VkCommandBuffer,
pLabelInfo: *const VkDebugUtilsLabelEXT,
);
}
extern "C" {
pub fn vkC... | Rust | 0 |
#[allow(dead_code)]
pub fn saw(&self) -> FunctionOsc {
FunctionOsc::new(self.sample_rate, |x| (x - 0.5) * 2.0)
}
#[allow(dead_code)]
pub fn square(&self) -> FunctionOsc {
FunctionOsc::new(self.sample_rate, |x| if x < 0.5 { 1.0 } else { -1.0 })
}
#[allow(dead_code)]
pub ... | Rust | 0 |
/ usize so array access works
min_y: usize,
max_x: usize,
max_y: usize,
}
fn main() {
let contents = fs::read_to_string("data/day3.txt").expect("Error reading file");
let mut fabric = [[0; 1000]; 1000];
for line in contents.lines() {
let claim = parse_line(line);
for x in claim.... | Rust | 0 |
from django.urls import path
from .views import MoviesView
app_name = 'moviesapp' # Добавлено пространство имен
urlpatterns = [
path('', MoviesView.as_view(), name='home'),
] | Python | 1 |
)
arubaWiredBridgeVlanLoopProtectLoopDetectedNotification = NotificationType(
(1, 3, 6, 1, 4, 1, 47196, 4, 1, 1, 3, 1, 1, 5, 0, 2)
)
arubaWiredBridgeVlanLoopProtectLoopDetectedNotification.setObjects(
*(("IF-MIB", "ifIndex"),
("ARUBAWIRED-BRIDGE-MIB", "arubaWiredLoopProtectPortLoopCount"),
... | Python | 1 |
import math
# Kirjoita ohjelma, joka kysyy suorakulmion kannan ja korkeuden.
# Ohjelma tulostaa suorakulmion piirin ja pinta-alan.
# Suorakulmion piiri tarkoittaa sen neljän sivun yhteispituutta.
suorakulmakanta_str = input("Ole hyvä ja anna suorakulmiosi kannan pituus kokonaislukuna:")
suorakulmakanta = int(suoraku... | Python | 1 |
elf.timesolts))
self.timesolts = np.array(self.timesolts, dtype='datetime64[ns]')
for idx, _ts in enumerate(self.timesolts):
self.idx_of_timesolts[_ts] = idx
# 转3-d数组
feature_dim = len(dynafile.columns) - 2
df = dynafile[dynafile.columns[-feature_dim:]]
... | Python | 1 |
{
use super::*;
#[test]
fn filenames() {
assert_eq!(
Files::EgkAllgemein.filename(),
"eGK_allgemeineVersicherungsdaten.xml"
);
assert_eq!(
Files::EgkGeschuetzt.filename(),
"eGK_geschuetzteVersichertendaten.xml"
);
ass... | Rust | 0 |
,
size.0 as i32,
size.1 as i32,
data.buf()
.iter()
.map(|c| [c.r, c.g, c.b, c.a])
.flatten()
.collect::<Vec<u8>>()
.as_slice(),
... | Rust | 0 |
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class AssetMaintenanceTeam(Document):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.
from typing i... | Python | 1 |
args['figure_anchor'] == top_left
dx = -float(xinit)
dy = -float(yinit)
# print(self.positionner.x, self.positionner.y)
if 'bottom' in self.figure_anchor:
self.positionner.y['anchor'] = 'bottom'
if 'right' in self.figure_anchor:
... | Python | 1 |
Some(("foo", false)));
/// assert_eq!(iter.next().map_or(false, |node| node.is_removed()), true);
/// assert_eq!(iter.next().map(|node| (*node.get(), node.is_removed())), None);
/// ```
///
/// [`is_removed()`]: struct.Node.html#method.is_removed
pub fn iter(&self) -> impl Iterator<Item = &Node... | Rust | 0 |
import datetime
import os
mip = "obs"
dat = "IMERG"
var = "pr"
frq = "day"
ver = "v20230407"
# prd = [2001, 2019] # analysis period
prd = [2001, 2020] # analysis period
fac = 86400 # factor to make unit of [mm/day]
# res = [0.25, 0.25] # target horizontal resolution [degree] for interporation (lon, lat)
# res = [... | Python | 1 |
psc::channel::<i32>(1);
let tx2 = tx.clone();
core.spawn(rx.collect().map(|xs| assert_eq!(xs, [1, 2])));
core.spawn(lazy(move || tx.send(1).map(|_| ()).map_err(|e| panic!("{}", e))));
core.run(lazy(move || tx2.send(2))).unwrap();
}
#[test]
fn mpsc_send_unpark() {
let core = Core::new();
let (tx... | Rust | 0 |
for d in dashboards if d["id"] == dashboard_id), None
)
if not selected_dashboard:
await query.answer("未找到该面板", show_alert=True)
return
if selected_dashboard["is_default"]:
await query.answer("这已经是默认面板了", show_alert=True)
return
# 直接切换默... | Python | 1 |
class Solution:
def matrixScore(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
res = (1 << (m - 1)) * n
for j in range(1, m):
val = 1 << (m - 1 - j)
set_count = 0
for i in range(n):
if grid[i][j] == grid[i][0]:
... | Python | 1 |
34.567, FluentNumberFormat.DECIMAL_ZERO, "1235"), # Rounds up
(1234.567, FluentNumberFormat.DECIMAL_ONE, "1234.6"), # Rounds up
(1234.567, FluentNumberFormat.DECIMAL_TWO, "1234.57"), # Rounds up
(1234567.89, FluentNumberFormat.WITH_COMMAS, "1,234,567.89"),
(1234567.89, FluentNumberFormat... | Python | 1 |
from collections import defaultdict
class PreferencePairGenerator:
def __init__(self, reward_model):
self.reward_model = reward_model
def generate_preference_pairs(self, responses, P=10):
"""Generate preference pairs by scoring and ranking the responses."""
grouped = defaultdict(list)... | Python | 1 |
# Copyright 2022 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Python | 1 |
nvention the lifetime `'t` in this crate is the lifetime of the input text.
//! Almost all structures with a lifetime are bound to this lifetime.
use thiserror::Error;
#[cfg(feature = "compile")]
pub mod compile;
mod filter;
pub mod rule;
pub mod rules;
pub mod tokenizer;
pub mod types;
pub(crate) mod utils;
pub use ... | Rust | 0 |
import pygame
import sys
import time
import numpy as np
pygame.init()
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Test Gizmo")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
Green_trans = (159, 255, 159)
LINE_X = WIDTH // 2
... | Python | 1 |
6K1.verify(&public_key, &msg_hash, &signature);
java_safe_set_boolean_field!(_env, result_jobject, result, "booleanResult");
result_jobject.into_inner()
}
#[cfg(feature = "wedpr_f_signature_secp256k1")]
#[no_mangle]
/// Java interface for
/// 'com.webank.wedpr.crypto.NativeInterface->secp256k1RecoverPublicKey... | Rust | 0 |
r(|e| Error::new(ErrorKind::Other, e.to_string()))?;
match resp.status().as_u16() {
// not modified
304 => Ok(Config::NotChanged),
404 => Ok(Config::NotFound),
200 => {
let resp: Response = resp
.json()
.awai... | Rust | 0 |
import torch
from timm.models.vision_transformer import VisionTransformer
def get_pretrained_url(key):
URL_PREFIX = "https://github.com/lunit-io/benchmark-ssl-pathology/releases/download/pretrained-weights"
model_zoo_registry = {
"DINO_p16": "dino_vit_small_patch16_ep200.torch",
"DINO_p8": "di... | Python | 1 |
*array.offset(pos.wrapping_add(amount).wrapping_add(1 as
libc::c_int
as
libc::c_... | Rust | 0 |
"""
Contains paths to dataset, working directory, and tfrecords
"""
import os
import time
# TODO Set path
COLOR_IMAGES = "..../unsupervised_llamas/color_images"
GRAYSCALE_IMAGES = "..../unsupervised_llamas/grayscale_images"
LABELS = "..../unsupervised_llamas/labels"
# TODO set path
WORKING_DIRECTORY = ".../some_path... | Python | 1 |
from .base_selector import BasePoisonNodeSelector
class DegreeBasedSelector(BasePoisonNodeSelector):
def select_poison_nodes(self, victim_nodes, num_poison_nodes):
mapped_nodes = self._map_victim_nodes(victim_nodes)
degree_dict = dict(self.homo_g.degree())
sorted_target_nodes = sorted(map... | Python | 1 |
ior, Pointer},
key_entry::{KeyEntry, PositionIndex},
modify::{CompareSwap, CompareSwapFn, Modification, Operation, PersistenceMode},
root::{AnyTreeRoot, Root, TreeRoot},
serialization::BinarySerialization,
state::{ActiveState, State},
unversioned::{Unversioned, UnversionedTreeRoot},
versione... | Rust | 0 |
Callback<Option<Task>>,
}
#[function_component(TasksList)]
pub fn tasks_list(
TasksListProps {
tasks,
selected_task,
on_task_select,
}: &TasksListProps,
) -> Html {
tasks
.iter()
.map(|task| {
let task_is_selected = selected_task
.clone()... | Rust | 0 |
eyboard_name,
))
}
}
fn assert_defined_keyboards_equal(
interpreter: &mut Interpreter,
spec_code: &str,
) {
let result = library::get_defined_devices_list(interpreter).unwrap();
let expected =
interpreter.execute_in_main_environment(spec_code)... | Rust | 0 |
``
fn find_all<F>(self, f: F) -> Vec<T>
where
F: Fn(&T) -> bool + Sync,
T: Send,
{
self.find_map_all(|x| f(&x).then(move || x))
}
/// Low-level API for manually implementing mapping and reducing.
///
/// # Example
///
/// ```rust
/// # use rayoff::*;
/... | Rust | 0 |
ssert_eq!(p1(s), "99332");
assert_eq!(p2(s), "DD483");
}
#[test]
fn ex1() {
let s = include_str!("input/d02_ex1.txt");
assert_eq!(p1(s), "1985");
assert_eq!(p2(s), "5DB3");
}
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
//... | Rust | 0 |
n_1e-20.hkl')
# hkl.dump(y_train, DATA_PATH+'y_train_1e-20.hkl')
# hkl.dump(x_test, DATA_PATH+'x_test_1e-20.hkl')
print(sy[sy<=MIN_STD_Y].shape)
DATA_PATH = 'C:/kaggle/CD 1/'
for i1 in tqdm(range(1,9)):
if i1 == 1:
lower = 2
else:
lower = 1
for j1 in range(lower,13):
df_i_j = pd.... | Python | 1 |
current_time = get_current_time()
if current_time > market_close_time:
log_message(
"Market is closed. Waiting for next market open...", "DEBUG"
)
break
trades_data = await fetch_trades(sess... | Python | 1 |
()
.map(|(id, (v, i))| (id.clone(), (fun(v), i.clone())))
.collect();
#[cfg(feature = "dot")]
{
graph.labels = self.labels.clone();
}
graph
}
/// Returns true if the graph has cycles.
///
/// ```rust
/// use graphlib::Graph;
... | Rust | 0 |
from .__meta__ import *
try:
from tracer.packageManagers.ipackageManager import IPackageManager
from tracer.packageManagers.dnf import Dnf
except ImportError: pass
@unittest.skipIf((DISTRO != 'fedora') and (DISTRO != 'mageia'), "Skipping tests because they are distro-specific")
class TestDnf(unittest.TestCase):
def... | Python | 1 |
s, to make sure our test doesn't leak memory
let _ignore: Ref<String> = unsafe { mem::transmute((pointer, cell)) };
}
#[test]
fn test_as_aref() {
fn get_str(x: &impl AsARef<String>) -> ARef<str> {
ARef::map(x.as_aref(), |x| x.as_str())
}
let a = RefCell::new("he... | Rust | 0 |
layout_path;
let path: &Path = match general.layout {
Layout::Contents(ref contents) => {
tempfile = NamedTempFile::new()?;
tempfile.write_all(contents.as_bytes())?;
tempfile.flush()?;
tempfile.path()
}
Layout::M... | Rust | 0 |
pub items: Option<Vec<Item>>,
#[serde(default)]
pub folders: Option<Vec<Folder>>,
#[serde(default)]
pub share_index: Option<ShareIndex>,
#[serde(default)]
pub sub_shares: Option<HashMap<String, Share>>,
}
impl Share {
pub fn to_secret_item(&self, path: &str) -> Result<SecretItem, APIError> ... | Rust | 0 |
altitude 20000km
M = 6.42 * 10**23 #Mass of Mars
R = 3400 * 10**3 #Radius of Mars
h = 20000 * 10**3 #Altitude
G = 6.67 * 10**(-11) #Gravitational Constant
v0 = np.sqrt(G*M/(R+h)) #Velocity for circular Orbit
ve = np.sqrt(2) * v0
time_max = 2000000 #Max time for simulation considered
dt = 1000 #Step size such that 200... | Python | 1 |
in game.
///
/// This system should be run after all other systems that affect kinematics have run.
#[derive(Debug, Default, new)]
pub struct ObjectKinematicsUpdateSystem;
/// `ObjectKinematicsUpdateSystemData`.
#[derive(Derivative, SystemData)]
#[derivative(Debug)]
pub struct ObjectKinematicsUpdateSystemData<'s> {
... | Rust | 0 |
while True:
try:
n = int(input())
if n == 0:
print('vai ter copa!')
else:
print('vai ter duas!')
except EOFError:
break
| Python | 1 |
ean_matrix_slice_norm,
norm::test_euclidean_vector_metric,
|| should_panic!(norm::test_euclidean_vector_metric_bad_dim()),
norm::test_euclidean_matrix_metric,
|| should_panic!(norm::test_euclidean_matrix_metric_bad_dim()),
norm::test_euclidean_matrix_slice_metric,
|| should_panic!(norm::test_euclidean_matrix_slice_metr... | Rust | 0 |
apper around `X509` enabling things like Serde serialization and fingerprint caching.
#[derive(Clone, DataSize)]
pub struct TlsCert {
/// The wrapped x509 certificate.
#[data_size(skip)] // Skip OpenSSL type.
x509: X509,
/// Cached certificate fingerprint.
cert_fingerprint: CertFingerprint,
//... | Rust | 0 |
::v1::ObjectMeta>,
/// Webhooks is a list of webhooks and the affected resources and operations.
/// +optional
/// +patchMergeKey=name
/// +patchStrategy=merge
#[prost(message, repeated, tag="2")]
pub webhooks: ::prost::alloc::vec::Vec<ValidatingWebhook>,
}
/// ValidatingWebhookConfigurationList... | Rust | 0 |
compression: BincodeCompression<Ch, B>,
chunks_iter: impl IntoIterator<Item = (PointN<N>, Ch)>,
) -> Self
where
B: Copy,
{
// Only do one parallel batch at a time to avoid decompressing the entire map at once (assuming the underlying storage
// does compression).
... | Rust | 0 |
xchange_dimensions={self._parameter_name: s_range},
exchange_criterium=exchange_criterium, steps_between_trials=steps_between_trials)
if (exchange_trajs):
self.exchange_param = "trajectory"
else:
self.exchange_param = "_currentPosition"
self._ex... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from vtkmodules.vtkCommonCore import (
vtkFloatArray,
vtkLookupTable,
)
from vtkmodules.vtkCommonDataModel import vtkTable
from vtkmodules.vtkChartsCore import vtkChartParallelCoordinates
from vtkmodules.vtkRenderingCore import vtkColorTransferFunction
fr... | Python | 1 |
}
for value in &self.modes {
my_size += ::protobuf::rt::enum_size(6, *value);
};
for value in &self.storageTypes {
my_size += ::protobuf::rt::enum_size(7, *value);
};
for value in &self.storageIds {
my_size += ::protobuf::rt::string_size(8, &va... | Rust | 0 |
str())
{
Testbed::from_builders(0, vec![builders[i]]).run()
} else {
eprintln!("Invalid example to run provided: '{}'", demo);
}
}
Command::RunAll => Testbed::from_builders(0, builders).run(),
Command::List => {
for ... | Rust | 0 |
# 文件名: src/postprocess.py
import json
from jsonschema import validate, ValidationError
from src.schemas import REQUIREMENTS_SCHEMA, BDD_SCHEMA, SEQUENCE_SCHEMA
# ========== 基础验证 ==========
def validate_json(obj, schema):
"""用 schema 验证 JSON 结构"""
if isinstance(obj, str):
try:
obj = json.loa... | Python | 1 |
t!(header
.find_entry_or_err(&IndexSignatureTag::RPMSIGTAG_MD5)
.is_ok());
assert!(header
.find_entry_or_err(&IndexSignatureTag::RPMSIGTAG_SHA1)
.is_ok());
}
}
<reponame>lpalmes/relay
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source c... | Rust | 0 |
t isinstance(tag, tuple): # the key has to be tuple (TagName, SignalName); elements with key of str type should be dropped
continue
if row[4] in ('USD-F64', 'USR-PVI'): # InstrumentType
sql_select = f"""
SELECT d.DataItemName, d.Value, CASE
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.