text string | label_name string | labels int64 |
|---|---|---|
from django.db.models import Prefetch
from django.db.models.query import ModelIterable, RawQuerySet
class GenericPrefetch(Prefetch):
def __init__(self, lookup, querysets, to_attr=None):
for queryset in querysets:
if queryset is not None and (
isinstance(queryset, RawQuerySet)
... | Python | 1 |
sselap],
'cheby1': [cheb1ap, cheb1ord],
'chebyshev1': [cheb1ap, cheb1ord],
'chebyshevi': [cheb1ap, cheb1ord],
'cheby2': [cheb2ap, cheb2ord],
'chebyshev2': [cheb2ap, cheb2ord],
'chebyshevii': [cheb2ap, cheb2ord],
}... | Python | 1 |
or
"""
SolverFunction = Callable[['InternalVars', np.ndarray], np.ndarray]
"""Differentiable solver function.
Signature: (internal_vars, initial_guess) -> solution
"""
# Boundary condition types
LocationFunction = Callable[[CoordinateArray], Union[bool, np.ndarray]]
"""Function that identifies boundary locations.
Sig... | Python | 1 |
#!/usr/bin/env python
from sys import argv
if len(argv) != 2:
print('usage: %s filename.kv' % argv[0])
exit(1)
from kivy.lang import Builder
from kivy.app import App
from kivy.core.window import Window
from kivy.clock import Clock, mainthread
from kivy.uix.label import Label
from watchdog.observers import O... | Python | 1 |
"path_rewrite", False)
data["rewrites"] = eval(service_domain.rewrites) if service_domain.rewrites else []
try:
# 给数据中心传送数据更新域名
region_api.update_http_domain(service.service_region, tenant.tenant_name, data)
except region_api.CallApiError as e:
if e.status != ... | Python | 1 |
import unittest
from torch.utils.data.sampler import SequentialSampler
from nuplan.planning.training.data_loader.distributed_sampler_wrapper import DistributedSamplerWrapper
class TestDistributedSamplerWrapper(unittest.TestCase):
"""
Skeleton with initialized dataloader used in testing.
"""
def set... | Python | 1 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: autokitteh/runtimes/v1/runtime.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol... | Python | 1 |
entrada=time(9, 7, 13),
saida=time(15, 0, 53),
)
fun = Funcionario.objects.get(email="antonio.soares@emp1.com")
Ponto.objects.create(
funcionario=fun,
data=date(2025, 1, 2),
entrada=time(9, 3, 15),
saida=time(15, 3, 42),
)
... | Python | 1 |
# ---------------------------------------------------------------------------
# src/vol_modelling/parameters.py
# ---------------------------------------------------------------------------
"""Centralized parameters configuration for the Heston model and tasks."""
from vol_modelling.common import HestonParams
# Def... | Python | 1 |
" => FieldKind::Int,
"number" => FieldKind::Float,
"boolean" => FieldKind::Bool,
"object" => FieldKind::Object,
"null" => FieldKind::Null,
_ => panic!(format!("unknown type {}", s))
}
}
fn parse_array_definition(node: &Map<String, Value>) -> F... | Rust | 0 |
import gc
import time
import math
from servo import ServoCluster, servo2040
"""
Demonstrates how to create a ServoCluster object to control multiple servos at once.
NOTE: ServoCluster uses the RP2040's PIO system, and as
such may have problems when running code multiple times.
If you encounter issues, try resetting y... | Python | 1 |
_pressed = false;
use sdl2::mouse::MouseButton;
match mouse_btn {
MouseButton::Left => input.mouse_button_left.set_state(is_pressed),
MouseButton::Middle => input.mouse_button_middle.set_state(is_pressed),
Mo... | Rust | 0 |
google_api_key = "" # add config key
weather_api_key = "" # add config key
# adding domains for intent classification
domains = ['music', 'restaurant', 'weather']
geolocation_api = "https://geolocation-db.com/json"
weather_temperature_format = "metric" # It gives temperature in celsius
| Python | 1 |
cessary to trigger a wake-up interrupt.
///
/// Each count accounts for a delay of `1/data_rate`.
/// The minimum value is 1. Configuring with `fault_count = 0`
/// will return an `Error::InvalidSetting`.
pub fault_count: u8,
/// Wake-up acceleration change threshold in G.
///
/// This w... | Rust | 0 |
.refresh.as_ref());
assert_eq!(from_token.client_id, "Client");
assert_eq!(from_token.owner_id, "Owner");
assert!(Utc::now() < from_token.until);
let issued_2 = issuer.issue(request).expect("Issuing failed");
assert_ne!(issued.token, issued_2.token);
assert_ne!(Some(&iss... | Rust | 0 |
TTRIBUTE_NORMAL, color.clone()); // HACK
// mesh.set_attribute(bevy::render::mesh::Mesh::ATTRIBUTE_UV_0, color.clone()); // HACK
mesh.set_attribute(ATTRIBUTE_COLOR, color);
mesh.set_indices(Some(index));
let mesh_handle = meshes.add(mesh);
commands
... | Rust | 0 |
import httpx
import json
from tenacity import retry, stop_after_attempt, wait_fixed
import utils
from settings import settings
class SearchWeb():
"""
Web search with a query with session support:
- get more links following the previous searches
- get all links of this session
"""
def __ini... | Python | 1 |
import numpy as np
import scipy.interpolate as interp
import visu_ramses
def check_solution():
# Load RAMSES output
data = visu_ramses.load_snapshot(2)
order = data["data"]["x"].argsort()
x_sim = data["data"]["x"][order]
amrlev = data["data"]["level"][order]
rho_sim = data["data"]["density"][o... | Python | 1 |
er.scope(|scope| {
/// // within this scope, we can spawn jobs that access data outside of it.
/// for i in &mut v {
/// scope.submit(move || *i *= 2);
/// }
/// });
/// // all jobs submitted in the scope are completed before execution resumes here.
/// ```
pub fn sco... | Rust | 0 |
.add_closure_params(closure, closure_type);
for param in &mut closure.params {
let param_value = ValueKind::FunctionParam(param.name.clone()).anon(param.typ.clone());
closure_scope.add_symbol(param.name.clone(),
Visibility::Local,
... | Rust | 0 |
"""
String utilities for common string operations.
"""
import re
import unicodedata
def title_case_with_exceptions(text, exceptions=None):
"""
Convert text to title case with exceptions for specific words.
Args:
text (str): The text to convert to title case.
exceptions (list): List of... | Python | 1 |
l.device)
score = model.compute_itm(
image_inputs=image_inputs,
text_ids=text_ids[topk_idx],
text_atts=text_atts[topk_idx],
).float()
score_matrix_i2t[start + i, topk_idx] = score + topk_sim
sims_matrix = sims_matrix.t()
score_matrix_t2i = torch.full(... | Python | 1 |
larities(word)
def marithime_semantic_similarities_add(word: str, replaced_word: str):
"""Update the semantics file with a new addition"""
global phonetic_search
phonetic_search.add_semantic_similarity(word, replaced_word)
def marithime_semantic_similarities_get(word: str) -> [str] or ... | Python | 1 |
roperty
#[dbus_proxy(property)]
fn discoverable_timeout(&self) -> zbus::fdo::Result<u32>;
#[DBusProxy(property)]
fn set_discoverable_timeout(&self, value: u32) -> zbus::fdo::Result<()>;
/// Discovering property
#[dbus_proxy(property)]
fn discovering(&self) -> zbus::fdo::Result<bool>;
/... | Rust | 0 |
len(peak_indices) > 0 and len(trough_indices) > 0:
axs[i + 1].scatter(peak_indices, [profiles['center'][index] for index in peak_indices], color='red', label=f'Element {element_number} Peaks', marker='x')
axs[i + 1].scatter(trough_indices, [profiles['center'][index] for index in ... | Python | 1 |
self.offset = Conv2d(
in_channels,
deformable_groups * offset_channels,
kernel_size=kernel_size,
stride=stride,
padding=padding,
groups=1,
dilation=dilation
)
for l in [self.offset, ]:
torch.nn.init.kaiming_... | Python | 1 |
import os
import sys
import time
os.system('cls||clear')
Diametro = 0.0
Perimetro = 0.0
Raio = 0.0
Area = 0.0
Const_PI = 3.14
Perimetro = int(input('Entre com o valor do Perimetro: '))
Diametro = Perimetro / Const_PI
print(f'O valor do Diametro é: {Diametro:.3f}')
Raio = Diametro/2
print(f'O valor do raio é: {Raio:.... | Python | 1 |
import os
import openpyxl
from openpyxl import Workbook
from openpyxl.worksheet.worksheet import Worksheet
# 工作区确定
os.chdir(path="./resources/exer_1")
# 作者投稿登记表文件夹所在路径
registerPath = "sub"
# 读取["18年", "19年", "20年"]的数据,(可指定查找年份)
years = ["18年", "19年", "20年"]
for year in years:
# 组装相应年表格文件的路径
registerFileNam... | Python | 1 |
}
/// Decodes the given whitespace string back into binary.
///
/// - \u{0020} (whitespace) represents a high bit
/// - \u{200b} (zero width whitespace) represents a low bit
///
/// ## Errors
///
/// The function returns a `DecodeError` under the following circumstances:
///
/// - `DecodeError::InvalidLength` if the ... | Rust | 0 |
state.expected_emits.iter_mut().find(|expect| expect.log.is_none())
{
// We have unfilled expects, so we fill the first one
next_expect_to_fill.log = Some(log);
} else if let Some(next_expect) = state.expected_emits.iter_mut().find(|expect| !expect.found) {
// We do not have unfilled exp... | Rust | 0 |
from unittest import mock
from django.test import RequestFactory, SimpleTestCase
from corehq.apps.sso.utils.url_helpers import add_username_hint_to_login_url
class FakeIdp:
def __init__(self, slug):
self.slug = slug
@classmethod
def get_active_idp_by_username(cls, username):
if usernam... | Python | 1 |
unused_features,
unused_variables,
unused_imports
)]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate hyper;
extern crate mime;
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate yup_oauth2 as oauth2;
#[macro_use]
extern crate serde_derive;
extern crate strsim... | Rust | 0 |
pan class="sidebar-text">知识库</span>
</a>
<a class="flex items-center px-4 py-2.5 text-text-gray hover:bg-bg-light-gray rounded-lg nav-link" href="#">
<span class="material-icons-outlined mr-3 nav-item-icon">bar_chart</span>
<span class="sidebar-tex... | Python | 1 |
)
jwt = response_json['jwt']
if jwt:
logger.success(f'[{self.wallet_address}] | Successfully grabbed auth token')
self.headers.update({'sf-jwt': jwt})
return True
return False
@retry(retries=3, delay=30, backoff=1.5)
async def register_referr... | Python | 1 |
{
TextBoxXY { x: $x.into(), y: $y.into() }
};
() => {
TextBoxXY::default()
};
//
// Pattern matching
//
($x: ident $(,)? $y: ident $(,)?) => {
TextBoxXY { x: $x, y: $y }
};
}
impl From<TextBoxXY> for (f32, f32) {
fn from(TextBoxXY { x, y }: TextBoxXY) -> Sel... | Rust | 0 |
an empty `Response`.
pub fn new() -> Self {
Self {}
}
}
<reponame>theawless/isahc
//! Helpers for working with tasks and futures.
use std::{
io,
net::{SocketAddr, UdpSocket},
task::Waker,
};
/// Helper methods for working with wakers.
pub(crate) trait WakerExt {
/// Create a new waker... | Rust | 0 |
# Copyright (c) 2025, NVIDIA CORPORATION. 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 appli... | Python | 1 |
():
try:
if handler(event):
return True
except Exception:
LOG_CURRENT_EXCEPTION()
return False
def handleMouseEvent(event):
if GUI.handleMouseEvent(event):
return True
elif OfflineMode.handleMouseEvent(event):
... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains tests for the voice estimation methods.
"""
import numpy as np
import unittest
from tempfile import TemporaryFile
from tests import VOSA_TESTFILES
from partitura import load_musicxml
from partitura.musicanalysis import estimate_voices
import part... | Python | 1 |
tant(0x803381C0); // ERROR_WSMAN_ENUMERATE_SHELLCOMAMNDS_FILTER_EXPECTED
#[doc(hidden)] pub const WSMAN_ENUMERATE_SHELLCOMMANDS_EPRS_NOTSUPPORTED : HResultError = HResultError::from_constant(0x803381C1); // ERROR_WSMAN_ENUMERATE_SHELLCOMMANDS_EPRS_NOTSUPPORTED
#[doc(hidden)] pub const WSMAN_CLIENT_CREATESHELL_NAME_INVA... | Rust | 0 |
Deserialize_repr;
#[derive(Debug, Deserialize_repr)]
#[repr(u8)]
enum MaybeAnimatedTag {
Fixed = 0,
Animated = 1,
}
let tagged =
deserializer.deserialize_any(TaggedContentVisitor::<MaybeAnimatedTag>::new(
"a",
... | Rust | 0 |
};
Self::from_intermediate(s)
}
fn duplicate(&mut self) -> Result<Self> {
puffin::profile_function!();
Self::from_intermediate(self.make_intermediate()?)
}
}
fn vg_call(mut caller: Caller<Context>, ptr: u64, len: u64) {
puffin::profile_function!();
// let mem = caller.get_... | Rust | 0 |
for input in &[7, 8, 9] {
let result = Interpreter::new(tape.to_vec())
.with_input(&[*input])
.run()
.map_err(|(err, _)| err)?;
assert_eq!(result.output()[0], (*input == 8) as isize);
}
}
... | Rust | 0 |
t tasks
percentage_create_pdfs = create_pdfs_time / total_time
percentage_multi = time_multi_main / total_time
percentage_planning = percentage_multi * (planning_time / multi_time)
percentage_plotting = percentage_multi * (plotting_time / multi_time)
percentage_load_scenarios = percentage_multi * (l... | Python | 1 |
let config_default_path = dir.path().join("configurations").join("config_default");
let mut config_default_file = File::create(&config_default_path)?;
config_default_file.write_all(
b"\
[core]
project = default
",
)?;
let config_overridden_path = dir.path().join("configurati... | Rust | 0 |
UCT_BUNDLE_V1,
]
}
}
/// Description of a FMS container file that collects many instances of FMS
/// metadata.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProductBundleContainerV2 {
/// A unique name identifying the instance.
pub name: String,... | Rust | 0 |
docker_image=docker_image,
use_gpu_image=run_mode.use_gpu,
mounts=mounts)
result = run_mode.run_script(archive, return_output=return_output, verbose=False)
if return_output:
... | Python | 1 |
elf.key, &self.val)
}
/// # Safety
///
/// The unsafety of this function reflects [`crate::types::ExtensionRef::into_owned`].
///
/// If its safety criteria is met, then this function is safe.
pub unsafe fn into_owned(self) -> MapEntry {
MapEntry::new(self.key.into_owned(), self.val... | Rust | 0 |
import multiprocessing
import time
from arguments import PretokenizationArguments
from datasets import load_dataset
from transformers import AutoTokenizer, HfArgumentParser
def tokenize(example):
output = {}
output["input_ids"] = tokenizer(example["content"], truncation=False)["input_ids"]
output["ratio... | Python | 1 |
, ld(2021, 8, 29))]
#[case::start_of_work_week(ld(2021, 8, 25), "soww", ld(2021, 8, 30))]
#[case::end_of_today(ld(2021, 8, 25), "eod", ld(2021, 8, 26))]
#[case::start_of_today(ld(2021, 8, 25), "sod", ld(2021, 8, 25))]
fn test_local_timestamp(
#[case] now: Box<dyn Fn(FixedOffset) -> DateTime<Utc>... | Rust | 0 |
"""webOS Smart TV device turn on trigger."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_PLATFORM,
CONF_TYPE,
)
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callb... | Python | 1 |
from flask import Flask, render_template_string
app = Flask(__name__)
home_page = '''
<!DOCTYPE html>
<html>
<head>
<title>Acme Software Solutions</title>
<style>
body {font-family: Arial, sans-serif; background-color: #f0f2f5; margin: 0; padding: 0;}
.header {background-color: #283e4a; color:... | Python | 1 |
::arm::stm::Stm, architecture::arm::stm::f7x3::F7x3, architecture::arm::stm::f7x3::f753::F753>();
assert!(bad_generic_sequence.is_none());
// Normally we don't know what the type parameters are because of the dynamic nature.
// We're protected against using the wrong types, but that doesn't mak... | Rust | 0 |
.
:param workspace: Workspace name. This value is required for Perforce.
:param host: Host name. This value is required for Perforce.
:return: A tuple containing log items generating during the request.
"""
args = {"provider": provider, "server": server, "port": port, "username":... | Python | 1 |
import heapq
def initialize():
# Define the initial state of the tubes, represented as a list of lists
initial_state = [['Green', 'Blue', 'Green', 'Red'], ['Red', 'Green', 'Blue', 'Red'], ['Blue', 'Red', 'Green', 'Blue']]
num_tubes = 3
tube_capacity = 6
visited_costs = {}
visited_costs[str(initial_... | Python | 1 |
ew();
obj.body
.unwrap()
.into_blocking_read()
.read_to_end(&mut manifest)
.unwrap();
let manifest: Manifest = serde_json::from_slice(&manifest).unwrap();
let mut manifests = Vec::new();
for ManifestFile { key } in manifest.files {
let obj = s3
.get_ob... | Rust | 0 |
, BlockNumber(1), 0);
let empty_account_id = AccountId(1);
let empty_account_address = [7u8; 20].into();
let deposit_op = DepositOp {
priority_op: Deposit {
from: empty_account_address,
token: TokenId(0),
amount: BigUint::from(1u32),
to: empty_account... | Rust | 0 |
import logging
import sys
import typing
from easy_tpp.utils.const import LogConst
# -------- log setting ---------
DEFAULT_LOGGER = "easytpp.logger"
class CustomFormatter(logging.Formatter):
grey = "\x1b[38;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"... | Python | 1 |
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import asyncio
from discord import app_commands
import sys # Import sys
import os # Import os if not already imported
load_dotenv("ai.env")
discord_token = os.getenv("DISCORD_TOKEN")
# Add the current working directory to sys.pat... | Python | 1 |
import warnings
import jax.lax as lax
import jax.numpy as jnp
import jax.random as jrandom
from jaxtyping import Array, PRNGKeyArray
from .._module import Module
from ._misc import named_scope
class Dropout(Module):
"""Applies dropout.
Note that this layer behaves differently during training and inference.... | Python | 1 |
ence-update
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct PresenceUpdate(pub Presence);
impl Deref for PresenceUpdate {
type Target = Presence;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for PresenceUpdate {
fn deref_mut(&mut self) -> &mut S... | Rust | 0 |
mod job_spec;
pub use self::job_spec::*;
mod job_status;
pub use self::job_status::*;
use crate::{IndividTrip, PersonID, PersonSpec, SpawnTrip, TripEndpoint, TripMode};
use geom::{Distance, FindClosest, LonLat, Pt2D, Time};
use map_model::Map;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct ExternalPerson ... | Rust | 0 |
| // mapping is private to other threads / processes
linux_sys::MAP_GROWSDOWN | // mapping suitable for stacks
linux_sys::MAP_UNINITIALIZED, // leave memory uninitialized
!0, // file descriptor; needs to be `-1` because of MAP_ANONYMOUS
0, // offset; ignored because of ... | Rust | 0 |
from fontTools.varLib.instancer import *
from fontTools.ttLib import newTable
import sys
def run(infile, outfile, wt):
ttft=TTFont(infile)
insname=dict()
for ins in ttft['fvar'].instances:
name=ttft['name'].getDebugName(ins.subfamilyNameID)
if 'wght' not in ins.coordinates: continue
... | Python | 1 |
# Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
import attr
import typing
import io
@attr.s
class UploadApprovalFileReqContent(object):
pass
@attr.s
class UploadApprovalFileReq(object):
name: str = attr.ib(
default="", metadata={"req_... | Python | 1 |
pe_names);
Ok(Json(response))
}
#[openapi]
#[get("/types/names/<type_id>")]
pub fn get_type_name(
sql: State<PkmnapiSQL>,
_rate_limit: RateLimit,
access_token: Result<AccessToken, AccessTokenError>,
type_id: u8,
) -> Result<Json<TypeNameResponse>, ResponseError> {
let access_token = utils::get... | Rust | 0 |
e : filter type (e.g. LIQUID_FIRFILT_RRRC)
/// k : samples/symbol
/// m : symbol delay
/// beta : excess bandwidth factor, _beta in [0,1]
/// dt : fractional sample delay
pub fn prototype(type_: FirdesFilterType, k: usize, m: usize, beta: f32, dt: f32) -> Fir {
let mut ... | Rust | 0 |
// Case 1: 2 blocks in L1, reorg on block #1
(
vec![STATE_UPDATE_LOG0.clone(), STATE_UPDATE_LOG1.clone()],
1,
),
]
.into_iter()
.map(|(updates, reorg_on_block)| async move {
let storage = Storage::in_memory().unwrap();
... | Rust | 0 |
me);
buffer.push_str("e_identifier(name));
if let Some(ref arg) = item.arg {
buffer.push_str(" = ");
DefArg(&**arg, false).build(buffer)?;
}
}
buffer.push(')');
Ok(())
}
}
pub(in crate::str) struct CreatedbOptList<'a>(p... | Rust | 0 |
= true;
}
}
}
gst::PadProbeReturn::Ok
});
StreamProducer {
appsink: appsink.clone(),
consumers,
}
}
}
/// Wrapper around a HashMap of consumers, exists for thread safety
/// and also protects some of the p... | Rust | 0 |
import os
from django.apps import AppConfig
from src.config.settings.static import PACKAGES_PATH, TRAINED_MODELS_PATH, MEDIA_ROOT
class VideoAnalysisConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'src.modules.video_analysis'
label = 'video_analysis'
verbose_name = 'Вид... | Python | 1 |
self.ruleset_table_model.ruleset.remove(self.message_type.ruleset[-1])
self.ruleset_table_model.update()
self.ui.btnRemoveRule.setEnabled(len(self.message_type.ruleset) > 0)
@pyqtSlot()
def on_rb_assign_automatically_clicked(self):
self.message_type.assigned_by_ruleset = True
... | Python | 1 |
de/#text=512_maskz_fnmadd_pd&expand=2714)
#[inline]
#[target_feature(enable = "avx512f")]
#[cfg_attr(test, assert_instr(vfmadd))] //vfnmadd132pd or vfnmadd213pd or vfnmadd231pd
pub unsafe fn _mm512_maskz_fnmadd_pd(k: __mmask8, a: __m512d, b: __m512d, c: __m512d) -> __m512d {
let fnmadd = _mm512_fnmadd_pd(a, b, c).a... | Rust | 0 |
in successes {
t.pass(&format!("{}/{}", TEST_DIR, passing_test));
}
for &failing_test in failures {
t.compile_fail(&format!("{}/{}", TEST_DIR, failing_test));
}
}
<filename>rustfst/src/algorithms/isomorphic.rs<gh_stars>0
use std::cmp::Ordering;
use std::collections::VecDeque;
use failure::... | Rust | 0 |
c>> {
None
}
}
impl DataDictionary for Box<StubDataDictionary> {
type Entry = DictionaryEntryRef<'static>;
fn by_name(&self, _: &str) -> Option<&DictionaryEntryRef<'static>> {
None
}
fn by_tag(&self, _: Tag) -> Option<&DictionaryEntryRef<'static>> {
None
}
}
// Copyrigh... | Rust | 0 |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... | Python | 1 |
file.read(self.path_perf)
return data, fs
def load_song(config: dict, cur_path_score, cur_path_perf, real_perf=False) -> SongBase:
cur_song_name = os.path.splitext(os.path.basename(os.path.normpath(cur_path_score)))[0]
npzfile = np.load(cur_path_score, allow_pickle=True)
score = (npzfile['sheet'... | Python | 1 |
stream.write(b"+").unwrap();
}
// fake that server decided to go away
if value == QUIT_SERVER {
thread::sleep(Duration::from_millis(5));
return;
}
match data.as_ref() {
"QStartNoAckMode" => {
... | Rust | 0 |
n filter tracking cookies flag (boolean)
"""
return self.__filterTrackingCookies
def setFilterTrackingCookies(self, filterTrackingCookies):
"""
Public method to set the filter tracking cookies flag.
@param filterTrackingCookies filter tracking cookies flag (bool... | Python | 1 |
# Try safetensors directly
safetensors_files = list(model_path.glob("*.safetensors"))
if not safetensors_files:
raise Exception("No safetensors files found")
# Load the first safetensors file as example
tensors = {}
for sf_file in safetensors... | Python | 1 |
import os
import wave
from threading import Lock, Thread
from pyaudio import PyAudio, Stream, paInt16
from rich.console import Console
from rich.control import Control
from rich.segment import ControlType
from rich.status import Status
from ..types import Codes
codes: Codes = {
"CARRIAGE_RETURN": Control(Control... | Python | 1 |
rivers must take care of keeping a copy of the respective `*mut T` and `*mut K` for themselves
///
/// **Parameters**
/// * send: `Option<(*mut T, BuffSpec)>`
/// * None: No send buffers are provided to the device
/// * Some:
/// * `T` defines the structure which will be provided to the device
//... | Rust | 0 |
(!uppercase_a.is_ascii_control());
/// assert!(!uppercase_g.is_ascii_control());
/// assert!(!a.is_ascii_control());
/// assert!(!g.is_ascii_control());
/// assert!(!zero.is_ascii_control());
/// assert!(!percent.is_ascii_control());
/// assert!(!space.is_ascii_control());
/// assert!(lf.is_... | Rust | 0 |
from repositories.base import IWordRepository, IURLRepository
class FileWordRepository(IWordRepository):
"""Repository lấy từ nhạy cảm từ file"""
def __init__(self, word_file: str = "./assets/sensitive_words.txt"):
self.word_file = word_file
def get_sensitive_words(self):
"""Đọc danh sác... | Python | 1 |
from typing import List
from datapilot.core.insights.utils import get_severity
from datapilot.core.platforms.dbt.insights.checks.base import ChecksInsight
from datapilot.core.platforms.dbt.insights.schema import DBTInsightResult
from datapilot.core.platforms.dbt.insights.schema import DBTModelInsightResponse
from data... | Python | 1 |
etField, BaseField>,
TargetField,
Sub,
sub,
SubAssign,
sub_assign,
|this: &'a NonNativeFieldVar<TargetField, BaseField>, other: &'a NonNativeFieldVar<TargetField, BaseField>| {
use NonNativeFieldVar::*;
match (this, other) {
(Constant(c1), Constant(c2)) => Constant(*c... | Rust | 0 |
initialize(&program_id, &moebius_account_id, &authority).unwrap(),
vec![&mut moebius_account, &mut rent_sysvar]
)
);
moebius_account.lamports = mint_minimum_balance();
// create new moebius account.
do_process_instruction(
initialize(&program_i... | Rust | 0 |
# coding:utf-8
import requests
from lib.core.common import url_handle,get_random_ua
from lib.core.poc import POCBase
# ...
import urllib3
urllib3.disable_warnings()
class POC(POCBase):
_info = {
"author" : "jijue", # POC作者
"version" : "1", # POC版本,默认是1
... | Python | 1 |
+ 1]; E + 1];
let uspan = self.u_knots.find_span(uv.x);
let Nu_deriv = self.u_knots.basis_funs_derivs_for_span(uspan, uv.x, du);
let vspan = self.v_knots.find_span(uv.y);
let Nv_deriv = self.v_knots.basis_funs_derivs_for_span(vspan, uv.y, dv);
let mut temp = vec![TVec::zeros()... | Rust | 0 |
::columns().join(", ")
}
fn col_count() -> usize {
A::columns().len()
}
}
impl<A, B> Column for (A, B)
where
A: Column,
B: Column,
{
fn cols(&self) -> String {
let ca = self.0.cols();
let cb = self.1.cols();
ca + ", " + &cb
}
fn col_count() -> usize {
... | Rust | 0 |
from setuptools import setup
import os
PKG_ROOT = os.path.abspath(os.path.dirname(__file__))
def load_requirements() -> list:
"""Load requirements from file, parse them as a Python list."""
with open(os.path.join(PKG_ROOT, "requirements.txt"), encoding="utf-8") as f:
all_reqs = f.read().split("\n")
... | Python | 1 |
imit(self.soft_limit(), self.hard_limit());
}
*/
fn compute_medium_limit(soft: u32, hard: u32) -> u32 {
soft + ((hard - soft) >> 1)
}
fn set_limits(
limits: &mut [u32; LIMIT_COUNT],
underload: u32,
soft: u32,
hard: u32
) -> Result<()> {
if underload ... | Rust | 0 |
}
}
//! Entity component system implementation
// Features
#![feature(unboxed_closures)]
#![feature(fn_traits )]
#![feature(external_doc )]
// Warnings
//--------------------------------------------------------------------------------------------------
// Use all warnings from clippy
#![warn(
clippy::all... | Rust | 0 |
xception as e:
print("ERROR: VLLM can't summarize the text")
print(e)
sys.exit(0)
all_summaries.append(response["text_output"][len(text_input) :].strip())
all_text_outputs = "\n\n".join(all_summaries)
with open("./temp... | Python | 1 |
3_lane_s64_(a: int64x1_t, b: int64x1_t, c: int64x1_t, n: i64, ptr: *const i8) -> int64x1x3_t;
}
vld3_lane_s64_(b.0, b.1, b.2, LANE as i64, a as _)
}
/// Load multiple 3-element structures to two registers
#[inline]
#[target_feature(enable = "neon")]
#[cfg_attr(test, assert_instr(ld3, LANE = 0))]
#[rustc_legacy... | Rust | 0 |
er_status: 0xaa,
config_generation: 0x55,
device_feature_select: 0x0,
driver_feature_select: 0x0,
queue_select: 0xff,
};
let dev = &mut DummyDevice(0) as &mut dyn VirtioDevice;
let mut queues = Vec::new();
// Can set all bits of driver_st... | Rust | 0 |
async def test_timings(one_conf, flow, scheduler, start, caplog):
"""Test that setting outputs does not change the task timings."""
wid = flow({
**one_conf,
'runtime': {
'one': {
'execution time limit': 'PT100S',
},
},
})
schd: Scheduler = ... | Python | 1 |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404
from django.views import View
from .forms import AlunoCreationForm
from django.contrib.auth import authenticate, logout
from django.... | Python | 1 |
x += self
.play_pause_button
.draw(canvas, data, controller, last_event)
.width
+ 10.0;
canvas.restore();
canvas.save();
canvas.translate((x, 0.0));
x += self
.stop_button
.draw(canvas, data, controller, last_even... | Rust | 0 |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
import plotly.colors as pcolors
pio.renderers.default = "browser"
# 1) Read the merged CSV
df = pd.read_csv("merged_nudat_data.csv")
# 2) Ensure 'a' exists
if "a" not in df.columns:
df["a"] = df["z"] + df["n"]
# 3) ... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.