text string | label_name string | labels int64 |
|---|---|---|
# Generated by Django 2.0.7 on 2018-07-25 14:28
from django.db import migrations
def forwards_add_initial_data(apps, schema_editor):
group_model = apps.get_model("auth", "Group")
group_model.objects.bulk_create(
[
group_model(name="Administrator"),
group_model(name="Tester"),
... | Python | 1 |
out.save(output).unwrap();
}<filename>src/main.rs<gh_stars>1-10
extern crate atkin;
use atkin::sieve::SieveOfAtkin;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
println!("An argument for the sieve limit is required.");
return;
}
let n: u... | Rust | 0 |
32 = 0;
pub const FLASH_LED_MODE_FLASH: u32 = 1;
pub const FLASH_LED_MODE_TORCH: u32 = 2;
pub const CID_FLASH_STROBE_SOURCE: u32 = CID_FLASH_CLASS_BASE + 2;
pub const FLASH_STROBE_SOURCE_SOFTWARE: u32 = 0;
pub const FLASH_STROBE_SOURCE_EXTERNAL: u32 = 1;
pub const CID_FLASH_STROBE: u32 = CID_FLA... | Rust | 0 |
#[test]
fn test_getegid() {
assert_eq!(process::getegid(), process::getegid());
}
#[test]
fn test_getpid() {
assert_ne!(process::getpid(), 0);
assert_eq!(process::getpid(), process::getpid());
}
#[test]
fn test_getppid() {
assert_eq!(process::getppid(), process::getppid());
}
//! <https://www.codewars... | Rust | 0 |
er_of_bins(min: f64, max: f64, n: usize, bspec: BinSpec) -> usize {
if min == max {
1
} else {
match bspec {
BinSpec::Automatic | BinSpec::LogScaled =>
(2.0 * (n as f64).cbrt()).ceil() as usize,
BinSpec::FixedNumber(n) =>
n,
Bin... | Rust | 0 |
'''
6. Você está trabalhando com processamento de linguagem natural (NLP) e, dessa vez, sua líder requisitou que você criasse um trecho de código que recebe uma lista com as palavras separadas de uma frase gerada pelo ChatGPT.
Você precisa criar uma função que avalia cada palavra desse texto e verificar se o tratament... | Python | 1 |
} else {
Some(SecCertificate::wrap_under_get_rule(certificate as *mut _))
}
}
}
}
#[cfg(test)]
mod test {
use test::certificate;
use trust::SecTrust;
use policy::SecPolicy;
use secure_transport::ProtocolSide;
#[test]
fn create_with_certifica... | Rust | 0 |
, 120, 120);
const PICKED_BRUSH: Brush = Brush::Solid(PICKED_COLOR);
const NORMAL_BRUSH: Brush = Brush::Solid(NORMAL_COLOR);
const SELECTED_BRUSH: Brush = Brush::Solid(SELECTED_COLOR);
#[derive(Debug, Clone, PartialEq)]
pub enum TransitionMessage {
Activate,
}
impl TransitionMessage {
define_constructor!(Tra... | Rust | 0 |
price=int(input("Enter the price you seek:"))
inctx=0
ins=0
if price>=72000 and price<150000:
inctx=0.10*price
ins=0.15*price
elif price>=150000 and price<200000:
inctx=0.25*price
ins=0.20*price
elif price>=200000:
inctxs=(35/100)*price
ins=(28/100)*price
else:
print("Our minimum price shoul... | Python | 1 |
{
let links = self
.jobs
.iter()
.filter_map(|job| {
if self.selected.is_selected(job.id()) {
if let Some(res) = job.get_result() {
return Some(res.link());
}
}
No... | Rust | 0 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
(~little-endian).
/// Panics if the chunk doesn't have the unique representation in the field (chunk size exceeds the field capacity).
pub fn to_chunks_as_field_elements<F: PrimeField>(&self, limbs_in_chunk: usize) -> Vec<F> {
let bits_in_chunk = BITS_IN_LIMB * limbs_in_chunk;
let capacity = (F... | Rust | 0 |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
lowP = float("inf")
res = 0
for p in prices:
if lowP > p:
lowP = p
res = max(p-lowP, res)
return res | Python | 1 |
}
};
}
x => {
return Err(RuntimeErrorKind::UnstructuredError {
message: format!("currently we do not support type casting to {}", x),
})
}
};
let casted_integer = match left {
Object::Arithmetic(arith) => {
let c... | Rust | 0 |
bool>::field_of("side", &jedi_table);
let force_level = NamedField::<i8>::field_of("force_level", &jedi_table);
let query = jedi_table.select_all().group_by(&[&name, &side]);
assert_sql!(query, "SELECT * FROM jedi GROUP BY name, side;");
// Edge case where `by` is empty
let empty: &[&UntypedExpres... | Rust | 0 |
dEquipmentIndex,
QsdItemBase1000, QsdVariableType,
};
use crate::{
bundles::ability_values_get_value,
scripting::{
quest::get_quest_variable, QuestFunctionContext, ScriptFunctionContext,
ScriptFunctionResources,
},
};
fn quest_condition_operator<T: PartialEq + PartialOrd>(
operator... | Rust | 0 |
),
Ref(ref mut index) => f(index),
}
}
do_for_each_ref_mut(val, &mut f.f)
}
<filename>libindy_vdr/src/config/constants.rs
use hex_literal::hex;
use once_cell::sync::Lazy;
use ursa::bls::Generator;
use crate::pool::ProtocolVersion;
pub const DEFAULT_ACK_TIMEOUT: i64 = 20;
pub const DEFAULT... | Rust | 0 |
response we want returned. We assume a 200 OK
//! // response by default.
//! i.response
//! .content_type("text/plain")
//! .body("That is some good Mallory.");
//! })
//! .build();
//! ```
//!
//! You can than use an HTTP client like `reqwest` to make requests against y... | Rust | 0 |
#!/usr/bin/env python3
import sys
from collections import defaultdict, deque
def neighbors(grid, r, c, ignore_slopes):
cell = grid[r][c]
if ignore_slopes or cell == '.':
for r, c in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if grid[r][c] != '#':
yield r, c
elif cell == 'v': yield (r + 1, c)
elif... | Python | 1 |
"%s -m pip install pymongo>=4.3" % (python_path)
)
is_srv = True
scheme_free = uri[SRV_SCHEME_LEN:]
else:
raise InvalidURI(f"Invalid URI scheme: URI must begin with '{SCHEME}' or '{SRV_SCHEME}'")
if not scheme_free:
raise InvalidURI("Must provide at least one hostn... | Python | 1 |
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
# 打开NetCDF文件
dataset = Dataset('E:\MarineDatasets\HYCOM\hycom_GLBv0.08_530_1994010112_t000.nc', 'r')
# 访问底层水温数据
water_temp_bottom_data = dataset.variables['water_temp_bottom'][0,...] # (3251, 4500)=>(3120, 4320)
# 为了适应训练,进行裁切
water_temp_bo... | Python | 1 |
import os
from pymongo import MongoClient
from dotenv import load_dotenv
# Завантаження змінних середовища
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")
# Підключення до MongoDB
client = MongoClient(MONGO_URI)
db = client["cats_database"]
collection = db["cats"]
# Читання (Read)
def read_all_records():
"""Вив... | Python | 1 |
=> {
#[bench]
fn $name(b: &mut Bencher) {
#![allow(unused_mut)]
use std::sync::Mutex;
lazy_static! {
static ref RE: Mutex<Regex> = Mutex::new($re);
};
let mut re = RE.lock().unwrap();
b.bytes = SHERLOCK.len() as u... | Rust | 0 |
cpStream) -> Vec<u8> {
let (session_setup_response_body, session_id) =
Self::go_to_session_setup_negotiate_state(stream);
connect::send_session_setup_authenticate_request(
stream,
session_setup_response_body,
session_id.clone(),
None,
)... | Rust | 0 |
://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ienr](index.html) module"]
pub struct IENR_SPEC;
impl crate::RegisterSpec for IENR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ienr::R](R) reader structure"]
impl crate::Readable for IENR_SPEC {
type Read... | Rust | 0 |
didate_clusters.zonal) != 9"
)
cluster_type_counts = Counter(
zone.cluster_type for zone in plan.candidate_clusters.zonal
)
assert len(cluster_type_counts) == 3, "Expecting 3 cluster types"
assert cluster_type_counts["elasticsearch-search"] == 3, (
"Expe... | Python | 1 |
from typing import Any, Optional, Tuple, Union # type: ignore
from discord.ext.commands import AutoShardedBot # type: ignore
from tools.important.services.TikTok import (TikTokClient, # type: ignore
User, UserFeed, Video)
from typing_extensions import Self # type: ignor... | Python | 1 |
are always the same for
//! both.
//!
//! The following options are available:
//!
//! ## `#[funcmap(crate = "...")`
//!
//! This defines the path to the `funcmap` crate instance to use when referring
//! to `funcmap` APIs from generated implementations. This will only be needed
//! in rare cases, e.g. when you rename... | Rust | 0 |
resolved using ``SRV`` record (or similar mechanism) instead of
/// using hostname (i.e. standard expects using `_service._proto` prefix but
/// does not requires that).
#[derive(Debug)]
pub enum AutoName<'a> {
/// Auto-determine how to treat the name
Auto(&'a str),
/// Resolve host and attach specified po... | Rust | 0 |
# Add a horizontal line at y=0 for reference
plt.axhline(y=0, color='r', linestyle='--', alpha=0.3)
# Save the plot
plt.tight_layout()
plt.savefig(save_dir / "voxel_importance.png")
plt.close()
def plot_concept_accuracy_bar(accuracies: dict, results_dir: Path) -> None:
sns.set(font_s... | Python | 1 |
.plot(epoch_array, rouge_2_r_array)
ax.xaxis.set_major_locator(x_major_locator)
png_path = args.output_dir + '/rouge_2_r.png'
plt.savefig(png_path)
plt.figure(8)
plt.title('rouge_L_r',fontsize=24)
plt.xlabel('epochs',fontsize=14)
plt.ylabel('accuracy',fontsize=14)
x_major_locator=MultipleLocator(10)
ax=plt.gc... | Python | 1 |
ywords[1:]:
cmd.append(f"-HierarchicalSubject+={kw}")
# Write Subject field (flat keywords)
if flat_keywords:
cmd.append(f"-Subject={flat_keywords[0]}")
for kw in flat_keywords[1:]:
cmd.append(f"-Subject+={kw}")
# Add inpu... | Python | 1 |
=process_youtube_in_thread,
args=(update, context, youtube_url)
)
thread.daemon = True
thread.start()
return
except Exception as e:
logger.error(f"创建处理线程时出错: {str(e)}", exc_info=True)
update.m... | Python | 1 |
xtern crate pest_consume;
extern crate yaml_rust;
use yaml_rust::YamlLoader;
extern crate stopwatch;
use stopwatch::Stopwatch;
use pest_consume::Parser;
use pest_consume::Error;
use pest_consume::match_nodes;
type Node<'i> = pest_consume::Node<'i, Rule, ()>;
type Result<T> = std::result::Result<T, Error<Rule>>;
typ... | Rust | 0 |
lf):
# these values just chosen randomly, change to different ones if necessary
key_1 = {"split_reductions": False, "compute_all_bounds": True}
def create_key_1():
def myfn():
if (
not inductor_config.split_reductions
and induc... | Python | 1 |
dir) if csv.endswith("csv") and csv != "summary.csv"]
for csv in csvs:
df = pd.read_csv(os.path.join(runsdir, csv))
best_run = df.sort_values(by="testloss")#.iloc[0]
value = best_run['testloss'].mean()
sd = best_run['testloss'].std()
params = {k.replace("params_", ""): v for ... | Python | 1 |
rtswith("usage: %%itikz")
def test_magic_cell_usage(itikz_magic):
expected_md5 = "15d53b05d3a27e1545c9a3688be5e3b4"
tmp_dir = os.path.join(tempfile.gettempdir(), 'itikz')
res = itikz_magic.itikz("--temp-dir --file-prefix test_", RECTANGLE_TIKZ)
for ext in 'tex', 'svg':
path = os.path.join(tm... | Python | 1 |
"""Constants for the Nissan Leaf integration."""
from __future__ import annotations
from datetime import timedelta
from typing import Final
DOMAIN: Final = "nissan_leaf"
DATA_LEAF: Final = "nissan_leaf_data"
DATA_BATTERY: Final = "battery"
DATA_CHARGING: Final = "charging"
DATA_PLUGGED_IN: Final = "plugged_in"
DAT... | Python | 1 |
from typing import List
def isValidSudoku(board: List[List[str]]) -> bool:
# following leetcoding guide on the bottom right
# create 9 hashsets for columns, 9 for rows and 9 for subgrids
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
# determining subgrid will be tricky
subgrids =... | Python | 1 |
from typing import (
Collection,
Optional,
)
import attr
import dl_formula_ref as package
from dl_formula_ref.plugins.base.plugin import FormulaRefPlugin
from dl_formula_ref.plugins.registration import FORMULA_REF_PLUGIN_REG
from dl_utils.entrypoints import EntrypointClassManager
_PLUGIN_EP_GROUP = f"{packa... | Python | 1 |
num_image_tokens += 1
content = content.replace(self.image_token, "{{image}}", 1)
while self.video_token in content:
num_video_tokens += 1
content = content.replace(self.video_token, "{{video}}", 1)
content = co... | Python | 1 |
cf(co != 0);
rhs.set(self, val);
}
pub fn swap<GS>(&mut self, rhs: GS)
where
GS: Get<u8> + Set<u8>,
{
let read = rhs.get(self);
let val = (read >> 4) | (read << 4);
self.reg.set_zf(read == 0);
self.reg.set_nf(false);
self.reg.set_hf(false);
... | Rust | 0 |
IXME: #[simd_test(enable = "neon")]
fn test_veorq_s16() {
testq_bit_s16(
|i, j| unsafe { veorq_s16(i, j) },
|a: i16, b: i16| -> i16 { a ^ b },
);
}
#[test] //FIXME: #[simd_test(enable = "neon")]
fn test_veor_s32() {
test_bit_s32(
|i, j| unsafe { veor_s32(i, j) },
|a: i32, b: ... | Rust | 0 |
_order.amount} COINALPHA has been filled at {Decimal('10000')} HBOT."
)
)
self.assertTrue(
self.is_logged(
"INFO",
f"The SELL order {sell_order.client_order_id} amounting to {sell_order.executed_amount_base}/{sell_order.amount} COINALPHA has been ... | Python | 1 |
self.generic_sub_params.insert(id.clone());
}
}
for segment in &path.segments {
self.visit_path_segment(segment);
}
}
/// Traverse syntax tree.
fn visit_type(&mut self, ty: &syn::Type) {
match ty {
syn::Type::Array(ty) => self.visit_type(&ty.elem),
syn::Type::BareFn(ty) => {
for arg in ... | Rust | 0 |
# src/feature_engineering.py
import pandas as pd
import numpy as np
def load_synthetic_data(n_samples=1000):
"""Generate synthetic NILM dataset with aggregate and appliance powers."""
timestamps = pd.date_range(start='2025-01-01', periods=n_samples, freq='T')
# Appliances (random ON/OFF with some power us... | Python | 1 |
)
runner.docking(
out_dir / "savedir",
num_modes=1,
search_mode=search_mode,
seed=seed,
)
res: list[tuple[None, float] | tuple[RDMol, float]] = []
for i in range(num_mols):
try:
do... | Python | 1 |
// features may be returned in different order, so assert on the
// geojson encoding length. (you can also view the geojsons for
// comparison)
let result_str = feature_collection.to_string();
assert_eq!(expect_str.len(), result_str.len());
}
None => ... | Rust | 0 |
an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ip.rsh"
//#pragma rs_fp_relaxed
static int histR[256] = {0}, histG[256] = {0}, histB[256] = {0};
rs_all... | Rust | 0 |
chaError;
pub struct CommentFilter(pub actix::Addr<client::ClientConnector>, /* The secret of recaptcha. */pub String);
#[derive(Deserialize, Debug)]
struct Recaptcha {
recaptcha: String
}
#[derive(Deserialize, Debug)]
#[serde(rename_all="kebab-case")]
struct RecaptchaResult {
... | Rust | 0 |
print '\n%s [%s*%s] akun %sOK%s tersimpan di >%s okeh.txt'%(P,K,P,H,P,H);jeda(0.2)
print '%s [%s*%s] akun %sCP %stersimpan di > %scepeh.txt\n'%(P,K,P,K,P,K);jeda(0.2)
with ThreadPoolExecutor(max_workers=30) as log:
for ro in mi:
try:
_bff_ = []
_r_ = ro.encode("utf-8")
_o_ = _r_.split("|")[0]
_m_... | Python | 1 |
import requests
from bs4 import BeautifulSoup
def get_image_url(URL):
response = requests.get(URL)
soup = BeautifulSoup(response.content, 'html.parser')
image_tag = soup.find('meta', {'property': 'og:image'})
image_url = image_tag['content']
return image_url
#Test URL
#URL = "https://www.roma... | Python | 1 |
if colored {
use fern::colors::{Color, ColoredLevelConfig};
let color_level = ColoredLevelConfig::new()
.error(Color::BrightRed)
.warn(Color::BrightYellow)
.info(Color::BrightGreen)
.debug(Color::BrightCyan)
.tra... | Rust | 0 |
tualizó python3-rich.\n"
"Reinicia el script para aprovechar las nuevas funcionalidades de interfaz.",
title="🔄 Reinicio de Script Recomendado",
style="blue"
)
# Actualizar cache del estado de herramientas después de l... | Python | 1 |
- v1))
tp += xs
x = torch.where(cover > 0, tp, y)
return x
def _process_index(self, k_ind):
k_ind = k_ind.type(torch.int64)
# Create cover for x outside [-self.bound, self.bound]
cover = torch.where((k_ind != 0) & (k_ind != (self.num_elmt + 1)), 1.0, 0.0)
#... | Python | 1 |
fn square_root(&mut self) -> SQUARE_ROOT_W {
SQUARE_ROOT_W { w: self }
}
#[doc = "Bits 16:19 - 19:16\\]
Indicates the hardware support for FP divide operations. The value of this field is: 0b0001 - supported."]
#[inline(always)]
pub fn divide(&mut self) -> DIVIDE_W {
DIVIDE_W { w: self }... | Rust | 0 |
> {
type Output = UnitComplex<N>;
#[inline]
fn mul(self, rhs: UnitComplex<N>) -> UnitComplex<N> {
Unit::new_unchecked(self.unwrap() * rhs.unwrap())
}
}
impl<'a, N: Real> Mul<UnitComplex<N>> for &'a UnitComplex<N> {
type Output = UnitComplex<N>;
#[inline]
fn mul(self, rhs: UnitComp... | Rust | 0 |
from collections import deque
def solution(storage, requests):
n = len(storage)
m = len(storage[0]) if n > 0 else 0
# 패딩 포함한 grid 생성 (실제 내용은 [1..n][1..m])
grid = [[0] * (m + 2)]
for row in storage:
grid.append([0] + list(row) + [0])
grid.append([0] * (m + 2))
dx = [1, -1, 0, 0]
... | Python | 1 |
from __future__ import division
import sys
import operator
DefaultSpecialWords = ["<blank>", "<unk>", "<s>", "</s>"]
def Collect(inputFiles, vocabPath, toLower=False, userDefineSpecial=None):
global DefaultSpecialWords
specialWords = []
if userDefineSpecial:
for item in userDefineSpecial:
... | Python | 1 |
items.push(item);
}
items
}
pub async fn collect_n_limited<T: Send + 'static>(mut rx: LimitedReceiver<T>, n: usize) -> Vec<T> {
let mut items = Vec::new();
while items.len() < n {
match rx.next().await {
Some(item) => items.push(item),
None => break,
}
... | Rust | 0 |
from flask import Flask
import os
app = Flask(__name__)
@app.route("/")
def home():
return "SkinPulse backend funcionando no Render! 🚀"
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port)
| Python | 1 |
ath.exists(filename):
conf = public.readFile(filename)
rep = r'\s*root\s+(.+);'
path = re.search(rep, conf)
if not path:
return_message = public.return_msg_gettext(False, 'Get Site run path false')
del return_message... | Python | 1 |
'a> IC_SDA_TX_HOLD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff);
self.w
}
}
impl R {
#[doc = "Bits 16:23 - Sets the required SDA hold time in unit... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. 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 requir... | Python | 1 |
# -*- coding: utf-8 -*-
# © 2016 Danimar Ribeiro <danimaribeiro@gmail.com>, Trustcode
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import re
from odoo import api, fields, models
class EletronicDocument(models.Model):
_inherit = 'eletronic.document'
pos_order_id = fields.Many2one(
... | Python | 1 |
(), SolverError> {
rosenbrock_grad(a, b, u, grad);
Ok(())
};
let f = |u: &[f64], c: &mut f64| -> Result<(), SolverError> {
*c = rosenbrock_cost(a, b, u);
Ok(())
};
// define the bounds at every iteration
let bounds = constraints::B... | Rust | 0 |
it, UnitCommands}, party::{GenerateParty, Party, PartyUnit},
GENERATE_PARTY_SYSTEM, LdtkHandles, unit::Player};
use super::{map::{BUILD_MAP_SYSTEM, CollisionMap}, spawn::Spawner, MapUnit, BattleMapEntity, MapUnits, get_valid_spawn_points, PlayerBase};
//use super::Spawner;
pub struct BattleMapPlayerPlugin;
impl P... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
import torch
from mmpose.models.backbones import DSTFormer
from mmpose.models.backbones.dstformer import AttentionBlock
class TestDSTFormer(TestCase):
def test_attention_block(self):
# BasicTemporalBlock with causal == False
... | Python | 1 |
tent'])
tools.mysql_exec(sql, values)
log_meta = []
def parse_mysql_alert_logs(tags,host,log_stream):
log_meta = {}
reg_date = re.compile('(\d{6} \d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})|(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})')
log_buffer = []
for log... | Python | 1 |
.iter()
.map(|account| {
let mut accounts = Vec::with_capacity(account.folders.len());
accounts.resize(account.folders.len(), account.clone());
account.folders.iter().zip(accounts).map(|(folder, acct)| {
rt.spawn(watch(
// root.new(o!("... | Rust | 0 |
# Copyright (c) 2018-2020 Louisiana State University
# 2020-2025 Cardiff University
#
# This file is part of GWpy.
#
# GWpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the... | Python | 1 |
ioc::PC10<hal::gpio::Analog>; // PIN_03, SD Data2, USART3 Tx
pub type SeedPin3 = hal::gpio::gpioc::PC9 <hal::gpio::Analog>; // PIN_04, SD Data1, I2C3 SDA
pub type SeedPin4 = hal::gpio::gpioc::PC8 <hal::gpio::Analog>; // PIN_05, SD Data0
pub type SeedPin5 = hal::gpio::gpiod::PD2 <hal::gpio::Analog>; // PIN_06, S... | Rust | 0 |
import torch
def rename_model_variable(input_file, output_file, input_var_list, output_var_list):
assert(len(input_var_list) == len(output_var_list))
checkpoint = torch.load(input_file)
state_dict = checkpoint['model_state_dict']
for i in range(len(input_var_list)):
input_var = input_var_list... | Python | 1 |
ne, strs, _("Update Manager"), wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
else:
# No upgrade required
strs = _("You have the latest version of DEVSimPy libraries.")
dlg = wx.MessageDialog(None, strs, _('Update Manager'), wx.OK|wx.ICON_INFORMATION)
if dlg.ShowModal() == wx.ID_YES:
### update t... | Python | 1 |
pub struct MyPSP22Pausable {
#[PSP22StorageField]
psp22: PSP22Data,
#[PausableStorageField]
pause: PausableData,
}
impl PSP22 for MyPSP22Pausable {}
impl PSP22Transfer for MyPSP22Pausable {
/// Return `Paused` error if the token is paused
#[modifiers(when_no... | Rust | 0 |
racter_10000(b: &mut Bencher) {
// be consistent across runs, but avoid sequential/caching.
let mut rng: XorShiftRng = SeedableRng::from_seed([0xFF, 0x00, 0xFF, 0x00, 0xF0, 0xF0, 0xF0, 0xF0,
0x00, 0xFF, 0x00, 0xFF, 0x0F, 0x0F, 0x0F, 0x0F]);
... | Rust | 0 |
(n),
pos: linspace(dmin, dmax, n + 1),
n: n - 1,
dmin,
dmax,
};
Gradient {
gradient: Box::new(gradbase),
dmin,
dmax,
}
}
#[derive(Debug)]
struct SharpGradientX {
colors: Vec<Color>,
pos: Vec<f64>,
dmin: f64,
dmax: f64,
last_idx: u... | Rust | 0 |
MBOL_BMPS: [&[u8]; SYMBOL_COUNT] = [
include_bytes!("bmps/symbol0.bmp"),
include_bytes!("bmps/symbol1.bmp"),
include_bytes!("bmps/symbol2.bmp"),
include_bytes!("bmps/symbol3.bmp"),
include_bytes!("bmps/symbol4.bmp"),
include_bytes!("bmps/symbol5.bmp"),
include_bytes!("bmps/symbol6.bmp"),
... | Rust | 0 |
import os
import json
import re
re_mid_data_path = './data/dgre/re_mid_data'
mid_data_path = './data/dgre/mid_data'
train_file = mid_data_path + '/train.json'
dev_file = mid_data_path + '/dev.json'
rel_labels_file = re_mid_data_path + '/rels.txt'
if not os.path.exists(re_mid_data_path):
os.mkdir(re_mid_data_path)
... | Python | 1 |
KEY>",
],
[
"0x235a03a1f31060c62a1bb1b6cbce38317dcf3501e3f0b3d92b4b01a070ee58b2",
"0x1b0481c924c00fd4b7809ff4a9f9daa7f12efea4821078b869159d34e7c9caca",
"0x2f1ced49ea067ad0f3a22b51ad12da2d7b0280f3f50977f9b09d4bea92e6b34e",
"<KEY>",
"0x05c29dff5d6ae85f7bc09637a86134c63a8052d1905a8057449cc7d92658f24d",
],
[
... | Rust | 0 |
::Utc;
use lazy_static::lazy_static;
struct SensorData {
pub id: String,
pub temperature: f32,
pub timestamp: String,
}
fn get_sensor_dirs() -> Vec<String> {
let base = "/sys/devices/w1_bus_master1/";
let mut sensor_dirs: Vec<String> = Vec::new();
// Create a list of directories where we migh... | Rust | 0 |
} else {
barrett_reduce(p[j] + t)
};
}
}
}
}
pub fn invntt(a: &mut [u16; N]) {
for level in 0..8 {
for start in 0..(1 << level) {
for (jt, j) in (start..(N - 1)).step_by(2 * (1 << level)).enumerate() {
let w = OM... | Rust | 0 |
# -*- coding: utf-8 -*-
import os
import time
import uuid
import json
from flask import Flask, request, render_template, make_response
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, TextSendMessag... | Python | 1 |
String,
/// The percentage of all mutants which should be executed
#[clap(short, long, default_value_t = 100)]
sample_threshold: i32,
/// Path to the wasm module
wasmfile: String,
},
/// Create new configuration file.
NewConfig {
/// Path to the new config... | Rust | 0 |
r#"{
"code_id": "f1c3bcc0279865fe3058404b2831d9e64135386c",
"code_file": "crash",
"debug_id": "c0bcc3f1-9827-fe65-3058-404b2831d9e6",
"arch": "arm64",
"image_addr": "0x0",
"image_size": 4096,
"image_vmaddr": "0x8000",
"other": "value",
"type": "elf"
}"#;
let image = Annotated::new(DebugImage::El... | Rust | 0 |
};
Ok(IntegerValue {
value: number,
grain,
..IntegerValue::default()
})
},
);
b.rule_1_terminal(
"integer (1..10) - TYPE 2",
b.reg(r#"(하나|둘|셋|넷|다섯|여섯|일곱|여덟|아홉)"#)?,
|text_match| {
let ... | Rust | 0 |
show figure
plt.gcf().set_size_inches(12, 16)
plt.show()
# Define first figure using subplot_mosaic, which allows for subplots to be
# created with custom spacing and empty plots, represented by '.' in function
fig = plt.figure(constrained_layout=True).subplot_mosaic("""
..AA..
BBCCDD
.EEFF.
.... | Python | 1 |
# Define a função para cadastrar produtos em uma lista (dicionário)
def cadastra_produto(lista_de_produtos):
# Solicita ao usuário o nome do produto e armazena na variável nome_prod
nome_prod = input("Digite o nome do produto: ")
# Solicita ao usuário o valor do produto, converte para float e armazena na va... | Python | 1 |
kl_loss_seq_mean (torch.Tensor): KL-divergence computed as a mean over batch size and seq length (scalar)
ll_loss_seq_mean (torch.Tensor): Log-likelihood computed as a mean over batch size and seq length (scalar)
n_vlb_loss_seq_mean (torch.Tensor): Negative of the Variational lower bound computed as a ... | Python | 1 |
}
}
/// Returns a reference to the `Ssl` associated with this context.
pub fn ssl(&self) -> Result<Option<&SslRef>, ErrorStack> {
unsafe {
let idx = cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx())?;
let ssl = ffi::X509_STORE_CTX_get_ex_data(self.as_ptr(), idx);
... | Rust | 0 |
from tkinter import *
from PIL import Image, ImageTk
root = Tk() # https://s8.uupload.ir/files/5_aysm.png
img5 = Image.open(r'ilia\5.png')
img5 = img5.resize((300, 300))
img5 = ImageTk.PhotoImage(img5)
aks5 = Button(root, image=img5)
aks5.place(width=300, height=300)
img4 = Image.open(r'ilia\4.png')
img4 = img4.resi... | Python | 1 |
Ok(())
})
}
}
}
}
tuple_impls!(
(10 => K),
(9 => J),
(8 => I),
(7 => H),
(6 => G),
(5 => F),
(4 => E),
(3 => D),
(2 => C),
(1 => B),
(0 => A),
);
impl_layout!((), align: 0, size: 0);
impl Encodable for () {
f... | Rust | 0 |
e_size, [x[0] for x in F1_result], label='Global', fmt='o-')
axes[2].errorbar(starting_feature_size, [x[1] for x in F1_result], label='iCARE', fmt='o-')
axes[2].errorbar(starting_feature_size, [x[2] for x in F1_result], label='eGuided', fmt='o-')
axes[2].set_xlabel('Number of Initial Features')
axes[2].set_ylabel('F1 S... | Python | 1 |
field::{BitField, UnvalidatedBitField, Validate};
use serde::{Deserialize, Serialize};
use fil_actors_runtime::runtime::Policy;
/// Maps deadlines to partition maps.
#[derive(Default)]
pub struct DeadlineSectorMap(BTreeMap<u64, PartitionSectorMap>);
impl DeadlineSectorMap {
pub fn new() -> Self {
Default... | Rust | 0 |
#!/usr/bin/env python
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from glob import glob
from os.path import join as pjoin
from jupyter_packaging import (
combine_commands,
create_cmdclass,
ensure_targets,
get_version,
install_npm,... | Python | 1 |
ec.consignee_hsn = rec.product_template_id.consignee_hsn
class SaleReportInherti(models.Model):
_inherit = "sale.report"
delivery_date_done = fields.Datetime("Effective Date", readonly=True)
def _select_additional_fields(self):
additional_fields = super()._select_additional_field... | Python | 1 |
from cmath import log
from distutils.sysconfig import PREFIX
import discord
from dotenv import load_dotenv
import os
load_dotenv()
import random
import gacha
import soriziller
import omikuji
import arcade
from datetime import datetime
from pytz import timezone
PREFIX = os.environ['PREFIX']
TOKEN = os.environ['TOKEN']... | Python | 1 |
st[cr][cc] > 0:
# if 0 <= nr < R + 3 and 0 <= nc < C and v[nr][nc] == 0 and forest[nr][nc] != 0 and forest[cr][cc] == \
# forest[nr][nc]:
# q.append([nr, nc])
# mx = max(mx, nr)
# return mx
#
#
# for i in range(1, len(a_lst) + 1):
# ... | Python | 1 |
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>MediaMTX Monitor - Мониторинг БПЛА</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; background-color... | Python | 1 |
np.load('norm2.npy')
# self.eig_vecs /= nn[:,:50]
# ==== VISUALIZATION CODE ==========
if False:
num_mesh_to_viz = 6
meshes = []
for i in range(num_mesh_to_viz):
meshes.append(trimesh.Trimesh(self.vertices + np.array([i*1,0,0]), self.faces, p... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.