text string | label_name string | labels int64 |
|---|---|---|
from collections import deque, defaultdict
def solution(edges):
max_node = max(max(edges, key = lambda x : x[0])[0], max(edges, key = lambda x : x[1])[1])
in_graph = [[] for _ in range(max_node + 1)]
out_graph = [[] for _ in range(max_node + 1)]
find_start = defaultdict(int)
for s, e in edges:... | Python | 1 |
ub mod context_data;
pub mod memory_layout;
use self::context_data::ContextData;
use crate::arch::target_arch::device::cpu;
use crate::arch::target_arch::paging::{PAGE_MASK, PAGE_SIZE};
use crate::kernel::manager_cluster::{get_cpu_manager_cluster, get_kernel_manager_cluster};
use crate::kernel::memory_manager::data_t... | Rust | 0 |
loyment complete 🚀! Your app is now available for serving in the standalone folder '{}'! You can run it by executing the `server` binary in that folder.", &output_path.to_str().map(|s| s.to_string()).unwrap());
Ok(0)
} else {
// If we don't have the executable, throw an error
Err(DeployErr... | Rust | 0 |
basis: unit!(90 pct),
size: size!(100 pct, 90 pct),
padding: rect!(30 px),
},
..Default::default()
};
let column = NodeBundle {
style: style! {
flex_direction: ColumnReverse,
size: size!(33 pct, 100 pct),
padding: rect!(10 px),
... | Rust | 0 |
#!/usr/bin/env python
import functools as func
import glob
import re
from os import path as osp
import numpy as np
url_prefix = 'https://github.com/open-mmlab/mmdetection3d/blob/master/'
files = sorted(glob.glob('../configs/*/README.md'))
stats = []
titles = []
num_ckpts = 0
for f in files:
url = osp.dirname(f... | Python | 1 |
", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my",
"ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl",
"so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi",
"wo", "xh", "yi", "yo", "zh",... | Rust | 0 |
-> u32 {
// the address is 32-bit aligned by this point so adding 2 like this is safe.
let offset_lo = Self::io_off(addr);
match offset_lo {
ioregs::DMA0CNT_L => return self.dma.channel(DMAChannelIndex::DMA0).control() as u32,
ioregs::DMA1CNT_L => return self.dma.channe... | Rust | 0 |
Value=[11,22,44,55,32,45,22]
total=sum(Value)
print(total) | Python | 1 |
ls.parsers.rst.directives'),
('py:mod', 'sphinx.ext'),
('py:obj', 'sphinx.util.relative_uri'),
('rst:role', 'c:any'),
('std:confval', 'autodoc_inherit_docstring'),
('std:confval', 'automodule_skip_lines'),
('std:confval', 'autossummary_imported_members'),
('std:confval', 'gettext_language_te... | Python | 1 |
4 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If pr... | Python | 1 |
from sklearn.metrics import confusion_matrix
import numpy as np
from .embedding_tools import load_or_compute_projections
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(... | Python | 1 |
"""
Copyright © 2020-2025 Ralph Seichter
This file is part of "Fangfrisch".
Fangfrisch is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fan... | Python | 1 |
# function to Calculate Monthly installment
def calculate_monthly_installment(loan_amount, tenure, interest_rate):
# Converting annual interest rate to monthly and calculating monthly interest rate
monthly_interest_rate = (interest_rate / 12) / 100
# Calculating the total number of monthly installments
... | Python | 1 |
import math
def circle_stats(radius):
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
return area, circumference
a, c = circle_stats(3)
print("Area: ", a, "Circumference: ", c) | Python | 1 |
'''
Demonstrate different transtree plotting options
'''
import covasim as cv
import sciris as sc
tstart = sc.tic()
plot_sim = 0
verbose = 0
simple = 1
animated = 1
animate_days = 1
iday = 15
pop_type = 'random'
lkeys = dict(
random='a',
hybrid='hswc'
)
tp = cv.test_prob(start_day=ida... | Python | 1 |
_base_ = './fcos_r50-caffe_fpn_gn-head_1x_coco.py'
# model settings
model = dict(
backbone=dict(
depth=101,
init_cfg=dict(
type='Pretrained',
checkpoint='open-mmlab://detectron/resnet101_caffe')))
| Python | 1 |
pub struct tdTPM_IDENTITY_PROOF {
pub ver: TPM_STRUCT_VER,
pub labelSize: UINT32,
pub identityBindingSize: UINT32,
pub endorsementSize: UINT32,
pub platformSize: UINT32,
pub conformanceSize: UINT32,
pub identityKey: TPM_PUBKEY,
pub labelArea: *mut BYTE,
pub identityBinding: *mut BYTE... | Rust | 0 |
def somar_elementos(lista):
return sum(lista)
numeros = [1, 2, 3, 4, 5]
# Testando a função
print(f"A soma dos elementos da lista {numeros} é: {somar_elementos(numeros)}") | Python | 1 |
import json
import re
import sys
from nostril_detector import nonsense_detector
import enchant
from secrets_verifying_service import verify_secret
def import_json(json_path):
try:
with open(json_path, "r", encoding="utf-8") as file:
raw_json = file.read()
cleaned_json = re.sub(r'(... | Python | 1 |
gree on handshake version for client connection".into()),
}
}
#[cfg(target_family = "unix")]
fn setup_unix_multiplexer(path: &str) -> Result<Multiplexer, Error> {
let unix = UnixStream::connect(path)?;
Multiplexer::setup(unix, &[0, 5, 7])
}
fn setup_tcp_multiplexer(address: &str) -> Result<Multiplexer, E... | Rust | 0 |
destination_device: u8,
pub command_id: u8,
pub category: u8,
pub parameter: u8,
pub data_type: u8,
pub operation: u8,
pub data: Vec<u8>,
}
impl RawCommand {
/// Takes the BLE name of the camera and returns a new BluetoothCamera instance
pub fn from_raw(data: &[u8]) -> Result<Self, Com... | Rust | 0 |
return lambda fn: fn
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
# Numba keeps original function around as append.py_func
append_args = inspect.getfullargspec(append.py_func).args
except (TypeError, AttributeErr... | Python | 1 |
es(add_dnas_calls)
.return_const(());
dna_store
.expect_add_entry_defs::<Vec<_>>()
.times(add_entry_defs_calls)
.return_const(());
dna_store
}
}
/// Read-only access to a DnaStore, and only for DNAs
pub trait DnaStoreRead: Default + Send + Sync {
... | Rust | 0 |
index += 4;
}
codes[0]
}
use std::io;
use super::{
consteval_expression, get_binary_operator, get_unary_operator, Associativity, BinaryOperator,
Block, Parser, ParserError, Precedence, UnaryOperator, MIN_OPERATOR_PRECEDENCE,
};
use crate::lexer::Token;
/// An expression in `Lua` can be:
///
/... | Rust | 0 |
"""Convert an :class:`omf.VolumeElement` to :class:`discretize.TensorMesh`."""
geometry = element.geometry
h = [geometry.tensor_u, geometry.tensor_v, geometry.tensor_w]
orientation = np.array(
[
geometry.axis_u,
geometry.axis_v,
geom... | Python | 1 |
Operation::Inc),
"dec" => Ok(Operation::Dec),
_ => Err(format!("Couldn't parse `{}` as operation", input)),
}
}
}
#[derive(Clone, Debug)]
pub struct Condition {
pub register: String,
pub comparison: Comparison,
pub value: isize,
}
impl Condition {
fn from_parts(part... | Rust | 0 |
messages: vec![],
log: vec![],
data: Some(to_binary(&callback)?),
})
}
pub fn add_file<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
env: Env,
path: String,
content_type: String,
time: u64,
content: Vec<u8>,
mode: String,
) -> StdResult<HandleResponse>... | Rust | 0 |
::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct NodeId(pub(crate) &'static str);
impl From<&'static str> for NodeId {
fn from(s: &'static str) -> Self {
Self(s)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct DagInde... | Rust | 0 |
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
... | Rust | 0 |
ender, receiver) = mpsc::unbounded_channel();
let watcher = sioctl.watch(move |control| {
if let Err(error) = sender.send(control.clone()) {
println!("Error sending sioctl message: {}", error);
}
});
let mut stream = stream::iter(controls).chain(receiver)... | Rust | 0 |
for DayGameState {
fn on_state_start(&self, ecs: &mut ECS) {
register_core_systems(ecs);
ecs.add_system(Box::new(mouse_click_system));
ecs.add_system(Box::new(mouse_cursor_system));
ecs.add_system(Box::new(day_state_countdown));
if ecs.read_res::<StateTimer>().countdown_s <... | Rust | 0 |
nge(num_sys)]
sacrelogger.info(f'Found {num_sys} systems.')
if not paired_test_mode:
# Bootstrap resampling or the usual single score computation mode
sigs = {}
scores = defaultdict(list)
scores['System'] = sys_names
for sys_name, system in n... | Python | 1 |
r = dhtxx::Dht22::new(
fake_pin,
|| Instant::now(),
|instant| instant.elapsed(),
None,
)?;
let result = sensor
.read(|duration| tokio::time::sleep(duration.into()))
.await?;
assert_eq!(result.get_temperature(), -25.7f32);
Ok(())
}
#[tokio::test]
async fn... | Rust | 0 |
update_last_error(err),
},
_ => new_error("Not a Uri Value"),
},
None => new_error("Invalid Value reference"),
};
std::ptr::null()
}
<filename>crates/base/src/syscalls/arm-linux.rs
use ::core::{
hint::unreachable_unchecked,
result::Result::{
self,
... | Rust | 0 |
Res<AssetServer>) {
commands
.spawn_bundle(OrthographicCameraBundle::new_2d())
.insert(MainMenuUi {});
commands
.spawn_bundle(SpriteBundle {
texture: asset_server.load("images/pyrite.png"),
..Default::default()
})
.insert(MainMenuUi {});
// F... | Rust | 0 |
"""
Geometrical transformations
==============================
This examples demos some simple geometrical transformations on a Racoon face.
"""
import numpy as np
import scipy.misc
from scipy import ndimage
import matplotlib.pyplot as plt
face = scipy.misc.face(gray=True)
lx, ly = face.shape
# Cropping
crop_face = ... | Python | 1 |
c = "*Required features: 'Win32_System_Registry'*"]
pub const REGSTR_VAL_ESDI: &'static str = "ESDI\\";
#[doc = "*Required features: 'Win32_System_Registry'*"]
pub const REGSTR_VAL_EXISTS: &'static str = "Exists";
#[doc = "*Required features: 'Win32_System_Registry'*"]
pub const REGSTR_VAL_EXTMEM: &'static str = "ExtMe... | Rust | 0 |
.style("--background-color", "var(--background-secondary-alt)")
.style("--text-color", "var(--ui-text)")
})
};
pub static ref BUTTON_ICON_RIGHT: String = class! {
.style("font-size", "20px")
.style("margin-left", "13px")
};
pub static ref BUTTON_TEXT: String = class! {
.style("... | Rust | 0 |
/libcnb.rs<gh_stars>1-10
//! This crate provides a library to implement [Cloud Native Buildpacks](https://buildpacks.io/).
// Enable rustc and Clippy lints that are disabled by default.
// https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unused-crate-dependencies
#![warn(unused_crate_dependencies)... | Rust | 0 |
),
]
# hook for doxygen
def run_doxygen(folder):
"""Run the doxygen make command in the designated folder."""
try:
retcode = subprocess.call("cd %s; make doxygen" % folder, shell=True)
retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True)
retcode = subprocess.call("mkdir _... | Python | 1 |
en"],
),
message="Login successful",
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Login failed: {str(e)}")
raise HTTPException(500, "Login failed")
@auth_router.post("/token", response_model=Token)
def token_for_swagger(
form_d... | Python | 1 |
raise NotImplementedError()
# mbbox = Bbox(*mean_cuboid(cluster))
# dist = (segment_iou(mbbox, s) for s in cluster)
# nearest_pos, _ = max(enumerate(dist), key=lambda e: e[1])
# return cluster[nearest_pos]
def merge_cluster(self, cluster):
label, label_score = self.... | Python | 1 |
n<Box<dyn Future<Output = Result<(), Box<dyn error::Error>>> + Send>>
+ Send
+ Sync
+ 'a,
>;
pub async fn pass_back<C>(
request_body_bytes: &[u8],
app_secret: &str,
ctx: C,
callback: Arc<PassBackCallbackFn<'_, C>>,
) -> PassBackResponse {
match form_urlencoded::parse(request... | Rust | 0 |
ne()
assert hass.states.get("scene.test").state == now.isoformat()
assert len(calls) == 1
assert calls[0].domain == "light"
assert calls[0].service == "turn_on"
assert calls[0].data.get("transition") == 42
async def test_restore_state(
hass: HomeAssistant, entities, enable_custom_integration... | Python | 1 |
p='An optional, textual description for the HTTPS health check.')
def Run(self, args):
"""Issues the request necessary for adding the health check."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
health_check_ref = self.HTTPS_HEALTH_CHECKS_ARG.ResolveAsResource(... | Python | 1 |
"""
-------------------------------------------------------
Assignment 4, Task 3
-------------------------------------------------------
Author: David Brown
ID: 999999999
Email: dbrown@wlu.ca
__updated__ = "2023-02-21"
-------------------------------------------------------
"""
# see t04.py
| Python | 1 |
_some() { 1 } else { 0 };
Self::list_where_name_le_inner(conn, name_le, offset, filter).and_then(|mut res| {
if let Some(offset_id) = offset_id {
for (i, user) in res.iter().enumerate() {
if &user.id == offset_id {
let offset: i64 = (i + 1)... | Rust | 0 |
# -*- coding: utf-8 -*-
"""."""
import sys
from PySide6 import QtCore, QtGui, QtQml
APPLICATION_NAME = 'br.com.justcode.Qt'
ORGANIZATION_NAME = APPLICATION_NAME.split('.')[2]
ORGANIZATION_DOMAIN = '.'.join(APPLICATION_NAME.split('.')[0:3])
BASE_DIR = QtCore.QDir(QtCore.QFileInfo(__file__).absolutePath())
QML_DIR = ... | Python | 1 |
as_recharge_delay(&mut self) -> _HPOSC_BIAS_RECHARGE_DELAYW {
_HPOSC_BIAS_RECHARGE_DELAYW { w: self }
}
#[doc = "Bits 3:4 - 4:3\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved2(&mut... | Rust | 0 |
Regex;
use reqwest::blocking::Client;
use reqwest::Url;
use sha2::{Digest, Sha256, Sha384, Sha512};
use std::collections::HashMap;
use std::default::Default;
use crate::css::embed_css;
use crate::js::attr_is_event_handler;
use crate::opts::Options;
use crate::url::{clean_url, create_data_url, is_url_and_has_protocol, ... | Rust | 0 |
ctx.kernels().multiply_slice::<T>();
let a_dim_steps = dim_steps_as_ulong4(a.dim_steps);
let b_dim_steps = dim_steps_as_ulong4(b.dim_steps);
let out_dim_steps = dim_steps_as_ulong4(out.dim_steps);
let a_offsets = tensor_view_offsets_as_ulong4(a);
let b_offsets = tensor_view_offsets_as_ulong4(b);
... | Rust | 0 |
["fail", "error", "incorrect", "missing core logic", "does not align", "significant issues"]
if any(keyword in review_lower for keyword in negative_keywords):
if decision != GUARDRAIL_BLOCK: decision = GUARDRAIL_WARN
reason = f"AI Reviewer flagged potential issues."
... | Python | 1 |
], line={"row": 0})
pxs.plot_grid()
pxs.plot_bc("CHD", alpha=0.4)
pxs.plot_bc("WEL", alpha=0.4)
pxs.plot_array(hds[0], alpha=0.1)
pxs.plot_vector(qx, qy, qz, normalize=True, color="white")
for ipl, ((iprp, irpt, trelease), pl) in enumerate(mf6_plines):
pl.plot(
title="MF6, cr... | Python | 1 |
kp_exp_coeffs:
a, b = coeff
keypoint_reward_exp += (
1.0 / (torch.exp(a * keypoint_dist_sep) + b + torch.exp(-a * keypoint_dist_sep))
).mean(-1)
else:
# Use single exponential: average keypoint distance first, then apply exponential
keypoint_dist ... | Python | 1 |
{
pub enum Error for Module<T: Trait> {
/// Local accounts - UNAVAILABLE (Consider adding one via `author_insertKey` RPC)
AccountUnavail,
/// API Resoibse - UNEXPECTED
APIRespUnexp,
/// Best Header - NOT EXISTED
BestHeaderNE,
/// Block Number - OVERFLOW
BlockNumberOF,
/// Json - PARSING FAILED
... | Rust | 0 |
r) => OpModeS::Auth(keypair.try_lift::<Kem>()?),
AgileOpModeSTy::AuthPsk(keypair, bundle) => {
OpModeS::AuthPsk(keypair.try_lift::<Kem>()?, bundle.try_lift::<Kdf>()?)
}
};
Ok(res)
}
fn validate(&self) -> Result<(), AgileHpkeError> {
match &self.o... | Rust | 0 |
object::LLVMBinaryType::LLVMBinaryTypeELF64L => BinaryType::ELF64L,
object::LLVMBinaryType::LLVMBinaryTypeELF64B => BinaryType::ELF64B,
object::LLVMBinaryType::LLVMBinaryTypeMachO32L => BinaryType::MachO32L,
object::LLVMBinaryType::LLVMBinaryTypeMachO32B => BinaryType::M... | Rust | 0 |
tNextJobID()
self.currentJobs.add(jobID)
# Construct our style of job tuple
self.newJobsQueue.put(
(
jobID,
jobNode.cores,
jobNode.memory,
jobNode.disk,
jobNode.jobNam... | Python | 1 |
let vm_addr = ebpf::MM_INPUT_START.wrapping_add(reg[src]).wrapping_add(insn.imm as u32 as u64);
let host_ptr = translate_memory_access!(self, vm_addr, AccessType::Load, pc, u32);
reg[0] = unsafe { *host_ptr as u64 };
},
ebpf::L... | Rust | 0 |
import json
import re
class JsonPaser:
_code_fence_json = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```", re.IGNORECASE)
_json_prefixed = re.compile(r"\bjson\s*({[\s\S]*})", re.IGNORECASE)
def __init__(self):
pass
def extract_json_from_text(self, text):
if not isinstance(text, str):... | Python | 1 |
from discord.ext import commands
from src.MessageHandler import process_messages
from dotenv import load_dotenv
import discord
import asyncio
import os
import re
import logging
load_dotenv()
# Configuring basic logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create a bot instanc... | Python | 1 |
2549, 0.49020, 0.29412),
Xyz::new(18.74644744398548, 20.56235357029598, 46.16058375040178)
);
}
#[test]
fn test_convert_cmy_yxy() {
test_conversion(
Cmy::new(0.72549, 0.49020, 0.29412),
Yxy::new(20.56235357029598, 0.2193352332604094, 0.24058150912059142)
);
}use colored::*;
pub stru... | Rust | 0 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1
import typing, winrt
import enum
_ns_module = winrt._import_ns_module("Windows.Security.Credentials.UI")
try:
import winrt.windows.foundation
except:
pass
try:
import winrt.windows.storage.streams
except:
pass
cl... | Python | 1 |
t| {
if *t.borrow() == 0 {
*t.borrow_mut() = NTHREADS.fetch_add(1, Ordering::SeqCst) as usize;
}
*t.borrow()
});
res
}
pub fn murmur64(mut h: u64) -> u64 {
h ^= h >> 33;
h = h.overflowing_mul(0xff51afd7ed558ccd).0;
h ^= h >> 33;
h = h.overflowing_mul(0xc4ceb9... | Rust | 0 |
on": "ε",
"Epsilontonos": "Έ",
"epsilontonos": "έ",
"equal": "=",
"equivalence": "≡",
"Esmall": "",
"estimated": "℮",
"esuperior": "",
"Eta": "Η",
"eta": "η",
"Etatonos": "Ή",
"etatonos": "ή",
"ETH": "Ð",
"eth": "ð",
"Eth": "Ð",
"Ethsmall": "",
"euro": ... | Python | 1 |
import numpy as np
def f(x):
return x**3 + np.log(x)
def regra_de_simpson(a, b, passos, f):
x = np.linspace(a, b, passos+1)
h = (b - a) / passos
integral = f(a) + f(b)
for i in range(1, passos, 2):
integral += 4 * f(a + i * h)
for i in range(2, passos-1, 2):
integral ... | Python | 1 |
Format = 100;
pub const SpvReflectFormat_SPV_REFLECT_FORMAT_R32G32_UINT: SpvReflectFormat = 101;
pub const SpvReflectFormat_SPV_REFLECT_FORMAT_R32G32_SINT: SpvReflectFormat = 102;
pub const SpvReflectFormat_SPV_REFLECT_FORMAT_R32G32_SFLOAT: SpvReflectFormat = 103;
pub const SpvReflectFormat_SPV_REFLECT_FORMAT_R32G32B32... | Rust | 0 |
_sector_timeout as u64,
),
)
.map_err(|error| FlashError::EraseFailed {
sector_address: address,
source: Box::new(error),
})?;
log::info!(
"Done erasing sector. Result is {}. This took {:?}",
result,
... | Rust | 0 |
raise Exception('Unsupported result type: ' + str(result_type))
# assemble model
mdl = ResultsTable(data=y, index=labels, columns=columns,
title=title, ylabel=y_label, units=y_label)
return mdl
def export_all(self):
"""
Exports all the resul... | Python | 1 |
#!/usr/bin/env python3
# <xbar.title>Countdown</xbar.title>
# <xbar.version>v2.1</xbar.version>
# <xbar.author>Pere Albujer</xbar.author>
# <xbar.author.github>P4R</xbar.author.github>
# <xbar.desc>Shows countdown of established date.</xbar.desc>
# <xbar.image>https://cloud.githubusercontent.com/assets/7404532/1235678... | Python | 1 |
{
Device {
bus,
host,
sockets: [0b11111111],
}
}
pub fn reset(mut self) -> Result<UninitializedDevice<SpiBus>, ResetError<SpiBus::Error>> {
if self.sockets != [0b11111111] {
Err(ResetError::SocketsNotReleased)
} else {
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. 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 requir... | Python | 1 |
rt, inputs_as_options, end, seed)
}
pub fn assert_evolution(
start: Vec<&str>,
inputs: Vec<ferris_base::core::direction::Direction>,
end: Vec<&str>,
) -> bool {
seeded_assert_evolution(start, inputs, end, None)
}
<gh_stars>1-10
use super::prelude::*;
use crate::protocol::commands::ext::Resume;
use cra... | Rust | 0 |
d/src/prelude.rs
pub use crate::bus::*;
pub use lifeline::prelude::*;
pub use log::*;
pub use postage::{sink::Sink, stream::Stream};
pub use tab_api::client::{Request, Response};
// Copyright rafawo (<EMAIL>). All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apac... | Rust | 0 |
t@example.com")
user_id = u.user.id
community = minimal_community_factory(slug="test-community", owner=user_id)
community_id = community.id
# Create synthetic records
synthetic_records = []
sample_records = [
sample_metadata_book_pdf,
sample_metad... | Python | 1 |
ta * log_diff)).mean()
# 计算熵loss,鼓励分布更尖锐(熵更低)
def entropy_loss(q):
q = torch.softmax(q, dim=-1)
q = torch.clamp(q, min=1e-8)
return -(q * torch.log(q)).sum(dim=-1).mean()
entropy_weight = 0.06 # 可调节
entropy_losses = [
... | Python | 1 |
,
vec![Datum::Bytes(s1.clone()), Datum::Bytes(s2.clone())],
Datum::I64(0),
),
(
ScalarFuncSig::InString,
vec![Datum::Bytes(s1.clone()), Datum::Bytes(s2), Datum::Bytes(s1)],
Datum::I64(1),
),
(... | Rust | 0 |
BlockReceipts\",\"params\":[\"0x{:x?}\"],\"id\":\"r{}\"}}", block_num, block_num);
// tracing::debug!("RQ {}", payload2);
let rq2 = rpc_request(&rpc_addr);
let response2: String = rq2.send_string(&payload2).unwrap().into_string().unwrap();
let r2: RpcResponse<Vec<RpcResponseBlockReceiptsInfo>> = match s... | Rust | 0 |
]
async fn main() -> Result<()> {
let mut counters = disk::io_counters();
while let Some(counter) = counters.next().await {
dbg!(counter?);
}
println!("\n\n--- Per physical disk ---\n");
let mut counters = disk::io_counters_physical();
while let Some(counter) = counters.next().await {
... | Rust | 0 |
from llama_index.graph_stores.neptune.analytics import NeptuneAnalyticsGraphStore
from llama_index.graph_stores.neptune.database import NeptuneDatabaseGraphStore
from llama_index.graph_stores.neptune.analytics_property_graph import (
NeptuneAnalyticsPropertyGraphStore,
)
from llama_index.graph_stores.neptune.databa... | Python | 1 |
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Copyright the Hypothesis Authors.
# Individual contributors are listed in AUTHORS.rst and the git log.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the... | Python | 1 |
# Slixmpp: The Slick XMPP Library
# Copyright (C) 2020 Mathieu Pasquet <mathieui@mathieui.net>
# This file is part of Slixmpp.
# See the file LICENSE for copying permission.
from typing import (
Optional,
Set,
)
from slixmpp import JID, Iq
from slixmpp.exceptions import IqError, IqTimeout
from slixmpp.plugins ... | Python | 1 |
::IfcmpImm => {
panic!(
"op:{:?} ALU+imm and ALU+carry ops should not appear here!",
op
);
}
Opcode::Iabs => {
implemented_in_isle(ctx);
}
Opcode::AvgRound => {
unimplemented!();
}
Opcode::S... | Rust | 0 |
}
/// Table of all flags in the 2018-02-23 nightly build.
///
/// A number of these that affect output are dropped because we append our own
/// options.
static KNOWN_FLAGS: &[(&str, FlagType)] = &[
("--ignored", FlagType::Pass(false)),
("--test", FlagType::Pass(false)),
("--bench", FlagType::Pass(false))... | Rust | 0 |
context);
}
extern "C" {
pub fn duk_get_now(ctx: *mut duk_context) -> duk_double_t;
}
extern "C" {
pub fn duk_time_to_components(
ctx: *mut duk_context,
timeval: duk_double_t,
comp: *mut duk_time_components,
);
}
extern "C" {
pub fn duk_components_to_time(
ctx: *mut duk_c... | Rust | 0 |
"""
智能体训练入口,包含训练逻辑
"""
from tensorboardX import SummaryWriter
from ding.config import compile_config
from ding.worker import BaseLearner, SampleSerialCollector, InteractionSerialEvaluator, AdvancedReplayBuffer
from ding.envs import SyncSubprocessEnvManager, DingEnvWrapper, BaseEnvManager
from wrapper import MaxAndSkipW... | Python | 1 |
Some switches like for example Livolo light switches use the
same 'on' command to switch on and switch off the lights.
If the light is on and 'on' gets sent, the light will turn off
and if the light is off and 'on' gets sent, the light will turn on.
"""
def _handle_event(self, event):
... | Python | 1 |
);
}
#[test]
fn test_false_replace_str() {
test_shader(
r#"
.
#ifdef FALSE
IGNORE
#endif
.
"#,
&[],
r#"
.
.
"#,
);
}
#[test]
fn pbr_wgsl() {
test_shader(
r#"
#define_import_path bevy_pbr:... | Rust | 0 |
0
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::cmp::Ordering;
use std::convert::TryFrom;
use tidb_query_codegen::AggrFunction;
use tidb_query_datatype::{Collation, EvalType, FieldTypeAccessor};
use tipb::{Expr, ExprType, FieldType};
use super::*;
use tidb_query_common::Result;
use tidb... | Rust | 0 |
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILI... | Rust | 0 |
CToken::Development("beta")
].into())));
}
#[test]
fn test_parse_multi()
{
assert_eq!(
do_parse_multiset("Amidar (19xx)(Devstudio) & Amigos (1987)(Mr. Tosec)-(PD)(Disk 1 of 2)[a]"),
Ok(("",
(
vec![
... | Rust | 0 |
range(dimY):
for x in range(dimX):
# Activate rising edge events on all keys
trellis.activate_key(x, y, NeoTrellis.EDGE_RISING)
# Activate falling edge events on all keys
trellis.activate_key(x, y, NeoTrellis.EDGE_FALLING)
trellis.set_callback(x, y, btnHandler)
#trell... | Python | 1 |
import os
import pickle
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--save_path', type = str, required = True,
help = 'Directory where all the partial clusterers are stored...')
parser.add_argument('--file_paths', nargs = '+',
... | Python | 1 |
for topic in topics:
# Skip topics without questions
if not topic.get("questions"):
continue
# Use rephrased_title if available, otherwise use original title
section_title = topic.get("rephrased_title", topic.get("title", ""))
... | Python | 1 |
return inputs
# -- Predicates for sub-command list -------------------------------
def has_lib(self):
"""Returns true if the current distribution has any Python
modules to install."""
return (self.distribution.has_pure_modules() or
self.distribution.has_ext_modu... | Python | 1 |
y config: {}",some_id);
Ok(some_id)
} else {
debug!("no spu is supplied, looking up env");
if let Ok(id_str) = env::var(FLV_SPU_ID) {
debug!("found spu id from env: {}",id_str);
let id = id_str.parse().map_err(|err| {
IoErro... | Rust | 0 |
pub fn from_octets(a: u8, b: u8, c: u8, d: u8) -> A {
A::new(Ipv4Addr::new(a, b, c, d))
}
pub fn addr(&self) -> Ipv4Addr { self.addr }
pub fn set_addr(&mut self, addr: Ipv4Addr) { self.addr = addr }
pub fn rtype() -> Rtype { Rtype::A }
fn parse_always(parser: &mut Parser) -> ParseResu... | Rust | 0 |
;
use nalgebra::{MatrixSlice3x1, Vector6};
mod spatial_transform;
pub type Vector3 = nalgebra::Vector3<f32>;
pub type Vector4 = nalgebra::Vector4<f32>;
pub type SpatialVector = nalgebra::Vector6<f32>;
pub type Quaternion = nalgebra::Quaternion<f32>;
pub type UnitQuaternion = nalgebra::UnitQuaternion<f32>;
pub type Mo... | Rust | 0 |
####
# CODE TAKEN WITH FEW MODIFICATIONS FROM https://github.com/caogang/wgan-gp
# ORIGINAL PAPER https://arxiv.org/pdf/1704.00028.pdf
####
import torch
from torch import autograd
def gradient_penalty(netD, real_data, fake_data, l=10):
batch_size = real_data.size(0)
alpha = real_data.new_empty((batch_size, 1,... | Python | 1 |
mod creeps;
mod logging;
mod spawn;
fn main() {
logging::setup_logging(logging::Debug);
js! {
var game_loop = @{game_loop};
module.exports.loop = function() {
// Provide actual error traces.
try {
game_loop();
} catch (error) {
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.