text string | label_name string | labels int64 |
|---|---|---|
"""
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from ...biased_nfw_phase_space import BiasedNFWPhaseSpace
from ...nfw_phase_space import NFWPhaseSpace
__all__ = ('test_biased_unbiased_agreement1', )
conc_bins = np.linspace(2, 30, 10)
gal_bias_bins = np.... | Python | 1 |
.db.models.deletion.CASCADE,
to=swapper.get_model_name("openwisp_users", "Organization"),
verbose_name="organization",
),
),
],
options={
"abstract": False,
},
bases=(openw... | Python | 1 |
on: crate::Reg<u1otgcon::U1OTGCON_SPEC>,
#[doc = "0x34 - U1OTGCONCLR register"]
pub u1otgconclr: crate::Reg<u1otgconclr::U1OTGCONCLR_SPEC>,
#[doc = "0x38 - U1OTGCONSET register"]
pub u1otgconset: crate::Reg<u1otgconset::U1OTGCONSET_SPEC>,
#[doc = "0x3c - U1OTGCONINV register"]
pub u1otgconinv: c... | Rust | 0 |
warn!("{}", e),
Some(Ok(Err(e))) => warn!("{}", e),
Some(Ok(Ok(crawl_response))) => {
spiders_finished = false;
let SpiderResponse {
mut new_findings,
crawl_link,
... | Rust | 0 |
# $Id$
#
# Copyright (C) 2009-2012 Internet Systems Consortium ("ISC")
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... | Python | 1 |
d = 0xDD57
PTP_OPC_Owner = 0xDD5D
PTP_OPC_Editor = 0xDD5E
PTP_OPC_Webmaster = 0xDD5F
PTP_OPC_URLSource = 0xDD60
PTP_OPC_URLDestination = 0xDD61
PTP_OPC_TimeBookmark = 0xDD62
PTP_OPC_ObjectBookmark = 0xDD63
PTP_OPC_ByteBookmark = 0xDD64
PTP_OPC_LastBuildDate = 0xDD70
PTP_OPC_TimetoLive = 0xDD71
PTP_OPC_MediaGUID = 0xDD7... | Python | 1 |
}"#,
21,
);
}
#[test]
fn test_resolve_local_name_shadow() {
do_check_local_name(
r"
fn foo(x: String) {
let x : &str = &x;
x<|>
}",
46,
);
}
}
//! Tests auto-converted from "sass-spec/spec/libsass-clo... | Rust | 0 |
import argparse
import gaussian_diffusion_loss as gd
class Training_args(argparse.Namespace):
data_dir = ""
schedule_sampler = "batch"
lr = 1e-4
weight_decay = 0.0
lr_anneal_steps = 100000
microbatch = -1 # -1 disables microbatches
log_interval = 10
save_interval = 5e3
mmd_alpha =... | Python | 1 |
rn:aws:ecs:::cluster/default'
response = get_cluster_name_from_arn(arn)
self.assertEqual(name, response)
def test_get_deploy_group_name_long(self):
cluster = 'ClusterClusterClusterClusterClusterClusterClusterCluster'
service = 'ServiceServiceServiceServiceServiceServiceServiceServi... | Python | 1 |
_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bits 16:25 - The length of the data in buffer 1."]
#[inline(always)]
pub fn length_1(&self) -> LENGTH_1_R {
LENGTH_1_R::new(((self.bits >> 16) & 0x03ff) as u16)
}
#[doc = "Bit 15 - Buffer 0 is full. For an IN transfer (TX to the host) t... | Rust | 0 |
let mut source: Initiator<_> = Actor::new(cfd_loads.clone());
let mut sink = Terminator::<_>::new(logging.clone());
// FEM
let mut fem: Actor<_> = Actor::new(state_space.clone());
// MOUNT
let mut mount: Actor<_> = Actor::new(mnt_ctrl.clone());
type D = Vec<f64>;
... | Rust | 0 |
let t_b5_3 = vmulq_f32(self.twiddle4im, x3m8);
let t_b5_4 = vmulq_f32(self.twiddle2im, x4m7);
let t_b5_5 = vmulq_f32(self.twiddle3im, x5m6);
let x0 = values[0];
let t_a1 = calc_f32!(x0 + t_a1_1 + t_a1_2 + t_a1_3 + t_a1_4 + t_a1_5);
let t_a2 = calc_f32!(x0 + t_a2_1 + t_a2_2 + t_... | Rust | 0 |
identity)
/// - For each a in $`\mathbb{R}`$ there exists −a in $`\mathbb{R}`$ such that
/// $`a + (−a) = 0`$ (that is, −a is the additive inverse of a)
/// 2. $`\mathbb{R}`$ is a monoid under multiplication, meaning that:
/// - $`(a * b) * c = a * (b * c), \forall a, b, c \in \mathbb{R}`$ (that is, *
/// is ass... | Rust | 0 |
# This file was auto-generated by Fern from our API Definition.
from __future__ import annotations
import typing
import pydantic
from ..core.pydantic_utilities import IS_PYDANTIC_V2, update_forward_refs
from ..core.unchecked_base_model import UncheckedBaseModel
class AstNotEqualsOperatorNode(UncheckedBaseModel):
... | Python | 1 |
रिणाम', 'sw':'kuhusika', 'bn':'এনটেইলমেন্ট',
'it':'implicazione', 'no':'entailment', 'es':'vinculación',
'is':'afleiðing', 'bg':'следствие', 'sv':'medföring', 'sl':'vpletenost', 'ms':'entailment', 'th':'การมีส่วนร่วม',
'pl':'majorat', 'ru':'логическое следстви... | Python | 1 |
rmat of results is identical to qrels)
retriever = EvaluateRetrieval(faiss_search, score_function="dot") # or "cos_sim"
results = retriever.retrieve(corpus, queries)
### Save faiss index into file or disk ####
# Unfortunately faiss only supports integer doc-ids, We need save two files in output_dir.
# 1. output_dir/{p... | Python | 1 |
# Copyright 2025 Gaudiy Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
'alpha': alpha,
'truncated': truncated,
'occluded': occluded,
'location': location,
'rotation_y': rotation_y}
ret['annotations'].append(ann)
if DEBUG and tmp[0] != 'DontCare':
box_3d = compute_box_3d(dim, location, rotati... | Python | 1 |
# -*- coding: utf-8 -*-
#引入依赖包
import requests
import MySQLdb
import re
import math
from bs4 import BeautifulSoup, NavigableString
#zhon是用来处理中文标点符号的包
from zhon.hanzi import punctuation
from functools import partial
#设置utf-8编码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#连接数据库
db = MySQLdb.connect(host="... | Python | 1 |
# Sebastian Raschka 2014-2024
# mlxtend Machine Learning Library Extensions
#
# A function for removing chart junk from matplotlib plots
# Author: Sebastian Raschka <sebastianraschka.com>
#
# License: BSD 3 clause
def remove_borders(axes, left=False, bottom=False, right=True, top=True):
"""Remove chart junk from ... | Python | 1 |
, A, Q>,
) -> StdResult<ConfigResponse> {
let state = read_config(&deps.storage)?;
let resp = ConfigResponse {
owner: deps.api.human_address(&state.owner)?,
mirror_token: deps.api.human_address(&state.mirror_token)?,
mint_contract: deps.api.human_address(&state.mint_contract)?,
o... | Rust | 0 |
import numpy as np
import cv2
import matplotlib.pyplot as plt
def transform_to_px(g, density, scale, frame_rate):
scaled_g = g * scale / frame_rate ** 2
scaled_density = density / scale ** 3
return scaled_g, scaled_density
def calculate_mass(radius, density):
volume = (4 / 3) * np.pi * (radius *... | Python | 1 |
from heapq import heappop, heappush
expensive = 10**8
def make_graph(n, fares) :
global graph
graph = [[] for _ in range(n + 1)]
for i in range(len(fares)) :
graph[fares[i][0]].append([fares[i][1], fares[i][2]])
graph[fares[i][1]].append([fares[i][0], fares[i][2]])
return graph
def mi... | Python | 1 |
# 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 |
p>, i: usize) -> &'p [u8] {
let segment = &self.segments[i];
unsafe {
std::slice::from_raw_parts(
self.buffer.buf_ptr().add(segment.offset as usize) as *const _,
segment.length as usize,
)
}
}
}
#[pymethods]
impl ZstdBufferWithSegment... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tornado.testing import AsyncTestCase as TornadoAsyncTestCase
from tornado.testing import gen_test # NOQA
import motorengine.connection
from motorengine import connect
class AsyncTestCase(TornadoAsyncTestCase):
def setUp(self, auto_connect=True):
super(... | Python | 1 |
/// "/" => -9, // static path, no query
/// "/foo/bar" => -9, // static path, no query
///
/// "/a/<b>?foo" => -8, // partial path, static query
/// "/a/<b..>?foo" => -8, // partial path, static query
/// "/<a>/b?foo" => -8, // par... | Rust | 0 |
import plotly.express as px
from die import Die
# Create two D6 dice.
die_1 = Die()
die_2 = Die()
# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
result = die_1.roll() + die_2.roll()
results.append(result)
# Analyze the results.
frequencies = []
max_result = die_1.... | Python | 1 |
from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI
from core.config import settings
from api_v1 import router as router_v1
from items_views import router as items_router
from users.views import router as users_router
# Запустить создание новой БД, если ее нет
@asynccontextmanager
... | Python | 1 |
byte_limiter=byte_limiter,
strict=strict,
dll=dll,
memory_kind=sharding.memory_kind,
)
for idx, devices in local_indices_devices_map.items()
]
dbs = sum(await asyncio.gather(*read_array_coros), [])
return jax.make_array_from_single_device_arrays(global_shape, s... | Python | 1 |
00):
rotate_vector(q,v)
stop = time.time()
print((stop-start) * 1000)
start = time.time()
for i in range(100000):
rotate_vector_fast(q,v)
stop = time.time()
print((stop-start) * 1000)
print(rotate_vector_fast(q,v))
exit()
a = pyquaternion.Quaternion([1,0,0... | Python | 1 |
layer.h > enemy.y
and enemy.y + enemy.h > self.player.y
):
enemy.is_alive = False
blasts.append(
Blast(
self.player.x + PLAYER_WIDTH / 2,
self.player.y + PLAYER_HEIGHT / 2,
... | Python | 1 |
== total { 1.0 }
else {
f64::from(done) / f64::from(total)
}
}
#[inline]
/// # Is Ticking.
///
/// This is `true` so long as `done` does not equal `total`, and `total`
/// is greater than `0`. Otherwise it is `false`.
///
/// For the most part, this struct's setter methods only work while
/// progress... | Rust | 0 |
/// has a type of \[LocationType.LOCALITY][google.cloud.talent.v4beta1.Location.LocationType.LOCALITY\].
#[prost(enumeration = "location::LocationType", tag = "1")]
pub location_type: i32,
/// Postal address of the location that includes human readable information,
/// such as postal delivery and pa... | Rust | 0 |
}
pub fn unknown() -> Self {
Self::Exp(LogicTree::Unknown)
}
}
impl<'a, T> Default for LogicValue<'a, T> {
fn default() -> Self {
Self::unknown()
}
}
}
pub type LogicArena<'a, T> = &'a Arena<LogicTree<'a, T>>;
struct CellVec<T>(Cell<Vec<T>>... | Rust | 0 |
cess
to.
include_email (bool):
Include the service account email in the token. If set to
``true``, the token will contain ``email`` and
``email_verified`` claims.
"""
name: str = proto.Field(
proto.STRING,
number=1,
)
delegates: Mu... | Python | 1 |
'''Практически каждый человек знаком с финансовыми инвестициями, целью которых является преумножение имеющихся средств в течение некоторого времени. Наиболее простым примером является банковский вклад, который ежегодно увеличивается путем начисления на него определенного числа процентов. Составляющими такого банковског... | Python | 1 |
#ESCREVA UM PROGRAMA QUE LEIA A VELOCIDADE DE UM CARRO , SE FOR MAIOR QUE 80 VAI TER UMA MULTA POR CADA KM A RODADO
limite = 50
valor_multa_por_km = 7
for i in range(2):
velocidade = float(input(f"Digite a velocidade do veículo {i + 1}: "))
if velocidade > limite:
excesso = velocidade - limite
... | Python | 1 |
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Python | 1 |
import glob
import json
import re
from typing import Dict, List
import joblib
from tqdm import tqdm
FLOATS = r"\b\d+\.\d+\b"
N_DIGITS = 2
DATA_DIR = "/fsx/proj-chemnlp/data/OrbNet_Denali_Training_Data/xyz_files"
OUT_DIR = "/fsx/proj-chemnlp/data/cleaned_orbnet_xyz"
def round_to_n(match: str) -> str:
"""Rounds a... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2020 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 |
idx) == LUA_TNONE as i32) as i32
}
/// <https://www.lua.org/manual/5.1/manual.html#lua_isnoneornil>
#[inline]
pub unsafe fn lua_isnoneornil(L: *mut lua_State, idx: libc::c_int) -> libc::c_int {
(lua_type(L, idx) <= 0) as i32
}
/// <https://www.lua.org/manual/5.1/manual.html#lua_pushliteral>
#[inline]
pub unsafe f... | Rust | 0 |
self.data_panel, label="这里找不到数据 /_ \\ \n你可以试试先在左边分析下"),
wx.EXPAND)
self.data_panel.SetFont(ft(12))
self.data_panel.SetSizer(self.data_sizer)
def on_filter_update(self, event: wx.Event):
if event.GetEventObject() == self.reset_btn:
self.active_filter =... | Python | 1 |
::Io(inner) => inner.source(),
ErrKind::Var(inner) => inner.source(),
_ => None,
}
}
}
impl fmt::Display for ErrKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.description())?;
match self {
ErrKind::Io(inner) => ... | Rust | 0 |
#!/usr/bin/env python
###############################################################################
# Copyright Kitware Inc. and Contributors
# Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0)
# See accompanying Copyright.txt and LICENSE files for details
##################################... | Python | 1 |
{
let v: Fixed<i16> = Fixed {
values: (10..20).collect(),
};
assert_eq!(v.last::<i64>(&[3, 5, 6, 7]), 17);
}
#[test]
fn min() {
let v: Fixed<i16> = Fixed {
values: vec![100, 110, 20, 1, 110],
};
assert_eq!(v.min::<i64>(&[0, 1, 2, 3, ... | Rust | 0 |
aximum Improvement>')
lines.append('')
lines.append(' #<Lower Rarities Receive Less Improvement>')
lines.append('')
for (gun_name,
start_preadd, target_preadd,
bodies,
(old_max_worst, old_max_best),
(old_min_worst, old_min_best),
materials,
) in weapon_info:
li... | Python | 1 |
let mut security_property: sgx_ps_sec_prop_desc_ex_t = Default::default();
let ret = unsafe { sgx_get_ps_sec_prop_ex(&mut security_property as * mut sgx_ps_sec_prop_desc_ex_t) };
match ret {
sgx_status_t::SGX_SUCCESS => Ok(security_property),
_ => Err(ret),
}
}
// NSFetchedResultsControl... | Rust | 0 |
or the playlist
if video_id:
find_video_id = re.compile(r'video_id=(?P<video_id>[^&]+)')
for video in videos:
video_id_match = find_video_id.search(video.get_uri())
if video_id_match and video_id_match.group('video_id') == video_id:
break
playlist_... | Python | 1 |
uilder, Message};
use hbbft::honey_badger::{EncryptionSchedule, SubsetHandlingStrategy};
use hbbft::queueing_honey_badger::*;
use rand::{OsRng, Rng, thread_rng};
use std::collections::BTreeMap;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread::{JoinHandle, sleep, spawn};
use std::time::{Duration, Ins... | Rust | 0 |
umption of token")
}
fn token(&mut self) -> Spanned<Token<'a>> {
if let Some(token) = self.buffer.take() { return token; }
let (start, character) = match self.characters.next() {
None => return Spanned::new(Token::End,
Span(self.string.len(), self.string.len() + 1)),
Some(character) => character,
};
... | Rust | 0 |
153 => 5,
153 => 5,
153 => 5,
153 => 5,
153 => 5,
153 => 5,
153 => 5,
161 => 5,
161 => 5,
161 => 5,
161 => 5,
161 => 5,
161 => 5,
161 => 5,
161 => 5,
167 => 5,
167 => 5,
167 => 5,
167 => 5,
167 => 5,
167 => 5,
167 => 5,
167 => 5,
... | Rust | 0 |
= 14;
pub const CU_RES_VIEW_FORMAT_UINT_4X32: ::libc::c_uint = 15;
pub const CU_RES_VIEW_FORMAT_SINT_1X32: ::libc::c_uint = 16;
pub const CU_RES_VIEW_FORMAT_SINT_2X32: ::libc::c_uint = 17;
pub const CU_RES_VIEW_FORMAT_SINT_4X32: ::libc::c_uint = 18;
pub const CU_RES_VIEW_FORMAT_FLOAT_1X16: ::libc::c_uint = 19;
pub con... | Rust | 0 |
from __future__ import annotations
import asyncio
import pytest
from mcp import ClientSession, StdioServerParameters, types
from pydantic.networks import AnyUrl
from uglychain.tools.utils.mcp_client import McpClient, McpResource, McpTool
@pytest.fixture
def mock_session(mocker):
"""创建一个模拟的ClientSession对象"""
... | Python | 1 |
e_date = date(love_year, love_month, love_day)
# 获取在一起的日期差
love_days = str(today.__sub__(love_date)).split(" ")[0]
# 获取所有生日数据
birthdays = {}
for k, v in config.items():
if k[0:5] == "birth":
birthdays[k] = v
data = {
"touser": to_user,
"template_id": config["t... | Python | 1 |
from __future__ import annotations
class ColumnNotFoundError(Exception): ...
| Python | 1 |
use measure_time::*;
use crate::{bbox::GyroData, optic_flow::{OpticFlowData, OpticFlowRotation, read_optic_flow_data}, util::ransac};
#[derive(Default, Clone, Copy)]
pub struct EstimatedOffset {
pub at_video_ts: f64,
pub offset: f64,
pub cost: f64,
}
impl Display for EstimatedOffset {
fn fmt(&self, f... | Rust | 0 |
extended {
tag_str.push_str(&format!("-{}", ident));
}
let quoted = quote! {
::maple_core::generic_node::GenericNode::element(#tag_str)
};
tokens.extend(quoted);
}
}
<reponame>regexident/optimization-engine<filename>src/core/problem.rs
//! An optimization p... | Rust | 0 |
# This file was auto-generated by Fern from our API Definition.
from ..core.unchecked_base_model import UncheckedBaseModel
from .get_knowledge_base_summary_response_model_type import GetKnowledgeBaseSummaryResponseModelType
import typing
from .get_knowledge_base_summary_response_model_dependent_agents_item import (
... | Python | 1 |
fn call(&mut self, logs: Vec<LambdaLog>) -> Self::Future {
let counter = self.counter.fetch_add(1, SeqCst);
for log in logs {
match log.record {
LambdaLogRecord::Function(record) => {
info!("[logs] {} [function] {}: {}", log.time, counter, record.trim())
... | Rust | 0 |
n = int(input('Количество дней: '))
syp = ['щи', 'борщ', 'щавелевый суп', 'суп овсяный', 'суп по-чабански']
c = []
for i in range(n):
print(syp[i % len(syp)], end='\n')
| Python | 1 |
import schedule
import time
import subprocess
import os
import sys
# Get absolute path of this script
base_dir = os.path.dirname(os.path.abspath(__file__))
# Correct relative paths
FETCH_SCRIPT = os.path.join(base_dir, "Daily_Fund_Fetcher.py")
BOT_SCRIPT = os.path.join(base_dir, "Bot.py")
MERGE_SCRIPT = os.path.join(b... | Python | 1 |
""
}
fn supported_extensions()->&'static [&'static str];
fn from_extension(ext:&str)->Option<Self>;
fn extension_from_filename(filename:&str)->Option<&'static str>{
Self::supported_extensions().iter()
.enumerate()
.filter(|(i,x)| filename.ends_with(*x))
.map(|(i,x)| (x.le... | Rust | 0 |
format!("{}&next_page_token={}", url, page), None)
.await?;
}
messages.append(&mut resp.messages);
if !resp.next_page_token.is_empty() && resp.next_page_token != page {
page = resp.next_page_token.to_string();
} else {
... | Rust | 0 |
shipping_address(self, shipping_address):
"""Sets the shipping_address of this CreateGuestCheckoutSessionRequestV2.
:param shipping_address: The shipping_address of this CreateGuestCheckoutSessionRequestV2. # noqa: E501
:type: ShippingAddress
"""
self._shipping_address = shi... | Python | 1 |
e_signed(origin)?;
CurrencyTokens::<T>::try_mutate(currency_id, |token_info| -> DispatchResult {
let info = token_info
.as_mut()
.ok_or(Error::<T>::CurrencyTokenNotFound)?;
let instance_id = CurrencyInstance::<T>::get().ok_or(Error::<... | Rust | 0 |
# Copyright (c) 2020 The Regents of the University of California
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this lis... | Python | 1 |
ils::nth;
/*
* Return a vector of fibonnaci numbers from n to n+count
*/
fn nth_fibonacci(n: usize, count: usize) -> Vec<BigUint> {
let mut f0: BigUint = Zero::zero();
let mut f1: BigUint = One::one();
let mut x = vec![];
for i in 0..(n + count - 1) {
let f2 = f0 + &f1;
// This is a l... | Rust | 0 |
_app.config.get("STRIPE_WEBHOOK_SECRET")
)
except ValueError as e:
current_app.logger.error(f"Invalid payload: {e}")
return jsonify(success=False), 400
except stripe._error.SignatureVerificationError as e:
current_app.logger.error(f"Error verifying webhook... | Python | 1 |
),
}
}
}
/// Returns the model's parameter values.
#[inline]
pub fn parameter_values(&self) -> &[f32] {
unsafe { self.param_val.as_ref() }
}
/// Returns a mutable slice of the model's parameter values.
#[inline]
pub fn parameter_values_mut(&mut self) -> &mu... | Rust | 0 |
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
Path_confusion_matrix = '../Confussion matrix/'
Methods = ["EVT", "MEVT(VME)", "MEVT(OF)"]
x = np.arange(len(Methods))
micro_f1_data = [0.8702, 0.9181, 0.8807]
plt.bar(x, micro_f1_data, alpha=0.9, width = 0.35, edgecolor = 'black', lw... | Python | 1 |
64, f64), tol: f64) -> (Vec<f64>, Vec<Self::Point>) {
let a = self.transform;
let n = a[0][0] * a[0][0]
+ a[0][1] * a[0][1]
+ a[0][2] * a[0][2]
+ a[1][0] * a[1][0]
+ a[1][1] * a[1][1]
+ a[1][2] * a[1][2]
+ a[2][0] * a[2][0]
... | Rust | 0 |
let complexity = complexity_metrics.get(&name).unwrap();
let mut stats = vec!(
name.clone(),
kanji_1plus.to_string(),
kanji_2plus.to_string(),
chars.to_string(),
... | Rust | 0 |
#[doc = " - either \\b N or \\b incx is zero, or"]
#[doc = " - the leading dimension is invalid;"]
#[doc = " - \\b clblasInvalidMemObject if either \\b A or \\b X object is"]
#[doc = " Invalid, or an image object rather than the buffer one;"]
#[doc = " - \\b clblasOutOfHostMemory if the ... | Rust | 0 |
.predict_retention_score(cid)
else:
with self.cache_manager.pattern_lock:
if cid not in self.cache_manager.access_patterns:
return 0.0
pattern = self.cache_manager.access_patterns[cid]
return pattern.retenti... | Python | 1 |
.0
use std::convert::TryInto;
use crate::*;
// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
pub const SC_UINT8_LENGTH: usize = 1;
// \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\ // \\
pub fn uint8_decode(dec: &mut WasmDecoder) -> u8 {
dec.byte()
}
pub fn ... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
batch_size = 1
STATIC_JOINT_NUM = 25
JOINT_ID_BONE_DICT = {
0: 0,
1: 1,
2: 2,
3: 3,
5: 4,
6: 5,
7: 6,
8: 7,
10: 8,
11: 9,
12: 10,
13: 11,
15: 12,
16: 13,
17: 14,
18: 15,
... | Python | 1 |
GROUP_ABSOLUTE)
pub type xcb_xkb_sa_t = u32;
/// The `xkb::SA::ClearLocks` enum variant.
///
/// This is a variant of [`xcb_xkb_sa_t`].
pub const XCB_XKB_SA_CLEAR_LOCKS: xcb_xkb_sa_t = 1;
/// The `xkb::SA::LatchToLock` enum variant.
///
/// This is a variant of [`xcb_xkb_sa_t`].
pub const XCB_XKB_SA_LATCH_TO_LOCK: xcb_... | Rust | 0 |
ackbones for {}...'.format(cfg.EXP_GROUP_PATH))
# log to file
logger.info('**********************Start logging**********************')
gpu_list = os.environ['CUDA_VISIBLE_DEVICES'] if 'CUDA_VISIBLE_DEVICES' in os.environ.keys() else 'ALL'
logger.info('CUDA_VISIBLE_DEVICES=%s' % gpu_list)
if dist_te... | Python | 1 |
, PartialOrd, Ord)]
pub struct Uuid {
discriminant: u8,
hash: u64,
}
impl Uuid {
pub const fn new(discriminant: u8, hash: u64) -> Self {
Self { discriminant, hash }
}
const fn from_u128(uuid: u128) -> Self {
Self::from_le_bytes(uuid.to_le_bytes())
}
#[allow(clippy::many_si... | Rust | 0 |
"tsss...For women.",
"All right, so are you ready, so we'll go out and get something to eat.",
"That's uh, KL5-8383.",
"Are you calling them soon because, they keep very strange hours.",
"I thought were a team.",
"(to Elaine) Do you want us to go with you?",
"'These pretzels are making me thirsty'?",
"... | Rust | 0 |
th);
///# let roberta_model = RobertaForQuestionAnswering::new(&vs.root(), &config);
/// let (batch_size, sequence_length) = (64, 128);
/// let input_tensor = Tensor::rand(&[batch_size, sequence_length], (Int64, device));
/// let mask = Tensor::zeros(&[batch_size, sequence_length], (Int64, device));
... | Rust | 0 |
&Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<TCR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<TCR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "F... | Rust | 0 |
'a> {
/// Creates a new [`BacktraceObserver`] with the given name.
#[must_use]
pub fn new(
observer_name: &str,
backtrace_hash: &'a mut Option<u64>,
harness_type: HarnessType,
) -> Self {
Self {
observer_name: observer_name.to_string(),
hash: Owned... | Rust | 0 |
import numpy as np
import torch
from .defaults import DEFAULT_PPB, MAX_SEQ_LENGTH
def patchify(imgs: torch.Tensor, patch_size: int = DEFAULT_PPB):
"""
imgs: (N, 3, H, W) x: (N, L, patch_size**2 *3)
or
imgs: (3, H, W) x: (L, patch_size**2 *3)
"""
is_single_image = len(imgs.shape) == 3
if i... | Python | 1 |
from datetime import date
from woningwaardering.stelsels._dev_utils import DevelopmentContext
from woningwaardering.stelsels.onzelfstandige_woonruimten.onzelfstandige_woonruimten import (
OnzelfstandigeWoonruimten,
)
from woningwaardering.stelsels.zelfstandige_woonruimten.zelfstandige_woonruimten import (
Zelf... | Python | 1 |
if status == ImmutagFileState::Valid {
insert_entry_same_doc(&doc, file_name, key, immutag)
} else if status == ImmutagFileState::NonExistant && file_name.is_some() {
insert_entry_new_doc(&doc, file_name.unwrap(), key, immutag)
} else {
// Invalid
let err = Error::new("invalid ... | Rust | 0 |
response directly as JSON
tool_choice = json.loads(response)
return AgentAction(
tool=tool_choice["tool"],
tool_input=tool_choice["input"],
log=f"Using {tool_choice['tool']} for step: {step}"
)
except json.JSONDecodeError:
... | Python | 1 |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Conv1D, Dropout
class GestureRecognizer:
def __init__(self, num_classes):
self.model = self.build_model(num_classes)
def build_model(self, num_classes):
model = Seque... | Python | 1 |
"""
Модуль для парсинга товаров с сайта Ozon.
Этот модуль предоставляет функции для сбора ссылок на товары по поисковому запросу,
а также для сохранения ссылок на/информации о товарах в JSON-файл.
Используются библиотеки: `selenium`, `undetected_chromedriver`, `BeautifulSoup`, `slugify`.
"""
import time
import json
i... | Python | 1 |
nc,
{
match format {
"files" | "tgz" => fetch_bundle_uri(uri, &local_dir, verbose, writer).await,
_ =>
// The schema currently defines only "files" or "tgz" (see RFC-100).
// This error could be a typo in the product bundle or a new image
// format has been added and this cod... | Rust | 0 |
def shift_sharded_axis(a):
if isinstance(a, pmap_lib.ShardedAxis) and a.axis >= sharded_in_axis:
return pmap_lib.ShardedAxis(a.axis + 1)
return a
# replication_factor represents the product of inner pmaps, so it goes
# after the outer pmapped axis at index 0
... | Python | 1 |
_mode=label_mode,
num_classes=len(class_names),
max_length=max_length,
)
dataset = dataset.prefetch(tf.data.AUTOTUNE)
if batch_size is not None:
if shuffle:
# Shuffle locally at each iteration
dataset = dataset.shuffle(buffer_si... | Python | 1 |
<u32, _MATCHREL7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MATCHREL7;
#[doc = "`read()` method returns [matchrel7::R](matchrel7::R) reader structure"]
impl crate::Readable for MATCHREL7 {}
#[doc = "`write(|w| ..)` method takes [matchrel7::W](matchrel7::W) writer structure"]
impl crate::Writable for MATCHREL7 ... | Rust | 0 |
(4, 32, 17),
occurred_at: Utc.ymd(2012, 1, 8).and_hms(4, 31, 54),
id: "ND20120108133201".to_owned(),
status: Status::Normal,
number: 3,
detail: None,
};
assert_eq!(parse(telegram), Ok(expected));
}
#[test]
fn it_should_parse_normal_eew_01()
{
let telegram = b"36 03 00 130804122905 C11 130804122849 \
ND... | Rust | 0 |
prob.add_constraint(vec![(x, 1.), (y, 1.), (z, 1.)], ConstraintOp::Gte, -3.)
.unwrap();
prob.add_constraint(vec![(x, -1.), (y, 1.), (z, -1.)], ConstraintOp::Gte, -4.)
.unwrap();
prob.add_constraint(vec![(x, 1.), (y, -1.), (z, -2.)], ConstraintOp::Gte, -1.)
.unwrap();
assert_... | Rust | 0 |
rint("\n--- Статистика дедупликации ---")
print(f"Прочитано строк: {lines_read}")
print(f"Найдено уникальных имен (записано строк): {lines_written}")
print(f"Пропущено строк (дубликаты по имени '{name_key}'): {lines_skipped_duplicate}")
print(f"Пропущено строк (без поля '{name_key}' или null): {lines_sk... | Python | 1 |
gradecoin::routes::consensus_routes;
use gradecoin::schema::create_database;
#[tokio::main]
async fn main() {
log4rs::init_file("log.conf.yml", Default::default()).unwrap();
let db = create_database();
let api = consensus_routes(db);
// Start the server
let point = ([127, 0, 0, 1], 8080);
w... | Rust | 0 |
s_emb:
output['res_emb'] = res_emb
if return_attention_map:
output['attention_map'] = pair_atten
# Residue-level prediction
if return_res_pred:
res_pred = self.res_pred_nn(res_emb)
for feature in self.res_feature_idx:
if feature ==... | Python | 1 |
mpts = attempts + 1;
if attempts == DEADLOCK_THRESHOLD
{
hvdebug!("BUG: {} mutex ({:p}) may be deadlocked", self.description, &self.content);
}
/* determine if the mutex is available, or may even
already be held by this physical core */
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.