text
string
label_name
string
labels
int64
from flask import Blueprint, jsonify from app.services.log_service import get_logs bp = Blueprint('log', __name__, url_prefix = '/logs') @bp.route('/', methods = ['GET']) def list_logs(): logs = get_logs() return jsonify([{'id': log.id, 'action': log.action, 'timestamp': log.timestamp} for log in logs]), 200
Python
1
. */ #[endpoint { method = GET, path = "/applicants", }] async fn api_get_applicants(rqctx: Arc<RequestContext<Context>>) -> Result<HttpResponseOk<Vec<Applicant>>, HttpError> { let api_context = rqctx.context(); let db = &api_context.db; Ok(HttpResponseOk(Applicants::get_from_db(db).0)) } /** * ...
Rust
0
lueprint<BuilderComplexNode>, right: Blueprint<BuilderComplexNode>) -> Self { Self { inner: BuilderLeafOrNodes::Nodes{left, right}, } } } impl SimpleBuilder for BuilderComplexNode { type Artifact = ComplexNode; fn build(&self, cache: &mut Resolver) -> Self::Artifact { ComplexNode{ id: COUNTER.fetch_add...
Rust
0
# Cross-correlation (to find potential time offset) cross_corr = correlate( aligned_audio[audio_key], aligned_video[video_key], mode='full' ) # Find max correlation and its offset ...
Python
1
t can_jump) = (0, true); for i in 0..nums.len() { let v = nums[i]; if v == 0 && last_reach <= i && i != nums.len() - 1 { can_jump = false; break; } last_reach = last_reach.max(v as usize + i); } can_jump } #[test] fn test_q55() { assert_eq!(can_jump(vec![0]), true); assert_eq!(c...
Rust
0
ystemServices'*"] pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_FIRST: u32 = 32u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const IMAGE_REL_AMD64_INDIR_BR_SWITCHTABLE_LAST: u32 = 47u32; #[doc = "*Required features: 'Win32_System_SystemServices'*"] pub const IMAGE_REL_AMD64_INDIR_CALL: u32 = 2...
Rust
0
] __jni_bindgen! { /// public interface [Callback](https://developer.android.com/reference/javax/security/auth/callback/Callback.html) /// /// Required feature: javax-security-auth-callback-Callback public interface Callback ("javax/security/auth/callback/Callback") extends crate::java::lang::Object { ...
Rust
0
::I64(_) | Value::F32(_) | Value::F64(_) => panic!(), } } pub fn expect_i64(&self) -> i64 { match self { Value::I64(i) => *i, Value::I32(_) | Value::F32(_) | Value::F64(_) => panic!(), } } } impl fmt::Debug for Value { fn fmt(&self, fmt: &mut fmt::Format...
Rust
0
#!/usr/bin/env python from math import sqrt from random import normalvariate as randn from random import randint,seed import subprocess as sp sigma=1. nx=256 ny=256 dx=6. dy=6. igntime=2. runtime=30*60 slpsigma=sigma*.1/sqrt(2) windsigma=sigma*5./sqrt(2) cenx=nx*dx/2. ceny=ny*dy/2. dz=sqrt(dx**2+dy**2) ignr=dz*2 hi...
Python
1
import torch from torch import nn from torch.utils.checkpoint import checkpoint from detectron2.modeling import BACKBONE_REGISTRY, Backbone, ShapeSpec @BACKBONE_REGISTRY.register() class D2Dinov2(Backbone): """Detectron2 wrapper for DINOv2 vision transformers.""" def __init__(self, cfg, input_shape): ...
Python
1
#!/usr/bin/env python3 import subprocess import re command = [ 'pdftotext', '-layout', '-f', '187', '-l', '191', '-enc', 'ASCII7', 'adsb-AN10_V3_cons.pdf', '-' ] main_line = re.compile(r' ([^*]+?)\s+\*\s+([01-]{4})\s+([01-]{2})\s+([01-]{3})\s+([01-]{3})\s+([01-]{2})\s+([-]{10})\s*') conti...
Python
1
slice(s![c, i_y..(i_y + k_n), i_x..(i_x + k_m)]) * &hp.kernel; output[[c, y, x]] = temp.sum(); } } } } <gh_stars>1-10 //! Top-level font file representation. use std::borrow::Cow; use crate::binary::read::{ReadBinary, ReadCtxt}; use crate::error::{ParseError, ReadWriteError}; u...
Rust
0
ace<R>, }, /// A toplevel surface requested to stop being maximized UnMaximize { /// The surface surface: ToplevelSurface<R>, }, /// A toplevel surface requested to be set fullscreen Fullscreen { /// The surface surface: ToplevelSurface<R>, /// The output ...
Rust
0
.0 // => True 2.0 <=. 1.0 // => False } "#, ); } #[test] fn wide_float_div() { assert_js!( r#" fn go() { 111111111111111111111111111111. /. 22222222222222222222222222222222222. } "#, ); } #[test] fn int_patterns() { assert_js!( r#" fn go(x) { let 4 = x } "#, ); } #[test] f...
Rust
0
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum OU...
Rust
0
{}.", index, ["totally awesome", "really fancy", "still going strong"][(index as usize) % 3]), path: format!("/Device{}", index).into(), index: index, online: Cell::new(index % 2 == 0), checking: Cell::new(false), check_complete_sender: s, ...
Rust
0
Cursor::NwResize => "nw-resize", Cursor::SwResize => "sw-resize", Cursor::SeResize => "se-resize", Cursor::EwResize => "ew-resize", Cursor::NsResize => "ns-resize", Cursor::NeswResize => "nesw-resize", Cursor::NwseResize => "nwse-resize", ...
Rust
0
.v); let select0: __m128 = _mm_and_ps(comp, x); let select1: __m128 = _mm_andnot_ps(comp, rflx); x = _mm_or_ps(select0, select1); let x2: __m128 = _mm_mul_ps(x, x); // Compute polynomial approximation const SC1: XMVECTOR = unsafe { g_XMSinCoefficients1.v }; let ...
Rust
0
#!/usr/bin/env python3 import pandas as pd import os import matplotlib.pyplot as plt import seaborn as sns IMAGE_TYPE = os.environ.get("IMAGE_TYPE", "png") DATASET = os.environ.get("DATASET", "output_single.csv") SHOW = bool(os.environ.get("SHOW", "")) N_QUBITS = os.environ.get("N_QUBITS", "") def plot( df, ...
Python
1
ec()).unwrap(); assert!(first_response_text.contains("world"), format!( "A request without name parameter should contain Hello World in the response. Got : \n {:?}", first_response_text ) ); // <- check name parameter assert!(first_respo...
Rust
0
import shutil from Bio import SeqIO # GTF output # TODO: Perhaps fix the order of the - strand exons def write_rescue_gtf(input_gtf, ref_gtf, inclusion_list, prefix): output_gtf = f"{prefix}_rescued.gtf" shutil.copy(input_gtf, output_gtf) with open(ref_gtf, 'r') as infile, open(output_gtf, 'a') as outfile:...
Python
1
ectedRecoScore( test_name='three different salaries and one outlier (score)', salaries=[17000 for x in range(2)] + [20000 for x in range(7)] + [50000], expected_reco=[ _RecoScore(from_salary=17000.0, gained_offers=0.0), _RecoScore(f...
Python
1
y().u8() - 1, source_pos.x().u8() - 1, source_pos.y().u8() + 1, source_pos.x().u8() + 1, true, ); // let objs = js_sys::Array::from(&area).map(|x: Vec<StructureObject>| x.map().collect()); } use windows::core::Result; use windows::Win32::System::Com::{ CoInitializeEx, CoUnin...
Rust
0
::str::from_utf8_unchecked(include_bytes!("js_ops/99_main.js"))} ))); files }; } // DENO_OPS.iter().for_each(|(name, file) | { // js_runtime.execute(name, file).unwrap(); // }); /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in t...
Rust
0
_handles: MockHandles, expected_crash_info: fsys::ComponentCrashInfo, mut success_reporter: mpsc::Sender<()>, ) -> Result<(), Error> { let crash_introspect_proxy = mock_handles.connect_to_service::<fsys::CrashIntrospectMarker>()?; let (thread_koid_sender, mut thread_koid_receiver) = mpsc::chann...
Rust
0
nal[torch.tensor] = None attention_mask: Optional[torch.tensor] = None @dataclass class PackedAVLMRawBatch(AVLMRawBatch): """Sample type for image text raw batch""" position_ids: torch.Tensor = field(default_factory=lambda: torch.empty(0, dtype=torch.float)) packed_seq_params: PackedSeqParams = field...
Python
1
"register { a: 192, b: 0, c: 138, d: 0, e: 192, f: 0, h: 126, l: 121, pc: 32363, sp: 57337 }" ); } #[test] fn test_opcode_0X31() { let mem = Rc::new(RefCell::new(FakeMemory::new())); let reg = Register::new_from_debug_string( "register { a: 0, b: 0, c: 19, d: 0, e: 216, f: 160, h: 1, l: 77, pc:...
Rust
0
s = os.cpu_count() or 4 print(f"\n - 初始化線程池,最大線程數: {max_worker_threads}") print(f" - 開始對 {len(fuku_files)} 套 fuku 進行並行處理...") with ThreadPoolExecutor(max_workers=max_worker_threads) as executor: # 提交所有任務 futures = [executor.submit(process_fuku_task, fuku_file, char_name, all_dirs, all_fil...
Python
1
but key data must be duplicated across both /// the array and bitmap sections of the report //25 bytes //byte 0 - modifiers //byte 1 - reserved 0s //byte 2-7 - array of keycodes - used for boot support //byte 9-24 - bit array of pressed keys #[rustfmt::skip] pub const NKRO_BOOT_KEYBOARD_REPORT_DESCRIPTOR: &[u8] = &[ ...
Rust
0
if self.precise_locator: result = self.precise_locator.refine_pattern_bbox( frame, bbox, text, debug=False ) if result is not None: # 实际进行了精确定位 refined_bbox, refined_text = ...
Python
1
f._ConditionFactors._DesignLocations = filtered for r in value: if self not in r._DesignLocations: r._DesignLocations.append(self) self._ConditionFactors = value ConditionFactors = property(getConditionFactors, setConditionFactors) def addConditionFactors(self, *Con...
Python
1
# logical operators (abd, or, not) = used to check if two or more conditional are true temp = int(input("What is the temperature outside?: ")) if not(temp >= 0 and temp <= 30): print("The temperature is bad today!") print("Stay insside brrrrrr!") #print("The temperature is good today!") #rint("Go out...
Python
1
Err(_) => None, }; Ok(Expression::If(test, csq, alt)) } fn analyze_cond(exprs: List) -> Result<Expression, Error> { let mut clauses = Vec::new(); let mut else_clause = None; let mut next = exprs; while let Ok((car, cdr)) = next.unpack() { if let Ok((test, body)) = car.list()?.unpack() {...
Rust
0
def dump_to_str(self, obj, **kwargs): kwargs.setdefault('Dumper', Dumper) return yaml.dump(obj, **kwargs)
Python
1
=> [@"c"]}, "body" => (++ true {"Expr" "struct_expr": "component_name" => [@"c"], "component" => [@"c"]})}), env.clone(), qenv.clone(), ast!({"Type" "type_apply" : "type_rator" => (,expr_type.clone()), "arg" => [{ "Type" "struct" : ...
Rust
0
&RefCell<Box<FnMut(&T, &FrameClock) -> Continue + 'static>> = transmute(func); (&mut *func.borrow_mut())( &Widget::from_glib_borrow(this).downcast_unchecked(), &from_glib_borrow(frame_clock) ).to_glib() } unsafe extern "C" fn destroy_closure<T>(...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests import re import time from urllib.parse import urljoin, urlparse, parse_qs import json def test_with_proxy(): """使用代理测试登录流程""" print("=== 使用代理测试登录流程 ===") # 方法1: 使用不同的请求头 print("\n方法1: 使用不同的请求头...") # 创建全新的会话,使用不同的请求头 ses...
Python
1
c_0() {} pub fn ret_nop_0() {} pub fn ret_shutdown_0() {} pub fn ret_fail_0() {} pub fn ret_fail_1() {} pub fn ret_fail_2() {} pub fn ret_failthru_0() {} pub fn ret_failthru_1() {} pub fn ret_failthru_2() {} pub fn fail_0() {} pub fn fail_1() {} pub fn fail_2() {} pub fn stop_0() {} pub fn kill_0() {} pub fn kill_1() {...
Rust
0
filecoin_proofs_v1::constants::get_parameter_data(&id); ensure!(params.is_some(), "missing params for {}", &id); Ok(params.expect("param cid failure").cid.clone()) } } } pub fn into_winning_post(self) -> RegisteredPoStProof { use RegisteredPoStProof...
Rust
0
_s * np.exp(-1 * exponent) class IsothermalProfile(DMProfile): r"""Isothermal Profile. .. math:: \rho(r) = \frac{\rho_s}{1 + (r/r_s)^2} Parameters ---------- r_s : `~astropy.units.Quantity` Scale radius, :math:`r_s`. References ---------- * `Begeman et al. (1991), "Extended ...
Python
1
# Copyright 2024 THU-BPM MarkLLM. # # 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 writ...
Python
1
yper.echo("No parsed pages found", err=True) return if number_of_pages < 1: raise ValueError("Number of pages must be greater than 0") if start_page_num <= 0 or start_page_num > len(book_pages): raise ValueError(f"Invalid start page number {start_page_num}") if len(book_pages) < s...
Python
1
as an explicit dependency. pub fn parse(text: &str) -> impl Iterator<Item = Event<'_>> + '_ { Parser::new(text) } <reponame>sonald/lxxtcode-rs pub struct Solution; impl Solution { pub fn count_primes(n: i32) -> i32 { Self::by_direct(n) } // naive sieve pub fn by_sieve(n: i32) -> i32 { ...
Rust
0
or Prefix } else if len > 0 { alias == pattern || alias.starts_with(&format!("{}_", pattern)) } else { false } } /* fn load_transcript(mut flac_path: PathBuf) -> Option<String> { flac_path.set_extension("txt"); if let Ok(mut file) = File::open(flac_path) { let mut text...
Rust
0
path::Path; use game::*; pub fn from_file<P: AsRef<Path>>(path: P) -> Option<ControlMap> { let spec: Option<StringControlSpec> = game_file::read_toml(path).ok(); spec.as_ref().map(ControlMap::from) } pub fn to_file<P: AsRef<Path>>(path: P, map: &ControlMap) { game_file::write_toml(path, &StringControlSpe...
Rust
0
presigned_request_with_reqwest(&presigned_request, body.clone()).await; send_presigned_request_with_hyper(presigned_request, hyper::Body::from(body.clone())).await; Ok(()) } /// This function demonstrates how you can convert a presigned request into a cURL command /// that you can run from your terminal of ch...
Rust
0
from social.backends.oauth import BaseOAuth2 from django.conf import settings from ide.models.user import UserGithub from ide.models.project import Project import ide.utils.mailinglist as mailinglist class PebbleOAuth2(BaseOAuth2): name = 'pebble' AUTHORIZATION_URL = '{0}/oauth/authorize'.format(settings.SOCIA...
Python
1
} _ => unreachable!(), }; abi.emit_stack_pre_adjust(ctx); assert!(inputs.len() == abi.num_args()); for (i, input) in inputs.iter().enumerate() { let arg_reg = put_input_in_reg(ctx, *input, NarrowValueMode::None); abi.e...
Rust
0
TEMPORARY_SOURCES).unwrap(), ); // Create the `log` directory if it doesn't exist, but don't remove it if it does exist! fs::create_dir(env::var(constants::RADULA_ENVIRONMENT_DIRECTORY_LOGS).unwrap()); // Remove cross log file if it exists fs::remove_file(env::var(constants::RADULA_ENVIRONMENT_FIL...
Rust
0
>src/discord/interface/channel/thread_member.rs use chrono::{DateTime, Utc}; use crate::discord::snowflake::Snowflake; #[derive(Serialize, Deserialize, Debug)] pub struct ThreadMember { id: Snowflake, user_id: Snowflake, join_timestamp: DateTime<Utc>, flags: usize, } <reponame>loicngr/Squar...
Rust
0
opcode = 6; pub const ibv_wr_opcode_IBV_WR_BIND_MW: ibv_wr_opcode = 8; pub const ibv_wr_opcode_IBV_WR_LOCAL_INV: ibv_wr_opcode = 7; pub const ibv_wr_opcode_IBV_WR_RDMA_READ: ibv_wr_opcode = 4; pub const ibv_wr_opcode_IBV_WR_RDMA_WRITE: ibv_wr_opcode = 0; pub const ibv_wr_opcode_IBV_WR_RDMA_WRITE_WITH_IMM: ibv_wr_opcode...
Rust
0
from typing import List import sys # Increase recursion depth limit for potentially deep DFS paths # Be cautious with this in production environments, but useful for deep grids in competitive programming. # sys.setrecursionlimit(10000) # Usually not needed for constraints m, n <= 300 class Solution: """ Solve...
Python
1
impl Dataset { fn size(&self) -> usize { match self { Dataset::Small => 1024, Dataset::Medium => 10_000, Dataset::Large => 1_000_000, } } } pub fn scans(c: &mut Criterion) { // Handle the single gets #[cfg(debug_assertions)] let sizes = [Dataset::...
Rust
0
potion available use it /// instead of attacking in the current turn. fn autopotion(game: &mut Game, enemy: &Character) -> bool { if game.player.current_hp > game.player.max_hp / 3 { return false; } // If there's a good chance of winning the battle on the next attack, // don't use the potion. ...
Rust
0
ion.set_host_numa_node_id(host_numa_node_id); region.set_file_offset(file_offset); region.set_perm_flags(perm_flags); if is_hotplug { region.set_hotplug(); } region } /// Create an address space region to map memory into the virtual machine. /// /// ...
Rust
0
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List, Optional from .. import models, schemas, database router = APIRouter(prefix="/meals", tags=["meals"]) def get_db(): db = database.SessionLocal() try: yield db finally: db.close...
Python
1
k. /// /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_kor_mask32&expand=3240) #[inline] #[target_feature(enable = "avx512bw")] #[cfg_attr(test, assert_instr(or))] // generate normal and code instead of kord pub unsafe fn _kor_mask32(a: __mmask32, b: __mmask32) -> __mmas...
Rust
0
import os import mne import matplotlib.pyplot as plt # Define the path to the dataset data_path = "chb-mit-scalp-eeg-database-1.0.0/chb01" # List all the .edf files in the "chb01" directory edf_files = [f for f in os.listdir(data_path) if f.endswith('.edf')] # Create a list to store the loaded EEG data raw_list = []...
Python
1
xb䶈 l U 32%22H1"%5\-ڕ9?ƨ4 pX͒;'q5%.~p U)wž$n/qqċm^yi9޶z_,ͼfx7K[|n]|e 3kY U&xV]!«e !u@Y-S9.e {+4V(.I8wT1<|y:k El(i.\O.nx[۩ uADek Rhtx)",We`޺r@>:ڧ 38m;$^$JB4!\.5J6ڂȳcZ79^uϻNHr~u$8$c 8#!x^ ˺B0| ]HϽ8Sː^[t [lMb tkZ#);/=;#ގQ9]I%ǁ9-ld"jVUM`VŘLϥB\tɝb"OЊC0ѹj<pr...
Python
1
crate) data: ProgramData<CgroupSkbLink>, pub(crate) expected_attach_type: Option<CgroupSkbAttachType>, } impl CgroupSkb { /// Loads the program inside the kernel. pub fn load(&mut self) -> Result<(), ProgramError> { self.data.expected_attach_type = self.expected_attach_type ...
Rust
0
EN_W { w: self } } #[doc = "Bit 7 - I2C No Hold BUS Enable Bit Note: The I2C controller could respond when WKIF event is not clear, it may cause error data transmitted or received. If data transmitted or received when WKIF event is not clear, user must reset I2C controller and execute the original operation aga...
Rust
0
terest: Ready, opts: PollOpt) -> RegistrationData { RegistrationData { token: token, interest: interest, opts: opts, } } fn update(&mut self, token: Token, interest: Ready, opts: PollOpt) { self.token = token; self.interest = interest; ...
Rust
0
A list of labels corresponding to each error. """ cls_embbedings = self.get_embeddings(errors) cls_embbedings = self.preprocess_features(cls_embbedings) self.int_to_labels = {i: label for i, label in enumerate(set(labels))} self.labels_to_int = {label: i for i, label in...
Python
1
if "item" in ret.kwargs: ret.kwargs["item"] = item elif "items" in ret.kwargs: # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal ret.kwargs["items"][i] = item i += 1 elif "items" in...
Python
1
import os import shutil base_dir = "stableOsuData/Songs" output_dir = "organized" mp3_dir = os.path.join(output_dir, "mp3") osu_dir = os.path.join(output_dir, "osu") os.makedirs(mp3_dir, exist_ok=True) os.makedirs(osu_dir, exist_ok=True) def get_overall_difficulty(osu_file): with open(osu_file, 'r', encoding='u...
Python
1
}', '\u{05BC}']), (0xf9c7, &['\u{5289}']), (0x476, &['\u{0474}', '\u{030F}']), (0x1cd, &['\u{0041}', '\u{030C}']), (0xf9bf, &['\u{6A02}']), (0x1ead, &['\u{0061}', '\u{0323}', '\u{0302}']), (0x105, &['\u{0061}', '\u{0328}']), (0x2f9a4, &['\u{26C36}']), (0x15b, &['\u{0073}', '\u{0301}']), ...
Rust
0
(2, 2))) model.add(Dropout(0.4)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.4)) model.add(Dense(64, activation='relu')) model.add(Dense(n_classes)) model.add(Activation('softmax')) adam_optimizer = Adam(learning_rate=0.001) model.compile(loss=...
Python
1
StmtKind<'tcx>, pub opt_destruction_scope: Option<region::Scope>, } #[derive(Debug)] pub enum StmtKind<'tcx> { Expr { /// scope for this statement; may be used as lifetime of temporaries scope: region::Scope, /// expression being evaluated in this statement expr: ExprId, }...
Rust
0
import socket import threading import hashlib import json HOST = '0.0.0.0' PORT = 5000 block_data = { "previous_hash": "0000000000000000abc123...", "target": "00000fffffffffffffffffffffffffffffffffffffff", "difficulty": 5 } TOTAL_NONCE = 100_000 SEGMENT_SIZE = 20_000 worker_id = 0 def sha256d(s): re...
Python
1
ration: {event['duration']}" ) for user_id in users: try: context.bot.send_message(user_id[0], message) except: continue def check_active_events() -> dict: """Check and clean up expired events.""" current_time = datetime.now() expired = [] for e...
Python
1
, "jiào,jiāo"), ('挎', "kuà,kū,kōu"), ('挏', "dòng"), ('挐', "ná,rú,nú"), ('挑', "tiāo,tiǎo,táo,diào,tiáo,tiao"), ('挒', "liè"), ('挓', "zhā"), ('挔', "lǚ"), ('挕', "dié,shè"), ('挖', "wā"), ('挗', "jué"), ('挘', "liě"), ('挙', "jǔ"), ('挚', "zhì"), ('挛', "luán"), ('挜', "y...
Rust
0
class ConfigEmail : def __init__(self): self.config = {} # 存储配置的字典 self.load_config() # 加载配置 def load_config(self): # 加载配置 self.config = { "emails": [ ("WilliamLewisWL1987@outlook.com", "William61899...
Python
1
se_tail<'def, 'r>( name: Span<'def>, input: Tokens<'def, 'r>, ) -> ParseResult<'def, 'r, Invoke<'def>> { if let Ok((input, args)) = parse_args(input) { Ok(( input, Invoke { invoker_opt: None, name, args, method_d...
Rust
0
tx.try_send(i).is_ok()); } assert_eq!(tx.try_send(n), Err(TrySendError::NoCapacity(n))) } const SIZE_RANGE: Range<usize> = 1..5; #[test] fn send_until_full() { for n in SIZE_RANGE { send_until_full_for(n); } } async fn send_until_full_async_for(n: usize) { let (mut tx, _rx) = super::chann...
Rust
0
from django.urls import path from . import views urlpatterns = [ path("menu/", views.Menu_list, name="menu_list"), path("menu_item/<str:slug>", views.item_details, name="menu_item"), path("order/", views.order, name="order"), path("orders/<str:slug>", views.past_orders, name="past_orders"), ]
Python
1
# 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 app...
Python
1
($( $(#[$meta:meta])* $vis:vis struct $vt:ident as $rate:ident { $( $van:ident: $vat:ty $(as $semantics:literal)? ),* $(,)? } )*) => {$( $(#[$meta])* #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] $vis struct $vt { ...
Rust
0
c! { r#" model A { id String @id @default(dbgenerated()) @map("_id") @test.ObjectId list_field String[] @test.Array(ObjectId) } "# }; schema.to_owned() } #[connector_test(schema(oid_list))] async fn objectid_...
Rust
0
t("src_port") if rule.get("dest_port"): match_kwargs["tcp_dst"] = rule.get("dest_port") elif proto == 0x11: if rule.get("src_port"): match_kwargs["udp_src"] = rule.get("src_port") if rule.get("dest_port"): ...
Python
1
rvice(), &p_internal, unblocker, &blobfs_verifier, &finspect::Node::default(), &Config::builder().blobfs(Mode::RebootOnFailure).build(), ) .await; assert_matches!( res, Err(MetadataError::Verify(VerifyError::Blo...
Rust
0
TokenSimplePushBuilder { fn as_ref(&self) -> &DeviceTokenSimplePush { &self.inner } } /// A token for Tizen Push Service #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct DeviceTokenTizenPush { #[doc(hidden)] #[serde(rename(serialize = "@type", deserialize = "@type"))] td_name: String, ...
Rust
0
1, 0, 0, 0, 0]) x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2) return x def rand_cutout(x, param): ratio = param.ratio_cutout cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5) set_seed_DiffAug(param) offset_x = torch.randint(0,...
Python
1
} } None } fn run(&mut self) -> Result<PackageOutPaths, File> { self.calculator.find() } } type PackageOutPaths = HashMap<PackageArch, OutPath>; #[derive(Debug, PartialEq, Hash, Eq, Clone)] pub struct PackageArch { pub package: Package, pub architecture: Architectur...
Rust
0
[0.0, 0.0, 5.0]), mass=0.5, radius=0.25 ) else: # -- Ball geometry cube_prim_path = omni.kit.commands.execute("CreateMeshPrimCommand", prim_type="Sphere")[1] prim_utils.move_prim(cube_prim_path, "/World/envs/env_0/ball") # -- Ball physics RigidPrim(prim_path="/World/e...
Python
1
:param ce_kwargs: :param aggregate: :param square_dice: :param weight_ce: :param weight_dice: """ super().__init__() if ignore_label is not None: ce_kwargs['ignore_index'] = ignore_label self.weight_dice = weight_dice self.weight_ce...
Python
1
from .delete import DeleteBulkAction __all__ = ["DeleteBulkAction"]
Python
1
.unwrap(); chart .configure_mesh() .disable_mesh() .y_label_formatter(&|x| format!("{:.1}", *x as f64 / 1024.0 / 1024.0 / 1024.0)) .x_labels(5) .y_desc("Size(GiB)") .x_desc("Dictionary Size") .draw() .unwrap...
Rust
0
ONS.precedence.get(left).unwrap() > OPTIONS.precedence.get(right).unwrap() || rank.0 == 0 { operators.push(op); break; } } // The above will hold t...
Rust
0
// Returns temperature as milli-kelvins if a temperature reading is available. fn temperature_as_millikelvins(&self) -> Option<u32>; /// Returns temperature as milli-Celsius if a temperature reading is available. fn temperature_as_millicelsius(&self) -> Option<i32> { self.temperature_as_millikelvin...
Rust
0
disk", disk_columns).await?; assert_table_eq(expected_disk_table, &partitions); } // check that it recovers from the wal { let db = Db::restore_from_wal(dir).await?; let partitions = db.table_to_arrow("cpu", cpu_columns).await?; assert_table_eq(e...
Rust
0
= &document[idx..idx + SHINGLE_SIZE]; let mut hasher = DefaultHasher::new(); shingle.hash(&mut hasher); let shingle_hash = hasher.finish(); shingles.insert(shingle_hash); } shingles } fn jaccard_similarity(a: &HashSet<u64>, b: &HashSet<u64>) -> f32 { let intersection_cardin...
Rust
0
name="tinycoder_1M", block_size=2048, vocab_size=49152, padding_multiple=64, n_layer=2, n_head=8, n_embd=256, rotary_percentage=1.0, parallel_residual=False, bias=False, _norm_class="FusedRMSNorm", norm_eps=1e-5, _mlp_class=...
Python
1
w: u16, h: u16, } /// CRT Controller attributes (signal format) struct CrtcAttrs { frequency: u16, h_front_porch: u16, h_active: u16, h_back_porch: u16, h_sync_len: u16, v_front_porch: u16, v_active: u16, v_back_porch: u16, v_sync_len: u16, } static S_VGA_PCI_DRIVER: VgaPciDriver = VgaPciDriver; static S...
Rust
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright Huawei Technologies Co., Ltd. 2022-2022. All rights reserved. from . import accelerate_api, math_api, numpy_api, sklearn_api, torchmetrics_ops, utils, thop_api
Python
1
<MyAbout>>,i32)>> = RefCell::new(None) ); pub(crate) fn init(builder: GtkBuilder) { let my_about = Rc::new(RefCell::new(MyAbout::new(builder))); UI_AB_DLG_GLOBAL.with(move |global| { *global.borrow_mut() = Some((my_about, 0)); }); } pub(crate) struct MyAbout { ab: gtk::AboutDialog, } impl MyAb...
Rust
0
with com: logger.info("getting growth rates for %s knockout." % sp) [ r.knock_out() for r in com.reactions.query(lambda ri: ri.community_id == sp) ] sol = optimize_with_fraction(com, fraction) ...
Python
1
_d, RoleD, 3 | send_mpst_b_to_e, RoleE, 4 | send_mpst_b_to_f, RoleF, 5 | send_mpst_b_to_g, RoleG, 6 | send_mpst_b_to_h, RoleH, 7 | send_mpst_b_to_i, RoleI, 8 | send_mpst_b_to_j, RoleJ, 9 | send_mpst_b_to_k, RoleK, 10 | send_mpst_b_to_l, RoleL, 11 | send_mpst_b_to_m, RoleM, 12 | s...
Rust
0
ave(&self.memory); self.allocator.deallocate(source_address); lower } fn allocate_node(&mut self, node_type: NodeType) -> Node { Node { address: self.allocator.allocate(), entries: vec![], children: vec![], node_type, max_key_...
Rust
0
import os, json, requests def execute(question: str, parameter): repo_name = run_git_workflow(parameter["email"]) return repo_name def run_git_workflow(email): # GitHub repository details GITHUB_OWNER = "23f2004837" # Replace with your GitHub username/org GITHUB_REPO = "daily-commit" ...
Python
1
multiple_languages() { let mut ctx = Context::new(); ctx.init(InitOptions::new().expand_address()) .unwrap(); let mut opts = ExpandAddressOptions::new(); opts.set_languages(vec!["es", "fr"].as_slice()); let expansions = ctx .expand_address("Thirty W 26th St Fl...
Rust
0