text string | label_name string | labels int64 |
|---|---|---|
# Enqueue all subdirectories
for dirname in dirnames:
queue.append(os.path.join(dirpath, dirname))
cls._model_directory = Path(basedir)
cls._basedir = basedir
return Path(basedir)
# Disable the use of xformers
disable_xformers = Switch()
# Re... | Python | 1 |
"""
Direct fix for account status button.
This module bypasses the regular callback flow to provide reliable status information.
"""
import logging
import time
import sqlite3
from typing import Dict, Any, List, Optional
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
... | Python | 1 |
],
}
define_error! {
WrongArity {
span: FreeSpan,
arity: usize,
args: usize,
},
message: "mismatched arity",
labels: [
Label::primary(span, format!("called with {} arguments", args)),
],
notes: [
... | Rust | 0 |
part),
Command::Info { name } => info(&name),
Command::Select { name } => select(&name),
Command::Deselect { name } => deselect(&name),
}
}
use crate::attributes;
use libc::c_uint;
use rustc_ast::expand::allocator::{AllocatorKind, AllocatorTy, ALLOCATOR_METHODS};
use rustc_middle::bug;
use r... | Rust | 0 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader
cl... | Python | 1 |
from sqlalchemy.orm import Session
from models import (head_of_department as model_head_of_department,
doctor as model_doctor,department as model_department)
from schemas import head_of_department as schema_head_of_department
def create_head_of_department(db: Session, head_of_department: schema_hea... | Python | 1 |
{
for vertex_id in self.vertex_iter() {
let p = self.vertex_position(vertex_id);
self.move_vertex_to(vertex_id, vec3(p.x * scale_x, p.y * scale_y, p.z * scale_z));
}
}
/// Translates the entire mesh by applying the `translation` to each vertex position.
///
/// ... | Rust | 0 |
ngs
) # matches downvoted tokens in neuron-viewer page for neuron 5:0
elif kind == "read":
assert (
" unison" in top_token_strings
) # matches upvoting input tokens in neuron-viewer page for neuron 5:0
ds_store, _... | Python | 1 |
import pytest
from spacy.lang.yo.lex_attrs import like_num
def test_yo_tokenizer_handles_long_text(yo_tokenizer):
text = """Àwọn ọmọ ìlú tí wọ́n ń ṣàmúlò ayélujára ti bẹ̀rẹ̀ ìkọkúkọ sórí àwòrán ààrẹ Nkurunziza nínú ìfẹ̀hónúhàn pẹ̀lú àmì ìdámọ̀: Nkurunziza àti Burundi:
Ọmọ ilé ẹ̀kọ́ gíga ní ẹ̀wọ̀n fún kí... | Python | 1 |
")
userdao.grant_cohort_write_privileges(schema_name, userdao.read_role)
@task(log_prints=True)
def insert_cdm_version(cdm_version: str, dbdao: DaoBase, cdm_schema: str, vocab_schema: str, use_placeholder_values=False):
logger = get_run_logger()
# Populate 'cdm_version_concept_id' and 'vocabulary_v... | Python | 1 |
> {
fn partial_cmp(&self, other: &RemotePtr<T>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for RemotePtr<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.ptr.cmp(&other.ptr)
}
}
impl<T> PartialEq for RemotePtr<T> {
fn eq(&self, other: &Self) -> bool {
se... | Rust | 0 |
# Time: O(n)
# Space: O(1)
#
# The API: int read4(char *buf) reads 4 characters at a time from a file.
#
# The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
#
# By using the read4 API, implement the function int read(char *buf, int n) ... | Python | 1 |
b[5], 0.0, 1.0],
];
let result = [
[
a[0][0].mul_add(b[0][0], a[0][1].mul_add(b[1][0], a[0][2].mul_add(b[2][0], a[0][3] * b[3][0]))),
a[0][0].mul_add(b[0][1], a[0][1].mul_add(b[1][1], a[0][2].mul_add(b[2][1], a[0][3] * b[3][1]))),
a[0][0].mul_add(b[0][... | Rust | 0 |
#!/usr/bin/env python
# encoding: utf-8
"""
Show how to use `dur` and `delay` parameters of play() and out()
methods to sequence events over time.
"""
from pyo import *
import random
s = Server(duplex=0).boot()
num = 70
freqs = [random.uniform(100, 1000) for i in range(num)]
start1 = [i * 0.5 for i in range(num)]
fa... | Python | 1 |
ana_program::rent::ACCOUNT_STORAGE_OVERHEAD + size_of::<Bridge>() as u64) *
solana_program::rent::DEFAULT_LAMPORTS_PER_BYTE_YEAR) as f64
* solana_program::rent::DEFAULT_EXEMPTION_THRESHOLD) as u64;
/// Check that a key was derived correctly and create account
pub fn check_and_create_account<T: ... | Rust | 0 |
p_header_extension::*;
extern crate nom;
use nom::bits::bits;
use nom::bits::complete::take as bits_take;
use nom::bytes::complete::take as bytes_take;
use nom::combinator::rest;
use nom::error::make_error;
use nom::error::ErrorKind;
use nom::multi::count;
use nom::number::complete::{be_u16, be_u32};
use nom::sequence... | Rust | 0 |
whnf(arg3, should_count);
match (*arg1, *arg2, *arg3) {
(
DAG::Lit(x_link),
DAG::Lit(y_link),
DAG::Lit(z_link),
) => {
let x = unsafe { &(*x_link.as_ptr()).lit };
let y = unsafe { &(*y_link.as_ptr()).lit };
... | Rust | 0 |
rt(intrinsic.id.clone(), intrinsic);
}
let mut all_valid = true;
for rust in FUNCTIONS {
// Skip some intrinsics that aren't part of MSA
match rust.name {
"break_" => continue,
_ => {}
}
let mips = match intrinsics.get(rust.name) {
Some(i)... | Rust | 0 |
scalar_negate_over_mul() -> Result<(), AlkaliError> {
let mut p = Point::generate()?;
let mut q = p;
let mut s = Scalar::generate()?;
p.scalar_mult_in_place(&s)?;
s.additive_inverse()?;
q.scalar_mult_in_place(&s)?;
p.add_in_place(&q)?;
assert_eq!(
... | Rust | 0 |
{
Self { tab_stop: 4, quit_times: 2, message_dur: Duration::new(3, 0), show_line_num: true }
}
}
impl Config {
/// Load the configuration, potentially overridden using `config.ini` files that can be located
/// in the following directories:
/// - On Linux, macOS, and other *nix systems:
... | Rust | 0 |
eTime, Datelike};
use serde::{Deserialize, Deserializer};
use itertools::Itertools;
use super::{Result, DataError, PlayerId, Player, RikishiId, Rank, RankGroup, RankSide, Day, Award};
use crate::data::leaders::{Rankable, assign_ord};
pub struct BashoInfo {
pub id: BashoId,
pub start_date: DateTime<Utc>,
p... | Rust | 0 |
_metadata: Option<Self::Metadata>,
subscription_id: SubscriptionId,
) -> JsonRpcResult<bool> {
Ok(self.subscriptions.cancel(subscription_id))
}
}
//! Client Requests
use std::marker::PhantomData;
use std::io::{self, Write};
use url::Url;
use method::{self, Method};
use header::Headers;
use header::Host;
use net... | Rust | 0 |
s necessary unless requote is False.
If charset is specified, the parameter will be encoded according to RFC
2231. Optional language specifies the RFC 2231 language, defaulting
to the empty string. Both charset and language should be strings.
r r6 )r r r r4 N)
r r ... | Python | 1 |
mmandList>::null(),
render_targets : [WeakPtr::null(); G_MAX_FRAME_COUNT],
root_signature : WeakPtr::<d3d12::ID3D12RootSignature>::null(),
pipeline_state : WeakPtr::<d3d12::ID3D12PipelineState>::null(),
frame_count : frame_count,
frame_index : 0,
vertex_buffer : WeakPtr::<d3d12::ID3D12Resource>::null(... | Rust | 0 |
,
/// ???
Pstore = 22,
/// ???
IoMmu = 23,
/// ??? Expanded memory?
Memory = 24
}
}
// FIXME: Move all this stuff into the userspace driver.
/*const CURRENT_VERSION: usize = 2;
impl Device {
/// Reads the device's ... | Rust | 0 |
ty: &str) -> bool {
path.leading_colon.is_none()
&& path.segments.len() == 1
&& path.segments.iter().next().unwrap().ident == from_ty
}
if let Type::Path(p) = ty {
if p.qself.is_none() && path_is(&p.path, from_ty) {
if let PathArguments::AngleBracketed(a) = &... | Rust | 0 |
14,
33,
125,
135,
24,
101,
512,
66,
7,
28,
822,
15,
542,
69,
59,
110,
14,
365,
229,
7,... | Python | 1 |
solution[edge.var_idx]).get_i64();
let argmax = unravel_index_ptr(idx, &dimensions, n_dim);
n_dim = 0;
for &e in &factor.edges {
if e != ue_pair.1 {
solution[bp.edges[e].var_idx] = argmax[n_dim];
n_dim +=... | Rust | 0 |
_owned(), "1H5QuOYI1b2r9ET".to_owned()).unwrap(),
public_key: "NOT_USED_FOR_THIS_USER".to_owned(),
balance: 0,
is_bot: false,
},
);
/*
<KEY>
-----END RSA PRIVATE KEY-----
*/
db.pending_transactions.write().inse... | Rust | 0 |
test]
#[ignore]
/// Fuzz test the multithreaded collapser.
///
/// Command: `cargo test fuzz_collapse_perf --release -- --ignored --nocapture`
fn fuzz_collapse_perf() -> io::Result<()> {
let seed = thread_rng().gen::<u64>();
println!("Random seed: {}", seed);
let mut rng = Sm... | Rust | 0 |
# Copyright (C) 2004, 2005, 2006, 2007 StatPro Italia srl
#
# This file is part of QuantLib, a free-software/open-source library
# for financial quantitative analysts and developers - http://quantlib.org/
#
# QuantLib is free software: you can redistribute it and/or modify it under the
# terms of the QuantLib license.... | Python | 1 |
ig = cc::Build::new();
base_config.include(&include_dir);
base_config.include(libusb_source.join("libusb"));
base_config.define("PRINTF_FORMAT(a, b)", Some(""));
base_config.define("ENABLE_LOGGING", Some("1"));
if std::env::var("CARGO_CFG_TARGET_ENV") == Ok("msvc".into()) {
fs::copy(
... | Rust | 0 |
t mut announced_service = String::new();
line_reader.as_read().read_to_string(&mut announced_service)?;
let expected_service_announcement = format!("# service={}", service.as_str());
if announced_service.trim() != expected_service_announcement {
return Err(client::Error::Http(Error::... | Rust | 0 |
# Copyright (c) 2015-2018 Cisco Systems, Inc.
# Copyright (c) 2018 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
#... | Python | 1 |
les-1.properties')
variables = string_utils.load_properties(target_variables_file)
self._match(7001, variables, 'ms1.port')
self._match('jdbc:oracle:thin:@host.com:1521/pdborcl', variables, 'JDBC.ds1.URL')
self._match('a', variables, 'prefix')
self._match('z', variables, 'suffix'... | Python | 1 |
#!/usr/bin/env python
# coding: utf-8
import tensorflow as tf
from ...losses.dml_loss import __get_similarity_matrices
def make_multi_class_count_triplet(n_class, triplet_margin=0.1, sim='cosine'):
""" Builder for a multi-class active triplet counter.
Note that the batch must be built using M exclusive clas... | Python | 1 |
A=5
B=20
print(A+B) | Python | 1 |
agent():
"""获取Mac OS的用户代理字符串"""
ua = UserAgent()
while True:
agent = ua.chrome
if "Macintosh" in agent:
return agent
else:
continue
if __name__ == "__main__":
print_logo()
# greater_than_0_45 = check_cursor_version()
browser_manager = None
try... | Python | 1 |
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/impl/auxiliary/vehicle_helper.py
import typing
from gui.shared.gui_items.Vehicle import VEHICLE_TAGS, getNationLessName
if typing.TYPE_CHECKING:
from gui.impl.gen.view_models.common.vehicle_info_model import VehicleInfoModel... | Python | 1 |
# So we have nums[i], nums[j], nums[k] and we need to find the sum of these three numbers that is equal to 0.
# Method: Two Pointers
# 1. Sort the list
# 2. Iterate through the list
# 3. If the current number is greater than 0, then we can break the loop because we can't find a sum that is equal to 0
# 4. If the curre... | Python | 1 |
#
#
# Copyright (C) 2007, 2008, 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | Python | 1 |
}{z}, zmm2/m512, imm8`
///
/// `EVEX.512.66.0F.WIG 71 /4 ib`
///
/// `AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpsraw_zmm_k1z_zmmm512_imm8 = 1644,
/// `PSLLW mm1, imm8`
///
/// `NP 0F 71 /6 ib`
///
/// `MMX`
///
/// `16/32/64-bit`
Psllw_mm_imm8 = 1645,
/// `PSLLW xmm1, imm8`
///
/// `66 0F 71 /6 ib`
///... | Rust | 0 |
r"""
TD Learning
===========
.. autosummary::
:nosignatures:
coax.td_learning.SimpleTD
coax.td_learning.Sarsa
coax.td_learning.ExpectedSarsa
coax.td_learning.QLearning
coax.td_learning.DoubleQLearning
coax.td_learning.SoftQLearning
coax.td_learning.ClippedDoubleQLearning
coax.td_le... | Python | 1 |
assert_eq!(encoded_input, expect);
}
}
// FIXME: this can be greatly simplified via $()?
// as soon as MRSV hits 1.32
/// Build [`Diagnostic`](struct.Diagnostic.html) instance from provided arguments.
///
/// # Syntax
///
/// See [the guide](index.html#guide).
///
#[macro_export]
macro_rules! diagnostic {
... | Rust | 0 |
deallocate_frame(&mut self, frame: PhysFrame<Size4KiB>) {
let _ = self
.bt
.free_pages(frame.start_address().as_u64(), 1)
.expect("EfiAllocator failed to deallocate frame");
}
}
<filename>src/main.rs
extern crate gh;
extern crate clap;
use std::{env, process};
use std:... | Rust | 0 |
G: Optional[Union[np.ndarray, spa.csc_matrix]] = None,
h: Optional[np.ndarray] = None,
A: Optional[Union[np.ndarray, spa.csc_matrix]] = None,
b: Optional[np.ndarray] = None,
lb: Optional[np.ndarray] = None,
ub: Optional[np.ndarray] = None,
initvals: Optional[np.ndarray] = None,
verbose: bo... | Python | 1 |
container, ignore);
let (merge_points, alignment, log_prob, e_hist) = align(&container)?;
merged_and_aligned(
container.iter()
.map(|c| c.1),
merge_points,
alignment,
log_prob,
e_hist
)
}
/// # Results of the simulation
/// This is what we do the simulat... | Rust | 0 |
import os
class ConfigManager:
"""
A singleton class responsible for managing configuration settings across the application.
This class implements the singleton design pattern to ensure that only one instance of the
ConfigManager exists at any time. It provides methods to set, apply, and clear proxy s... | Python | 1 |
向为正的概率-0.5 除以 每组新闻条数,作为影响股票收益率的参数
for result in AN_results:
AN_sen_days.append((result-0.5)/listcount)
for result in SN_results:
SN_sen_days.append((result-0.5)/listcount)
AN_days_list=predict_yield[:]#将未加入舆情信息的预测结果赋值给AN预测结果
SN_days_list=predict_yield[:]
for i in range(1,sentiment... | Python | 1 |
w")]
msg = r"Input has different freq=W-SUN from PeriodIndex\(freq=B\)"
with pytest.raises(IncompatibleFrequency, match=msg):
PeriodIndex(vals)
vals = np.array(vals)
with pytest.raises(IncompatibleFrequency, match=msg):
PeriodIndex(vals)
# tuple freq disa... | Python | 1 |
params -= self.transformer.wpe.weight.numel()
return n_params
def _init_weights(self, module):
# this is the same as huggingface repo:
# initialize range: https://huggingface.co/transformers/v3.0.2/_modules/transformers/configuration_gpt2.html#GPT2Config
# initialize function: https... | Python | 1 |
pub struct CssValidation {
pub uri: String,
pub checkedby: String,
pub csslevel: String,
pub date: String,
pub timestamp: String,
pub validity: bool,
pub result: CssResult,
pub warnings: Option<Vec<Message>>,
pub errors: Option<Vec<Message>>,
}
#[derive(Serialize, Deserialize)]
pub... | Rust | 0 |
给定时间步长 t 的累积乘积。
return self.alphas_cumprod[t] / (1 - self.alphas_cumprod[t])
# 用于从一个 1-D 张量中根据给定的索引生成一个新的张量,其中索引由参数 timesteps 指定。
# 这个函数的目的是根据索引生成一个与输入形状相同的新张量,其中每个位置的值来自于输入张量相应索引位置的值。
# arr为[step],timesteps为[batch_size],broadcast_shape为[batch_size,item_num]
def _extract_into_tensor(self, a... | Python | 1 |
ATTRIBUTE_PROMPT: ATTRIBUTEID = 76u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetworkPolicyServer\"`*"]
pub const RADIUS_ATTRIBUTE_CONNECT_INFO: ATTRIBUTEID = 77u32;
#[doc = "*Required features: `\"Win32_NetworkManagement_NetworkPolicyServer\"`*"]
pub const RADIUS_ATTRIBUTE_CONFIGURATION_TOKEN: ATTRIBU... | Rust | 0 |
:marker::PhantomData<::std::cell::UnsafeCell<T>>,
}
impl<T> Default for StyleFoo_Bar_Body<T> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct StyleFoo_Baz_Body<T> {
pub tag: StyleFoo_Tag,
pub _0: StylePoint<T>,
pub _phantom_0: :... | Rust | 0 |
nt(f"📁 All plots saved to {output_dir}/ directory")
print("✅ All visualizations completed!")
# Example usage
if __name__ == "__main__":
# Replace with your actual model path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(BASE_DIR, 'models', 'ep30000_MARIO_... | Python | 1 |
K).unwrap();
println!("subcommand matches: {:#?}", subcommand_matches);
let res = send_bulk(&subcommand_matches);
println!("res: {:#?}", res);
assert!(res.is_ok())
}
#[test]
fn test_attachment_odt_dry() {
let args = vec![
cmd::BIN,
cmd::SEND... | Rust | 0 |
push.rs
//! Async push and publish.
use super::*;
use log::debug;
#[derive(Debug, PartialEq)]
enum PushState {
Ready,
Sending,
}
#[derive(Debug)]
struct PushContextAioArg {
aio: NngAio,
state: PushState,
sender: Option<oneshot::Sender<Result<()>>>,
socket: NngSocket,
}
impl PushContextAioArg... | Rust | 0 |
_out_degree}")
print(f"Max Guest Out-Degree: {max_guest_out_degree}")
print("In Degree Distribution")
guest_power_law_exponent, guest_power_law_r2 = compute_and_plot_degree_distribution(graph, "g", city)
print("Out Degree Distribution")
host_power_law_exponent, host_power_law_r2 = compute_and_pl... | Python | 1 |
# -*- coding: utf-8 -*-
# Scrapy settings for jobbole project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest... | Python | 1 |
$( $Trait:ident => $gd_method:ident; )*
}
) => (
$(
impl_basic_trait_as_sys!(
$Trait for $Type as $GdType : $gd_method
);
)*
)
}
macro_rules! godot_test {
($($test_name:ident $body:block)*) => {
$(
#[cfg(feature... | Rust | 0 |
serialization_dupe_fields() {
// From RFC 7517, Section 4:
// "The member names within a JWK MUST be unique; JWK parsers MUST either
// reject JWKs with duplicate member names or use a JSON parser that
// returns only the lexically last duplicate member name, as specified
/... | Rust | 0 |
self):
"""
These have been checked against the Brier scores in the verification R package. The 'bins'
attribute was set to False, and the code had to be changed because it didn't work for cases
where forecasts were not equal to whole 1/10ths (i.e. 0.1, 0.2).
To give the same res... | Python | 1 |
[test]
fn invalid_attributes() {
let cfi_a1 = parse_strict("ESZUFR");
let cfi_a2 = parse_strict("ESVZFR");
let cfi_a3 = parse_strict("ESVUZR");
let cfi_a4 = parse_strict("ESVUFZ");
assert_eq!(cfi_a1.unwrap_err(), CFIError::InvalidAttribute {
was: (1, b'Z') });
... | Rust | 0 |
lf::Origin, Success=MultiLocation>;
/// Our XCM filter which messages to be executed using `XcmExecutor` must pass.
type XcmExecuteFilter: Contains<(MultiLocation, Xcm<Self::Call>)>;
/// Something to execute an XCM message.
type XcmExecutor: ExecuteXcm<Self::Call>;
}
#[pallet::event]
#[pallet::generate_de... | Rust | 0 |
= "File Structure:\n"
for file in selected_files:
content += f"- {file.path}\n"
content += "\n"
for file in selected_files:
content += f"File: {file.path}\n"
content += "-" * (len(file.path) + 6) + "\n"
file_content = base64.b64decode(file.content... | Python | 1 |
import os
import nbformat
def clean_notebook_metadata(file_path):
try:
nb = nbformat.read(file_path, as_version=nbformat.NO_CONVERT)
metadata_changed = False
if "widgets" in nb.metadata:
widgets = nb.metadata["widgets"]
if isinstance(widgets, dict):
... | Python | 1 |
d swap_candidates[swap_curve] == curve:
if (curve, swap_curve) not in processed_swaps and (swap_curve, curve) not in processed_swaps:
# 执行一次交换
curve_nearest[curve], curve_nearest[swap_curve] = curve_nearest[swap_curve], curve_nearest[curve]
# 记录处理过的交换对
... | Python | 1 |
gas. Return `OutOfGas` error.
pub fn fail(&mut self) -> ExitError {
self.inner = Err(ExitError::OutOfGas);
ExitError::OutOfGas
}
/// Record an explict cost.
pub fn record_cost(
&mut self,
cost: usize
) -> Result<(), ExitError> {
let all_gas_cost = self.total_used_gas() + cost;
if self.gas_limit < all... | Rust | 0 |
# -*- coding: utf-8 -*-
import xbmc
from xbmcgui import Window
from xbmc import sleep, getInfoLabel
from xbmcvfs import translatePath
from xbmcaddon import Addon
import json
import os
# from modules.logger import logger
window = Window(10000)
PROFILE_PATH = os.path.join(
translatePath("special://userdata/addon_d... | Python | 1 |
k_instance.get_task_names()
env_factory = instantiate(cfg.task.env_factory)
task_nums = cfg.task_nums if 'task_nums' in cfg else None
for task_no, task_name in enumerate(task_names):
if task_nums is not None and task_no not in task_nums:
continue
task_name = task_names[task_no... | Python | 1 |
} else {
(bs.clone(), c)
}
}).collect()
}
fn sequential_ftables(&self) -> CliResult<(Headers, FTables)> {
let mut rdr = self.rconfig().reader()?;
let (headers, sel) = self.sel_headers(&mut rdr)?;
Ok((headers, self.ftables(&sel, rdr.byte_re... | Rust | 0 |
import logging
import traceback
import os
import asyncio
class PluginManager:
def __init__(self, loop=None):
self.plugins = []
self.loop = loop or asyncio.get_event_loop()
def register_plugin(self, plugin_class, **kwargs):
"""Register a plugin"""
if plugin_class.__name__ in os.... | Python | 1 |
nitial conditions based on high-degree nodes
print("\nStep 9: Applying advanced initial conditions...")
high_degree_nodes = sorted(G_combined.degree, key=lambda x: x[1], reverse=True)[:10]
initial_conditions = np.zeros(2 * num_eigenvalues_to_compute)
for node in high_degree_nodes:
if node[0] in G_combined:
... | Python | 1 |
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
ans = []
carry = 0
i = len(num1) - 1
j = len(num2) - 1
while i >= 0 or j >= 0 or carry:
if i >= 0:
carry += int(num1[i])
if j >= 0:
carry += int(num2[j])
ans.append(str(carry % 10))
carry //... | Python | 1 |
from shelter.models import HeatShelter
from Weather.models import WeatherFutureInfo, UserDeviceToken, AlertLog
from .fcm_helper import send_push_notification
import logging
from datetime import datetime
logger = logging.getLogger(__name__)
# 🔹 혼잡도 분류 함수
def classify_congestion(current_count, capacity):
ratio = c... | Python | 1 |
continue;
}
}
}
return Some(current_slot);
}
}
epoch += 1;
start_index = 0;
}
None
}
fn slot_leader_at_no_compute(&self, slot: u64) ->... | Rust | 0 |
: Sized + PartialEq + Copy + Clone {
fn to_little_endian(self) -> Self;
fn from_little_endian(self) -> Self;
}
/// Macro for implementing an endian conversion using the stdlib `to_le` and
/// `from_le` functions. This is used for integer types. It is not used for
/// floats, because the `to_le` and `from_le` ... | Rust | 0 |
)V\0");
__jni_env.call_void_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// [onAttachFailed](https://developer.android.com/reference/android/net/wifi/aware/AttachCallback.html#onAttachFailed())
pub fn onAttachFailed<'env>(&'env self) -> __jni_bindg... | Rust | 0 |
u{7c9}',
Script::Nko), ('\u{7ca}', '\u{7ea}', Script::Nko), ('\u{7eb}', '\u{7f3}', Script::Nko),
('\u{7f4}', '\u{7f5}', Script::Nko), ('\u{7f6}', '\u{7f6}', Script::Nko), ('\u{7f7}',
'\u{7f9}', Script::Nko), ('\u{7fa}', '\u{7fa}', Script::Nko), ('\u{7fd}', '\u{7fd}',
Script::Nko)... | Rust | 0 |
# Copyright (c) QIU Tian. All rights reserved.
import itertools
import warnings
from sklearn import metrics as sklearn_metrics
from ..utils.misc import all_gather
warnings.filterwarnings('ignore')
class DefaultEvaluator:
def __init__(self, metrics: list):
self.metrics = metrics
self.outputs = ... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/file_options_test.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message a... | Python | 1 |
import unittest
import mock
import blinker
from alkali import signals
from . import MyModel
class TestSignals( unittest.TestCase ):
def setUp(self):
pass
def tearDown(self):
MyModel.objects.clear()
def test_blinker(self):
# a few tests so we know how blinker works
self.a... | Python | 1 |
arange(1), np.arange(4)], dtype=object)
for _ in range(1000):
mt19937.shuffle(a)
# Force Garbage Collection - should not segfault.
import gc
gc.collect()
def test_permutation_subclass(self):
class N(np.ndarray):
pass
mt19937 = Generator(MT1... | Python | 1 |
) -> Vec<usize> {
register[c] = register[a] * register[b];
register
}
fn muli(mut register: Vec<usize>, a: usize, b: usize, c: usize) -> Vec<usize> {
register[c] = register[a] * b;
register
}
fn banr(mut register: Vec<usize>, a: usize, b: usize, c: usize) -> Vec<usize> {
register[c] = register[a] ... | Rust | 0 |
}
}
#[inline]
pub fn set_ltk_len(&mut self, val: u8) {
unsafe {
let val: u8 = ::core::mem::transmute(val);
self._bitfield_1.set(2usize, 6u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
lesc: u8,
auth: u8,
ltk_len: u8,
) ->... | Rust | 0 |
ype=str, default = None)
parser.add_argument("--api_key", type=str, default=None)
parser.add_argument("--self_refinement", action='store_true', default=False)
parser.add_argument("--num_prompt", type=int, default = 3)
parser.add_argument("--max_rounds", type=int, default = 3)
args = parser.parse_arg... | Python | 1 |
clone();
tokio::spawn(async move {
ws.stream_at(path, sub, Duration::from_secs(300)).await;
});
Ok(resp)
}
extern crate oxygengine_core as core;
pub mod component;
pub mod resource;
pub mod system;
pub use ncollide2d as collide;
pub use nphysics2d as physics;
pub mod prelude {
pub use crate:... | Rust | 0 |
#!/usr/bin/env python3 -u
import os
import sys
import serial # pyserial
def make_serial():
from serial.tools.list_ports import comports
names = [ x.device for x in comports() if 'Bluetooth' not in x.device ]
print(names)
if not names:
raise Exception("No serial port found")
return serial.Se... | Python | 1 |
client0 = client.clone();
tokio::spawn(async move {
timer_process(client0, tx2).await;
});
}
HttpServer::new(move || {
App::new()
.app_data(Data::new(AppState::from(
&args,
client.clone(),
tx.clone(),
)))
// index
.service(get_index_handler)
... | Rust | 0 |
OraText,
flag: ub4,
) -> usize;
}
extern "C" {
pub fn OCICharSetToUnicode(
envhp: *mut ::std::os::raw::c_void,
dst: *mut ub2,
dstlen: usize,
src: *const OraText,
srclen: usize,
rsize: *mut usize,
) -> sword;
}
extern "C" {
pub fn OCIUnicodeToCharS... | Rust | 0 |
address, &farm),
}
}
fn create_raydium_stake_account(
&self,
wallet_address: &Pubkey,
farm: &Farm,
instruction_vec: &mut Vec<Instruction>,
signers: &mut Vec<Box<dyn Signer>>,
) -> Result<(), FarmClientError> {
let farm_id = match farm.route {
... | Rust | 0 |
textwrap::Options::with_termwidth(),
)
};
($item:expr) => {
textwrap::fill(
&format!("{}", $item),
textwrap::Options::with_termwidth(),
)
};
}
let location_str =
format!("-> src/Foo.he:{}:{}", line_number, co... | Rust | 0 |
ror("Local dataset ({local_head}) and remote ({remote_head}) have diverged (remote is ahead by {uncommon_blocks_in_remote} blocks, local is ahead by {uncommon_blocks_in_local})")]
#[error("Local and remote datasets have diverged. Local head: {local_head}, remote head {remote_head}")]
DatasetsDiverged {
... | Rust | 0 |
# coding: utf-8
"""
Qualtrics Survey API
The Qualtrics Survey endpoints give you access to the structure of the surveys you create. Surveys have a complex structure, and you are encouraged to become familiar with the structure using your brand's Qualtrics page to build surveys at first. Then you can query t... | Python | 1 |
# appointments/urls.py
from django.urls import path
from .views import AppointmentCreateView, AppointmentListView, AppointmentUpdateView
urlpatterns = [
path('appointments/', AppointmentCreateView.as_view(), name='appointment-create'),
path('appointments/list/', AppointmentListView.as_view(), name='appointment... | Python | 1 |
a AstNode<'a>) -> Option<String> {
if is_header_at_level(node, 3) {
let mut text = Vec::new();
collect_text(node, &mut text);
if let Ok(text) = std::str::from_utf8(&text) {
text.find(LITERATE_CONFIGURATION_TAG_PREFIX)
.map(|start| text[star... | Rust | 0 |
def power(base,expo):
if expo==0:
return 1
return base*power(base,expo-1)
print(power(4,4)) | Python | 1 |
"""Event tracker backend that emits events to the event-bus."""
import json
import logging
from datetime import datetime
from django.conf import settings
from openedx_events.analytics.data import TrackingLogData
from openedx_events.analytics.signals import TRACKING_EVENT_EMITTED
from eventtracking.backends.logger im... | Python | 1 |
el_inputs):
model_outputs = self.model(**model_inputs)
return model_outputs
def postprocess(self, model_outputs, top_k=5):
if top_k > self.model.config.num_labels:
top_k = self.model.config.num_labels
if self.framework == "pt":
probs = model_outputs.logits.s... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.