text string | label_name string | labels int64 |
|---|---|---|
from abc import ABCMeta, abstractmethod
from typing import List, Optional
from pylabrobot.machines.backend import MachineBackend
from pylabrobot.resources import Plate, PlateCarrier, PlateHolder
class IncubatorBackend(MachineBackend, metaclass=ABCMeta):
def __init__(self):
super().__init__()
self._racks: O... | Python | 1 |
e(Debug, Deserialize, PartialEq, Serialize)]
pub struct OrderStop {
stop_price: f64,
#[serde(rename = "stop")]
_type: OrderStopType,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum OrderStopType {
Loss,
Entry,
}
#[derive(Debug, Deserialize, Partial... | Rust | 0 |
lse {}
logger.info(f"SYNCER: Fetched {len(all_users_from_api)} users from panels and {len(db_users_map)} users from local DB.")
update_tasks = []
# ۳. مقایسه و آمادهسازی تسکهای آپدیت
for user_data in all_users_from_api:
uuid = user_data.ge... | Python | 1 |
from petsConstructor import *
dogList = []
dogSpec = ["German shepherd", "Golden Retriever", "Chocolate Labrador"]
dnames = ["Indy", "Simba", "Chockie"]
dprice = [450.0, 350.0, 200.0]
dages = [1, 2, 7]
dwords = ["dog", "dog one", "dog two"]
dsniff = ["sock", "food", "bottle"]
for n in range(len(dnames)):
dogList.... | Python | 1 |
reachable!(),
}
}
f.write_char(END_ESCAPE)
}
}
impl From<u8> for EscapedCodePoint {
fn from(value: u8) -> Self {
char::from(value).into()
}
}
impl From<char> for EscapedCodePoint {
fn from(value: char) -> Self {
match value {
'\t' => Self::Seque... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_beit(ckpt):
new_ckpt = OrderedDict()
for k, v in ckpt.items():
if k.startswith('patch_embed'):
... | Python | 1 |
ethernet_dma::RegisterBlock;
fn deref(&self) -> ðernet_dma::RegisterBlock {
&self.register_block
}
}
#[doc = "Cryptographic processor"]
pub const CRC: Peripheral<Crc> = unsafe { Peripheral::new(1073885184) };
#[doc = "Cryptographic processor"]
pub mod crc;
#[doc = "Cryptographic processor"]
pub struc... | Rust | 0 |
check_forward_backward(model_fn, data_gen_fn, output_transform_fn, loss_fn, test_config)
clear_layout_converter()
Randomizer.reset_index()
torch.cuda.empty_cache()
@parameterize(
"test_config",
[
{
"tp_size": 2,
"pp_size": 2,
"num_microbatches"... | Python | 1 |
func(arr, *arg, **kwargs)
return wrapper
@arr_to_pandas
def demean(arr, rolling_window=0, show=False):
"""
去均值化后处理demean, 如果输入的是np.array进行转换为pd.DataFrame处理,
被arr_to_pandas装饰,统一输出,且这样使用arr.mean()不需要axis参数区别np.array轴向
eg:
cc.head()
tsla bidu noah sfu... | Python | 1 |
import gym
import numpy as np
from baselines import deepq
BEST = 1
DEFAULT = .75
RANDOM = DEFAULT
ENV = "CartPole-v1"
FILE = "final_models/cartpole/cartpole.txt"
BC_FILE = "final_models/cartpole_bc/cartpole_bc.txt"
MODEL = "final_models/cartpole_model.pkl"
def main():
env = gym.make(ENV)
act = deepq.load(M... | Python | 1 |
#calcular el imc y colocar si esta bajo, normal o sobrepeso
# imc clasification
# imc = peso / (altura * altura)
# peso = kg
# altura = m
# imc < 18.5 = bajo peso
# imc >= 18.5 and imc < 24.9 = normal
# imc >= 25 and imc < 29.9 = sobrepeso
# imc >= 30 = obesidad I
# imc >= 35 = obesidad tipo II
# imc >= 40 = obesidad t... | Python | 1 |
#!/usr/bin/env python
import sys
import os
from subprocess import *
if len(sys.argv) <= 1:
print('Usage: %s training_file [testing_file]' % sys.argv[0])
raise SystemExit
svmscale_exe = "svm-scale"
svmtrain_exe = "svm-train"
svmpredict_exe = "svm-predict"
grid_py = "./svm-grid.py"
train_pathname = sys.argv[1]
asse... | Python | 1 |
;
pub fn igMenuItemBool(label: *const c_char, shortcut: *const c_char, selected: bool, enabled: bool) -> bool;
pub fn igMenuItemBoolPtr(
label: *const c_char,
shortcut: *const c_char,
p_selected: *mut bool,
enabled: bool,
) -> bool;
pub fn igNewFrame();
pub fn igNewLi... | Rust | 0 |
ecksum error */
/* no endpoint for port */
/* bad v-tag */
/* bad SID */
/* no memory */
/* number of multiple FR in a RTT window */
/* nagle allowed sending */
/* nagle doesn't allow sending */
/* max burst doesn't allow sending */
/* look ahe... | Rust | 0 |
import pandas as pd
def separar_datos_por_choque(csv_file, tiempo_choque):
df = pd.read_csv(csv_file)
# Crear la nueva columna "choque"
df['choque'] = df['Time'].apply(lambda x: 'antes' if x < tiempo_choque else 'despues')
# Guardar el archivo CSV con la nueva columna
df.to_csv(csv_file, index=F... | Python | 1 |
ICS.fpga.cfg_fails.inc();
return;
}
let config_slice = config.as_mut_slice();
config_slice[offset as usize..(data_len + offset as usize)].copy_from_slice(data);
}
fn activate(&mut self, mem: GuestMemoryMmap) -> ActivateResult {
debug!("Fpga: try to activate fpga");
... | Rust | 0 |
# imports
import random
def card_dealer_main(): #program 9-1
# card dealer main accepts no arguments
# it calls create_deck to generate a deck of cards
# and takes input from the user for the number of cards to deal
# it then calls deal_cards to deal the number of cards to the user
deck = create_de... | Python | 1 |
new_at(b"Bar", 4, 1, 5)
])
));
assert_eq!(qualified_name(input), output);
}
#[test]
fn case_name() {
let input = Span::new(b"_fooBar42");
let output = Ok((Span::new_at(b"", 9, 1, 10), input));
assert_eq!(name(input), output);
}
#[test]
fn ... | Rust | 0 |
= "Expected an outer attribute in a list format";
pub const UNEXPECTED_ATTR: &str = "Unexpected attribute";
pub const UNEXPECTED_LIT: &str = "Unexpected literal";
pub const EXPECTED_LIST: &str = "Expected a list";
const FIELD_PATH: &str = "path";
const FIELD_INPUT: &str = "input";
const FIELD_RAW: &str = "raw";
pub ... | Rust | 0 |
comprimento = float(input("Digite o comprimento do terreno a ser cercado: "))
largura = float(input("Digite a largura do terreno: "))
preço = float(input("Digite o preço do metro de tela: "))
custoPerimetro = (comprimento * 2 + largura * 2) * preço
print(f"O custo para cercar o terreno com tela é de: R$ {custoPerimet... | Python | 1 |
i32,
gap_open: i32,
gap_extend: i32,
}
#[pyclass]
pub struct Alignment {
x: Box<String>,
y: Box<String>,
aligned: bio_types::alignment::Alignment,
}
#[pymethods]
impl Alignment {
fn __str__(&self) -> PyResult<String> {
Ok(self.aligned.pretty(self.x.as_bytes(), self.y.as_bytes()))
}... | Rust | 0 |
", unicode fractions, etc.
// These heuristics are just an attempt of reducing the
// garbage, but a decent injection pipeline should be getting
// rid of these, not an ad-hoc filter
let text = term.text();
... | Rust | 0 |
ode";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_VAL_SRCPATH: &str = "SourcePath";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_VAL_SRVNAMECACHE: &str = "ServerNameCache";
#[doc = "*Required features: `\"Win32_System_Registry\"`*"]
pub const REGSTR_VAL_S... | Rust | 0 |
AccountField::Field(f) => &f.ident,
};
quote! {
account_infos.extend(self.#name.to_account_infos());
}
})
.collect();
quote! {
#[automatically_derived]
impl<#combined_generics> anchor_lang::ToAccountInfos<#trait_gener... | Rust | 0 |
print("Id do endereçço na memoria")
data_1 = "Aaa"
print(data_1)
print(id(data_1))
print("Tamanho da memoria")
data_2 = "Aaa"
print(data_2)
print(data_2.__sizeof__())
print("Tipo do objeto")
data_3 = "Aaa"
print(data_3)
print(type(data_3))
print("È instancia de um objeto int")
data_4: int = 123
print(isinstance(d... | Python | 1 |
import argparse
import pytest
import cv2
# Needs to be loaded
del cv2
METHOD_NAME = "mip-splatting"
@pytest.fixture
def mip_splatting_source_code(load_source_code):
load_source_code("https://github.com/autonomousvision/mip-splatting.git", "746a17c9a906be256ed85b8fe18632f5d53e832d")
class Rasterizer:
de... | Python | 1 |
}
},
}
Ok(())
}
use libc::close;
use std::os::unix::io::RawFd;
use crate::{
sys::perf_event_ioctl, PERF_EVENT_IOC_DISABLE, PERF_EVENT_IOC_ENABLE, PERF_EVENT_IOC_SET_BPF,
};
use super::{Link, LinkRef, ProgramData, ProgramError};
#[derive(Debug)]
struct PerfLink {
perf_fd: Option<RawFd>... | Rust | 0 |
::is_none")]
pub state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
impl AuthRequest {
pub fn credential_auth(id: &str, secret: &str) -> AuthRequest {
AuthRequest {
grant_type: GrantType::ClientCredentials,
client_id: So... | Rust | 0 |
}
left_working <<= 1;
}
ret
}
fn gf2_mod(mut quotient: u16, poly: IrreducablePolynomial) -> u8 {
let sub = poly.to_u16();
let mut degree = log2_floor(quotient);
while degree > 7 {
let shift_by = degree - 8;
let sub_shifted = sub << shift_by;
quotient ^= sub_... | Rust | 0 |
�体方法包括:
//! + get_account_name: 获取账户名称,基金或股票账户
//! + update_account: 根据实时行情更新账户持仓信息
//! + get_current_volume: 获取当前持仓数量
//! + get_current_value: 获取当前持仓价格
//! + get_current_asset: 获取当前资产,即持仓数量×持仓价格
//! + get_average_price: 获取当前持仓均价,根据买入成本计算
//! + get_lowest_price: 获取当前最低买入价格
//! + buy_with_volume: 以指定数量买入,适用于股票账户
//! + b... | Rust | 0 |
`resourceDir` can only be set once."]
pub fn fsSetPathForResourceDir(
pIO: *mut IFileSystem,
mount: ResourceMount,
resourceDir: ResourceDirectory,
bundledFolder: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn getUSec() -> i64;
}
extern "C" {
pub fn getTimerFrequ... | Rust | 0 |
#!/usr/bin/python
# Copyright 2015 Huawei Devices USA Inc. 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 r... | Python | 1 |
programming/index.html"));
// TODO: add assertion for syntax highlighting
// No tags or categories
assert_eq!(file_exists!(public, "categories/index.html"), false);
assert_eq!(file_exists!(public, "tags/index.html"), false);
// no live reload code
assert!(file_contains!(public, "index.html", "... | Rust | 0 |
type Epsilon = <T as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
<T as AbsDiffEq>::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
na::Point3::abs_diff_eq(&self.min, &other.min, epsilon)
&& na::Point3::abs_diff_eq(... | Rust | 0 |
extern "C" {
/// Create a SoundIo context. You may create multiple instances of this to
/// connect to multiple backends. Sets all fields to defaults.
/// Returns `NULL` if and only if memory could not be allocated.
/// See also ::soundio_destroy
pub fn soundio_create() -> *mut SoundIo;
pub fn s... | Rust | 0 |
from colorama import Fore, init
import shlex
from argparse import ArgumentParser
init(autoreset=True)
def parse_args():
parser = ArgumentParser(description="Ferramentas de desenvolvedor")
parser.add_argument("--xss", action="store_true", help="Ativar modo de depuração")
parser.add_argument("--path", action="sto... | Python | 1 |
let colon_idx = arg_line
.find(':')
.expect("directives provided at the top must be separated by a `:`");
let (command_name, value) = arg_line.split_at(colon_idx);
let value = value.strip_prefix(':').unwrap();
let value = value.trim();
... | Rust | 0 |
"""
Write a python function to count the number of non-empty substrings of a given string.
assert number_of_substrings("abc") == 6
"""
def number_of_substrings(string):
count = 0
for i in range(len(string)):
for j in range(i+1, len(string)+1):
count += 1
return count
print(number_of_su... | Python | 1 |
-> Result<(), Vec<String>> {
let mut errors = Vec::new();
if *other != *LOG_SCHEMA_DEFAULT {
// If the set value is the default, override it. If it's already overridden, error.
if self.host_key() != LOG_SCHEMA_DEFAULT.host_key()
&& self.host_key() != other.host_... | Rust | 0 |
one 'file' element.
"""
parser_context = parser_context or {}
request = parser_context['request']
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
meta = request.META
upload_handlers = request.upload_handlers
filename = self.get_filename(stream,... | Python | 1 |
n = observation[np.newaxis, :]
# actions_value = self.model.predict(observation)
# action = np.argmax(actions_value)
# return action
# def choose_action(self, observation):
# self.lstm_obs_history.append(observation)
# #choose action from model
# q_values = self.mode... | Python | 1 |
e", 7u32, "TextClassification"),
Self::TextClassificationMultilabel => serializer.serialize_unit_variant("TaskType", 8u32, "TextClassificationMultilabel"),
Self::TextNer => serializer.serialize_unit_variant("TaskType", 9u32, "TextNER"),
Self::UnknownValue(s) => serializer.serialize_s... | Rust | 0 |
import pandas as pd
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append([
'包含关键词的评论',
])
# df = pd.read_excel(r'D:\douyin\douyin_erp\douyin_8月\douyin_08_31\手机的压迫感(去重).xlsx')
df = pd.read_excel(r'D:\bilibili\bilibili_08_30\小米平板5_comment.xlsx')
df = df.dropna(axis=0, how='any')
comments = df['评论内容... | Python | 1 |
as i32,
mb_bytes.as_mut_ptr() as *mut i8,
mb_bytes.len() as i32,
dc as *const i8,
used_default_char
.into()
.map_or(null_mut(), |x| x as *mut _ as *mut _),
)
.map(|x| x as usize)
}
}
#[cfg(feature = "std")]
pub(crate) ... | Rust | 0 |
import hydra
from omegaconf import DictConfig, OmegaConf
import os
import logging
import optuna
import torch
from src.training.trainer import Trainer
from src.testing.evaluator import Evaluator
from utils.prepare_dataloader import prepare_dataloaders
from src.training.trainer_factory import get_trainer
from src.testin... | Python | 1 |
tences.append("</s>")
sentences.append(question)
sentences.append("</s>")
context = "".join(sentences)
proofs_offsets = torch.tensor([proof_offset])
tokenized_context = self.proofwriter_collator.tokenizer(
[context], add_special_tokens=False, ... | Python | 1 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
TypeCheckerCtx, Taggable, TypeCheckerCtx};
use crate::types::{PrimitiveType, VmType};
use crate::vm::VmRefSource;
use crate::Vm;
use super::{process_bi_op, process_u_op, AluExtensions};
fn handle_l_op<M: BiOpMarker>(chunk: &Chunk, vm: &mut Vm) -> Result<usize, VmError>
where
u64: BiOp<M, Output = u64>,
u32: B... | Rust | 0 |
Media_KernelStreaming'*"]
pub const KSPROPERTY_EXTXPORT_RTC_SEARCH: KSPROPERTY_EXTXPORT = 9i32;
#[doc = "*Required features: 'Win32_Media_KernelStreaming'*"]
pub const KSPROPERTY_RAW_AVC_CMD: KSPROPERTY_EXTXPORT = 10i32;
#[repr(C)]
#[doc = "*Required features: 'Win32_Media_KernelStreaming', 'Win32_Foundation'*"]
#[cfg(... | Rust | 0 |
from typing import Dict, List
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from core.data.sampler.base import BaseSampler
from core.data.sampler.utils import (cluster_by_label_indices, get_the_center,
read_embeddings)
class HierarchicalSampler(BaseSampl... | Python | 1 |
r#"{ "query" : { "raw": "test_text:5" } }"#;
let docs = run_query(body);
assert_eq!(docs.hits as usize, docs.docs.len());
assert_eq!(docs.docs[0].doc.test_text[0], "Test Document 5")
}
#[test]
fn test_term_query() {
let body = r#"{ "query" : { "term": { "test_text": "Docum... | Rust | 0 |
self.shadow_stack.get()
}
#[inline]
unsafe fn collector_ref(&self) -> &CollectorRef<C> {
&self.collector
}
#[inline]
fn state(&self) -> ContextState {
self.state.get()
}
}
// Pending collections
/// Keeps track of a pending collection (if any)
///
/// This must b... | Rust | 0 |
ra.communication.http.host.as_name': 'Example AS',
'extra.communication.http.host.asn': 50245,
'extra.communication.http.host.geolocation.cc': 'NL',
'extra.communication.http.host.geolocation.country': 'Netherlands',
'extra.communication.http.host.geolocation.latitude': 52.0,
'extra.communication.ht... | Python | 1 |
, user)
return
@bot.message_handler(content_types="text")
def handle_text(message):
if message.text not in commands:
reply_message = "Привет! Для того чтобы начать начать получать рекомендации от меня, введи /start"
bot.send_message(message.chat.id, reply_message)
elif message.text == ... | Python | 1 |
al) Ask the lorri daemon to report build events as they occur.
///
/// This is intended for scripts. However, we don’t guarantee any stability for now,
/// so if you want to use it in your scripts make sure you follow our changes.
/// Once it stabilizes a bit more we will start mentioning changes in the... | Rust | 0 |
ingtimer}"
)
startmvistimer = time.time()
mvis = MaskVisualization()
mvis.set_annotation(img=annotated_image, mask_objs=mask_objs)
annotated_image = mvis.get_masked_img()
mvis_mask_objs = mvis.mask_objs
print(f"Time taken for only the visualization: {time.time() -... | Python | 1 |
HESTRATOR_MODEL": "gemini-2.0-flash-thinking-exp",
"ORCHESTRATOR_API_KEY": "test-key",
"ORCHESTRATOR_THINKING_BUDGET": "10000",
},
):
config = AppConfig()
orch_config = config.active_orchestrator_config
assert orch_config.provider ... | Python | 1 |
ext(), crate::tests::Tests,);
mod os {
mod default;
}
use std::default::Default;
use std::fs;
use std::path::PathBuf;
use toml;
pub type Result<T> = std::result::Result<T, failure::Error>;
#[derive(Debug, Clone, Deserialize)]
pub struct User {
pub name: String,
pub password: String,
}
#[derive(Debug, Des... | Rust | 0 |
te>(),
);
Ok(())
}
// Copyright 2018-2022 argmin developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or ... | Rust | 0 |
ified (Chicago):</b> {chicago_time}\n"
await send_telegram_message(message, TELEGRAM_BOT_TOKEN, TELEGRAM_GRP)
log_message(f"Citron sitemap update sent to Telegram: {title} - {link}", "INFO")
async def run_citron_scraper():
processed_items = load_processed_items()
current_year = get_current_year()
... | Python | 1 |
ion`. Metric names that you choose must match the regular
/// expression "^[a-zA-Z0-9_]$".
///
/// Metrics are referenced by `name` in `metricFilter`, `orderBys`, and metric
/// `expression`.
#[prost(string, tag = "1")]
pub name: ::prost::alloc::string::String,
/// A mathematical expression ... | Rust | 0 |
#Teo Serpa
#11/26/24
#P3LAB
#Using integer division and if/else statements
import random
def disperse_change(change):
#Convert the float value into an integer
change = round(int(change * 100), 2)
if change == 0:
print("No Change Due")
#Calculate the amount of each coin needed... | Python | 1 |
10 => (ItuTT35::Brazil, &buf[1..]),
0b0001_0111 => (ItuTT35::BritishAntarcticTerritory, &buf[1..]),
0b0001_1000 => (ItuTT35::BritishIndianOceanTerritory, &buf[1..]),
0b0001_1001 => (ItuTT35::BritishVirginIslands, &buf[1..]),
0b0001_1010 => (ItuTT35::BruneiDarussalam, &buf... | Rust | 0 |
SHAKE256_RATE) * SHAKE256_RATE..out_length];
if (outlen % SHAKE256_RATE) > 0 {
keccak_squeezeblocks(&mut d, 1, &mut s, SHAKE256_RATE);
for i in 0..outlen % SHAKE256_RATE {
output[i] = d[i];
}
}
}
/*!
Generate mipmaps for [wgpu](https://github.com/gfx-rs/wgpu-rs) textures.
... | Rust | 0 |
import mysql.connector
# Kết nối tới cơ sở dữ liệu MySQL
conn = mysql.connector.connect(
host="127.0.0.1", # Địa chỉ máy chủ MySQL (hoặc IP của máy chủ MySQL)
user="root", # Tên đăng nhập MySQL
password="SQLdat1502:3", # Mật khẩu MySQL
database="firesmokesensor" # Tên cơ sở dữ liệ... | Python | 1 |
renderable instructions. The purpose of this
/// structure is two-fold:
/// - Reduce per-draw allocations with line and light caches (they are not cleared after each use)
/// - Store references to the in-use mesh textures during rendering (this cache is cleared after
/// use)
pub struct Compiler<P>
where
P: 'sta... | Rust | 0 |
#[serde(rename = "mappedStoreId", skip_serializing_if = "Option::is_none")]
pub mapped_store_id: Option<i32>,
#[serde(rename = "name", skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "rarity", skip_serializing_if = "Option::is_none")]
pub rarity: Option<crate... | Rust | 0 |
d_handle_: CommandHandle,
err: ErrorCode,
response_metadata: *const c_char,
),
>,
) -> ErrorCode {
debug!("indy_get_response_metadata > response {:?}", response);
check_useful_c_str!(response, ErrorCode::CommonInvalidParam2);
check_useful_c_callback!(cb, ErrorCode::Commo... | Rust | 0 |
new(),
MapperType::MBC1 => MBC1::new(cartridge_type),
_ => panic!(
"Tried to create create an unsupported mapper: {:?}",
cartridge_type.mapper
)
}
}
}
pub enum MBCMode {
Ram,
Rom
}
#[derive(Debug)]
pub struct MBC1 {
cartridge_... | Rust | 0 |
.join(args.data_dir, "dev")),
("test", os.path.join(args.data_dir, "test"))]
final_dict = {"train": [], "dev": [], "test": []}
for name, path in splits:
if not os.path.isdir(path):
print(f"[warn] {path} 不存在, 跳过.")
continue
res = process_split(
... | Python | 1 |
def mix(x,y):
return x^y
def prune(x):
return x % 16777216
with open("Advent of Code 2024/Day 22/input.txt") as f:
rawInput = f.read()
initialNums = list(map(int, rawInput.splitlines()))
def calc2000(secretNum):
for i in range(2000):
step1 = secretNum*64
secretNum = mix(step1, secre... | Python | 1 |
'*"]
pub const IMAGE_REL_M32R_PCREL24: u32 = 5u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const IMAGE_REL_M32R_PCREL8: u32 = 7u32;
#[doc = "*Required features: 'Win32_System_SystemServices'*"]
pub const IMAGE_REL_M32R_REFHALF: u32 = 8u32;
#[doc = "*Required features: 'Win32_System_SystemServi... | Rust | 0 |
= "Verdana 11 italic", text='EXIT', command=einde).grid(row=7, column=3,sticky=E)
Button(master, font = "Verdana 11 italic",highlightbackground='red',text='START', command=callback).grid(row=7, column=3,sticky=W)
Button(master, font = "Verdana 11 italic",fg='red',highlightbackground='blue',text='Default Settings', com... | Python | 1 |
# coding:utf8
"""
DESC:自定义提前特征词:人名、地名、机构名等
Author:伏草惟存
Prompt: code in Python3 env
"""
import jieba.posseg as ps
# 不同业务场景:评论情感判断,可以自定义特征抽取规则.
def extract_feature_words(str_doc):
featWord =""
stwlist = get_stop_words()
user_pos_list = [ 'nr', 'ns','nt','nz'] # 用户自定义特征词性列表
for word, pos in ps.cut(str_... | Python | 1 |
# This example script demonstrates how to send a basic command over UDP to Tello
# We will use PacketSender to simulate Tello for the purposes of this demonstration.
# PacketSender makes it easy to test code that can then be run when connected to Tello.
# https://packetsender.com/
# This script is part of our course o... | Python | 1 |
_peer_disconnect, if
* a peer has timed out, or if a connection request intialized by
* enet_host_connect has timed out. The peer field contains the peer
* which disconnected. The data field contains user supplied data
* describing the disconnection, or 0, if none is available.
*/
ENET_EVE... | Rust | 0 |
# @author Alberto Revel
# Crea un comentario en el código y coloca la URL del sitio web oficial del
# https://www.python.org/
# Representa las diferentes sintaxis que existen de crear comentarios en el lenguaje (en una línea, varias...).
# Representa las diferentes sintaxis que existen
# de crear comentarios en el ... | Python | 1 |
import cv2 # OpenCV para manipulação de imagem e vídeo
import torch # PyTorch, um framework de aprendizado de máquina
import easyocr # Biblioteca de OCR para reconhecimento de caracteres
from LPR.sort.sort_ import Sort # Importa o algoritmo SORT para rastreamento de objetos
from collections import deque # Importa ... | Python | 1 |
").as_ptr(),
(*b"out of memory\0").as_ptr(),
0i32 as (*const u8),
0i32 as (*const u8),
0i32 as (*const u8),
0i32 as (*const u8),
0i32 as (*const StrErr),
);
}
if dns::ip4::qualify(
&mu... | Rust | 0 |
args__ = dict()
__args__['displayName'] = display_name
__args__['labels'] = labels
__args__['project'] = project
__args__['type'] = type
__args__['userLabels'] = user_labels
opts = pulumi.InvokeOutputOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke_o... | Python | 1 |
from django.db import models
from PIL import Image
import os
from django.core.exceptions import ValidationError
from ms_brd.settings import MEDIA_ROOT
from django.core.files.storage import default_storage
import io
from django.core.files.base import ContentFile
new_height = 300
# def validate_image_size(image):
# ... | Python | 1 |
nt_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_parent_trampoline<P, F: Fn(&P) + 'static>(
this: *mut nm_sys::NMSettingVlan,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<SettingVlan>... | Rust | 0 |
#Sumatoria de 1 hasta n
n=int(input())
sumatoria=0
factorial=1
for i in range(n):
i=i+1
factorial=factorial*i
sumatoria=sumatoria+factorial
print("La sumatoria de factorial de n es", sumatoria)
print("El de factorial de n es", factorial) | Python | 1 |
from myproject.utils.symbolic.simplification.custom_simplify import custom_simplify
import sympy as sp
import logging
logger = logging.getLogger(__name__)
class ComputeEinsteinTensor:
def __init__(self, Ricci, Scalar_Curvature, g, g_inv, n):
self.Ricci = Ricci
self.Scalar_Curvature = Scalar_Curva... | Python | 1 |
"""
name: pillow_block.py
by: Gumyr
date: July 14th 2022
desc:
This example demonstrates placing holes in a part in a rectangular
array.
license:
Copyright 2022 Gumyr
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the Licen... | Python | 1 |
import pickle
import numpy as np
class GetData:
def __init__(self, n_instance, n_cities, capacity):
self.n_instance = n_instance
self.n_cities = n_cities
self.capacity = capacity
def generate_instances(self):
"""each instance -> (coordinates, distances, demands, capacity)"""
... | Python | 1 |
for code in stock_codes:
data = self.load_stock_data(code)
if data is None:
quality_report['missing_files'].append(code)
continue
if len(data) < 1200: # 7年数据要求至少1200个交易日
quality_report['insufficient_data'].append(code)
... | Python | 1 |
df_old_1['是否必填'] = df_old['是否必填'].apply(lambda x: '是' if pandas.notna(x) and '必填' in str(x) else '否')
# 3.两张表通过第三表join,以新表规为主表,展示新表的变化
df_link = pandas.read_excel(r'D:\donghua\6-7 对比\对比专用表格.xlsx',sheet_name='关联',usecols=['新规表中文名','新规表英文名','原表中文名','原表英文名'])
df_m1 = pandas.merge(df_new_1.loc[:,['表名','数据项代码',... | Python | 1 |
which this
// source was automatically generated.
//! Log traits live here, which are called throughout the library to provide useful information for
//! debugging purposes.
//!
//! There is currently 2 ways to filter log messages. First one, by using compilation features, e.g \"max_level_off\".
//! The second one, c... | Rust | 0 |
delta-E
/// standard.
///
/// See: https://en.wikipedia.org/wiki/Color_difference
pub fn distance_delta_e_ciede2000(&self, other: &Color) -> Scalar {
delta_e::ciede2000(&self.to_lab(), &other.to_lab())
}
/// Mix two colors by linearly interpolating between them in the specified color s... | Rust | 0 |
t0 and ret1:
# Add artificial motion if triggered
if trigger_motion:
h, w = frame0.shape[:2]
mx = int(motion_x * w)
my = int(motion_y * h)
cv2.circle(frame0, (mx, my), 30, (255, 255, 255), -1)
cv2.circle(frame1, (mx,... | Python | 1 |
f=open("input.txt",'r')
mapp=[]
while line:=f.readline():
mapp.append(list(line.strip('\n')))
f.close()
def check_trail(coord,mapp,coord_list):
num=mapp[coord[1]][coord[0]]
if num=="9":
if coord in coord_list:
return 0
coord_list[coord]=1
return 1
summ=0
did_something=0
if coord[1]+1<len(mapp) and (map... | Python | 1 |
;
let $i = 1; $e;
let $i = 2; $e;
let $i = 3; $e;
}}
}
#[cfg(debug_assertions)]
macro_rules! loop8 {
($i:ident, $e:expr) => {
for $i in 0..8 { $e }
}
}
#[cfg(not(debug_assertions))]
macro_rules! loop8 {
($i:ident, $e:expr) => {{
let $i = 0; $e;
let $i = ... | Rust | 0 |
nts *MUST*
/// ensure that they have the same view as all other participants of the
/// commitment!
///
/// An implementation of `vss_verify()` from the [spec].
///
/// [spec]: https://www.ietf.org/archive/id/draft-irtf-cfrg-frost-04.html#appendix-B.2-4
pub fn verify(&self) -> Result<(), &'s... | Rust | 0 |
# special case for mass job copy action
return super().get_readonly_fields(request, obj)
def get_inlines(self, request, obj):
if self.is_copy_view(request):
return [ContactInline] # special case for mass job copy action
return super().get_inlines(request, obj)
def save_r... | Python | 1 |
adjustment::PointerCast;
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::{self, Instance, IntTy, Ty, UintTy, VtblEntry, COMMON_VTABLE_ENTRIES};
use rustc_target::abi::{FieldsShape, Primitive, TagEncoding, Variants};
use tracing::{debug, warn};
impl<'tcx> GotocCtx<'tcx> {
fn codegen_comparison(&mut se... | Rust | 0 |
ppend(ints)
ext_list.append(exts)
poses = np.stack(poses)[:, :3, :]
transform = np.array([
[0, 0, 1, 0],
[-1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, 0, 1]
])
poses = np.matmul(poses, transform)
pos = poses[:, :, -1]
xyz_min = np.min(pos, axis=0)
xyz_max = n... | Python | 1 |
not data.timestamps:
raise ValueError("No data to cache.")
# Check for overlapping segments
if self.metadata._check_for_overlapping_segments(symbol, data_type, start_time, end_time):
raise ValueError(f"Overlapping segments found for symbol {symbol} and data type {data_type}")
... | Python | 1 |
output = plugins.egui(|ctx| {
egui::SidePanel::left("side_panel").show(&ctx, |ui| {
ui.heading("Egui Plugin Example");
ui.separator();
if ui.button("Quit").clicked() {
app.exit();
}
ui.separator();
ui.label("Welcome to a ... | Rust | 0 |
pub s: Cow<'a, str>,
pub one: mod_TestOneof::OneOfone<'a>,
}
impl<'a> MessageRead<'a> for TestOneof<'a> {
fn from_reader(r: &mut BytesReader, bytes: &'a [u8]) -> Result<Self> {
let mut msg = Self::default();
while !r.is_eof() {
match r.next_tag(bytes) {
Ok(234) => ms... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.