text
string
label_name
string
labels
int64
stars>0 use core::cell::UnsafeCell; use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use zephyr_sys::raw::k_mutex; use super::NegErr; use crate::kobj::*; // Declare the Zephyr struct to be a kernel object unsafe impl KObj for k_mutex {} pub use zephyr_sys::raw::k_mutex as KMutex; /// Defines a newt...
Rust
0
_base_ = [ 'co_dino_5scale_lsj_r50_1x_coco.py' ] # model settings model = dict( query_head=dict( transformer=dict( encoder=dict( type='DetrTransformerEncoder', num_layers=9, # number of layers that use checkpoint with_cp=9))))
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- # # 5_extract_quarter_round.py - NoSuchCon 2013 Extract a quarter of a round. # Copyright (C) 2013 Axel "0vercl0k" Souchet - http://www.twitter.com/0vercl0k # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Python
1
r: 1 -------- 0 /| /| 2 -------- 3 . | | | | . 5 -------- 4 |/ |/ 6 -------- 7 ''' qs = qs.astype(np.int32) for k in range(0,4): #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html ...
Python
1
} } impl FloatLiteralE for FloatError { fn float_no_leading_digits() -> Self { Self::LeadingDigits } fn float_no_point() -> Self { Self::NoPoint } fn float_no_trailing_digits() -> Self { Self::TrailingDigits } fn float_no_exponent_digits() -> Self { Self::...
Rust
0
import json import random import string import spacy from spacy.symbols import ORTH # run python -m spacy download en_core_web_sm # def subject_drop(doc, prob): # if random.random() < prob: # return " ".join([tok.text for tok in doc if tok.dep_ != "nsubj"]) # return doc.text # def remove_stop...
Python
1
from fastapi import APIRouter,Depends,HTTPException from sqlalchemy.orm import Session from sqlalchemy import text from Schema.Blog import BlogResponse as blog_response,BlogRequest from Models.database import get_db from Models.Blog import Blog as blog_db from Routers.auth import get_user_from_header_token blog_router...
Python
1
_TOKEN_ID, ALICE)], mock_hash)); assert_eq!( <Tokens as LockableCurrencies<AccountId>>::locked_balance(TEST_TOKEN_ID, &ALICE), 0 ); }) } #[test] fn locks_not_shared_between_proposals() { // The whole point of quadratic voting is to force people to car...
Rust
0
aler(&params, &sk, &pk, bob, &vote_id, &bob_sealer_id); // Use 2. Sealer: Charlie let (charlie, _, charlie_sealer_id) = get_sealer_charlie(); let (charlie_key, _) = setup_sealer(&params, &sk, &pk, charlie, &vote_id, &charlie_sealer_id); // combine the public key shares ...
Rust
0
(&state.gitlab_client) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let merge_request = commit_merge_requests.first().ok_or(StatusCode::OK)?; info!("Pipeline has an MR"); let endpoint = PipelineJobs::builder() .project(pr...
Rust
0
_base_ = [ '../rotated_retinanet/rotated_retinanet_obb_r50_fpn_6x_hrsc_rr_le90.py' ] model = dict( bbox_head=dict( reg_decoded_bbox=True, loss_bbox=dict( _delete_=True, type='GDLoss', loss_type='kld', fun='log1p', tau=1, sq...
Python
1
_is_any_true(tokens[:,prompt_len:] == EOS) or torch._is_any_true(tokens[:,prompt_len:] == PAD): break generated_ids.extend(tokens[0][- 1: ].tolist()) generated_text = ( tokenizer.decode( generated_ids, skip_special_tokens...
Python
1
#[doc = "Bits 22:23 - PRS Stop Mode"] #[inline(always)] pub fn prsstopmode(&mut self) -> PRSSTOPMODE_W { PRSSTOPMODE_W { w: self } } #[doc = "Bits 26:27 - PRS Clear Mode"] #[inline(always)] pub fn prsclearmode(&mut self) -> PRSCLEARMODE_W { PRSCLEARMODE_W { w: self } } } <fil...
Rust
0
import time import random class First: initial=[] wheel=[] number_Of_Characters_List=[] individual_Characters=[] characters_Length=0 counter_Up=0 test=["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] key="" question="" question2="" haver="" que...
Python
1
; use std::mem::transmute; glib::wrapper! { #[doc(alias = "WebKitDOMHTMLParamElement")] pub struct DOMHTMLParamElement(Object<ffi::WebKitDOMHTMLParamElement, ffi::WebKitDOMHTMLParamElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { type_ ...
Rust
0
# -*- coding: utf-8 -*- from kivymd.app import MDApp from kivymd.uix.screen import MDScreen from kivymd.uix.floatlayout import MDFloatLayout from kivymd.uix.dialog import MDDialog from kivymd.uix.boxlayout import MDBoxLayout #from kivymd.uix.pickers import MDDatePicker from datetime import datetime class Alarm_clock(...
Python
1
grp_setgid == 0o002000 { flags[6] = 'S'; } else if xgrp_setgid == (0o000010 | 0o002000) { flags[6] = 's'; } // sticky let xoth_sticky = mode & (0o000001 | 0o001000); if xoth_sticky == 0o001000 { flags[9] = 'T'; } else if xoth_sticky == (0o000001 | 0o001000) { fla...
Rust
0
3, carry) = mac64_typemax(0, u, carry); let (a4, carry2) = adc64(0, 0, carry); let (_, carry) = mac64(a0, x0, y0, 0); let (a1, carry) = mac64(a1, x0, y1, carry); let (a2, carry) = mac64(a2, x0, y2, carry); let (a3, carry) = mac64(a3, x0, y3, carry); let (a4, a5) = adc64(...
Rust
0
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: # Check if the given strings are valid if len(s1) > len(s2): return False # Maintain a dictionary for character counts of s1 value_of_s1 = {} for c in s1: if c in value_of_s1: ...
Python
1
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ We have a pony and/or a unicorn. """ from paste.request import construct_url PONY = """ eJyFkkFuxCAMRfdzCisbJxK2D5D2JpbMrlI3XXQZDt9PCG0ySgcWIMT79r...
Python
1
true) .with_spacer(10.) .with_child(chat_button) .with_spacer(10.) .with_child(contacts_button) .with_spacer(10.) .with_child(settings_button) .with_flex_spacer(1.) .padding(10.) .background(Color::BLACK); } #[doc = "Reader of register COMMAND"] pu...
Rust
0
]. mod guidance; mod licence; mod organisation; mod section; mod standard; mod theme; mod topic; pub use guidance::{GuidanceRecord, GuidanceStandardRecord}; pub use licence::LicenceRecord; pub use organisation::OrganisationRecord; pub use section::SectionRecord; pub use standard::{EndorsementStateRecord, RelatedStand...
Rust
0
deck belonging to the given user from the current league. pub fn lookup_deck(conn: &PgConnection, user: &SerenityUser) -> Result<Option<Deck>> { use crate::schema::decks::dsl::*; let lg = match current_league(conn)? { Some(l) => l, None => return Ok(None), }; let user = match lookup_us...
Rust
0
me>src/real.rs use crate::IntoInner; /// The error produced when NaN is encountered. #[derive(Debug, Clone, Copy)] pub struct NanError; impl std::fmt::Display for NanError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "encountered NaN unexpectedly") } } /// Trait for a f...
Rust
0
data.id; let version = manifest_metadata.version; printer.status( "Deleting", format!( "catalog schema (namespace = {}, id = {}, version = {})", namespace, id, version ), )?; delete_catalog_schema(client, namespace.clone...
Rust
0
gpio::write_output_pin(gpio::Pin::OkLed, gpio::Output::Clear); timer::wait(500); gpio::write_output_pin(gpio::Pin::OkLed, gpio::Output::Set); timer::wait(500); if switch == true { spi::ili9340::draw_girl(); switch = false; } else { spi...
Rust
0
ildcard(WildcardType<'a>), Primitive(PrimitiveType<'a>), } impl<'a> TypeArg<'a> { pub fn to_type(&self) -> Type<'a> { match self { TypeArg::Parameterized(p) => Type::Parameterized(p.clone()), TypeArg::Class(c) => Type::Class(c.clone()), TypeArg::Array(a) => Type::Arr...
Rust
0
import time from 读取class获取行 import 排序 # 存储字符及其行号的字典 char_line_mapping = {} char_line_mapping2 = {} def 排序RS(filename,filename2): 列表 = {} 列表2 = {} print(f'------------------------------------------filename------------------------------------------') 排序2 = 排序(filename=filename, char_line_mapping=列表) ...
Python
1
"""Constants for Hyperion integration.""" CONF_AUTH_ID = "auth_id" CONF_CREATE_TOKEN = "create_token" CONF_INSTANCE = "instance" CONF_INSTANCE_CLIENTS = "INSTANCE_CLIENTS" CONF_ON_UNLOAD = "ON_UNLOAD" CONF_PRIORITY = "priority" CONF_ROOT_CLIENT = "ROOT_CLIENT" CONF_EFFECT_HIDE_LIST = "effect_hide_list" CONF_EFFECT_SHO...
Python
1
)).or_insert_with(|| { verts.push(VertNT { pos: obj.position[i.0], norm: match i.2 { Some(i) => obj.normal[i], None => [0.; 3] }, tex: match i.1 { Some(i) => obj.texture[i], None => [0.; 2] }, }); verts.len() as u32 - 1 })); ...
Rust
0
# Convert annotated image to base64 _, buffer = cv2.imencode('.jpg', annotated_image) annotated_image_b64 = base64.b64encode(buffer).decode('utf-8') return jsonify({ 'predictions': predictions, 'annotated_image': f"data:image/jpeg;base64,{annotated_image_b64}", ...
Python
1
import tensorrt as trt import os def onnx2trt(model_version_dir, onnx_model_file, max_batch): logger = trt.Logger(trt.Logger.WARNING) builder = trt.Builder(logger) # The EXPLICIT_BATCH flag is required in order to import models using the ONNX parser network = builder.create_network(1 << int(trt.Netw...
Python
1
# Copyright 2024 Superlinked, 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 wri...
Python
1
k(); }) } { fatal_err(daemonise, "Can't install SIGHUP handler", e); } if let Err(e) = unsafe { signal_hook::low_level::register(signal_hook::consts::SIGCHLD, move || { // All functions called in this function must be signal safe. See signal(3)...
Rust
0
to_string(&JsonRpcCallSer::new(Id::Number(req_id), method, params)).map_err(|e| { self.id_guard.reclaim_request_id(); Error::ParseError(e) })?; log::trace!("[frontend]: send request: {:?}", raw); if self .to_back .clone() .send(FrontToBack::Request(RequestMessage { raw, id: req_id, send_back: Some...
Rust
0
.1:8000"; println!("server has on: {}", address); let mut app = tide::new(); // 设置请求的中间件处理 app.with(log::LogMiddleware::new()); app.at("/orders/shoes").post(order_shoes); app.at("/").get(home); app.at("/index").get(|_| async { Ok("hello rust") }); app.at("/submit").post(submit); ap...
Rust
0
# -*- coding: utf-8 -*- """ 超參數調優基礎類別 此模組定義超參數調優的基礎類別和介面,提供: - 統一的調優介面 - MLflow 實驗追蹤整合 - 結果管理和視覺化 Classes: HyperparameterTuner: 超參數調優器基礎類別 """ import logging from abc import ABC, abstractmethod from typing import Any, Callable, Dict, Optional, Union import mlflow import pandas as pd from src.config import LOG_...
Python
1
def image_box_region_area(img_cumsum, bbox): """check a 2d voxel is contained by a box. used to filter empty anchors. Summed-area table algorithm: ==> W ------------------ | | | |------A---------B | | | | | | |----- C---------D Iabcd = I...
Python
1
s = weights[ig, 0] for i in range(1, nz): a1 = circle_circle_intersection_area(ze[i], k, b) weights[ig, i] = a1 - a0 a0 = a1 s += weights[ig, i] for i in range(nz): weights[ig, i] /= s return gs, gs[1] - gs[0], weights @njit def calculat...
Python
1
make_table(&mut m, "foreach_pin", &pins_table); make_table(&mut m, "foreach_dma_channel", &dma_channels_table); let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); let out_file = out_dir.join("_macros.rs").to_string_lossy().to_string(); fs::write(out_file, m).unwrap(); // ======== ...
Rust
0
#[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Multiplier { pub id: String, pub field: u32, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Classifier { pub id: String, pub field: u32, } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Field { #[serd...
Rust
0
tasks.is_empty() } } <gh_stars>0 fn part1(pos: &[i64]) -> i64 { let n = pos.len(); let m = pos[n / 2]; pos.iter().map(|p| (p - m).abs()).sum() } fn part2(pos: &[i64]) -> i64 { let n = pos.len(); let sum = pos.iter().sum::<i64>(); let avg = sum / n as i64; (avg..=avg + 1) .map(|a...
Rust
0
y.shape`, `ndarray.size` and `ndarray.ndim` can return `ndarray` objects instead of returning integer (or tuple of integer) values. * `__len__`, `__iter__` and `__index__` properties of `ndarray` may similarly not be supported in graph mode. Code using these may need to change to explicit shape operations...
Python
1
+ serde::Serialize + serde::de::DeserializeOwned, { #[inline] fn pre_exec(&mut self) -> Result<(), Error> { self.reset_map() } } impl<T> Named for VariableMapObserver<T> where T: Default + Copy + 'static + serde::Serialize + serde::de::DeserializeOwned, { #[inline] fn name(&self) -> &s...
Rust
0
#!/usr/bin/env python __all__ = ['sohu_download'] from common import * def real_url(host, prot, file, new): url = 'http://%s/?prot=%s&file=%s&new=%s' % (host, prot, file, new) start, _, host, key, _, _ = get_html(url).split('|') return '%s%s?key=%s' % (start[:-1], new, key) def sohu_download(url, merge=True): v...
Python
1
int e, int f, int g, int h, int i, int j, int k, int l) foo = rec(a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0, j=0, k=0, l=0); } fn main() { f(); } <filename>benches/ts-format.rs<gh_stars>1-10 use std::io::Write; use chrono::{format::strftime::StrftimeItems, Datelike, FixedO...
Rust
0
bars. ') return ohlcvs def fetchAll(self, symbol, timeframe): return self.fetchRange( symbol, timeframe ) def fetchCandles( self, symbol, timeframe, ohlcv_cache = None ): if( len(ohlcv_cache) > 0 ): oldestTimestamp = ohlcv_cache[0][0] newestTimestamp = ohlc...
Python
1
assert_eq!(colors[5], Color::new(134, 123, 107)); // 156, 175, 121 assert_eq!(colors[6], Color::new(160, 178, 120)); // 131, 121, 110 assert_eq!(colors[7], Color::new(167, 199, 221)); // 167, 198, 220 assert_eq!(colors[8], Color::new(212, 80, 7)); // 213, 75, 8 } #[test] fn image2() { let img = i...
Rust
0
#!/usr/bin/env python3 from typing import List # time: O(nlog(n)), space: O(n) class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: pass print(Solution().findTheCity(n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4)) print('Expected:...
Python
1
_events: true, emit_warning_events: false, attach_stacktraces: true, dest_log: None, } } } impl LogIntegration { /// Initializes an env logger as destination target. #[cfg(feature = "env_logger")] pub fn with_env_logger_dest(mut self, logger: Option<env_logge...
Rust
0
#주민번호를 입력받아 #1900년대면 1,2 2000년이면 3,4 #태어난 년도를 계산해 나이를 출력 jumin = input("주민번호 : ") this_year = 2024 print(jumin[7]) if jumin[7] == '1' or jumin[7] == '2': # in ('1','2') 도 됨 result1 = int('19' + jumin[0:2]) result2 = (this_year - result1) + 1 print(f"당신의 나이 : {result2}") elif jumin[7] == '3' or jumin[7] ...
Python
1
from setuptools import setup, find_packages setup( name="discovery_markets", version="0.1", packages=find_packages(), install_requires=[ # Add your project dependencies here # Example: 'requests==2.25.1', ], entry_points={ "console_scripts": [ "discovery_mark...
Python
1
6d6dcc59dba617b5f4b', 'e3ae3f7b32cf99b29d3c8681ec3be321', 'f10ce4008da194626f38f937fb9c1a03', 'e6f24af5f87558d31db17b86fe269cf2', '1dba3a1039c6ec1a3c141a1cb0ad0757', 'b814705bc93d428507a516b866efda28', '26e33980e4b4345587d6278460746ec4', '5f3f959c7b3e6f091898caa8e828f110', 'b5bd72478fce2a2dbd1beb1baca48abd'...
Python
1
from typing import Dict, List, Optional, Any MAIN_LOCALE_LIST = [ 'af', 'am', 'ar', 'as', 'az', 'be', 'bg', 'bn', 'bs', 'ca', 'cs', 'cy', 'da', 'de', 'el', 'en-GB', 'es-419', 'fr', 'fr-CA', 'gl', 'gu', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lo', 'lt', 'lv', 'ml...
Python
1
], device=self.device, dtype=torch.float32, ) for ii in range(n_samples) ] self.data[f"one_hot_{idx}"] = [ torch.tensor( [ ATOM_MAPPING[_at] for _at in data["charges"][ii][: data[...
Python
1
| { Ok(Response { body: serde_json::to_string(&page_tokens).expect("Token page failure"), status_code: 200, }) }); // Known Addresses // the current safe does not get requested as a knownAddress by design // The...
Rust
0
.randomize(); loop { universe.update(); check_cell_state_change(&mut universe, cell_size); let padding = get_board_padding(cell_size); render_cells(cell_size, padding, &universe); draw_grid(cell_size, padding); check_restart_signal(&mut universe); next_frame()...
Rust
0
name_atomic_ptr( get_proc_address, b"glGetBooleanv\0", &self.glGetBooleanv_p, ) } #[inline] #[doc(hidden)] pub fn GetBooleanv_is_loaded(&self) -> bool { !self.glGetBooleanv_p.load(RELAX).is_null() } /// [glGetBufferParameteri64v](http://docs.gl/es3/glGetBuffer...
Rust
0
peripheral. pub trait AlternateVeryHighSpeed { /// Puts the pin in the Alternate Function 11 with Very High Speed. fn into_af11_very_high_speed(self); } pub struct EthPins<REFCLK, IO, CLK, CRS, TXEN, TXD0, TXD1, RXD0, RXD1> { pub ref_clk: REFCLK, pub md_io: IO, pub md_clk: CLK, pub crs: CRS, ...
Rust
0
&[125243]), (125210, &[125244]), (125211, &[125245]), (125212, &[125246]), (125213, &[125247]), (125214, &[125248]), (125215, &[125249]), (125216, &[125250]), (125217, &[125251]), ]; #[allow(dead_code)] pub const UPPER: &'static [(u32, &'static [u32])] = &[ (97, &[65]), (98, &[...
Rust
0
] #if _x == 20: # continue #print _x,dijkstra['x_range']#,_y#,dijkstra['x_range'][1],dijkstra['y_range'][1] _score = clip(int(abs(dijkstra['map'][y,x])),0,9) #_score = int(dijkstra['map'][y,x]) if (_x,_y,0) in path: _score = 'O ' elif _score == -1: _score = 'x ' else: _sc...
Python
1
import matplotlib.pyplot as plt import numpy as np # รายชื่อหุ่นยนต์ robots = [ "BigDog", "HyQ", "MiniHyQ", "HyQ2Max", "HyQReal", "Minitaur", "ANYmal", "MIT Mini Cheetah", "Stanford Doggo", "Spot", "Solo8", "Unitree Go2" ] # ประเภทเซนเซอร์ sensors = [ "Encoders", "IMU", "Force/Torque", "Hydraulic Pres...
Python
1
ator at {:.1f} Years Observed Data Span at 90% CI'.format(span), color=color, alpha=0.5) one_year_mean_ci.append((cis[-1][1]-cis[-1][0])[:12].mean()) five_year_mean_ci.append((cis[-1][1]-cis[-1][0]).mean()) moving_sum_median.append(quantile(moving_sum(sample, 12, 1), [0.5])[0].detach().numpy()) ...
Python
1
from typing import Any, Dict, Iterator, List, Optional from langchain_core.documents import Document from langchain_community.document_loaders.base import BaseLoader class TiDBLoader(BaseLoader): """Load documents from TiDB.""" def __init__( self, connection_string: str, query: str,...
Python
1
ref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub fn parse_metadata(blob: &str) -> Result<MetadataMap, Error> { let mut map = MetadataMap(HashMap::new()); for line in blob.split('\n').filter(|s| s != &"") { let pos = match line.bytes().position(|b| b == b':') { Some(...
Rust
0
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import datetime import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import MapCompose, TakeFirst, Join import re class ArticleSpiderItem(s...
Python
1
ath_keyword='path') bus.add_signal_receiver(scanDone, dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, signal_name="ScanDone", path=path) bus.add_signal_receiver(bssAdded, dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE, signal_name="BSSAdded", path=path) bus.add_signal_receiver(bssRemoved, ...
Python
1
unwrap(); match *guard { ShellWindow::Decorated(ref mut deco) => { deco.resize(x as i32, y as i32); }, _ => {} } } #[inline] pub fn create_window_proxy(&self) -> WindowProxy { WindowProxy } #[inline] pub fn poll_events(&self) -> PollEventsIterato...
Rust
0
.call_aimFunc(offspring) # 求进化后个体的目标函数值 population = self.reinsertion(population, offspring, refPoint) # 重插入生成新一代种群 # 修改refPoint refPoint[NIND:, :] = self.renewRefPoint(population.ObjV, refPoint[NIND:, :]) if (self.currentGen) % np.ceil(self.fr * self.MAXGEN) == 0: ...
Python
1
#!/usr/bin/env python """Legacy code that isn't split up into resource based clients.""" from collections.abc import Callable import sys from googleapiclient import discovery from typing_extensions import TypeAlias from clients import client_project from clients import utils as bq_client_utils from utils import bq_e...
Python
1
:disallowed_method)] extern crate regex; use regex::Regex; fn main() { let a = vec![1, 2, 3, 4]; let re = Regex::new(r"ab.*c").unwrap(); re.is_match("abc"); a.iter().sum::<i32>(); } <filename>src/client/bridge/gateway/mod.rs //! The client gateway bridge is support essential for the [`client`][clien...
Rust
0
import typing from collections.abc import Mapping import pydantic.v1 as pydantic_v1 import pcapi.connectors.big_query as big_query_connector Row = typing.TypeVar("Row", bound=pydantic_v1.BaseModel) RowIterator = typing.Generator[Row, None, None] class MalformedRow(Exception): def __init__(self, msg: str, inde...
Python
1
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Description: @Author: Kermit @Date: 2024-02-18 17:15:19 """ import multiprocessing as mp from multiprocessing.pool import Pool from typing import Any, Optional, Union import cv2 import numpy as np import config from face_detection.retinaface_torch import RetinaFace...
Python
1
//! // Access std::process::Child. //! let shell_child = shell_command.spawn().unwrap(); //! { //! let mut lock = shell_child.0.write().unwrap(); //! let mut child = &mut lock.as_mut().unwrap().child; //! let mut str = String::new(); //! child.stdout.as_mut().unwrap().read_to_string(&mut str); //! } //! shell_c...
Rust
0
from pkg_resources import resource_filename DATA_ROOT = resource_filename('langcodes', 'data') import os def data_filename(filename): return os.path.join(DATA_ROOT, filename)
Python
1
self.0.has_duplicates() } pub fn is_upgradeable_loader_present(&self) -> bool { self.0.is_upgradeable_loader_present() } #[staticmethod] #[pyo3(name = "default")] pub fn new_default() -> Self { Self::default() } #[staticmethod] pub fn deserialize(data: &[u8]) -> P...
Rust
0
oreFoundationVersionNumber10_6: f64 = 550.0; pub const kCFCoreFoundationVersionNumber10_6_1: f64 = 550.0; pub const kCFCoreFoundationVersionNumber10_6_2: f64 = 550.13; pub const kCFCoreFoundationVersionNumber10_6_3: f64 = 550.19; pub const kCFCoreFoundationVersionNumber10_6_4: f64 = 550.29; pub const kCFCoreFoundationV...
Rust
0
令,尝试从代码块中提取 if not commands: code_blocks = re.findall( r'```(?:bash|shell|sh)?\s*([\s\S]*?)```', text) for block in code_blocks: lines = block.strip().split('\n') for line in lines: line = line.strip() ...
Python
1
import os import httpx from bert_score_api.utils import check_env_vars class BERTScoreClient: def __init__(self): check_env_vars(["BERT_SCORE_API_HOST", "BERT_SCORE_API_PORT"]) BERT_SCORE_API_HOST = os.environ["BERT_SCORE_API_HOST"] BERT_SCORE_API_PORT = os.environ["BERT_SCORE_API_PORT"...
Python
1
import time import sys from unitree_sdk2py.core.channel import ChannelSubscriber, ChannelFactoryInitialize from unitree_sdk2py.idl.default import unitree_go_msg_dds__WirelessController_ from unitree_sdk2py.idl.unitree_go.msg.dds_ import WirelessController_ key_state = [ ["R1", 0], ["L1", 0], ["start", 0]...
Python
1
: leo: 1, hw: 1 /// // Input: leo: 2, hw: 2, /// // Expect, status change, follower sync /// /// Simple HW mark calculation (assume LRS = 2) which is find minimum offset values that satisfy /// Assume: Leader leo = 10, hw = 2, /// follower: leo(2,4) => no change, since it doesn't sa...
Rust
0
# -*- coding: utf-8 -*- import sys , requests, re, random, string from multiprocessing.dummy import Pool from colorama import Fore from colorama import init init(autoreset=True) fr = Fore.RED fg = Fore.GREEN fw = Fore.WHITE requests.urllib3.disable_warnings() p = ''' NEMESIS TOOLS ''' print(fg + p + Fore.W...
Python
1
9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, ], [ 4, 13, 11, 0, 2, 11, 14, 7, ...
Rust
0
()).await?.unwrap(); assert_eq!(cloned.id(), loaded_session.id()); assert_eq!("value", &loaded_session.get::<String>("key").unwrap()); assert!(!loaded_session.is_expired()); task::sleep(Duration::from_secs(2)).await; assert_eq!(None, store.load_session(cookie_value).await?); ...
Rust
0
idx = df_metrics.sort_values(by=['num_less', 'num_more'], ascending=[True, False]).head(20) top20 = img_selections.loc[top20_idx.index] # Save the top 20 selections to a CSV top20.to_csv(f'{procdir}top20samp_selection.csv') # save the top selection and some "semi-distinct" other selections final_se...
Python
1
]); let mut form_data = MultipartFormData::parse(req_ct, data, options).unwrap(); let name = match form_data.texts.remove("name") { Some(mut name_fields) => { let name_field = name_fields.remove(0); name_field.text ...
Rust
0
rom_json(i) for i in resp["response"]["semesterCodeinfo"]["semestercode"]] @authenticated def get_exam_events(self, semester: Semester): """ :param semester: A Semester object :returns: A list of ExamEvent objects :raises APIError: Raised for generic API error """ ...
Python
1
2014", "14-20 sept. 2014"); example!(v, check_moment!(c, [2013, 2, 26]), "dentro de 2 semanas", "en dos semanas"); // 15j != 2 settimanas example!(v, check_moment!(c, [2013, 5, 12]), "dentro de 3 meses", "en tres meses"); example!(v, check_moment!(c, [2013, 2, 27]),"en 15 días","en los próximos quince d...
Rust
0
} path.join("/") } pub fn empty() -> Self { Self { children: vec![] } } pub fn add_level(&mut self, level: ChildOptions) { self.children.push(level); } pub fn append(&mut self, other: &Self) { for i in 0..other.children.len() { ...
Rust
0
r( &mut vm.arch.flag, res >= 1 << 7, res == 0, has_even_parity(res), ); if overflow { set_flag(&mut vm.arch.flag, Flags::OVERFLOW); } else { unset_flag(&mut vm.arch.flag, Flags::OVERFLOW); } } pub fn das(vm: &mut VM) { let al = get_byte_reg(vm, ByteRe...
Rust
0
raises(RuntimeError) as excinfo: m.private_op_new_value() assert "is neither movable nor copyable" in str(excinfo.value) assert m.private_op_new_reference().value == 1 def test_move_fallback(): """#389: rvp::move should fall-through to copy on non-movable objects""" m1 = m.get_moveissue1(1) ...
Python
1
//add omni output txouts.push(self.build_omni_output(property_id, self.amount)); //8.output data serialize let mut tx_to_sign = Transaction { version: 2i32, lock_time: 0u32, input: vec![], output: txouts, }; let mut output_seri...
Rust
0
| MEMORY_TO_REGISTER | WORD_TRANSFER | OPER_PCDI; pub const OP_MOVEM_16_ER_PCIX: u32 = OP_MOVEM | MEMORY_TO_REGISTER | WORD_TRANSFER | OPER_PCIX; pub const OP_MOVEM_32_RE_AI: u32 = OP_MOVEM | REGISTER_TO_MEMORY | LONG_TRANSFER | OPER_AI; pub const OP_MOVEM_32_RE_PD: u32 = OP_MOVEM | REGISTER_TO_MEMORY | LONG_TRANSFER...
Rust
0
math_2_in.try_into().unwrap(), NULL, ); utils::result( vips_op_response, VipsImage { ctx: out_out }, Error::Math2Error, ) } } /// VipsComplex2 (complex2), complex binary operations on two images /// left: `&VipsImage` -> Left-hand image argume...
Rust
0
"""Module header template for TAPAS GraphIR exporter.""" __copyright__ = """ Copyright (c) 2025 RapidStream Design Automation, Inc. and contributors. All rights reserved. The contributor(s) of this file has/have agreed to the RapidStream Contributor License Agreement. """ from tapa.verilog.graphir_exporter.assets.tem...
Python
1
i32; #[doc = "*Required features: `\"Win32_NetworkManagement_IpHelper\"`*"] pub const TcpConnectionEstatsObsRec: TCP_ESTATS_TYPE = 6i32; #[doc = "*Required features: `\"Win32_NetworkManagement_IpHelper\"`*"] pub const TcpConnectionEstatsBandwidth: TCP_ESTATS_TYPE = 7i32; #[doc = "*Required features: `\"Win32_NetworkMan...
Rust
0
. See the License for the // specific language governing permissions and limitations // under the License. use std::prelude::v1::*; use crate::ipc::{IpcReceiver, IpcService}; // Implementation of Receiver // The receiver is TEE, the sender is App pub struct ECallReceiver; impl IpcReceiver for ECallReceiver { f...
Rust
0
import sys class VendorImporter: """ A PEP 302 meta path importer for finding optionally-vendored or otherwise naturally-installed packages from root_name. """ def __init__(self, root_name, vendored_names=(), vendor_pkg=None): self.root_name = root_name self.vendored_names = set(v...
Python
1
''' Bài 7: Viết chương trình giải phương trình bậc 1: ax + b = 0 (a, b nhập từ bàn phím). Xét tất cả các trường hợp có thể. ''' a = int(input('Nhập giá trị a: ')) b = int(input('Nhập giá trị b: ')) print("Phương trình của bạn là : ",a,'x +',b,'= 0') if (a == 0) and (b == 0): print('Phương trình có vô số nghiệm') el...
Python
1
count = count + 1 NmC = NmC + int(NmC_c) NC = NC + int(NC_c) # line_c = CGMAP.readline() # # # End for reading files # while line_r: if count > 0: print(f'{chr_r}\t{pos_r1}\t{pos_r2}\t{mC/count:....
Python
1