text string | label_name string | labels int64 |
|---|---|---|
_TOL
{
primary_axis = polygon_axis;
} else {
primary_axis = edge_axis;
}
if one_sided {
// Smooth collision
// See https://box2d.org/posts/2020/06/ghost-collisions/
let mut edge0: B2vec2 = v1 - edge_a.m_vertex0;
edge0.normalize();
let normal0 = B2vec2::new(edge0.y, -edge0.x);
let convex1: bool = b... | Rust | 0 |
total_votes: i64) -> bool {
assert!(got_votes <= total_votes);
assert!(got_votes >= 0);
assert!(total_votes > 0);
let need_votes = (total_votes * 2 + 3) / 3;
got_votes >= need_votes
}
///
/// Create a new multi-signature from individual signatures
///
pub fn create_multi_signature(
validators:... | Rust | 0 |
f[comparison_results_df.type == 'SM']) / float(num_oracle_template) # RTA
# over_generalized = len(comparison_results_df[comparison_results_df.type == 'OG']) / count_total
# under_generalized = len(comparison_results_df[comparison_results_df.type == 'UG']) / count_total
# mixed = len(comparison_results_df[... | Python | 1 |
_channel
}
}
except UnidentifiedImageError as e:
print(f"[-] Error: {e} - the file should be an image")
except OSError as e:
print(f"[-] Error: {e} - error opening the file")
def extract_info(self):
file_exten... | Python | 1 |
#!/usr/bin/python3
"""
Rotate 2D Matrix module
"""
def rotate_2d_matrix(matrix):
"""
Rotate a 2D matrix clockwise by 90 degrees.
Args:
matrix (List[List[int]]): The input matrix to be rotated.
Returns:
None: The matrix is modified in-place.
"""
n = len(matrix[0])
""" It... | Python | 1 |
alse
assert isint(3) == True
assert isint(0) == True
assert isint(long(3)) == True
assert isint(long(0)) == True
assert isint(mpf(3)) == True
assert isint(mpf(0)) == True
assert isint(mpf(-3)) == True
assert isint(mpf(3.2)) == False
assert isint(3.2) == False
assert isint(nan) ==... | Python | 1 |
import pandas as pd
def simulate_seasonal_profile(da_prices, start_date="2025-01-01", end_date="2025-12-31", rolling_window=None):
df = da_prices.copy().dropna().sort_index()
df['year'] = df.index.year
df['normalized'] = df.groupby('year')['price'].transform(lambda x: x / x.mean())
df['month'] = df.i... | Python | 1 |
import os
from tqdm import tqdm
import cv2
import open3d as o3d
import torch
from torchvision.transforms.functional import to_tensor
from utils import geometry, config, misc
def main():
args = config.load_parser()
if args.use_debug_mode:
torch.autograd.set_detect_anomaly(True)
depth_path... | Python | 1 |
{
self.variant(REV6NP_A::VALUE1)
}
#[doc = "Select service request line 3 of group x"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(REV6NP_A::VALUE2)
}
#[doc = "Select shared service request line 0"]
#[inline(always)]
pub fn value3(self) -> &'a mut W... | Rust | 0 |
zzy_matcher::FuzzyMatcher;
use itertools::Itertools;
use json::JsonValue;
use powerpack::Item;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Bookmark {
name: String,
link: String,
}
impl Bookmark {
pub fn from_json_value(value: &JsonValue) -> Bookmark {
let name = value["title"].as_str().unwra... | Rust | 0 |
LUT(frame, lookup_table)
# Aumentar brilho e contraste
frame = cv2.convertScaleAbs(frame, alpha=1.2, beta=25)
elif avg_brightness > 180: # Muito claro
# Reduzir gamma para ambientes muito claros
gamma = 0.8
... | Python | 1 |
_and_ghost_board<'a>(
grade_and_ghost_boards: &'a [mtc::GradeAndGhostBoard],
state: &mtc::GhostState,
turn: u8,
) -> &'a mtc::GradeAndGhostBoard {
let hist_len = grade_and_ghost_boards.len() as u8;
if hist_len == 0 {
&EMPTY_GRADE_AND_GHOST_BOARD
} else {
let effective_turn = if l... | Rust | 0 |
est_instr(&[0xc5, 0xfa, 0x7e, 0x10], "vmovq xmm2, [rax]");
test_instr(&[0xc5, 0xfc, 0x10, 0x0f], "vmovups ymm1, [rdi]");
test_instr(&[0xc5, 0xfd, 0x10, 0x0f], "vmovupd ymm1, [rdi]");
test_instr(&[0xc5, 0xfe, 0x10, 0x0f], "vmovss xmm1, [rdi]");
test_instr(&[0xc5, 0xff, 0x10, 0xcf], "vmovsd xmm1, xmm0, xm... | Rust | 0 |
break;
}
http_request_headers.push(line_uw);
}
// If the request is GET / we return the index.html client
if http_request_definition_split[0] == "GET" {
if http_request_definition_split[1] == "/" {
return (4, 0, 0, 0, vec![0]);
}
else if http_request_defi... | Rust | 0 |
gCriterionLabelModel(TypedDict, total=False):
input: Required[Iterable[TestingCriterionLabelModelInput]]
labels: Required[List[str]]
"""The labels to classify to each item in the evaluation."""
model: Required[str]
"""The model to use for the evaluation. Must support structured outputs."""
na... | Python | 1 |
arLabel::new(lbl), is_true).raw()
}
#[no_mangle]
#[cfg(not(target_family="wasm"))]
pub extern "C" fn rsdd_and(mgr: *mut BddManager, a: u64, b: u64) -> u64 {
let mgr = unsafe { &mut *mgr };
mgr.and(BddPtr::from_raw(a), BddPtr::from_raw(b)).raw()
}
#[no_mangle]
#[cfg(not(target_family="wasm"))]
pub extern "C" f... | Rust | 0 |
ontent, and the
/// search path.
path: &'a Path,
},
/// Read a Nix expression from a non-file source.
Other {
/// The Nix expression source code.
source: &'a str,
/// Name of this source.
name: &'a str,
/// The search path relative to which file refer... | Rust | 0 |
e.window_frameless = True
# page.window_focused=True
page.scroll=True
page.vertical_alignment = ft.MainAxisAlignment.CENTER
page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
###################### COLOR
page.theme_mode = ft.ThemeMode.DARK #ft.ThemeMode.LIGHT
# page.bgcolor = ... | Python | 1 |
3)),
(Point2D::new(-0.1, -0.1), Point2D::new(-0.1, 0.1)),
(Point2D::new(-0.1, 0.1), Point2D::new(0.1, 0.1)),
(Point2D::new(0.1, 0.1), Point2D::new(0.1, -0.1)),
(Point2D::new(0.1, -0.1), Point2D::new(-0.1, -0.1)),
(Point2D::new(0.1, 0.1), Po... | Rust | 0 |
f p[1] >= threshold else 0 for p in predictions]
y_true = y.argmax(axis=1).tolist()
accuracy = accuracy_score(y_true, y_pred)
positive_precision = precision_score(y_true, y_pred, pos_label=1)
positive_recall = recall_score(y_true, y_pred, pos_label=1)
negative_precision = precisi... | Python | 1 |
inner_rect.y1),
self.zoom,
None,
);
g.enable_clipping(inner_rect);
g.redraw(&app.primary.draw_map.boundary_polygon);
g.redraw(&app.primary.draw_map.draw_all_areas);
g.redraw(&app.primary.draw_map.draw_all_unzoomed_parking_lots);
g.redraw(&app.prim... | Rust | 0 |
import argparse
import sys
from getpass import getpass
from jupyter_core.paths import jupyter_config_dir
from jupyter_server.auth import passwd
from jupyter_server.config_manager import BaseJSONConfigManager
def set_password(args):
password = args.password
while not password:
password1 = getpass("" ... | Python | 1 |
tr, String);
#[cfg(feature = "std")]
impl_partial_eq!(&'a BStr, String);
#[cfg(feature = "std")]
impl_partial_eq_cow!(&'a BStr, Cow<'a, BStr>);
#[cfg(feature = "std")]
impl_partial_eq_cow!(&'a BStr, Cow<'a, str>);
#[cfg(feature = "std")]
impl_partial_eq_cow!(&'a BStr, Cow<'a, [u8]>);
... | Rust | 0 |
2),
], {
assert_eq!(a - b, r);
}}
<reponame>FallingSnow/aleph.js
// Copyright 2020 the Aleph.js authors. All rights reserved. MIT license.
use indexmap::IndexSet;
use sha1::{Digest, Sha1};
use std::rc::Rc;
use swc_common::{SourceMap, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{private_ident, quo... | Rust | 0 |
lt
assert data_transfer.get_checksum_chunksize(1024 * 1024 * 1024) == default
assert data_transfer.get_checksum_chunksize(10_000 * default) == default
# Big file: exceeds 10,000 parts
assert data_transfer.get_checksum_chunksize(10_000 * default + 1) == default * 2
assert data_tr... | Python | 1 |
import datetime
import doctest
from functools import lru_cache
import requests
@lru_cache()
def _is_holiday(day):
# 该接口可能将于 2016.7.1 过期, 请关注该主页
api = 'http://www.easybots.cn/api/holiday.php'
params = {'d': day}
rep = requests.get(api, params)
res = rep.json()[day if isinstance(day, str) else day[... | Python | 1 |
s<'s>) -> Validator<'v, 'ast, 's> {
Validator {
ast,
specs,
cache: Default::default(),
_marker: PhantomData,
}
}
fn validate_node_def(&self, node_def: &'v NodeDef<'ast>) -> Result<ValidNode<'ast>, Error> {
let cache = self.cache.borrow();
Ok(ValidNode {
tag: node_def.t... | Rust | 0 |
cont and there is an out-dest, this ends
// the basic block.
if effect.dest.is_some() {
let dest_addr = next;
if add_split(self, dest_addr, true) { // TODO: t.len());
}
result.push(dest_addr);
println!("add_edge as ... | Rust | 0 |
::{convert::TryInto, fmt}; // converts the vector of bytes inside the struct back to string for more friendly display.
use sp_core::crypto::KeyTypeId; // for using keys for signed extrinsics
use sp_runtime::{
offchain as rt_offchain, // offchain worker
offchain::storage::StorageValueRef, // offchain worker storage
... | Rust | 0 |
ut AppData, _: &_| data.clicked_count += 1),
)
.with_spacer(4.0)
.with_child(Label::new(|data: &AppData, _: &_| {
format!("Clicked {} times!", data.clicked_count)
})),
"Button",
))
... | Rust | 0 |
"""Test backward compatibility with liquidctl 1.1.x."""
import pytest
import usb
from liquidctl.driver.kraken2 import Kraken2
from liquidctl.driver.usb import hid, HidapiDevice
class _MockPyUsbHandle(usb.core.Device):
def __init__(self, serial_number):
self.idVendor = 0x1e71
self.idProduct = 0x... | Python | 1 |
epoch_shuffling_id,
execution_status,
)?;
Ok(Self {
fc_store,
proto_array,
queued_attestations: vec![],
_phantom: PhantomData,
})
}
/// Instantiates `Self` from some existing components.
///
/// This is useful if the e... | Rust | 0 |
import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 1000
# Colors
WHITE = (255, 255, 255)
SOFT_YELLOW = (255, 255, 224)
BLACK = (0, 0, 0)
BRIGHT_YELLOW = (255, 255, 0)
LIGHT_GRAY = (200, 200, 200)
# Setup the screen
screen = pygame.display.set_mode((SCR... | Python | 1 |
= self.measure_with(&ctx);
if offset >= len {
return Err(error::Error::BadOffset(offset).into())
}
N::try_from_ctx(&self[offset..], ctx).and_then(|(n, _)| Ok(n))
}
#[inline]
/// Reads a value from `self` at `offset` with a default `Ctx`. For the primitive numeric values,... | Rust | 0 |
print(f"Procedimento extraído: {procedimento}")
# Obtém o nome do médico e data
print("Extraindo nome do médico e data...")
botao = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[starts-with(@id, "edit_formeletronico_")]/d... | Python | 1 |
PathPrinter { path, reg_exp }
}
pub fn print(&self) {
if atty::isnt(Stream::Stdout) {
self.print_to_non_tty();
} else {
self.print_to_tty();
}
}
fn print_to_non_tty(&self) {
println!("{}", self.path);
}
fn print_to_tty(&self) {
... | Rust | 0 |
class Solution:
def sortVowels(self, s: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u'}
positions = []
vowels_to_sort = []
for i in range(len(s)):
if s[i].lower() in vowels:
positions.append(i)
vowels_to_sort.append(s[i])
sorted_vow... | Python | 1 |
")]
pub username: String,
}
fn duration_to_u32<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
let mut s: &str = Deserialize::deserialize(d)?;
let mut seconds = 0;
if let Some(idx) = s.find('h') {
let hrs = s[..idx]
.parse::<u32>()
.map_err(|_| Error::custom... | Rust | 0 |
callback, *args, **kwargs):
self._requester.doRequestEx(ctx, callback, (api, 'join_room'), self.__getPeripheryIDStr(), ctx.getUnitMgrID())
def __matchmakingInfo(self, api, ctx, callback, *args, **kwargs):
self._requester.doRequestEx(ctx, callback, (api, 'matchmaking_info'), self.__getPeripheryIDStr... | Python | 1 |
range of 16-240 for 8 bits"]
pub const AVColorRange_AVCOL_RANGE_MPEG: AVColorRange = 1;
#[doc = " Full range content."]
#[doc = ""]
#[doc = " - For RGB and luminance planes:"]
#[doc = ""]
#[doc = " (2^n - 1) * E"]
#[doc = ""]
#[doc = " F.ex. the range of 0-255 for 8 bits"]
#[doc = ""]
#[doc = " - For chrominan... | Rust | 0 |
env::args().nth(1).unwrap();
////read argv as a string
//let file: std::string::String = fs::read_to_string(filename).expect("");
////use the string method `split_whitespace()` to split each word in string into an iterator
//let words = file.split_whitespace();
//let start = time::Instant::now();
... | Rust | 0 |
mut VkMemoryFdPropertiesKHR) -> vk::VkResult>;
#[cfg(feature = "function_prototypes")]
extern "system" {
/// See [`vkGetMemoryFdKHR`](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#vkGetMemoryFdKHR)
pub fn vkGetMemoryFdKHR(device: vk::VkDevice, pGetFdInfo: *const VkMemoryGetFdInf... | Rust | 0 |
"cpu": "8000m",
"memory": "32Gi",
"storage": "1Ti",
}
# Update cluster status in database
await self.db.clusters.update_one(
{"_id": ObjectId(cluster_id)},
{
"$set": {
"statu... | Python | 1 |
V2, "MovingThreshold", 24, Word, RW),
Reg::new("H54-100-S500-RA", V2, "TemperatureLimit", 31, Byte, RW),
Reg::new("H54-100-S500-RA", V2, "MaxVoltageLimit", 32, Half, RW),
Reg::new("H54-100-S500-RA", V2, "MinVoltageLimit", 34, Half, RW),
Reg::new("H54-100-S500-RA", V2, "PWMLimit", 36, Half, RW),
Reg... | Rust | 0 |
variant as u8 != 0
}
}
#[doc = "Field `reg_gpio_25_pu` reader - Pull Up Resistor for GPIO25."]
pub struct REG_GPIO_25_PU_R(crate::FieldReader<bool, REG_GPIO_25_PU_A>);
impl REG_GPIO_25_PU_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_25_PU_R(crate::FieldReader::new(bits))
}
#[doc... | Rust | 0 |
_with_shape)
else:
return torch.FloatTensor(1).fill_(0.).to(pred_vertices.device)
def smpl_losses(
pred_rotmat,
pred_betas,
gt_pose,
gt_betas,
has_smpl,
criterion,
):
pred_rotmat_valid = pred_rotmat[has_smpl == 1]
gt_rotmat_valid = batch_rodrigues(gt... | Python | 1 |
import unittest
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from config.capabilities import get_android_capabilities
import time
from RecoverPasswordPage import RecoverPasswordPage
appium_server_url = 'http://localhost:4723'
... | Python | 1 |
label='Upload video')
# video_processing_text_input_component = gr.Textbox(
# label='Text prompt',
# placeholder='Enter comma separated text prompts')
# video_processing_submit_button_component = gr.Button(
# value='Subm... | Python | 1 |
println!("This point will never be reached");
}
println!("Exited the outer loop");
}
use core::alloc::{AllocErr, Layout};
use core::mem;
use core::ptr::{self, NonNull};
use winapi::um::errhandlingapi::GetLastError;
use winapi::um::memoryapi::VmOfferPriorityVeryLow;
use winapi::um::memoryapi::{OfferVirtualMemo... | Rust | 0 |
tus - Show container status")
print(" <any command> - Execute in container")
elif command.lower() == "info":
self.get_container_info(container_id)
elif command.lower() == "status":
self.execute_command(container_id, "ps aux | h... | Python | 1 |
# Description: Tests for the kirbi module
import tempfile
import pathlib
from minikerberos.common.kirbi import Kirbi
from .config import *
def test_load_kirbi():
for kirbifile in get_testfiles_kirbi():
kirbi = Kirbi.from_file(kirbifile)
desc = str(kirbi)
with tempfile.NamedTemporaryFile()... | Python | 1 |
run(**kwargs)
def run(app, **kwargs):
config = Config(app, **kwargs)
server = Server(config=config)
if (config.reload or config.workers > 1) and not isinstance(app, str):
logger = logging.getLogger("uvicorn.error")
logger.warning(
"You must pass the application as an impo... | Python | 1 |
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from frappe.tests.utils import FrappeTestCase
class TestEmployeeOnboardingTemplate(FrappeTestCase):
pass
| Python | 1 |
import datetime
def verificar_dia_trabalho():
hoje = datetime.date.today()
dia_do_mes = hoje.day
while True:
resposta = input("Você trabalhou hoje? (sim/não): ").strip().lower()
if resposta in ["sim", "não"]:
trabalhou_hoje = resposta == "sim"
break
print("R... | Python | 1 |
.connect_with(self.client_config.clone(), &server_addr, "localhost")
.unwrap()
.instrument(error_span!("client"))
.await
})
.unwrap();
(endpoint, connection, runtime)
}
}
fn rt() -> Runtime {
Builder::new_current_t... | Rust | 0 |
ideo_download_button_str2, data=compressed_video, file_name=f"{os.path.splitext(video_file.name)[0]}_compressed_algorithm2.mp4", mime="video/mp4", key="algorithm2")
def multipage():
pages = {
"Home": home_page,
"Audio Compression": audio_compression,
"Image Compression": image_compression,
... | Python | 1 |
# Copyright (c) 2018-2023 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
import pytest
import fuzzinator
from .common_formatte... | Python | 1 |
iface: d.base_iface,
mode: MacVtapMode::from(d.mode),
flags: d.flags,
allowed_mac_addresses: d.allowed_mac_addresses,
}
}
}
pub(crate) fn get_mac_vtap_info(data: &nlas::InfoData) -> Option<MacVtapInfo> {
if let Some(info) = get_mac_vlan_info(data) {
Some(info.... | Rust | 0 |
/// The number of inputs.
pub i: usize,
/// The number of latches.
pub l: usize,
/// The number of outputs.
pub o: usize,
/// The number of AND gates.
pub a: usize,
}
impl FromStr for Header {
type Err = AigerError;
// In the interest of matching both the header structure and the n... | Rust | 0 |
f(&mut X2, &mut D_X2));
println!("{} {}", X2, D_X2);
//dbg!(&f_wrap(1.0, 1.0));
//dbg!(&g_wrap(1.0));
//dbg!(&enzyme3(1.0, 1.0));
//dbg!(&multi_args4(2.0, 1.0, 1.0));
}
}
<reponame>CapCap/aptos-core
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apach... | Rust | 0 |
:DIMS, count_args!($($dims),+));
}
#[test]
fn ones() {
let v = $name::ones();
$(assert_approx_eq!(v.$dims, 1.0);)+
}
#[test]
fn zeros() {
let v = $name::zeros();
$(assert_approx_eq!(v.$dims, 0.0);)+
}
#[te... | Rust | 0 |
}
}
impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.0.data.get() }
}
}
/// An owned guard that releases the mutex when dropped.
pub struct MutexGuardArc<T: ?Sized>(Arc<Mutex<T>>);
unsafe impl<T: Send + ?Sized> Send for MutexGuardArc<T> {}
... | Rust | 0 |
s: *const i32,
pub correlationMaskCount: u32,
pub pCorrelationMasks: *const u32,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct VkPhysicalDeviceMultiviewFeatures {
pub sType: VkStructureType,
pub pNext: *mut ::std::os::raw::c_void,
pub multiview: VkBool32,
pub multiviewGeometryShader: VkB... | Rust | 0 |
from sqlalchemy import Column, String, Integer, Boolean, ForeignKey, DateTime, Text, Float
from sqlalchemy.orm import relationship
from database import Base
import datetime
class User(Base):
__tablename__ = "users"
user_id = Column(Integer, primary_key=True, index=True)
username = Column(String(50), uniqu... | Python | 1 |
import datetime
from .base import Database
class InsertIdVar:
"""
A late-binding cursor variable that can be passed to Cursor.execute
as a parameter, in order to receive the id of the row created by an
insert statement.
"""
def bind_parameter(self, cursor):
param = cursor.cursor.var(... | Python | 1 |
("Parsing file");
// Get the first scene
let scene = gltf.scenes().next().unwrap();
// FIXME Only supports one mesh
// Go through the nodes and add the meshes to vertex_data
scene.nodes().for_each(|node| {
if let Some(mesh) = node.mesh() {
println!("... | Rust | 0 |
from fakepinterest import app
if __name__ == "__main__":
app.run(debug=True)
| Python | 1 |
class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
tree = [[] for _ in range(n + 1)]
q = collections.deque([1])
seen = [False] * (n + 1)
prob = [0] * (n + 1)
prob[1] = 1
seen[1] = True
for u, v in edges:
tree[u].append(v)
tre... | Python | 1 |
hange conditions.
demo_start=window.flip()
event.clearEvents()
fcount=0
while True:
# For the textBox and TextStim resource, change the text every
# chng_txt_each_flips, and record the time it takes to update the text
# and redraw() each resource type.
#
# Make sure timing of stim is for t... | Python | 1 |
}
},
&mut Cpy{nam: _, ref mut val, ref mut bod} => {
shift(val, inc, cut);
shift(bod, inc, cut + 2);
},
&mut Set => {}
}
}
// Substitutes the variable at given depth in term by value.
pub fn subs(term : &mut Term, value : &Term, dph : i32) {
let mu... | Rust | 0 |
# Given an array of strings, group the anagrams together. You can return the answer in any order. (LeetCode)
def group_anagrams(str):
anagram_map = {}
for word in str:
key = ''.join(sorted(word))
if key in anagram_map:
anagram_map[key].append(word)
else:
anagr... | Python | 1 |
mut buf = String::new();
while let Some(c) = self.peek() {
if c.is_alphabetic() {
buf.push(c);
self.next();
} else {
break;
}
}
if buf.is_empty() { None } else { Some(buf) }
}
fn parse_unary(&mut self) ... | Rust | 0 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2020/3/1 0:02
Desc:
"""
| Python | 1 |
stream.write(b" ").await?;
stream.write(meta.as_bytes()).await?;
stream.write(b"\r\n").await?;
Ok(())
}
async fn send_file<W: Write + Unpin>(stream: &mut W, path: PathBuf) -> Result<()> {
let mimetype = infer_mimetype(&path);
let mut file = File::open(path).await?;
send_header(stream, Status::... | Rust | 0 |
d = products.organization_id
FROM products
WHERE checkout_links.product_id = products.id
""")
op.alter_column("checkout_links", "organization_id", nullable=False)
op.create_foreign_key(
op.f("checkout_links_organization_id_fkey"),
"checkout_links",
"organizations",
... | Python | 1 |
#zadanie 1
a = 1+2 #dodawanie / typ liczb całkowitych
b = 1+4.5 #dodawanie / typ liczb rzeczywistych (zmiennoprzcinkowych)
c = 3/2 #dzielenie / typ liczb zmiennoprzecinkowych
d = 4/2 #dzielenie / typ liczb zmiennoprzecinkowych
e = 3//2 #dzielenie całkowite (zaokrągla w dół)/ typ liczb całkowitych
f = -3//2 #dzielenie c... | Python | 1 |
let ret = LSM {
config,
cache_manager: RefCell::new(cache_manager),
mut_table: BTreeMap::new(),
levels: Vec::new()
};
ret
}
pub fn open(config: LSMConfig) -> Self {
let mut ret = LSM::new(config);
let manifest_file_name = r... | Rust | 0 |
,
#[doc = "0x170 - DMA Channel 0 Configuration Register\\[1\\]"]
pub cconfig3: CCONFIG,
_reserved34: [u8; 12usize],
#[doc = "0x180 - DMA Channel 0 Source Address Register"]
pub srcaddr4: SRCADDR,
#[doc = "0x184 - DMA Channel 0 Destination Address Register"]
pub destaddr4: DESTADDR,
#[doc... | Rust | 0 |
.radius;
rec.set_normal_face(r, &outward_normal);
return Some(self.material);
}
}
None
}
}
pub struct HittableList {
objects: Vec<Box<dyn Hittable>>,
}
impl HittableList {
pub fn new(objects: Vec<Box<dyn Hittable>>) -> HittableList {
Hitt... | Rust | 0 |
= "Write proxy for field `GIRn`"]
pub struct GIRN_W<'a> {
w: &'a mut W,
}
impl<'a> GIRN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: GIRN_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "MUA General Interrupt n is not requested to th... | Rust | 0 |
_channel_ids
/// (ChannelManager::list_usable_channels will never include such channels).
///
/// The fees on channels from us to next-hops are ignored (as they are assumed to all be
/// equal), however the enabled/disabled bit on such channels as well as the
/// htlc_minimum_msat/htlc_maximum_msat *are* checked as the... | Rust | 0 |
} else $write
};
}
#[allow(unused_macros)]
macro_rules! __yarte_write_bytes_long {
($b:expr) => {
__yarte_check_write!($b.len(), {
... | Rust | 0 |
first = false;
continue;
};
if c == '.' {
tokens.push(Token::End);
tokens.push(Token::Start);
first = true;
continue;
}
if first {
tokens.push(Token::FirstLett... | Rust | 0 |
Configuration")
.boolean(*var_131);
}
if let Some(var_132) = &input.result_configuration_updates {
let mut object_133 = object.key("ResultConfigurationUpdates").start_object();
crate::json_ser::serialize_structure_crate_model_result_configuration_updates(
&mut object_133,... | Rust | 0 |
# Copyright 2020 Google LLC
#
# 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, s... | Python | 1 |
assert!(result.is_err());
test_util::tests::teardown(tmp_dir);
}
#[test]
fn test_verify_artifact() {
let tmp_dir = test_util::tests::setup();
let mut log = TransparencyLog::new(&tmp_dir).unwrap();
log.add_artifact("id", "hash")
.expect("Adding artifac... | Rust | 0 |
argument-on-linked-field.invalid.graphql", "validate_required_arguments/fixtures/missing-argument-on-linked-field.invalid.expected", input, expected);
}
#[test]
fn missing_argument_on_linked_field_on_abstract_type() {
let input = include_str!("validate_required_arguments/fixtures/missing-argument-on-linked-field-o... | Rust | 0 |
from .views import add_to_cart, viewCart, reduceQuantity
from django.urls import path
urlpatterns = [
path('add-to-cart/<int:product_id>/', add_to_cart, name='add-to-cart'),
path('view-cart/', viewCart, name='view-cart'),
path('reduce-quantity/<int:product_id>/', reduceQuantity, name='reduce-quantity'),
... | Python | 1 |
micPtr<T> {
type Target = std::sync::atomic::AtomicPtr<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> fmt::Debug for AtomicPtr<T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.deref().fmt(fmt)
}
}
// alpha.rs Alpha channel handling.
//
// C... | Rust | 0 |
from uuid import UUID
from Application.schemas.Agriculture_Activity.agriculture_activities import Argiculture_Activities_Schema
from Application.schemas.activity_type import Agricultural_Activity_Type_Schema
from Domain.Entities.Agricultural_Activity.agricultural_activity import Agricultural_Activity
from Domain.servic... | Python | 1 |
struct BroadcastFakeBlobsRun {
last_blockhash: Hash,
partition: usize,
}
impl BroadcastFakeBlobsRun {
pub(super) fn new(partition: usize) -> Self {
Self {
last_blockhash: Hash::default(),
partition,
}
}
}
impl BroadcastRun for BroadcastFakeBlobsRun {
fn run... | Rust | 0 |
ados antes do "evento".
dados_brr.qtd_rebatidas = qtd_rebates_barra;
dados_brr.atualiza(
barra,
(barra.esqueleto.posicao, barra.esqueleto.sentido)
);
// renomeando para legibilidade.
let pos = bola.esqueleto.posicao;
let sent = bola.esqueleto.sentido;
let (bat... | Rust | 0 |
运行的设备(例如,'cuda', 'cpu')。
workers (int): 数据加载的工作线程数。
optimizer (str): 用于训练的优化器。
lr0 (float): 初始学习率。
patience (int): 在没有可观察到的改进时,提前停止训练的等待周期数。
"""
# 检查 YAML 配置并解析
overrides = yaml_load(kwargs["cfg"]) if kwargs.get("cfg") else self.ove... | Python | 1 |
gs = ReceivedTextMessage::index(&conn).unwrap();
assert_eq!(recv_msgs, vec![recv_msg1.clone(), recv_msg2.clone(), recv_msg3.clone()]);
let find1 = ReceivedTextMessage::find(&recv_msg1.id, &conn).unwrap();
assert_eq!(find1, recv_msg1);
let find2 = ReceivedTextMessage::find_by_source_pub_k... | Rust | 0 |
imxrt_dma::on_interrupt(4);
}}
handler!{unsafe fn DMA5() {
imxrt_dma::on_interrupt(5);
}}
handler!{unsafe fn DMA6() {
imxrt_dma::on_interrupt(6);
}}
handler!{unsafe fn DMA7() {
imxrt_dma::on_interrupt(7);
}}
handler!{unsafe fn DMA8() {
imxrt_dma... | Rust | 0 |
wrap();
if turn_of_1 {
player1 = 1 + ((player1 - 1) + rolls.0 + rolls.1 + rolls.2) % 10;
score1 += player1;
}
else {
player2 = 1 + ((player2 - 1) + rolls.0 + rolls.1 + rolls.2) % 10;
score2 += player2;
}
turn_of_1 = !turn_of_1;
dice_rolls += 3;
}
println!("{:?}, {}", (score1, score2), dice_ro... | Rust | 0 |
_prefix, True
)
assert hot_water["unique_id"] == f"{name_prefix}_boil1_hot_water"
assert hot_water["entity_id"] == f"sensor.{name_prefix}_boil1_hot_water"
# Heating Circuit Climate Entity
heating_circuit = generate_sensor_names(
"hc1", "Heating Circuit", "heating_cir... | Python | 1 |
from .monad import (
Identity,
NonEmptyPowerset,
Prob,
bernoulli,
from_list,
singleton,
uniform,
weighted,
)
from .nesy_framework import Interpretation, NeSyFramework, nesy
from .parser import parse
__all__ = [
"NeSyFramework",
"Interpretation",
"nesy",
"parse",
"Pro... | Python | 1 |
#!/usr/bin/env python
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import pylab
import random
from optparse import OptionParser
import seaborn
delim = '\t'
parser = OptionParser()
parser.add_option("-l",
"--log_y",
action="store_true", dest="logy", default=... | Python | 1 |
3, 4";
let res = parse_line(line);
assert_eq!(res, [2, 0, 3, 4]);
}
<filename>RBE/std_box.rs<gh_stars>1-10
/*
* @Author: BertKing
* @version:
* @Date: 2020-08-25 09:57:56
* @LastEditors: BertKing
* @LastEditTime: 2020-08-25 10:50:03
* @FilePath: /RustConqueror/RBE/std.rs
* @Description: Rust的标准库std
* ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.