text string | label_name string | labels int64 |
|---|---|---|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
max_depth = 0
result = 0
def deepestLeavesSum(self, root):
"""
:type root: TreeNode
:rtyp... | Python | 1 |
nt
);
}
println!("\t}}");
}
/// Function that prints all the paths in a graph
fn print_paths(&self) {
use bio::alphabets::dna;
use bstr::BString;
println!("\tPaths: {{");
// get all the path
for path_id in self.paths_iter() {
... | Rust | 0 |
import time
import requests
headers = {
'accept': 'application/json, text/javascript, */*; q=0.01',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'dnt': '1',
'referer': 'https://tu.gxnas.com/',
'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Bran... | Python | 1 |
# PyGame in combination with other libraries - tkinter
# https://www.pygame.org/docs/ref/pygame_and_othere_libraries.html
#
# Embedding a Pygame window into a Tkinter or WxPython frame
# https://stackoverflow.com/questions/23319059/embedding-a-pygame-window-into-a-tkinter-or-wxpython-frame
#
# https://www.libsdl.org/re... | Python | 1 |
data,
error: Error::last(),
});
}
Ok(Mutex(Handle::new(handle), data))
}
}
/// The timeout is specified in milliseconds
/// Specifying None for the timeout means to wait forever
pub fn wait(&self, timeout: Option<u32>) -> Resul... | Rust | 0 |
'season': nextjs_data.get('seasonName'),
'season_number': int_or_none(nextjs_data.get('seasonNumber')),
'channel': traverse_obj(nextjs_data, ('catalog', 'title')),
'channel_id': traverse_obj(nextjs_data, ('catalog', 'id'), 'catalogId'),
**traverse_obj(nextjs_data, (... | Python | 1 |
from prowler.lib.check.models import Check, Check_Report_AWS
from prowler.providers.aws.services.awslambda.awslambda_client import awslambda_client
from prowler.providers.aws.services.ec2.ec2_client import ec2_client
class ec2_securitygroup_not_used(Check):
def execute(self):
findings = []
for sec... | Python | 1 |
= 2144u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_CPU_THROTTLE: u32 = 3u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_CPU_TRACE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MD_CREATE_PROCESS_AS_USER: u32 = 6035u32;
#[doc = "*Requir... | Rust | 0 |
environment gracefully handles any
/// mismatches between itself and the manifest.
pub struct Manifested<E> {
/// The manifest.
pub manifest: model::manifest::Manifest,
/// The environment being interpreted by the manifest.
pub env: E,
}
impl<E: abs::Env> Manifested<E> {
/// Resets the environmen... | Rust | 0 |
_max_size: u64,
/// The maximum age in milliseconds of the stats log.
pub stats_log_max_age_millis: u128,
/// The amount of time in milliseconds to wait beforing closing a connection.
/// This is set to 2 minutes by default. This means that if a request is made,
/// and no additional requests are made for two minu... | Rust | 0 |
from collections import defaultdict
for _ in range(int(input())):
count=0
dic ={}
n =int(input())
s=input()
for i in range(n):
if s[i] in dic:
count+=i-dic[s[i]]
dic[s[i]]=i
for key in dic:
count+=n-dic[key]
print(count)
... | Python | 1 |
;
b.iter(|| clock.scaled(clock.end()))
}
fn time_instant_delta(b: &mut Bencher) {
b.iter(|| {
let start = StdInstant::now();
let d = StdInstant::now() - start;
(d.as_secs() * 1_000_000_000) + u64::from(d.subsec_nanos())
})
}
fn time_quanta_raw_delta(b: &mut Bencher) {
let clock... | Rust | 0 |
"""
Module to implement predicate classes.
Class of every predicate registered to ``Q`` is defined here.
"""
| Python | 1 |
range(4)]
crypto_hash_sha512_tweet(d, sk, 32)
d[0] &= 248
d[31] &= 127
d[31] |= 64
# There is no (simple?) way to return this argument's value back to the
# user in python. Rather than redefining the return value of this function
# it is better to advise the user that ``smlen`` does not ... | Python | 1 |
async def test_no_maps(
hass: HomeAssistant,
mock_roborock_entry: MockConfigEntry,
bypass_api_fixture: None,
) -> None:
"""Test that a device with no maps is handled correctly."""
prop = copy.deepcopy(PROP)
prop.status.map_status = 252
with (
patch(
"homeassistant.compo... | Python | 1 |
).unwrap();
let path = Path::new(&env::var("OUT_DIR").unwrap())
.join(item.ident.to_string())
.with_extension("rs")
.to_str()
.unwrap()
.to_string();
quote!(
#[path = #path]
#item
)
.into()
}
// "Tifflin" Kernel - Networking Stack
// - By <NAME> (t... | Rust | 0 |
ts_max: 1000,
notify_when_attacked: true,
disabled: false,
cooldown: 10,
action_log: StructureLinkActions {
transfer_energy: None,
},
user: "57874d42d0ae911e3bd15bbc".to_owned(),
}
);
... | Rust | 0 |
=> None,
Ok(response) => match response.status() {
StatusCode::OK | StatusCode::NOT_MODIFIED => self.fetch_result(response),
_ => None,
},
}
}
}
<filename>src/connectivity/bluetooth/core/bt-gap/src/test/configuration.rs
// Copyright 2020 The Fuchsia A... | Rust | 0 |
managed
/// reference counting.
///
/// Does not increment the reference count.
pub fn attach( itf : ComItf<T> ) -> ComRc<T> {
ComRc { itf }
}
/// Attaches a floating ComItf reference and brings it under managed
/// reference counting.
///
/// Does not increment the referen... | Rust | 0 |
S BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//! > FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//! > DEALINGS IN THE SOFTWARE.
//==============================================================================
// Possib... | Rust | 0 |
import re
import fitz # PyMuPDF
import pandas as pd
def extract_words_from_pdf(file_path, output_csv_path):
# Strict pattern to match words, part of speech, and CEFR levels
pattern = r'\b([a-zA-Z]+(?:, [a-zA-Z]+)?)\s+([a-zA-Z.]+)\s+(A[12]|B[12]|C[12])\b'
# Function to extract words using PyMuPDF
def... | Python | 1 |
from pathlib import Path
base_path = Path(__file__).parent
data = base_path.joinpath("input.in").read_text().strip().splitlines()
# print(data) | Python | 1 |
ee.EEException as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Earth Engine error: {e}"
)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Input data error: {e... | Python | 1 |
;
#[doc = "*Required features: 'Win32_System_Ioctl'*"]
pub const STORAGE_ATTRIBUTE_PERF_SIZE_INDEPENDENT: u32 = 32u32;
#[doc = "*Required features: 'Win32_System_Ioctl'*"]
pub const STORAGE_ATTRIBUTE_VOLATILE: u32 = 8u32;
#[repr(C)]
#[doc = "*Required features: 'Win32_System_Ioctl'*"]
pub struct STORAGE_BREAK_RESERVATI... | Rust | 0 |
CLR {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt Enable Clear"]
pub mod intenclr;
#[doc = "Interrupt Enable Set"]
pub struct INTENSET {
register: ::vcell::VolatileCell<u32>,
}
#[doc = "Interrupt Enable Set"]
pub mod intenset;
#[doc = "Interrupt Flag Status and Clear"]
pub struct INTFLAG {
re... | Rust | 0 |
let key = format_ident!("{}", k);
let name = format!("{}{}", prefix, v);
let kv = quote! { #key: &str = #name };
quote! { pub const #kv; }
});
let sub_metric_spaces = self.sub_scopes.iter().map(|(name, scope)| {
let prefix = format!("{}{}{}", pr... | Rust | 0 |
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, redirect
from .models import Profile
from django.urls import reverse
from .forms import ProfileForm, KeyWordFormSet
# Create your views here.
def profiles(request):
profiles = Profile.objects.all()
context = {
'profiles_lis... | Python | 1 |
# Copyright (c) 2020 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS... | Python | 1 |
from datetime import date
from django.contrib.auth.models import User
from django.test import TestCase
from evaluate_m2.tests.evaluator_test_helper import acct_record
from rest_framework.renderers import JSONRenderer
from parse_m2.initiate_post_parsing import post_parse
from parse_m2.models import M2DataFile, Metro2Ev... | Python | 1 |
/ Only listener needs PAIR1_POLY
//b.socket_mut().set_bool(NngOption::PAIR1_POLY, true)?;
b.set_ms(NngOption::RECVTIMEO, 100)?
.set_ms(NngOption::SENDTIMEO, 100)?;
let listener_ready = Arc::new(AtomicBool::default());
let done = Arc::new(AtomicBool::default());
let mut threads = vec![];
... | Rust | 0 |
(char.to_digit(10).unwrap() as usize),
':' => {
skip = 1;
state = ParseState::UnkownRule
}
'\n' => {
text_idx = idx + 1;
break;
}
_ => panic!("Invalid input: {}... | Rust | 0 |
атаем узел
if node.left:
self._print_tree(node.left, level + 1, 'Left ') # Печатаем левое поддерево
if node.right:
self._print_tree(node.right, level + 1, 'Right ') # Печатаем правое поддерево
def print_tree(self):
# Метод для начала печати дерева
... | Python | 1 |
);
}
let id = id.unwrap();
let price = body["price"].as_i64();
let name = body["name"].as_str();
if price.is_none() && name.is_none() {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"message": "The name, price, or both values of an item must be ... | Rust | 0 |
import logging
import platform
from pathlib import Path
from typing import Tuple
import pyopencl as cl
from base58 import b58decode
def check_character(name: str, character: str) -> None:
try:
b58decode(character)
except ValueError as e:
logging.error(f"{str(e)} in {name}")
raise Syst... | Python | 1 |
from .get_chat_llm import get_llm
from typing import List
from keybert.llm import LangChain
from keybert import KeyLLM
from langchain.chains.question_answering import load_qa_chain
class KeywordExtractor:
def __init__(self, request):
"""
Initialize the KeywordExtractor object.
Paramete... | Python | 1 |
v
&& self.front_face == rhs.front_face
}
}
pub trait Hittable {
fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<Hit>;
fn bounding_box(&self, t0: f64, t1: f64) -> Option<AABB>;
}
impl Hittable for Vec<Box<dyn Hittable>> {
fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<Hi... | Rust | 0 |
.original_stack_size,
Self::Block(frame) => frame.original_stack_size,
Self::Loop(frame) => frame.original_stack_size,
Self::Body(_) => 0,
Self::Unreachable(frame) => frame.original_stack_size,
}
}
/// Returns `true` if the control frame is a Wasm `Loop`.... | Rust | 0 |
elf) -> Result<VariableLengthTimestamp> {
use once_cell::sync::OnceCell;
use regex::bytes::Regex;
static RE: OnceCell<Regex> = OnceCell::new();
let re = RE.get_or_init(|| Regex::new(r"^[0-9]{4}[0-9]{2}{5}(\.[0-9]{1,3})?Z$").unwrap());
let octets = self.read_var_octet_string()?;... | Rust | 0 |
, 11, 42, &X, &T);
C = f_round3(C, D, A, B, 3, 16, 43, &X, &T);
B = f_round3(B, C, D, A, 6, 23, 44, &X, &T);
A = f_round3(A, B, C, D, 9, 4, 45, &X, &T);
D = f_round3(D, A, B, C, 12, 11, 46, &X, &T);
C = f_round3(C, D, A, B, 15, 16, 47, &X, &T);
B = f_round3(B, C, D, ... | Rust | 0 |
'fa': ':بوسه_زن_مرد_و_پوست_طلایی:',
'id': ':berciuman_wanita_pria_warna_kulit_sedang:',
'zh': ':亲吻_女人男人中等肤色:',
'ru': ':поцелуй_женщина_мужчина_средний_тон_кожи:'
},
'\U0001F469\U0001F3FD\U0000200D\U00002764\U0000FE0F\U0000200D\U0001F48B\U0000200D\U0001F468\U0001F3FF': { # 👩🏽❤️💋... | Python | 1 |
structured_long() {
let mut qc = quickcheck::QuickCheck::new()
.tests(1_000_000)
.max_tests(1_000_000);
qc.quickcheck(
contents_formatted_reproduces_state_structured
as fn(TerminalInput) -> bool,
);
}
#[test]
fn qc_structured_short() {
let mut qc = quickcheck::QuickC... | Rust | 0 |
ek::constants;
/// # fn main() {
///
/// let A = RistrettoPoint::identity();
/// let B = constants::RISTRETTO_BASEPOINT_POINT;
///
/// let mut P = A;
///
/// P = RistrettoPoint::conditional_select(&A, &B, Choice::from(0));
/// assert_eq!(P, A);
/// P = RistrettoPoint::conditional... | Rust | 0 |
"LIVE",
"NMQ",
"XCJ",
"ACUR",
"HRO",
"IIIIU",
"NWMO",
"HMR",
"HMR.WS",
"NCCpF",
"TUX.WS",
"EWSTD",
"MTBpA",
"FUE",
"JZY.CL",
"TKP.WS",
"WZE",
"SUTR",
"APP.WS.CL",
"MERR",
"TYM",
"UBD",
"UEM",
"ULQ",
"CIO.WS",
"DARA",
"TCL",
"ARST",
"AXG",
"AXG.WS",
"BEST",
"... | Rust | 0 |
=> s.get_boolean(),
None => Err(Error::MissingValue {
name: name.to_string(),
}),
}
}
/// If `SlashMap` has value, call `SlashValue::get_user()` on it
pub fn get_user(&self, name: &str) -> Result<UserOrMember> {
match self.0.get(name) {
So... | Rust | 0 |
value
.map_or(Err(anyhow!("Account not found")), Ok)?;
}
// Cut off account discriminator.
let mut d: &[u8] = &account.data[8..];
let idl_account: IdlAccount = AnchorDeserialize::deserialize(&mut d)?;
let mut z = ZlibDecoder::new(&idl_account.data[..]);
let mut s = Vec::new();
... | Rust | 0 |
impl<F: Float> std::ops::Div<F> for Matrix3<F> {
type Output = Matrix3<F>;
fn div(self, rhs: F) -> Matrix3<F> {
self.div_scalar(rhs)
}
}
impl<F: Float> std::ops::Index<usize> for Matrix3<F> {
type Output = Vector3<F>;
fn index(&self, index: usize) -> &Self::Output {
&self.m[inde... | Rust | 0 |
um_bxdfs = 0;
if !reflect.is_black() {
num_bxdfs += 1;
}
if !transmit.is_black() {
num_bxdfs += 1;
}
let bxdfs = alloc.alloc_slice::<&BxDF>(num_bxdfs);
let mut i = 0;
let fresnel = alloc <- Dielectric::new(1.0, eta);
if !reflect.is... | Rust | 0 |
static ref CARD_RE: Regex = Regex::new(format!(r"(?i){}", CARD_PATTERN).as_str()).unwrap();
}
if !FOUNDATIONS_RE.is_match(string) {
return Err(format!("Could not parse foundations: \"{}\"", string))
}
let top_cards: Vec<Card> = CARD_RE.find_iter(string)
... | Rust | 0 |
#!/usr/bin/python
x = 21
y = 5
# Output: x + y = 26
# Addition
print('x + y =',x+y)
# Output: x - y = 16
# Subtraction
print('x - y =',x-y)
# Output: x * y = 105
# Multiplication
print('x * y =',x*y)
# Output: x / y = 4.2
# Division, always results in float
print('x / y =',x/y)
# Output x % y = 1
# Modulo divisio... | Python | 1 |
y: str = DEFAULT_TEXT_QUERY
):
"""
Endpoint to detect objects in an image and return bounding box information as JSON.
Args:
file: Uploaded image file.
text_query: Text query for objects to detect (e.g., "a tank.").
Returns:
JSONResponse with bounding box coordinates, l... | Python | 1 |
VT_OFFSET: flatbuffers::VOffsetT = 8;
pub const VT_BIAS: flatbuffers::VOffsetT = 10;
#[inline]
pub fn variant(&self) -> AnchorVariant {
self._tab.get::<AnchorVariant>(Anchor::VT_VARIANT, Some(AnchorVariant::Start)).unwrap()
}
#[inline]
pub fn insertion_id(&self) -> Option<&'a super::Timestamp> {
... | Rust | 0 |
p.insert("342600", "安徽省巢湖地区");
map.insert("342601", "安徽省巢湖市");
map.insert("342621", "安徽省肥东县");
map.insert("342622", "安徽省庐江县");
map.insert("342623", "安徽省无为县");
map.insert("342624", "安徽省巢县");
map.insert("342625", "安徽省含山县");
map.insert("342626", "安徽省和县");
map... | Rust | 0 |
""" Test functions for linalg module using the matrix class."""
import numpy as np
from numpy.linalg.tests.test_linalg import (
LinalgCase, apply_tag, TestQR as _TestQR, LinalgTestCase,
_TestNorm2D, _TestNormDoubleBase, _TestNormSingleBase, _TestNormInt64Base,
SolveCases, InvCases, EigvalsCases, EigCases, ... | Python | 1 |
use std::f64::INFINITY;
#[derive(Debug)]
pub(crate) struct Bin2Return {
pub(crate) node: Node,
pub(crate) mean_val: f64,
pub(crate) n_obs: usize,
}
/// Just a range function that can works in reverse:
/// range(0, 5) = [0, 1, 2, 3, 4]
/// range(5, 0) = [5, 4, 3, 2, 1]
fn range(start: usize, end: usize) -... | Rust | 0 |
0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x69, 0x3,
]);
let mai = mock_new!(mock);
assert_eq!(mai.set_mode_sun(0x08, 1, 2.2).unwrap(), ());
}
#[test]
fn set_mode_sun_bad() {
let mock = MockStream::default();
let mai = mock_new!(mock);
assert_eq!(
mai.se... | Rust | 0 |
import py5
import tkinter as tk
# Shared variables
bg_color = 128
circle_size = 50
circle_x = 300
circle_y = 300
def setup():
py5.size(600, 600)
def draw():
py5.background(bg_color)
py5.fill(255, 100, 100)
py5.circle(circle_x, circle_y, circle_size)
# Start py5 FIRST in non-blocking mode
py5.run_ske... | Python | 1 |
# -*- coding:utf-8 -*-
# author : gfjiangly
# time : 2019/6/28 14:22
# e-mail : jgf0719@foxmail.com
# software : PyCharm
from .file import (get_files_list, get_images_list, split_list, split_dict,
split_data, replace_filename_space, check_rept, makedirs,
sample_label_from_... | Python | 1 |
,
(0x1edf, &['\u{006F}', '\u{031B}', '\u{0309}']),
(0x22f, &['\u{006F}', '\u{0307}']),
(0x934, &['\u{0933}', '\u{093C}']),
(0x2f98a, &['\u{2339C}']),
(0x1fe8, &['\u{03A5}', '\u{0306}']),
(0xfaab, &['\u{78CC}']),
(0xfa5b, &['\u{8005}']),
(0x4d3, &['\u{0430}', '\u{0308}']),
(0x2226, &[... | Rust | 0 |
] = message
for field_name in ['region', 'region_us', 'region_canada']:
BidderAttendeeInfo.field_validation.validations[field_name][f'required_{field_name}'] = which_required_region(field_name)
AdminBidderSignup.field_validation.required_fields = {
'bidder_num': "Please enter a bidder number.",
}
@... | Python | 1 |
> {
if (x + width) >= input.info().width {
return Err(ImgProcError::InvalidArgError(format!("invalid width: input width is {} \
but x + width is {}", input.info().width, (x + width))));
} else if (y + height) >= input.info().height {
return Err(ImgProcError::InvalidArgError(format!("... | Rust | 0 |
]
pub type Event;
#[wasm_bindgen(method, getter)]
pub fn payload(this: &Event) -> JsValue;
}
}
// Copyright 2020-2021, The Tremor Team
//
// 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 Licen... | Rust | 0 |
#![allow(unsafe_code)]` (do not remove); aids auditing.
#![forbid(unsafe_code)]
// Uncomment before ship to reconcile use of possibly redundant crates, debug remnants, missing
// license files and more
//#![warn(clippy::cargo, clippy::restriction, missing_docs, clippy::missing_errors_doc, warnings)]
//#![deny(warnings)... | Rust | 0 |
coco = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcas... | Python | 1 |
ue)
data = subsample(data=zip(files_a, files_b),
bounds=config.get('bounds', (0, 1)),
hash_fn=hash_fn,
verbose=verbose)
files_a, files_b = map(list, zip(*data))
return PairedDataset(files_a=files_a,
... | Python | 1 |
###############################################################################
#
# File: update_trap_satus.py
#
# Author: Isaac Ingram
#
# Purpose: Provide function for AWS Lambda to handle trap status updates.
#
###############################################################################
from common import databas... | Python | 1 |
apultra_compress, apultra_decompress, apultra_get_max_compressed_size,
apultra_get_max_decompressed_size, apultra_stats,
};
pub type Stats = apultra_stats;
pub type Error = ApultraError;
pub use error::ApultraError::{
CompressInternalError, CompressReserveError, CompressSizeError, DecompressInternalError,
... | Rust | 0 |
[">= 1.0.0", ">=1.0.0"],
["> 1.0.0", ">1.0.0"],
["> 1.0.0", ">1.0.0"],
["<= 2.0.0", "<=2.0.0"],
["<= 2.0.0", "<=2.0.0"],
["<= 2.0.0", "<=2.0.0"],
["< 2.0.0", "<2.0.0"],
["<\t2.0.0", "<2.0.0"],
["^ 1", ">=1.0.0 <2.0.0-0"],
["~> 1", ">=1.0.0 <2.0.0-0"],
["~ 1.0", ">=1.... | Rust | 0 |
copy_param_alg = self._create_child_alg("CopyInstrumentParameters", InputWorkspace=merged_calib_ws, OutputWorkspace=calibrated_ws)
copy_param_alg.execute()
remove_history_alg = self._create_child_alg("RemoveWorkspaceHistory", Workspace=calibrated_ws)
remove_history_alg.execute()
A... | Python | 1 |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | Python | 1 |
"""k진수에서 소수 개수 구하기
n이라는 숫자를 k진수로 바꿈
그 바꾼 숫자에서 0으로 쪼갰을때 10진수 소수가 몇개인지 구하기.
예)
437674 3 -> 211020101011 -> 211 2 1 1 11 -> 소수 3개
진수 변환 -> divmod 쓰면서 2진수부터 계산해보면 금방 알고리즘 만들 수 있음.
소수 판별 -> 그냥 2부터 n**0.5까지 나눠보기 -> 한 번 할 때마다 O(루트n)
dp사용해서 에라토스테네스체(역발상)로 소수 저장해놨다가 갖다 쓰기
-> 세팅하는데 O(nloglogn)-> O(~n) 이고, 판별할때는 당연히 O(1)
이 ... | Python | 1 |
s',
'effector CD8+ T cells',
'effector CD4+ T cells',
'central memory CD8+ T cells',
'central memory CD4+ T cells',
'Tregs',
'T cells',
'L50_IL6',
'NKT cells',
'L50_IL7',
'B cell... | Python | 1 |
E8=").unwrap(), ethalon);
assert_eq!(parse_test!(parse_int256, "19F808EFD5DFDEAEEBE2AD523F3EF002A06DD16E828DABEE003383A33FC3404F").unwrap(), ethalon);
parse_test!(parse_int256, "11").expect_err("must generate error");
parse_int256(Option::<&str>::None, "test").expect_err("must generate error");... | Rust | 0 |
Ok(i)
}
fn flush(&mut self) -> Result<(), io::Error> {
Ok(())
}
}
pub trait ToMatcher<'a, S>
where
Self: crate::sealed::Sealed,
S: StateID + 'a,
{
type Automaton: DFA<ID = S>;
fn matcher(&'a self) -> Matcher<'a, S, Self::Automaton>;
}
impl<S> crate::sealed::Sealed for Patter... | Rust | 0 |
pub pwszStoreName: [::WCHAR; SCH_CRED_MAX_STORE_NAME_SIZE],
}
impl Clone for SCHANNEL_CERT_HASH_STORE { fn clone(&self) -> SCHANNEL_CERT_HASH_STORE { *self } }
pub type PSCHANNEL_CERT_HASH_STORE = *mut SCHANNEL_CERT_HASH_STORE;
pub const SCH_MACHINE_CERT_HASH: ::DWORD = 0x00000001;
pub const SCH_CRED_NO_SYSTEM_MAPPER: ... | Rust | 0 |
ion, InterfaceTypeExtension, List,
NamedTypeAnnotation, ObjectTypeExtension, SchemaDocument, StringNode, Token, TokenKind,
TypeAnnotation, TypeSystemDefinition,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use schema::{suggestion_list::GraphQLSuggestions, InterfaceID, SDLSchema... | Rust | 0 |
serial::*;
use crate::drivers::console::CONSOLE;
use core::fmt::{Arguments, Write};
pub fn getchar() -> u8 {
unsafe { SERIAL_PORT.force_unlock() }
SERIAL_PORT.lock().getchar()
}
pub fn getchar_option() -> Option<u8> {
unsafe { SERIAL_PORT.force_unlock() }
SERIAL_PORT.lock().getchar_option()
}
pub fn ... | Rust | 0 |
cSubType(code=934, label="Contemporary Gospel", slug="GOSPEL-CONTEMPORARY_GOSPEL"),
OldMusicSubType(code=935, label="Bluegrass Gospel", slug="GOSPEL-BLUEGRASS_GOSPEL"),
OldMusicSubType(code=936, label="Blues Gospel", slug="GOSPEL-BLUES_GOSPEL"),
OldMusicSubType(code=937, label="Count... | Python | 1 |
::core::option::Option<u32>,
#[prost(bytes="vec", optional, tag="2")]
pub groupname: ::core::option::Option<::prost::alloc::vec::Vec<u8>>,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ModGroupProfile {
#[prost(uint64, optional, tag="1")]
pub group_uin: ::core::option::Option<u64>,
#[p... | Rust | 0 |
import os
import asyncio
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional, Tuple
from dataclasses import dataclass
@dataclass
class PositionDetails:
"""Chi tiết vị thế đang mở"""
size: float
spot_symbol: str
futures_symbol: str
entry_basis: float... | Python | 1 |
\\[3\\]) is set."]
pub struct EPE_W<'a> {
w: &'a mut W,
}
impl<'a> EPE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPE_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Odd number of logic 1's is transmitted and checked in each wo... | Rust | 0 |
from concurrent.futures import ThreadPoolExecutor
from enum import Enum
from functools import partial
import numpy as np
import torch
from vector_vis_graph import WeightMethod, horizontal_vvg, natural_vvg
from vispool import USE_THREADPOOL
class VVGType(Enum):
NATURAL = "natural"
HORIZONTAL = "horizontal"
... | Python | 1 |
rs
/// Interface for a BME680 sensor using I2C.
use bitfield::bitfield;
macro_rules! sb {
($start:expr) => {
($start * 8)
};
}
macro_rules! eb {
($end:expr) => {
(sb!($end) + 7)
};
}
#[derive(Copy, Clone, Debug)]
pub enum Address {
Primary,
Secondary,
}
#[derive(Copy, Clone, ... | Rust | 0 |
elif test_group==2:
arr2=[]
for ro in array:
if ro[13]==6:
if ro[4] == test_mcl_count and ro[15] == test_lsf and ro[16]==test_rsf:
arr2.append(ro)
else:
arr2=[]
for ro in arra... | Python | 1 |
ayername'] and gameplayer['url'] == match['url']:
# tempmatch = dict(playername=_target_player, match=match)
# tempmatch = dict(playername=_target_player, msg=matching2string(tempmatch))
# eligible_Matches.append(tempmatch)
gameplayer['isga... | Python | 1 |
from functools import reduce
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# try:
# prod = reduce(lambda x,y : x*y, (i for i in nums if i!=0))
# except :
# prod = 0
# zero_cnt = nums.count(0)
# result = []
# for i in nums... | Python | 1 |
params['status'] = self.status.to_alipay_dict()
else:
params['status'] = self.status
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = QipanMerchantCrowd()
if 'apply_channel_list' in d:
o.ap... | Python | 1 |
print(f"\nStep {global_step}:")
print(f"New best model saved and pushed to HuggingFace Hub!")
print(f"Val Loss: {avg_val_loss:.4f}")
print(f"Average training loss: {avg_train_loss:.4f}")
p... | Python | 1 |
));
vec3 dark = vec3(0.32, 0.5, 0.5);
vec3 regular = vec3(0.55, 0.9, 0.9);
frag_color = vec4(mix(dark, regular, brightness), 1.0);
}
"#;
let quad_vertex_shader_src = r#"
#version 140
in vec3 position;
in vec2 tex_coord;
out vec2 frag... | Rust | 0 |