text string | label_name string | labels int64 |
|---|---|---|
#!/usr/bin/env python
# encoding: utf-8
import multiprocessing
from textwrap import dedent
from itertools import izip_longest
def process_chunk(d):
"""Replace this with your own function
that processes data one line at a
time"""
d = d.strip() + ' processed'
return d
def grouper(n, iterable, padvalue=None):
"... | Python | 1 |
fn emit_ir_current(&mut self, sig: TypeSignature, ins: Instruction) {
self.emit_ir(self.current().pos, sig, ins)
}
/// Makes a notice at a position
#[inline]
pub(crate) fn emit_notice(&mut self, pos: Position, level: NoticeLevel, msg: String) {
if level == NoticeLevel::Error {
... | Rust | 0 |
v_deniro(self):
"""
Test 'deniro.csv' file
"""
self.assertEqual(jc.parsers.csv.parse(self.generic_csv_deniro, quiet=True), self.generic_csv_deniro_json)
def test_csv_example(self):
"""
Test 'example.csv' file
"""
self.assertEqual(jc.parsers.csv.parse(... | Python | 1 |
play());
xshell::mkdir_p(&output_dir).expect("Unable to create output directory");
// build the project to the output directory
xshell::cmd!("cargo +{toolchain} build --target-dir {output_dir} --release")
.run()
.expect("Unable to build");
// zip output
let exe = executable_path(&o... | Rust | 0 |
lines: &Vec<String>, x: i32, y: i32) -> u32 {
let mut count = 0;
//println!("[{} {}]", x, y);
for dir_x in -1..2 {
for dir_y in -1..2 {
//print!("{} {}: ", dir_x, dir_y);
if dir_x != 0 || dir_y != 0 {
let mut col = x;
let mut row = y;
loop {
col = col + dir_x;
row = row + dir_y;
//... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import threading
from datetime import datetime
from collections import deque
from scapy.all import *
import curses
from curses import wrapper
import argparse
import signal
import binascii
class TerminalPacketSniffer:
def __init__(self... | Python | 1 |
edProcessError:
print(Fore.RED + f"[-] Homebrew is not installed. Installing Homebrew..."+ Fore.RESET)
install_homebrew()
# Install Docker using Homebrew
install_docker()
system_name = platform.system()
if system_name == "Darwin":
print(Fore.YELLOW + '[*] Installing docker' + Fore.RESET)
... | Python | 1 |
# Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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 2 of the License, or
# (at your o... | Python | 1 |
# mypy: allow-untyped-defs
import torch
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
from torch.overrides import TorchFunctionMode
class AutogradStateOpsFailSafeguard(TorchFunctionMode):
"""
Detect grad state ops during exporting the graph and fail the process by
raising an error,... | Python | 1 |
(full_name, alias.asname if alias.asname else alias.name)
)
return imports
def dynamic_import_modules(imports: list[tuple[str, str]]) -> dict[str, str]:
"""Dynamically imports the modules and returns a dictionary of imported names."""
global_vars = {}
for full_name, alias in import... | Python | 1 |
from time import time, sleep
from colorama import Fore, Style
from datetime import datetime
def cpm(content: str):
print(
f'{Fore.LIGHTBLACK_EX}{datetime.fromtimestamp(time()).strftime(f"[{Fore.LIGHTBLUE_EX}%H{Fore.LIGHTBLACK_EX}:{Fore.LIGHTBLUE_EX}%M{Fore.LIGHTBLACK_EX}:{Fore.LIGHTBLUE_EX}%S{Fore.LIGHTBL... | Python | 1 |
go!(ch, ch1, prime, filter(ch, ch1, prime));
ch = ch1;
}
}
#[test]
fn main() {
let primes = make::<i32>(1);
go!(primes, sieve(primes));
let a = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
... | Rust | 0 |
ialize, AnyLifetime)]
#[derivative(Debug)]
pub(crate) struct DefGen<V> {
parameters: ParametersSpec<V>, // The parameters, **kwargs etc including defaults (which are evaluated afresh each time)
parameter_captures: Vec<u32>, // Indices of parameters, which are captured in nested defs
parameter_types: Vec<(u... | Rust | 0 |
.x = input_state.pressed_point.x;
input_state.previous_point.y = input_state.pressed_point.y;
paint_tool.on_mouse_pressed(&settings, paint_nib, &input_state, k_image);
}
// TODO ⚡Mouse move
// 📖 [MouseRelativeEvent](https://docs.piston.rs/piston_window/piston_window/tr... | Rust | 0 |
n[-] Setup Instructions are given in config.py to turn it ON")
#==============================================
def getting_details():
line()
print(f'[#] Scanned [{phone_number}] @ [{current_time()}]')
line()
try:
# Phone number format: (+Countrycode)xxxxxxxxxx
phone_number_details = phonenumber... | Python | 1 |
:
continue
stats_pearson, pvalue_pearson = pearsonr(rate_array, indicator_array)
if pvalue_pearson < 0.05:
res_df.loc[k,"Indicator"] = indicator
res_df.loc[k,"Feature"] = feat
res_df... | Python | 1 |
u16,
/// A level of verbosity, and can be used multiple times
#[clap(short, long, parse(from_occurrences))]
verbose: i32,
/// Transmit or Receive mode
#[clap(subcommand)]
mode: Mode,
/// Number of packets to transmit or wait to receive
#[clap(short, long)]
n_pkts: u64,
/// W... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2025 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 |
import ee
from .aster_bare_emiss import (
emiss_bare_band10,
emiss_bare_band11,
emiss_bare_band12,
emiss_bare_band13,
emiss_bare_band14,
)
def add_band(dynamic, image):
"""
Compute broad-band emissivity from ASTER GED.
Parameters:
- dynamic (bool): If True, use vegetation cover co... | Python | 1 |
2}, loaded
@pytest.mark.asyncio
async def test_extra_fields(client: openai.AsyncOpenAI):
with pytest.raises(BadRequestError) as exc_info:
await client.chat.completions.create(
model=MODEL_NAME,
messages=[{
"role": "system",
"content": "You are a help... | Python | 1 |
";
const AES_128_CCM: &str = "aes-128-ccm";
const AES_256_CCM: &str = "aes-256-ccm";
fn get_nid(name: String) -> Result<Nid, Exception> {
match name.to_lowercase().as_ref() {
AES_128_CBC => Ok(Nid::AES_128_CBC),
AES_256_CBC => Ok(Nid::AES_256_CBC),
AES_128_CTR => Ok(Nid::AES_128_CTR),
... | Rust | 0 |
non-null and points to a u16 string terminated by a null character.
pub unsafe fn from_ptr_win32_wide_string(wide: *const u16) -> String {
assert!(!wide.is_null());
let len = strlen_ptr_u16(wide);
let slice = slice::from_raw_parts(wide, len);
String::from_utf16_lossy(slice)
}
pub fn duplicate_handle_w... | Rust | 0 |
"""
占位符流水线应用服务
把 Domain 的扫描/处理/替换 串入应用层编排:
- ETL 前扫描:识别统计/图表占位符并标记重分析
- 报告组装:通过端口生成SQL并执行/渲染,替换占位符并附20字说明
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from datetime import datetime, timedelta
from app.services.domain.placeholder.usecases.scanner import PlaceholderScanner
from ... | Python | 1 |
* ("Traditional Works of Scholarship")
* Copyright (c) 2020-, Meta Platforms, Inc. and its affiliates.
*
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! convenient functions for debugging tra... | Rust | 0 |
"""
Tests various capabilities of the libEnsemble fast_alloc alloc_f
Execute via one of the following commands (e.g. 3 workers):
mpiexec -np 4 python test_fast_alloc.py
python test_fast_alloc.py --nworkers 3
The number of concurrent evaluations of the objective function will be 4-1=3.
"""
# Do not change these... | Python | 1 |
every 100 timesteps.
# callback is a callback that logs the training process to wandb,
# this is done because wandb.watch() does not work with sb3.
if config.log_to_wandb:
model.learn(total_timesteps=config.total_timesteps,
log_interval=config.log_interval,
callback=[wandb_callb... | Python | 1 |
import pigpio
import time
servo_pin = 18
# Initialize pigpio
pwm = pigpio.pi()
# Set up GPIO pin for the servo
pwm.set_mode(servo_pin, pigpio.OUTPUT)
pwm.set_PWM_frequency(servo_pin, 100) # Set PWM frequency to 50 Hz
pwm.set_PWM_range(servo_pin, 20000) # Set PWM range (20,000 us for 100% duty cycle)
# Move servo... | Python | 1 |
jax.nn.relu,
eqx.nn.MaxPool2d(2, 2),
eqx.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1, key=keys[1]),
jax.nn.relu,
eqx.nn.MaxPool2d(2, 2),
jnp.ravel,
eqx.nn.Linear(64 * 7 * 7, 128, key=keys[2]),
jax.nn.relu,
... | Python | 1 |
sora sompeng', 'bs': 'sora sompeng pismo', 'bs-Cyrl': 'сора сомпенг писмо', 'bs-Latn': 'sora sompeng pismo', 'ca': 'sora sompeng', 'ca-ES-valencia': 'sora sompeng', 'cs': 'sora sompeng', 'de': 'Sora Sompeng', 'en': 'Sora Sompeng', 'eu': 'sora sompeng', 'ff-Adlm': '𞤅𞤢𞤪𞤢 𞤅𞤮𞤥𞤨𞤢𞤲𞤺', 'fi': 'sorang sompeng', 'fy':... | Python | 1 |
) -> result::Result<(), std::io::Error> {
Ok(())
}
fn notifier(&self, _index: InterruptIndex) -> Option<EventFd> {
Some(self.event_fd.try_clone().unwrap())
}
}
impl TestInterrupt {
fn new(event_fd: EventFd) -> Self {
TestInterrupt { event_fd ... | Rust | 0 |
locks,
block,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[serde(rename_all = "camelCase")]
pub enum ModifierInvocationKind {
ModifierInvocation,
BaseConstructorSpecifier,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[se... | Rust | 0 |
outputs=state_checkbox_group,
every=3,
)
image.change(
change_checkbox,
inputs=[state_checkbox_group, image, engine.manager._id_to_elem["top.lang"], gr.State("image_tag")],
outputs=state_checkbox_group,
)
video.change(
change_checkbox,
inputs=[st... | Python | 1 |
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, ClassVar
import llemon
if TYPE_CHECKING:
from llemon import (
Embedder,
EmbedderModel,
EmbedRequest,
EmbedResponse,
)
log = logging.getLogger(__name__)
cl... | Python | 1 |
# Function to perform BFS on a graph
def BFS(graph, start_node):
# Initialize visited list to keep track of visited nodes
visited = []
# Initialize queue with the start_node to process nodes level by level
queue = []
queue.append(start_node)
visited.append(start_node)
# Loop to process node... | Python | 1 |
ataSourceReader, AsyncSeekableSource, AsyncUnseekableDataSource},
async_once_cell::OnceCell as AsyncOnceCell,
async_std::{fs::File as AsyncFile, path::PathBuf as AsyncPathBuf},
futures::{future::BoxFuture, lock::Mutex as AsyncMutex, AsyncSeekExt},
std::num::NonZeroUsize,
};
enum Source<A: Digest> {
... | Rust | 0 |
ame>crates/mist-core/src/timing.rs
//! Functions used for formatting of times.
/// Convert milliseconds into a readable time in the form HH:MM:SS.mmm.
///
/// Optionally rounds to a valid number of milliseconds on which a frame
/// can occur, at any framerate.
///
/// # Arguments
///
/// * `ms` - the value to convert ... | Rust | 0 |
import unittest
import numpy as np
from impl import maps, shapes
from impl import types as t
class ShapesTestCase(unittest.TestCase):
def test_occlusion_maps(self):
full = t.BlockShape(
map=maps.Map(
origin=(0, 0, 0),
values=np.ones((8, 8, 8), dtype=bool),
... | Python | 1 |
rs.logging.INFO``
- ``transformers.logging.DEBUG``
"""
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
def set_verbosity_info():
"""Set the verbosity to the :obj:`INFO` level."""
return set_verbosity(INFO)
def set_verbosity_warning():
"""Set the v... | Python | 1 |
try!(s.emit_struct_field("id", 1, |s2| {
self.1.to_bytes_be().encode(s2)
}));
Ok(())
})
}
}
impl serialize::Decodable for NodeK {
fn decode<D:serialize::Decoder> (d : &mut D) -> Result<Self, D::Error> {
d.read_struct("Node", 2, |d| {
... | Rust | 0 |
let mut residual: f64 = 0.0;
for i in 0..rho.len() {
residual += rho[i as usize];
if i == 0 {
residual += (phi[i+1 as usize] - 2.0*phi[i as usize] + phi[(rho.len()-1) as usize])/dx_g.powi(2);
}
else if i+1 == rho.len() as usize {
residual += (phi[0] - 2.0*phi[i as usize] + phi[(i-1) as usize])/dx_g.pow... | Rust | 0 |
, $is_valid_fn:ident) => {
impl $t {
/// # Safety
///
/// MCL Function, unsure why it is unsafe
pub fn is_valid(&self) -> bool {
unsafe { $is_valid_fn(self) == 1 }
}
}
};
}
macro_rules! serialize_impl {
($t:ty, $size:ex... | Rust | 0 |
pub down: glm::Vec2,
pub current: glm::Vec2,
pub last: glm::Vec2,
}
impl Dragging {
pub fn new(mouse_position: LogicalPosition<f32>) -> Self {
let position: glm::Vec2 = glm::vec2(mouse_position.x, mouse_position.y);
Self {
down: position,
current: position,
... | Rust | 0 |
equency(&self.params, &mut self.coeffs);
}
}
#[inline]
fn tick(
&mut self,
input: &Frame<Self::Sample, Self::Inputs>,
) -> Frame<Self::Sample, Self::Outputs> {
let v0 = convert(input[0]);
let v3 = v0 - self.ic2eq;
let v1 = self.coeffs.a1 * self.ic1eq + se... | Rust | 0 |
}
<gh_stars>10-100
use std::any::TypeId;
use std::marker::PhantomData;
use std::mem::transmute;
use std::ptr::NonNull;
use xjbutil::void::Void;
use crate::data::Value;
use crate::data::generic::GenericTypeVT;
use crate::data::traits::{ChildrenType, StaticBase};
use crate::data::tyck::{ContainerTyckInfo, TyckInfo, Tyc... | Rust | 0 |
.exceptHandlers.pop()
# Process the other nodes: "except:", "else:", "finally:"
for child in iter_child_nodes(node):
if child not in node.body:
self.handleNode(child, node)
TRYEXCEPT = TRY
def EXCEPTHANDLER(self, node):
# 3.x: in addition to handling childre... | Python | 1 |
k, Inc. and its affiliates.
*
* 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 wr... | Rust | 0 |
#!/usr/bin/python
# Example of pass, break, continue
# pass: does nothing. useful when testing something or when that code block is not required
# break: terminates the current loop and resumes execution at the next statement
# continue: returns the control to the beginning of the loop
port_details = {
'21': 'ft... | Python | 1 |
The briefing document should include:
* A summary of the target company and its industry.
* Key findings from the research and industry analysis.
* Recommended NVIDIA solutions and their benefits.
* Talking points, questions, and strategic... | Python | 1 |
= csle_collector.ryu_manager.ryu_manager_pb2.RyuDTO(ryu_running=ryu_running,
monitor_running=monitor_running,
port=self.ryu_port,
... | Python | 1 |
[`sort`](https://vega.github.io/vega-lite/docs/sort.html) documentation.
#[serde(default, skip_serializing_if = "RemovableValue::is_default")]
#[builder(default)]
pub sort: RemovableValue<Sort>,
/// Time unit (e.g., `year`, `yearmonth`, `month`, `hours`) for a temporal field.
/// or [a temporal fie... | Rust | 0 |
print("STARTING...")
bif="bg.jpg"
mif="cur.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption('Draw stuff :P')
Blue=(0,0,255)
points=[]
backdrop=pygame.image.load(bif).convert()
cur=pygame.image.load(mif).convert_alpha()
print(... | Python | 1 |
#!/usr/bin/env python3
"""
TradingAgents 简化演示脚本 - 使用阿里百炼大模型
这个脚本展示了如何使用阿里百炼大模型进行简单的LLM测试
"""
import os
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
from dotenv import load_dotenv
# 加载 .env 文件
load_dotenv()
def test_s... | Python | 1 |
gex),
Some(Value::from(regex)),
Some(bin),
Some(flags),
None,
None,
)
}
/// Create compare geospatial operation.
/// ```
/// use aerospike::expressions::{geo_compare, geo_bin, geo_val};
/// // Query region within coordinates.
/// let region = "{\"type\": \"Polygon\", \"coord... | Rust | 0 |
_PERIOD, TEST_REMOTE_IPV4);
// Now insert a static entry.
insert_static(&mut ctx, (), TEST_REMOTE_IPV4, TEST_REMOTE_MAC);
// The timer should have been canceled.
assert_eq!(ctx.timers().len(), 0);
}
#[test]
fn test_arp_entry_expiration() {
// Test that, if a dynami... | Rust | 0 |
].dropna().sort_values(by=assists_col, ascending=False)
if not season_assists.empty and season_assists.iloc[0][assists_col] > 0:
assist_king = season_assists.iloc[0]
q_templates_assist_pos = [
f"谁是{season}赛季的英超助攻王?",
f"请问{season}赛季贡献助攻最... | Python | 1 |
ou::prelude::*;
mod util;
use util::captured_frame_path;
use util::interp::{Interp, Interpolate};
fn main() {
nannou::sketch(view).size(1024, 1024).run();
}
fn view(app: &App, frame: Frame) {
let win = app.window_rect();
let pi2 = PI * 2.0;
app.set_loop_mode(LoopMode::NTimes {
// two frames are necessary... | Rust | 0 |
import os
import pickle
from typing import Dict, List
from types import FunctionType
from Script.Core import (
game_type, json_handle, get_text,
text_handle, cache_control, dijkstra,
game_path_config, get_text
)
from Script.Design import map_handle, constant
cache: game_type.Cache = cache_control.cache
"""... | Python | 1 |
#[doc = ""]
#[doc = " @param [in] context: The context the graph will run inside;"]
#[doc = " could be NULL and the graph is created in a private context."]
#[doc = ""]
#[doc = " @param [in] model_format: The model format type,such as \"caffe\",\"tengine\""]
#[doc = " @param [i... | Rust | 0 |
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_lifesmart_devices: list,
mock_client: MagicMock,
mock_hub_for_testing,
):
"""测试卸载时服务取消注册。"""
mock_config_entry.add_to_hass(hass)
# 设置集成
with patch(
"custom_components.life... | Python | 1 |
way to go?
* to town
let's go to town
-> town
* to the moon
let's go to the moon
-> moon
== town
town is cool
-> END
== moon
moon is great
-> END";
let mut runner = StoryRunner::build_from_str(story);
let start... | Rust | 0 |
(error) => {
error!("Failed to bind to root component: {:?}", error);
process::exit(1)
}
}
// make sure root component exposes trigger protocol.
let expose_dir_proxy = io_util::open_directory(
&hub_proxy,
&PathBuf::from("exec/expose"),
OPEN_RIGHT_READ... | Rust | 0 |
import pytest
import logbook
def test_level_properties(logger):
assert logger.level == logbook.NOTSET
assert logger.level_name == "NOTSET"
logger.level_name = "WARNING"
assert logger.level == logbook.WARNING
logger.level = logbook.ERROR
assert logger.level_name == "ERROR"
def test_reflected... | Python | 1 |
nt) GST_VIDEO_TRANSFER_ADOBERGB", "12"),
("(gint) GST_VIDEO_TRANSFER_ARIB_STD_B67", "15"),
("(gint) GST_VIDEO_TRANSFER_BT2020_10", "13"),
("(gint) GST_VIDEO_TRANSFER_BT2020_12", "11"),
("(gint) GST_VIDEO_TRANSFER_BT601", "16"),
("(gint) GST_VIDEO_TRANSFER_BT709", "5"),
("(gint) GST_VIDEO_TRANSFE... | Rust | 0 |
N_A2).unwrap()).unwrap();
share_set.try_add_share(share2).unwrap();
assert!(
share_set.next_action() == NextAction::AskUserForPassword,
"Two different shares are sufficient."
);
let alice_secret = share_set.recover_with_passphrase(PASSPHRASE_A).unwrap();
assert!(alice_secret == SECR... | Rust | 0 |
processor.file_writer = mock_writer
with patch('os.path.exists', return_value=True), patch(
'os.access', return_value=True
):
result = processor.process_file("/test/concept_file.adoc")
self.assertTrue(result)
# Verify content was updated
... | Python | 1 |
print(f"({p2}, {p1}): d=({d1_b:.6f}, {d2_b:.6f})")
# Check symmetry
assert abs(d1_a - d2_b) < 1e-10, f"Demand symmetry broken"
assert abs(d2_a - d1_b) < 1e-10, f"Demand symmetry broken"
assert abs(profit1_a - profit2_b) < 1e-10, f"Profit symmetry broken"
assert abs(profit2_a - profit1_b) < 1e... | Python | 1 |
:
tensors = self._build_from_meta()
for tensor in tensors:
if tensor is not None:
ops.append(P2POp(paddle.distributed.irecv, tensor, src, group))
return tensors
def append_isend(self, ops, tensors, dst, group, need_broadcast_meta=False):
if need_broad... | Python | 1 |
# -*- coding: utf-8 -*-
# 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... | Python | 1 |
Copyright 2003,2004 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later vers... | Python | 1 |
), &CondType::Eq, &CondArg::NumConst(ref c)) => format!("predicate <{} equals to {}>", name, c),
(&CondArg::StringConstant(ref c), &CondType::Eq, &CondArg::ColumnName(ref name)) => format!("predicate <'{}' equals to {}>", c, name),
(&CondArg::Limit, &CondType::Eq, &CondArg::NumConst(ref c)) => f... | Rust | 0 |
import numpy as np
import scipy.optimize as op
def fnceval(task, rnvec, p_il, method):
d = task.dim
nvars = rnvec[:d]
minrange = task.lb[:d]
maxrange = task.ub[:d]
y = maxrange - minrange
vars = y * nvars + minrange
if np.random.uniform() <= p_il:
res = op.minimize(task.fnc, vars, m... | Python | 1 |
label=label_name)
plt.legend(loc=loc_dict[data_name], fontsize=fontsize)
plt.xlabel('Communication rounds', fontsize=fontsize)
plt.ylabel('Test {}'.format(metric_name), fontsize=fontsize)
plt.ylim(ylim_dict['iid']['global'][data_name])
plt... | Python | 1 |
"predict_proba") and callable(getattr(self, "predict_proba")):
try:
y_train_pred_proba = self.predict_proba(X_train)
if X_test is not None and X_test.size > 0:
y_test_pred_proba = self.predict_proba(X_test)
... | Python | 1 |
//! `transmit_complete` callback until the next scheduler loop. In the future,
//! if there is support for software interrupts or deferred calls in capsules,
//! this timer should be removed.
//!
//! Todo
//! ----
//!
//! - Implement receive functionality.
//!
//! Usage
//! -----
//!
//! ```rust
//! pub struct Platform... | Rust | 0 |
from typing import Optional
import arrow
from arrow import Arrow
from sqlalchemy.exc import IntegrityError
from app.constants import JobType
from app.db import Session
from app.models import PartnerUser, PartnerSubscription, User, Job
from app.user_audit_log_utils import emit_user_audit_log, UserAuditLogAction
def ... | Python | 1 |
invocation_parts.append(f"{p.name}={p.name}")
varkw = get_varargs(signature, kind=inspect.Parameter.VAR_KEYWORD)
if varkw:
invocation_parts.append("**" + varkw.name)
candidate_names = ["f"] + [f"f_{i}" for i in range(1, len(used_names) + 2)]
for funcname in ... | Python | 1 |
########## This file is generated automatically based on ArcusPerformaxDriver.h ##########
# pylint: disable=unused-import, unused-argument, wrong-spelling-in-comment
import ctypes
import enum
from ...core.utils import ctypes_wrap
def _int32(v): return (v+0x80000000)%0x100000000-0x80000000
##### TYPE DEF... | Python | 1 |
pub(crate) use crate::{
client::Client,
coll::Collection,
cursor::Cursor,
db::Database,
};
pub use coll::Namespace;
}
#[cfg(all(
feature = "tokio-runtime",
feature = "async-std-runtime",
not(feature = "sync")
))]
compile_error!(
"`tokio-runtime` and `async-ru... | Rust | 0 |
/// Multimap implementation that behaves like `IndexMap<K, IndexSet<V>>`.
#[derive(Debug, Clone)]
pub struct IndexSetMultimap<K, V, S = RandomState> {
inner: IndexMap<K, IndexSet<V, S>, S>,
len: usize,
}
impl<K, V> IndexSetMultimap<K, V> {
multimap_base_impl! {IndexMap<K, IndexSet<V>>}
}
impl<K, V, S> In... | Rust | 0 |
e given function.
///
/// This function does not check that the slices are the same length and will crash horrifically on
/// index-out-of-bounds.
#[inline]
unsafe fn zip_map_in_place_unchecked<FA, FB, M>(a: &mut [FA], b: &[FB], mut zip_map: M)
where
FA: Frame,
FB: Frame,
M: FnMut(FA, FB) -> FA,
{
for i... | Rust | 0 |
is {:?}", c)
} else {
String::new()
};
err.span_label(span, &format!("byte constant must be ASCII{}", postfix));
if (c as u32) <= 0xFF {
err.span_suggestion(
span,
&format!(
"... | Rust | 0 |
canonicalize()
.expect("Failed to canonicalize base_path");
conf.base_path(base_path);
let options = "serde";
if !options.is_empty() {
conf.options(options);
}
conf
};
conf
.run(&[
"cgroupfs.thrift"
])
.expect... | Rust | 0 |
commands ... <' + node_list[i+1].tag + '>. ALERT! This element has an attribue "id" and it is "' + node_list[i+1].attrib["id"] + '"')
exit(1)
node_list.remove(node_list[i+1])
break
else:
cria_link(node_from, node_to)
def saida_links():
#... | Python | 1 |
import pandas as pd
import numpy as np
import scanpy as sc
import os
import matplotlib.pyplot as plt
plt.style.use('default')
# extract human cells and mouse cells
folder_list = os.listdir("../output/seperated_sample_matrix_raw")
folder_list = [x for x in folder_list if "DS_Store" not in x]
# filter out data for ... | Python | 1 |
class House(object):
def accept(self, visitor):
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, "worked on by", hvac_specialist)
def work_on_electricity(self, electrician):
print(self, "worked on by", electrician)
def __str__(self):
return ... | Python | 1 |
e: &mut Engine) -> Status {
dict(engine, "DICTIADDREF", keyreader_from_int, INV | RET | SET, valwriter_add_ref_without_unref)
}
// (int slice nbits - (slice' -1) | (slice 0))
pub(super) fn execute_dictidel(engine: &mut Engine) -> Status {
dict(engine, "DICTIDEL", keyreader_from_int, DEL | RET, valwriter_remove... | Rust | 0 |
# -*- coding: UTF-8 -*-
"""
@Project :CryptoCS
@File :FeatureBase.py
@Author :LeslieChiu
@Date :2024/4/11 14:27
"""
import pandas as pd
from tqdm import tqdm
import toml
#from FeatureFunc import Momentum, HighMoment, Volatility, Liquidity, Correlation
from ReturnTool import ReturnTool
from FactorAnalysis impor... | Python | 1 |
) -> Vec2 {
if let Some(val) = self.fields.get(field_name) {
if let Some(val) = val.as_array() {
if let Some(x) = val[0].as_f32() {
if let Some(y) = val[1].as_f32() {
return Vec2::new(x, y);
}
}
... | Rust | 0 |
red_fn {
($($f:ident),+) => {
extern {
$(
fn $f(
dst: *mut u8, stride: libc::ptrdiff_t, topleft: *const u8,
width: libc::c_int, height: libc::c_int, ac: *const u8,
alpha: libc::c_int,
);
)*
}
};
}
decl_cfl_pred_fn! {
rav1e_ipred_cfl_avx2,
rav1e_... | Rust | 0 |
\": {}", source))]
InvalidHooksProcess { source: mlua::Error },
#[snafu(display("Cannot evaluate Lua code defining \"hooks.shutdown\": {}", source))]
InvalidHooksShutdown { source: mlua::Error },
#[snafu(display("Cannot evaluate Lua code defining timer handler: {}", source))]
InvalidTimerHandler { s... | Rust | 0 |
Balance, CurrencyId, Price, Rate};
use orml_traits::parameter_type_with_key;
pub(crate) use pallet_traits::PricesManager;
use sp_core::H256;
use sp_runtime::{
testing::{Header, TestXt},
traits::{AccountIdConversion, BlakeTwo256, IdentityLookup, One},
};
use sp_std::cell::RefCell;
pub use test_helper::*;
// --------... | Rust | 0 |
1].strip()
elif "result-op" in class_list:
if div.h3:
title = div.h3.text.strip()
url = div.h3.a['href'].strip()
else:
title = div.text.strip().split("\n", 1)[0]
url = ... | Python | 1 |
s2_kv_proj_stride = 2,
s2_heads = 3,
s2_depth = 2,
s2_mlp_mult = 4,
s3_emb_dim = 384,
s3_emb_kernel = 3,
s3_emb_stride = 2,
s3_proj_kernel = 3,
s3_kv_proj_stride = 2,
s3_heads = 6,
s3_depth = 10,
s3_mlp_mult = 4,
dropout ... | Python | 1 |
tomock;
use rocksdb::{Options, DB};
use simple_logger::SimpleLogger;
use std::fmt::Display;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use std::{env, fs};
use tokio::sync::broadcast;
use tokio::task::JoinHandle;
use tokio::time::{timeout_at, Duration, ... | Rust | 0 |
pub const SPREAD_NONE: c_int = 0;
<reponame>koesterlab/datavzrd
use anyhow::Result;
use std::collections::HashMap;
use std::iter::FromIterator;
use std::path::Path;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
pub(crate) enum ColumnType {
None,
String,
Integer,
Float,
}
// TODO: Use Derive once ... | Rust | 0 |
t);
return (t - self.cuts[i]) / (self.cuts[i+1] - self.cuts[i]);
}
}
// TODO: Move these functions to a more appropriate submodule.
impl<T: Evaluate<EvalResult = Vector>+Primitive+Send+ Sync> Piecewise<Piecewise<T>>
{
// we split the primitive that contains t at t
pub fn subdivide(&self, t: f64) ->... | Rust | 0 |
while True:
n1 = int(input("Digite o 1º número: ")) # Lê o primeiro número
n2 = int(input("Digite o 2º número: ")) # Lê o segundo número
if n1 >= 30 and n1 <= 80 and n2 >= 30 and n2 <= 80: # Verifica se ambos os números estão no intervalo de 30 a 80
if n1 < n2:
while n1 < n2: # Loop par... | Python | 1 |
# Copyright (c) 2021, Matthew Booker
#
# 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 w... | Python | 1 |
ializer()
if cidEnum is ClassId.CLOSURE:
return ClosureDeserializer()
if cidEnum is ClassId.MINT:
return MintDeserializer()
if cidEnum is ClassId.DOUBLE:
return DoubleDeserializer()
if cidEnum is ClassId.GROWABLE_OBJECT_ARRAY:
return GrowableObjectArrayDeserializer()
# FIXME: should only target precompiled... | Python | 1 |
0xa3, 0xfe, 0xec, 0x08, 0xd1}
DEFINE_GUID! {GUID_PROCESSOR_PARKING_CORE_OVERRIDE,
0xa55612aa, 0xf624, 0x42c6, 0xa4, 0x43, 0x73, 0x97, 0xd0, 0x64, 0xc0, 0x4f}
DEFINE_GUID! {GUID_PROCESSOR_PARKING_PERF_STATE,
0x447235c7, 0x6a8d, 0x4cc0, 0x8e, 0x24, 0x9e, 0xaf, 0x70, 0xb9, 0x6e, 0x2b}
DEFINE_GUID! {GUID_PROCESSOR_PARKING... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.