text string | label_name string | labels int64 |
|---|---|---|
wp)
return mpf_mul(t, mpf_add(K, b), prec, rnd)
def mpc_ellipe(z, prec, rnd=round_fast):
re, im = z
if im == fzero:
if re == finf:
return (fzero, finf)
if mpf_le(re, fone):
return mpf_ellipe(re, prec, rnd), fzero
wp = prec + 15
mag = mpc_abs(z, 1)
p = ma... | Python | 1 |
ploy_file) as f:
yml_conf = yaml.safe_load(f)
arch = yml_conf['arch']
detector_func = 'Detector'
if arch == 'SOLOv2':
detector_func = 'DetectorSOLOv2'
elif arch == 'PicoDet':
detector_func = 'DetectorPicoDet'
detector = eval(detector_func)(
FLAGS.model_dir,
d... | Python | 1 |
Some(first) => String::from(first.to_uppercase().to_string() + &input[1..]),
}
}
// pub trait Input<'a> {
// fn to_vec(self) -> Vec<&'a str>;
// }
// impl<'a> Input<'a> for &'a str {
// fn to_vec(self) -> Vec<&'a str> { vec![self] }
// }
// impl<'a> Input<'a> for Vec<&'a str> {
// fn to_vec(self... | Rust | 0 |
def run_callbacks(self, event: str):
"""Execute all callbacks for a given event."""
for callback in self.callbacks.get(event, []):
callback(self)
| Python | 1 |
# Tạo tiêu đề CSV từ tất cả các thuộc tính của Player
header = [
'Player', 'From', 'To', 'Price'
]
| Python | 1 |
pub trait SparseAccess<T>: Matrix<T> {
/// Number of non-zero elements in the matrix.
fn nnz(&self) -> usize;
/// Retrieve the triplets that identify the coefficients of the sparse matrix.
fn fetch_triplets(&self) -> Vec<(usize, usize, T)>;
}
impl<T, X> Matrix<T> for &X
where
X: Matrix<T>,... | Rust | 0 |
# Copyright 2018 The Texar Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Python | 1 |
# kline_chart_lib/indicators.py
import pandas as pd
import numpy as np
from ta.trend import EMAIndicator, MACD
from typing import List, Tuple, Dict, Any, Optional
import logging
class TechnicalIndicators:
"""
技术指标类,用于计算和检测各种技术指标
"""
@staticmethod
def add_ema(df: pd.DataFrame, window: int = 2... | Python | 1 |
/// - `self` - Self reference
///
/// # Returns
///
/// `Player` reference
pub fn player(&self) -> &Player { &self.players[self.team as usize] }
/// Updates Agent's map for current turn
/// - updates turn
/// - reads research points for all `Player`'s
/// - reads ALL units, reso... | Rust | 0 |
for k in scene_stats[0].keys()
})
all_stats.append(scene_stats)
print(model_path, avg_stats[-1])
val_names = []
for i in range(NUM_SCALES):
for metric in ['psnr', 'ssim']:
val_names.append(f'{metric}_{i}')
val_names.append('num_hours')
names = [x[0] for x in list(models_meta.values())]... | Python | 1 |
payload(info, data.offset() as u32, data.len() as u32),
)
};
XdpAction::Pass
}
<gh_stars>1-10
use openlineage_sql::SqlMeta;
#[macro_use]
mod test_utils;
use test_utils::*;
#[test]
fn insert_values() {
assert_eq!(
test_sql("INSERT INTO TEST VALUES(1)",),
SqlMeta {
in_tab... | Rust | 0 |
in"))
// .unwrap();
let out_includes = PathBuf::from(std::env::var("OUT_DIR").unwrap());
// Write out an empty platform file: defines will be set through cc directly,
// sync to prevent potential IO troubles later on
let mut f =
File:... | Rust | 0 |
#!/usr/bin/env python3
import sys, os
# we're in directory 'tools/' we have to update sys.path
sys.path.append(os.path.dirname(sys.path[0]))
from graph.vanilla.graph_access import accessPointsDict
from rom.rom import RealROM, pc_to_snes, snes_to_pc
rom = RealROM(sys.argv[1])
for apName, ap in accessPointsDict.item... | Python | 1 |
# Copyright 2022 The FastEstimator Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | Python | 1 |
e\xdd\xaf\
\xb4\xba\xd4\x8f\x1f\xdbv\x96\xb0\xa2D\xf3\x9c\x024\xa7\
o`R\x1c[\x0c0k;\xab\x07\xd8\xea\xd4\xdd\x15\
\xef\xc7\x90\x958c\x92L\x99\x1c\x07\x00\xd1$dR\
\x96Uahq\xb0\x07\xb0\xcf\x0d\x946\xc5\xfa\xa8\x05\
h\xde\xc4\x82x\xc2X!\x0fr\x8c(\xb3,\x0cy\
\x84\x06,\xa7X_d\xa1\xb0\xfd\xd4l\x95\x0a\xbd\x01\
m-\xc6\xfb\x0b\... | Python | 1 |
utput_dir = Path(self.config_loader.get_value("app_config.output_dir", "backend/output"))
output_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Save main result
result_file = output_dir / f"coding_wo... | Python | 1 |
eDetails {
&self.details
}
/// Verifies that the parsed metadata matches known details.
pub(crate) fn verify(&self) {
self.graph
.verify()
.expect("graph verification should succeed");
self.details.assert_workspace(self.graph.workspace());
self.detai... | Rust | 0 |
import numpy as np
from scipy.special import gamma
import matplotlib.pyplot as plt
e = 1.602e-19
C = 1
c = 3 * 10 ** 8
m_e = 9.109e-31
def Power(B, p, omega):
return (np.sqrt(3) * e ** 3 * C * B) / (2 * np.pi * m_e * c ** 2 * (p + 1)) * gamma(p / 4 + 19 / 12) * gamma(p / 4 - 1 / 12) * (np.power(((m_e * c * omega) ... | Python | 1 |
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
with open("data.txt") as data:
self.high_score = int(data.read())
self.color("white")
self.hideturtle... | Python | 1 |
import typing
from underautomation.fanuc.ftp.variables.generic_variable_type import GenericVariableType
import clr
import os
clr.AddReference(os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", 'lib', 'UnderAutomation.Fanuc.dll')))
from UnderAutomation.Fanuc.Ftp.Variables import CoParamgpVariableType ... | Python | 1 |
))
}
use connection::{ConnectionInfo, IntoConnectionInfo, Connection, connect,
PubSub, connect_pubsub, ConnectionLike};
use types::{RedisResult, Value};
/// The client type.
pub struct Client {
connection_info: ConnectionInfo,
}
/// The client acts as connector to the redis server. By itself it... | Rust | 0 |
.clone())
.collect();
assert!(names.contains(&"a".to_string()));
assert!(names.contains(&"b".to_string()));
}
#[test]
fn test_highlight() {
test_init();
let text = r#"
module test;
logic clk;
assign clk = 1'b1;
endmodule"#;
let doc = Rope::from_str(&t... | Rust | 0 |
psbts.push(json.psbt);
}
psbts.extend(opt.psbts.clone());
let combined = client.combine_psbt(&psbts)?;
debug!("combined {:?}", combined);
let finalized = client.finalize_psbt(&combined, Some(true))?;
debug!("finalized {:?}", finalized);
let bytes = ... | Rust | 0 |
gl.enable_vertex_attrib_array(0);
let texture = Texture::new(gl.clone(),"resources/textures/awesomeface.png",true);
gl.bind_vertex_array(Some(0));
// uncomment this call to draw in wireframe polygons.
// gl.polygon_mode(glow::FRONT_AND_BACK, glow... | Rust | 0 |
from rest_framework import serializers
from .models import Notification, NotificationTemplate, WebhookEndpoint
class NotificationSerializer(serializers.ModelSerializer):
"""Serializer for Notification model"""
class Meta:
model = Notification
fields = ['id', 'title', 'message', 'notificat... | Python | 1 |
> {
type Error = RoomAliasId<T>;
fn try_from(id: RoomIdOrAliasId<T>) -> Result<RoomId<T>, RoomAliasId<T>> {
match id.variant() {
Variant::RoomId => Ok(RoomId { full_id: id.full_id, colon_idx: id.colon_idx }),
Variant::RoomAliasId => {
Err(RoomAliasId { full_id: i... | Rust | 0 |
out, 0)?.ptr)?;
let file_len_out = self.force_ptr(self.mplace_field(file_out, 1)?.ptr)?;
let line_out = self.force_ptr(self.mplace_field(location, 1)?.ptr)?;
let col_out = self.force_ptr(self.mplace_field(location, 2)?.ptr)?;
let layout = &self.tcx.data_layout;
let alloc = self.... | Rust | 0 |
#!/usr/bin/env python2
# HP Compaq 6715b ROM unpacker by roxfan
# compressed data begins like this:
# 0000010000: 01 00 14 01 70 00 00 00 | 60 00 00 00 00 00 02 00 O .Op . O
# 0000010010: 50 4F 53 54 FF B8 00 20 | 8E D8 66 B8 10 FF 20 00 POST.. ..f...
import struct, array, sys
def unpack1(cdata, ulen):
pos... | Python | 1 |
erStyle) -> Self {
self.0.border(style).boxed_cf()
}
pub fn pad_to(self, size: Size) -> Self {
self.0.pad_to(size).boxed_cf()
}
pub fn align(self, alignment: Alignment) -> Self {
self.0.align(alignment).boxed_cf()
}
pub fn centre(self) -> Self {
self.0.centre()... | Rust | 0 |
output_path: str):
return LearnedCompressor().compress(input_path, output_path)
def decompress(compressed_path: str, output_path: str):
return LearnedCompressor().decompress(compressed_path, output_path)
def verify(original_path: str, compressed_path: str):
return LearnedCompressor().verify(original_pa... | Python | 1 |
) = match button {
MouseButton::Left => (ffi::NX_LMOUSEUP, 0),
MouseButton::Right => (ffi::NX_RMOUSEUP, 1),
MouseButton::Middle => (ffi::NX_OMOUSEUP, 2),
};
button_event(self, event_type, button_number, false)?;
self.button_state &= !(1 << button_number);
... | Rust | 0 |
{}
#[doc = "Forces D+ and D- lines into the state defined in the DPDMVALUE register"]
pub mod tasks_dpdmdrive;
#[doc = "Stops forcing D+ and D- lines into any state (USB engine takes control)\n\nThis register you can [`reset`](crate::pac::generic::generic::Reg::reset), [`write`](crate::pac::generic::generic::Reg::write... | Rust | 0 |
"""
Gaussian kernel calculator
Adapted from:
https://observablehq.com/@jobleonard/gaussian-kernel-calculater
"""
import math
SQRT2 = math.sqrt(2)
def erf(x: float):
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
t = 1.0 / (1.0 + p * ... | Python | 1 |
uter.get_pcf_pin_address(int(ioarray[0]))
tmcp.writepin(trpin, int(ioarray[1]))
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"PCFGPIO"+str(ioarray[0])+": "+str(e))
def syncvalue(self,epin,value):
for x in range(0,len(Settings.Tasks)):
if (Settings.Tasks[x]) and type(Settings.Tasks... | Python | 1 |
import re
# Python3 code to split string on vowels using split() + regex
str1 = 'GFGABste4oCS'
res1 = re.split('[aeiou]', str1.lower())
print('The split string:', str(res1))
| Python | 1 |
0100}".into() });
assert_eq!(harness.debug_render(), "\u{E0100}\u{E0100}|");
ctx.do_edit(EditNotification::DeleteBackward);
assert_eq!(harness.debug_render(), "\u{E0100}|");
ctx.do_edit(EditNotification::DeleteBackward);
assert_eq!(harness.debug_render(), "|");
// Multip... | Rust | 0 |
Expr::Lambda(parms, body) => {
if parms.len() != args.len() { return Err("applied to incorrect number of args") }
let proc_env = env.borrow_mut().extend_env(env.clone());
for (p, a) in parms.iter().zip(args) {
proc_env.borrow_mut().insert(p.from_var().unwrap(... | Rust | 0 |
BinaryToken::F64(x) => wtr.write_f64(*x)?,
BinaryToken::Token(x) => match TokenLookup.resolve(*x) {
Some(id)
if ((self.rewrite && id == "is_ironman")
|| (id == "checksum" && !write_checksum))
... | Rust | 0 |
import re
import subprocess
from thefuck import utils
from thefuck.utils import replace_argument
from thefuck.specific.git import git_support
from thefuck.shells import shell
@git_support
def match(command):
return ('did not match any file(s) known to git.' in command.output
and "Did you forget to 'gi... | Python | 1 |
# SPDX-License-Identifier: MIT
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
import os
import runpy
import sys
def run_vllm_serve(tp=1, dp=1, model="/home/kc/models/DeepSeek-V2-Lite"):
# Define the parameters you want to pass to vllm serve
params = [
"vllm.entrypoints.openai... | Python | 1 |
# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author: HsuDan
@Date: 2022-02-18 19:12:58
@Version: 1.0
@LastEditors: HsuDan
@LastEditTime: 2022-03-01 19:05:17
@Description: file content
@FilePath: /Sentiment-Analysis-Chinese-pytorch/Sentiment_Analysis_Config.py
"""
class Config:
update_w2v = True # 是否在训练中更新... | Python | 1 |
configuration is invalid")
return False
import PyISY
# Connect to ISY controller.
isy = PyISY.ISY(host.hostname, port, username=user, password=password,
use_https=https, tls_ver=tls_version, log=_LOGGER)
if not isy.connected:
return False
_categorize_nodes(hass,... | Python | 1 |
d_RCP).json()
row_RCP = result_RCP['list']
data_RCP = row_RCP[0]['rcp_id']
data_Name = row_RCP[0]['rcp_name']
##########################################################################################
################################### 발화어 정보 Requset ##########################... | Python | 1 |
SessionActive<'q, Postgres>, Error> {
session.make_active(&resolve_profile_key).await
}
async fn resolve_profile_key(
conn: &mut PoolConnection<Postgres>,
cache: Arc<KeyCache>,
profile: String,
) -> Result<(ProfileId, Arc<ProfileKey>), Error> {
if let Some((pid, key)) = cache.get_profile(profile.as... | Rust | 0 |
#!/bin/python3
# Generates a list of rays with spherical distributed directions to be used with igtrace or other tracers
import numpy as np
import sys
THETA_C = 16
PHI_C = 32
def gen_directions():
theta = np.linspace(-np.pi/2, np.pi/2, THETA_C)
phi = np.linspace(0, 2*np.pi, PHI_C)
theta_v, phi_v = np.me... | Python | 1 |
};
use toolup::prelude::*;
#[tokio::main]
async fn main() -> AnyResult<()> {
dotenv::dotenv().ok();
human_panic::setup_panic!();
let opt = Opts::parse();
let global_folder = GlobalFolders::from(&opt.global_config);
let _gaurd = configure_logging(&opt.logging_opts, &global_folder);
info!(ve... | Rust | 0 |
e serde_json;
use super::*;
use std::fmt::Debug;
use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng;
fn test_roundtrip<T: Serialize + for<'a> Deserialize<'a> + Debug + PartialEq>(t: &T) {
let ser = serde_json::to_vec(t).unwrap();
//println!("Bytes: {:?}", ser);
... | Rust | 0 |
tring
pub async fn get<T: DeserializeOwned>(
&self,
endpoint: &str,
query_string: &str,
) -> Result<T, impl Error> {
let prefixed_query = if query_string.starts_with('&') {
query_string.to_owned()
} else {
'&'.to_string() + query_string
};
... | Rust | 0 |
_distance)
screen_x = x * raysize
screen_y = int(-wall_height / 2 + H / 2)
if textured:
texture_offset = texture * 32
texture_x = int(wall_x * 32) + texture_offset
texture_y = 0
texture_src_w = 1
texture_src_h = 32
blit(W... | Python | 1 |
__all__ = ["sora_pipeline_dict", "vlm_pipeline_dict"]
from mindspeed_mm.tasks.inference import sora_pipeline_dict, vlm_pipeline_dict
| Python | 1 |
)
}
}
impl From<IpAddr> for IpAddrRange {
fn from(addr: IpAddr) -> Self {
IpAddrRange {
addr,
mask: match addr {
IpAddr::V4(_) => 32,
IpAddr::V6(_) => 128,
},
}
}
}
impl TryFrom<(IpAddr, u8)> for IpAddrRange {
type Err... | Rust | 0 |
ive> { None } }
const METHOD_CALL: Option<NoDerive> = NoDerive::none();
match None { Some(_) => panic!("whoops"), METHOD_CALL => dbg!(METHOD_CALL), };
//~^ WARN must be annotated with `#[derive(PartialEq, Eq)]`
//~| WARN this was previously accepted
}
use anyhow::anyhow;
use clap::{App, Arg};
use ruso... | Rust | 0 |
terator, ExactSizeIterator, Future)]
//! # struct _Enum<A>(A);
//! enum Enum<A, B> {
//! A(A),
//! B(B),
//! }
//! ```
//!
//! Code like this will be generated:
//!
//! ```rust
//! enum Enum<A, B> {
//! A(A),
//! B(B),
//! }
//!
//! impl<A, B> std::iter::Iterator for Enum<A, B>
//! where
//! A: std:... | Rust | 0 |
from math import sqrt
n = 21102001
q, p = 947, 22283 # gdc = 2
phi_n = (q-1) * (p-1)
e1 = 1021
e2 = 1201
# Проверка на простоту
def is_prime(n):
if n < 2:
return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
print(f'{is_prime(n) = }', f... | Python | 1 |
),
Point2::new(-0.5, -0.5),
]);
let right_transform = Matrix3::new(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
let gjk = GJK2::new();
let contact = gjk.intersection(
&CollisionStrategy::FullResolution,
&left,
&left_transform,
... | Rust | 0 |
file_name = "Cargo.toml";
let output_path = build_dir.join(file_name);
let output = reg.render(file_name, &json).unwrap();
maybe_write_to_file(&output_path, output, tcfg.overwrite_existing);
}
fn maybe_write_to_file(output_path: &Path, output: String, overwrite: bool) -> Option<PathBuf> {
if output_pa... | Rust | 0 |
icon=utils.get_gui_icon(),
non_blocking=True,
keep_on_top=True,
)
continue
# 处理 MenubarCustom 事件(格式为 "菜单::子菜单")
elif self._use_menubar_custom and "::" in str(event):
menu_p... | Python | 1 |
#!/usr/bin/env python3
import gensim
from mediawords.util.log import create_logger
from mediawords.util.test_word2vec import (
sample_word2vec_model_path,
sample_word2vec_model_dictionary,
sample_word2vec_gensim_version_path,
)
log = create_logger(__name__)
def generate_sample_word2vec_model():
"""... | Python | 1 |
Element<P>,
com_b: ExtensionFieldElement<P>,
com_c: ExtensionFieldElement<P>,
ip_ab: ExtensionFieldElement<P>,
agg_c: P::G1Projective,
/// Called W in the paper
hidden_wire_com: P::G1Projective,
/// Transcript of an HWW protocol execution
hidden_input_proof: HwwProof<P::G1Projective>,
... | Rust | 0 |
j.get_fields()["time"])
print(obj.get_fields()["time"][1])
print(type(obj.SOURCE.dtype.fields["time"][1]))
obj = NpTimeSeriesAux(TS_EXAMPLE.LOAD_LIST_1)
ObjectInfo(obj.SOURCE).print()
exit()
print(obj.get_fields()["time"][1])
exit()
obj = NpTimeSeriesAux(TS_EXAMPLE.LOAD_LIST_1)
#... | Python | 1 |
sequences like '../'.
async fn full_path<P: AsRef<Path>, U: UserDetail>(&self, path: P, user: &Option<U>) -> Result<PathBuf> {
// `path.join(other_path)` replaces `path` with `other_path` if `other_path` is absolute,
// so we have to check for it.
let path = path.as_ref();
println!... | Rust | 0 |
import pickle
import numpy as np
# To load the model later, use:
loaded_model = pickle.load(open("finalised_xgboost_model.sav", 'rb'))
new_data = np.array([[1234, 123, 4565, 0, 1]])
predict = loaded_model.predict(new_data)
print(predict) | Python | 1 |
& (span.hi.0 as usize) >= *line_end_offset
});
if ignore {
return (index, 1);
}
let mut count = 0;
// Count the hits of ranges that include the entire line which will always be at-least one
// as long as the code has been evaluated.
for function in &s... | Rust | 0 |
t on nodes that support this RuntimeClass. Pods using this RuntimeClass can only be scheduled to a node matched by this selector. The RuntimeClass nodeSelector is merged with a pod's existing nodeSelector. Any conflicts will cause the pod to be rejected in admission.
"""
return pulumi.get(self, "node_se... | Python | 1 |
# import streamlit as st
# import json
# from utils import speak, listen
# from collections import defaultdict
# # Load products
# with open('products.json') as f:
# products = json.load(f)
# # Initialize session state
# if 'budget' not in st.session_state:
# st.session_state.budget = None
# if 'cart' not in ... | Python | 1 |
VirtioFpgaCommand::VirtioFpgaFmeBitstreamBuild(cmd) => fme.bitstream_build(cmd),
_ => Err(VirtioFpgaResponse::ErrUnspec),
}
}
}
<gh_stars>0
use std::io::{self,BufRead};
use crate::var::Var;
use crate::db::table::Book;
use super::super::component::BookList;
use super::View;
pub struct BookLis... | Rust | 0 |
:*;
use uscript::*;
use uset::*;
use ucnv::*;
use uloc::*;
use ures::*;
use unorm2::*;
use ucal::*;
use udat::*;
use unum::*;
use utrans::*;
use ubidi::*;
use ushape::*;
use ucol::*;
use usearch::*;
use ubrk::*;
use uregex::*;
use usprep::*;
use uidna::*;
use utmscale::*;
use umachine::*;
use parseerr::*;
use utext::*;... | Rust | 0 |
import os, pygame, random
import ctypes
from ctypes import wintypes
# os.environ['SDL_VIDEO_WINDOW_POS'] = "{},{}".format(random.randint(0, 1920), random.randint(0, 1080))
size = random.randint(400, 600)
screen = pygame.display.set_mode((size, size), pygame.NOFRAME)
user32 = ctypes.WinDLL("user32")
user32.SetWindowPo... | Python | 1 |
def agregar (productos, precios):
print("====AGREGAR PRODUCTO====")
product= str(input("Ingrese el nombre del producto:"))
precio= float(input("Ingresa el precio del producto:"))
productos.append(product)
precios.append(precio)
print("Producto agregado exitosamente")
def eliminar(productos,prec... | Python | 1 |
#!/usr/bin/python3
"""
0. Lockboxes
"""
def canUnlockAll(boxes):
"""
Determines if all the boxes can be opened.
Args:
- boxes: List of lists representing locked boxes.
Returns:
- True if all boxes can be opened, else False.
"""
# Set to keep track of opened boxes
opened_boxes = s... | Python | 1 |
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtUiTools import QUiLoader
from PySide6.QtGui import QFontDatabase
from qt_material import QtStyleTools
########################################################################
class RuntimeStylesheets(QMainWindow, QtStyleTools):
# -------------... | Python | 1 |
ader;
} else if (strcmp(type, "texture") == 0) {
mi.as_asset = asset_hndl_new_load(P(value));
type_id = mat_item_texture;
} else if (strcmp(type, "int") == 0) {
mi.as_int = atoi(value);
type_id = mat_item_int;
} else if (strcmp(type, "float") == 0) {
... | Rust | 0 |
const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(alt_CDataNodeReceivedEvent),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<alt_CDataNodeReceivedEvent>())).cancelled... | Rust | 0 |
Raw assembled bytes
bytes: Vec<u8>,
/// Address of executable copy of `bytes`, established by `finalize`
executable: Option<usize>,
}
/// Kinda gross, but here we load an assembly template and replace magic values
/// with JIT-time values
macro_rules! load_asm_template {
($template_path:expr, $base:e... | Rust | 0 |
ve(Debug, Copy, Clone)]
pub struct ClosestPointResult<T>
where
T: Real,
{
/// The start vertex index of the closest segment.
pub seg_start_index: usize,
/// The closest point on the closest segment.
pub seg_point: Vector2<T>,
/// The distance between the points.
pub distance: T,
}
/// Struc... | Rust | 0 |
#coding: utf-8
import random, string
import redis
import ledis
from redis_import import copy, scan, set_ttl
rds = redis.Redis()
lds = ledis.Ledis(port=6380)
def random_word(words, length):
return ''.join(random.choice(words) for i in range(length))
def get_words():
word_file = "/usr/share/dict/words"
... | Python | 1 |
fmt::Result {
let render_escape = format!("{}{}{}",
ESCAPE_CHAR, self.tag, self.arg.as_ref().map_or("", |arg| arg.as_str())
);
match self.kind {
StringEscapeErrorKind::InvalidEscapeTag => write!(fmt, "unrecognized escape sequence '{}'", render_escape),
... | Rust | 0 |
"""
Data collection modules for fetching posts from social media platforms.
""" | Python | 1 |
ith tf.name_scope(self.deberta.name):
self.deberta.build(None)
if getattr(self, "pooler", None) is not None:
with tf.name_scope(self.pooler.name):
self.pooler.build(None)
if getattr(self, "classifier", None) is not None:
with tf.name_scope(self.cla... | Python | 1 |
wf_activation_job::Variant::CancelWorkflow(_)
),
vec![CancelWorkflowExecution {}.into()],
)],
)
.await;
}
<reponame>softdevteam/ykbf<filename>src/main.rs
use std::{
env, fs,
io::{stderr, Bytes, Read, Stdin, Stdout, Write},
path::Path,
process,
};
use ... | Rust | 0 |
);
r.y.mul_assign(&e);
r.y.negate();
r.y.add_assign(&t0);
r.z.mul_assign(&e);
let mut t1 = lambda;
t1.mul_assign(&q.y);
let mut j = theta;
j.mul_assign(&q.x);
j.sub_assign(&t1);
theta.negate();
match self.twist_type {
... | Rust | 0 |
\n (c).-.(c) \n / ._. \\ \n __\\( Y )/__ \n(_.-/'-'\\-._)\n || X || \n _.' `-' '._ \n(.-./`-'\\.-.)\n `-' `-' \n",
'{': u'{\n \n \n \n \n \n \n \n \n',
'z': u" _ _ \n (c).-.(c) \n / ._. \\ \n __\\( Y )/__ \n(_.-/'-'\\-._)\n || Z || \n _.' `-' '._ \n(.-./`-'\\.-.)\n `-' `-' \... | Python | 1 |
import cv2
import imutils
import sys
import numpy as np
from normalizer import normalize
def get_large_contours(input):
contours= cv2.findContours(input.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
contours = sorted(contours, key = cv2.contourArea, reverse = Tr... | Python | 1 |
feature = "decoder", feature = "encoder"))]
#[inline]
pub(crate) fn internal_set_op0_register(this: &mut Instruction, new_value: Register) {
this.reg0 = new_value as u8;
}
#[cfg(feature = "decoder")]
#[inline]
pub(crate) fn internal_set_op0_register_u32(this: &mut Instruction, new_value: u32) {
this.reg0 = new_value... | Rust | 0 |
import unittest
from app.algorithms.sorting.oop.mergesort import MergeSort
class MergeSortAlgorithmTest(unittest.TestCase):
def test_merge_sort_empty_array(self):
"""
Test merge sort with an empty array.
"""
merge_sort = MergeSort()
self.assertEqual(merge_sort.sort([]), [])... | Python | 1 |
_tx.send(rx).await.unwrap();
println!("Receiving remote mpsc channel receiver");
let mut rx = b_rx.recv().await.unwrap().unwrap();
let mut rng = rand::thread_rng();
let mut tasks = Vec::new();
for i in 1..1024 {
println!("Sending sender");
let (n_tx, mut n_rx) = mpsc::channel(1);
... | Rust | 0 |
from __future__ import annotations
from dataclasses import dataclass, field
from pydantic import BaseModel, Field, ValidationError, field_validator
__all__ = ["Tool", "Tools"]
class ToolUrl(BaseModel):
name: str
url: str
class Tool(BaseModel):
name: str
urls: list[ToolUrl] = Field(default_factory... | Python | 1 |
PRAGMA temp_store = MEMORY;",
)
.expect("PRAGMA");
conn.execute(
"CREATE TABLE IF NOT EXISTS user (
id INTEGER not null primary key,
area CHAR(6),
age INTEGER not null,
active INTEGER not null)",
[],
)
.unwrap();
l... | Rust | 0 |
# Copyright 2017 Toolchain Labs, Inc. All rights reserved.
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from django.urls import path
from toolchain.django.site.views.check_infra import CheckSentryz
from toolchain.django.site.views.healthz import Healthz
from toolchain.django.site.views.reloadz impo... | Python | 1 |
ding)
if result_type == "kics" and results.get(result_type) is not None:
for kics_type in results[result_type].get("results", []):
name = kics_type.get("name")
for vulnerability in kics_type.get("vulnerabilities", []):
finding =... | Python | 1 |
"""
Utilities to ease the differences between async and sync code.
These object offer a similar interface between sync and async versions; the
script async_to_sync.py will replace the async names with the sync names
when generating the sync version.
"""
# Copyright (C) 2023 The Psycopg Team
from __future__ import an... | Python | 1 |
m setuptools.dist import Distribution
class DistributionWithoutHelpCommands(Distribution):
common_usage = ""
def _show_help(self, *args, **kw):
with _patch_usage():
Distribution._show_help(self, *args, **kw)
if argv is None:
argv = sys.argv[1:]
with _p... | Python | 1 |
one,
english: "Psyduck",
japanese: "コダック",
japanese_transliterated: "Koduck",
korean: "고라파덕",
chinese: "可達鴨",
french: "Psykokwak",
german: "Enton",
spanish: "Psyduck",
italian: "Psyduck",
};
pub const Golduck: &'static PokeSpecies = &PokeSpecies {
id: 55,
attack: 191,
defense: 163,
stamina: 160,
primary_... | Rust | 0 |
truncated: bool,
) -> (ExtendedFloat, bool)
where
F: Float,
{
let mut fp = ExtendedFloat {
mant: mantissa,
exp: 0,
};
let valid = multiply_exponent_extended::<F>(&mut fp, exponent, truncated);
(fp, valid)
}
// FALLBACK
// --------
/// Fallback path when the fast path does not w... | Rust | 0 |
println!("Number run {}", i);
}
}
#[test]
fn test_new() {
let mut context = get_context(accounts(1));
testing_env!(context.build());
let contract = Contract::new_default_meta(accounts(1).into());
testing_env!(context.is_view(true).build());
assert_eq!(contrac... | Rust | 0 |
.args(&["build_htslib.sh", &version])
.stdout(std::process::Stdio::null())
.spawn()
.expect("Unable to build htslib")
.wait()
.unwrap()
.success());
println!("cargo:rerun-if-changed=build_htslib.sh");
println!("cargo:rerun-if-changed=hts_inc.h");
pr... | Rust | 0 |
from llama_index.core.tools.tool_spec.base import BaseToolSpec
from llama_index.tools.python_file import PythonFileToolSpec
def test_class():
names_of_base_classes = [b.__name__ for b in PythonFileToolSpec.__mro__]
assert BaseToolSpec.__name__ in names_of_base_classes
| Python | 1 |
i32,
plain_v1,
0,
0,
NUM_PAGES,
NUM_LEVELS,
16,
std::i32::MIN,
std::i32::MAX
);
test!(
test_read_plain_v2_int32_required_non_repeated,
i32,
plain_v2,
0,
0,
NUM_PAGES,
NUM_LEVELS,
... | Rust | 0 |
> {
let mut data_file = File::open("./data/s1c4.txt")?;
let mut data = String::new();
data_file.read_to_string(&mut data).unwrap();
let best_guess = data
.split('\n')
.map(|line| challenge3::guess_xor_message(line).unwrap())
.min_by_key(|guess| guess.weight)
.unwrap();
... | Rust | 0 |
_uniq(&mut self) -> bool {
self.align_to::<~str>();
if ! self.inner.visit_estr_uniq() { return false; }
self.bump_past::<~str>();
true
}
fn visit_estr_slice(&mut self) -> bool {
self.align_to::<&'static str>();
if ! self.inner.visit_estr_slice() { return false; }... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.