text string | label_name string | labels int64 |
|---|---|---|
~= { origin }).load(&conn).unwrap();
assert_eq!(trips.len(), 1);
assert_eq!(trip1, trips[0]);
}
maketest_pg!(query_custom);*/
}
use fnv::FnvHashMap;
use crate::parser;
mod error;
mod expr;
mod func;
mod module;
mod stmt;
mod tree;
pub use error::*;
pub use func::Func;
pub use module::Module... | Rust | 0 |
"""study planned participants setup step
Revision ID: a98b40583e73
Revises: 6e99fcd0daf9
Create Date: 2022-07-12 17:26:14.646885
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from sqlalchemy import update
from sqlalchemy.dialects import postgresql
from model import Stu... | Python | 1 |
.and_then(|u| char::try_from(u).map_err(|err| err.to_string()))
.unwrap_or_else(|err| {
warn!(
"Failed to convert {0} (0x{0:x}) into a character: {1}",
codepoint, err
);
char::REPLACEMENT_CHARACTER
});
... | Rust | 0 |
result_repo = result["links"]["repository"]
# clone = sp.run(["git", "clone", result_repo, args.tmpdir + "/" + dep_name])
# with cd(args.tmpdir + "/" + dep_name):
# npm_install = sp.run(["npm", "install"])
# gen_d_ts = sp.run(["... | Python | 1 |
# Copyright (c) 2021 Horizon Robotics and ALF Contributors. 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... | Python | 1 |
うかを判定する.
fn is_garbage(&self, index: &LumpIndex, entry: &JournalEntry) -> bool {
match entry.record {
JournalRecord::Put(ref lump_id, ref portion) => {
index.get(lump_id) != Some(Portion::Data(*portion))
}
JournalRecord::Embed(ref lump_id, ref data) => {
... | Rust | 0 |
ThresholdImageFilter.SetSeedList([(0,0,0),(size[0]-1,size[1]-1,0)])
#得到body的mask,此时body部分是0,所以反转一下
bodymask = ConnectedThresholdImageFilter.Execute(threshold)
bodymask = sitk.ShiftScale(bodymask,-1,-1)
#用bodymask减去threshold,得到初步的lung的mask
# sitk.Cast(bodymask, sitk.sitkInt16)
# sitk.Ca... | Python | 1 |
import torch
import cppcuda_tutorial
import time
# Pure python version of trilinear interpolation for testing
def trilinear_interpolation(feats, points):
"""
Inputs:
feats: (N, 8, F) tensor
points: (N, 3) tensor
Outputs:
feats_interp: (N, F) tensor
"""
u = (points[:... | Python | 1 |
if only:
detectors_new_options["only"] = only
config.update(
{
"compiler": {"solc": compiler_new_options},
"detectors": detectors_new_options,
},
deleted_options,
)
asyncio.run(
detect_(
config,
no_artifacts,
... | Python | 1 |
# This file is part of Linux Show Player
#
# Copyright 2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 of the License, or
# ... | Python | 1 |
t)
match_check = match_check_bot.complete(max_tokens=1024, temperature=0.1)[
"content"
]
logger.debug(match_check)
match_check = parse_json(match_check)
if match_check["match"]:
right_person = person
break
if idx > 3:
break
... | Python | 1 |
read_exact(buf.as_mut_slice())?;
Ok(BPList::UID(buf))
}
fn load_array(
file: &mut File,
trailer: &Trailer,
reference_table: &ReferenceTable,
marker_low: u8,
) -> Result<BPList> {
let length = load_length(file, trailer, reference_table, marker_low)?;
let mut ref_buf = vec![0; trailer.object... | Rust | 0 |
"foo".to_string(), factory);
assert_eq!("foo", *pin);
});
// Spawn *another* thread that tries constructing the key "foo".
// Will be stuck same as first thread, but crucially the object
// will only be created once (verified later).
let copy_of_cache = Arc::clone(&c... | Rust | 0 |
import numpy as np
import re
import pandas as pd
from causalnex.structure.dynotears import from_pandas_dynamic
def dynotears(process, max_lags):
df = pd.DataFrame(process.T, columns=[f'X{i}' for i in range(len(process))])
sm = from_pandas_dynamic(df, p=max_lags)
cm = np.zeros((process.shape[0], process... | Python | 1 |
import os
import numpy as np
import glob
import sys
import json
from PIL import Image
from tqdm import tqdm
import shutil
import math
def fov2focal(fov, pixels):
return pixels / (2 * math.tan(fov / 2))
def rotmat2qvec(R):
Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
K = np.array([
[Rxx - Ry... | Python | 1 |
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (C) 2021 Intel Corporation
# All rights reserved.
#
from argparse import ArgumentParser
import os
import re
import subprocess
import sys
class TraceProcess:
def __init__(self, pid):
self._path = os.readlink(f'/proc/{pid}/exe')
... | Python | 1 |
ntStore):
msg = "document_store must be an instance of OpenSearchDocumentStore"
raise ValueError(msg)
doc_store = document_store
else:
doc_store = self._document_store
try:
docs = await doc_store._embedding_retrieval_async(
... | Python | 1 |
r(text).unwrap();
let mut security_groups = HashMap::new();
config.security_group.iter().for_each(|g| {
security_groups.insert(g.name.clone(), SecurityGroup {
name: g.name.clone(),
allowed_ip: g.allowed_ip.clone(),
});
});
let mut u... | Rust | 0 |
import re
import logging
from langchain.tools import tool
# Configure logging
logger = logging.getLogger(__name__)
@tool
def calculate_math(expression: str) -> str:
"""
Perform mathematical calculations safely.
Args:
expression: A mathematical expression to evaluate (e.g., "42 * 7", "15 + 27"... | Python | 1 |
tors such as "good", "highest rated" and "top-rated" are named viewers\' rating entities. '
'Performance metrics such as "highest-grossing" and "best-rated" are also named viewers\' rating entities.\n'
'Ambiguous identifiers such as "review" are not named entities.\n'
'Na... | Python | 1 |
see above
check!(0 + 0); // ERROR, see above
fn main() {}
use libradar::apk::*;
use libradar::callgraph::get_invoked_methods_names;
fn print_info_of_apk(apk: Apk) {
for dex in apk.dex_files {
for class in dex.classes() {
let class = class.expect("Failed to load class");
let class_... | Rust | 0 |
P r/m8`
///
/// `0F 9A /r`
///
/// `386+`
///
/// `16/32/64-bit`
Setp_rm8 = 1912,
/// `SETNP r/m8`
///
/// `0F 9B /r`
///
/// `386+`
///
/// `16/32/64-bit`
Setnp_rm8 = 1913,
/// `SETL r/m8`
///
/// `0F 9C /r`
///
/// `386+`
///
/// `16/32/64-bit`
Setl_rm8 = 1914,
/// `SETGE r/m8`
///
/// `0F 9... | Rust | 0 |
ce_average[i] = distance_average[i] / airspace_cover_num_
distance_average = list(distance_average)
distance_shortest_index = distance_average.index(min(distance_average))
airspace_best_bh = int(airspace_good_cover[distance_shortest_index])
"""计算最优空域中心"""
airspace_num_x = int((180 - scan_range_x) /... | Python | 1 |
# -*- coding: utf-8 -*-
'''
【简介】
PyQt5中 QScrollBar 例子
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout( )
self.l1 =... | Python | 1 |
"""
Forum conversation models
=========================
This module defines models provided by the ``forum_conversation`` application.
"""
from machina.apps.forum_conversation.abstract_models import AbstractPost, AbstractTopic
from machina.core.db.models import model_factory
Topic = model_factory(Abstr... | Python | 1 |
if self.filter_fn(key)
)
else:
yield from filter(self.filter_fn, self._index.ls(root_key, detail=False))
def has_node(self, key: DataIndexKey) -> bool:
return self.filter_fn(key) and self._index.has_node(key)
def delete_node(self, key: DataIndexKey) -> None:
... | Python | 1 |
from configuration import Config
import sys, os, time
import django
from django.core.management import call_command
from YAPO.wsgi import application
from utils.printing import Logger
log = Logger()
# First of all, check if the db is located in the old folder (root)
def boot():
dest = os.path.join(Config().databas... | Python | 1 |
println!("spawned {}", i)
});
i += 1;
println!("original {}", i);
t.join();
}
fn bar() {
// Here, the original i has not been moved, only copied, so is still
// mutable outside of the proc.
let mut i = 0;
while i < 10 {
let t = thread::spawn(move|| {
user(i);
... | Rust | 0 |
proposal
/// that is not build into the standard SNS and calls a canister outside
/// the SNS for execution.
/// The canister and method to call are derived from the `function_id`.
#[derive(candid::CandidType, candid::Deserialize)] #[cfg_attr(feature = "test", derive(comparable::Comparable))]
#[derive(Clone, PartialEq... | Rust | 0 |
)
args = parser.parse_args()
if args.width < 1:
parser.error("width must be a positive non-zero integer.")
if args.height < 1:
parser.error("height must be a positive non-zero integer.")
return args
def generate_flow_trails(env, points, length=100, step_size=0.2):
# move points... | Python | 1 |
/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rtc_ier](rtc_ier) module"]
pub type RTC_IER = crate::Reg<u32, _RTC_IER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RTC_IER;
#[doc = "`write(|w| ..)` method takes [rtc_ier::W](rtc_ier::W) writer structure"]
impl crate::Writable f... | Rust | 0 |
address).as_mut_ptr();
base.write_volatile(reg);
base.add(4).read_volatile()
}
fn new(id: u8, address: PhysAddr, gsi_base: u32) -> Self {
Self {
id,
address,
gsi_base,
}
}
unsafe fn write_vector_data(&self, regnum: u32, data: u64) {
... | Rust | 0 |
# Copyright 2023 The HuggingFace Team. 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 applicabl... | Python | 1 |
from kivy_ios.toolchain import Recipe, shprint
import sh
class LibffiRecipe(Recipe):
version = "3.4.8"
url = "https://github.com/libffi/libffi/releases/download/v{version}/libffi-{version}.tar.gz"
library = "build/Release-{plat.sdk}/libffi.a"
include_per_platform = True
include_dir = "build_{plat.... | Python | 1 |
F_T_BYTE = 0,
ELF_T_ADDR = 1,
ELF_T_DYN = 2,
ELF_T_EHDR = 3,
ELF_T_HALF = 4,
ELF_T_OFF = 5,
ELF_T_PHDR = 6,
ELF_T_RELA = 7,
ELF_T_REL = 8,
ELF_T_SHDR = 9,
ELF_T_SWORD = 10,
ELF_T_SYM = 11,
ELF_T_WORD = 12,
ELF_T_XWOR... | Rust | 0 |
l']}")
break
else:
update_data = {
"updatedAt": request_wb["cursor"]["updatedAt"],
"nmID": request_wb["cursor"]["nmID"]
}
json_obj["settings"]["cursor"].update(update_data)
# добавляем данные п... | Python | 1 |
-> HRESULT,
}}
RIDL!{#[uuid(0x0002df05, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)]
interface IWebBrowserApp(IWebBrowserAppVtbl): IWebBrowser(IWebBrowserVtbl) {
fn Quit() -> HRESULT,
fn ClientToWindow(
pcx: *mut INT,
pcy: *mut INT,
) -> HRESULT,
fn PutProperty(
... | Rust | 0 |
import seaborn as sns
import matplotlib.pyplot as plt
# tips = sns.load_dataset("Book1")
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [12, 13, 41, 65, 74, 26, 9, 5, 44]
sns.set(style="whitegrid")
# Create a scatter plot using Seaborn
sns.scatterplot(x=x, y=y)
# sns.despine()
plt.xlabel("Total Bill ($)")
plt.ylabel("Ti... | Python | 1 |
")]
HwPoison = libc::MADV_HWPOISON,
// Future expansion:
// MADV_SOFT_OFFLINE (since Linux 2.6.33)
// MADV_WIPEONFORK (since Linux 4.14)
// MADV_KEEPONFORK (since Linux 4.14)
// MADV_COLD (since Linux 5.4)
// MADV_PAGEOUT (since Linux 5.4)
}
<gh_stars>10-100
/// Implements `Deref` and `... | Rust | 0 |
import numpy as np
def quat_to_rpy(q):
w,x,y,z = q
sinr = 2*(w*x + y*z); cosr = 1-2*(x*x+y*y)
roll = np.arctan2(sinr, cosr)
sinp = 2*(w*y - z*x); pitch = np.arcsin(np.clip(sinp,-1,1))
siny = 2*(w*z + x*y); cosy = 1-2*(y*y+z*z)
yaw = np.arctan2(siny, cosy)
return np.array([roll, pitch, y... | Python | 1 |
[doc = "0x10bc - TCD Control and Status"]
pub tcd5_csr: TCD5_CSR,
_reserved_97_tcd5_biter: [u8; 2usize],
#[doc = "0x10c0 - TCD Source Address"]
pub tcd6_saddr: TCD6_SADDR,
#[doc = "0x10c4 - TCD Signed Source Address Offset"]
pub tcd6_soff: TCD6_SOFF,
#[doc = "0x10c6 - TCD Transfer Attributes"]
pub tcd6_... | Rust | 0 |
import importlib
import time
import os
from loguru import logger
from functools import lru_cache
pj = os.path.join
default_user_name = 'default_user'
def read_env_variable(arg, default_value):
arg_with_prefix = "AGENT_MATRIX_" + arg
if arg_with_prefix in os.environ:
env_arg = os.environ[arg_with_... | Python | 1 |
import yaml
import dotenv
from pathlib import Path
config_dir = Path(__file__).parent.parent.resolve() / "config"
with open(config_dir / "config.yml", 'r') as f:
config_yaml = yaml.safe_load(f)
config_env = dotenv.dotenv_values(config_dir / "config.env")
OPENAI_COMPLETION_OPTIONS = config_yaml["OPENAI_COMPLETI... | Python | 1 |
if sig.len() == 0 {
sig = id;
}
let startcontent = ix;
let mut about = read_id (bytes, &mut ix);
if about.len() == 0 {
about = id;
};
let s = xtendsizedec(bytes, &mut ix, KEY_LENGTH);
let key = if ix + s <= bytes.len() {
&bytes[ix .. ix + s]
} else {
&bytes[0 .. 0]
};
ix = ix ... | Rust | 0 |
import sys
from styles import setupTheme
from info import Info
from display import Display
from main_window import MainWindow
from buttons import ButtonsGrid
from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,
QLabel)
def temp_label(texto, font_size = 150):
... | Python | 1 |
heet, screen, scale, x, y,charge,Cx):
global doll,sprite_sheet,flipped_sprite_sheet,player_sprite
# Draws a player
if Cx>=x:
screen.blit(player_sprite, (x, y))
else:
screen.blit(pygame.transform.flip(player_sprite,1,0), (x, y))
rect = pygame.Rect(x - 8 * scale, y - 80, charge, 15)
... | Python | 1 |
}
}
pub mod storage_account_properties_create_parameters {
use super::*;
#[doc = "Required for storage accounts where kind = BlobStorage. The access tier used for billing."]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum AccessTier {
Hot,
Cool,
}
}
#[doc = "The p... | Rust | 0 |
let data: &[u8] = slice::from_raw_parts(
(*io_u).xfer_buf as *mut u8,
(*io_u).xfer_buflen as usize,
);
let filedesc = (*(*io_u).file).fd;
let fd = files.get(&filedesc).unwrap();
((*io_u).ddir, fd, (*io_u).offset, data)
};
rt.block_on(async {
match... | Rust | 0 |
f._handler_lock:
if plugin_name not in self._plugin_handlers:
return 0
handler_count = 0
plugin_handlers_map = self._plugin_handlers[plugin_name]
for event_type, handlers in plugin_handlers_map.items():
if event_type in self.event_bus.han... | Python | 1 |
#!/usr/local/bin/python3.7
#------------------------------------------------------------------------------
#
# Copyright (c) 2020 German Aerospace Center DLR e.V. (GSOC)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... | Python | 1 |
def get_views(self, height, width, window_size=128, stride=64,
random_jitter=False):
height //= self.vae_scale_factor
width //= self.vae_scale_factor
num_blocks_height = int((height - window_size) / stride - 1e-06
) + 2 if height > window_size else 1
num_blocks_width = int((width - window_si... | Python | 1 |
: value }
}
}
impl From<i64> for Integer {
fn from(num: i64) -> Self {
Integer { value: fixnum::i64_to_num(num) }
}
}
impl Into<i64> for Integer {
fn into(self) -> i64 {
fixnum::num_to_i64(self.value())
}
}
impl From<u64> for Integer {
fn from(num: u64) -> Self {
Integ... | Rust | 0 |
der, SliceReader},
Error, Result,
};
/// Deserializer for the Pot format.
#[derive(DeriveWhere)]
#[derive_where(Debug)]
pub struct Deserializer<'s, 'de, R: Reader<'de>> {
#[derive_where(skip)]
input: R,
symbols: SymbolMap<'s, 'de>,
peeked_atom: VecDeque<Atom<'de>>,
remaining_budget: usize,
}
i... | Rust | 0 |
/// # C layout (for some given type T)
///
/// ```c
/// typedef struct {
/// // Cannot be NULL
/// T * ptr;
/// size_t len;
/// } slice_T;
/// ```
///
/// # Nullable pointer?
///
/// If you want to support the above typedef, but where the `ptr` field is
... | Rust | 0 |
ripts and documentation.
// "Reserved Font Name" refers to any names specified as such after the
// copyright statement(s).
// "Original Version" refers to the collection of Font Software components as
// distributed by the Copyright Holder(s).
// "Modified Version" refers to any derivative made by adding to, deleti... | Rust | 0 |
::VecRRR {
alu_op: VecALUOp::Bsl,
rd: r_dst,
rn: r_b,
rm: r_a,
size: VectorSize::Size8x16,
});
} else {
panic!("Opcode::FminPseudo | Opcode::FmaxPseudo: unhandled type");
... | Rust | 0 |
)
if choice.isdigit() and 1 <= int(choice) <= len(demo_sites):
url = demo_sites[int(choice) - 1]
elif choice.startswith('http'):
url = choice
else:
print("❌ Invalid choice")
return
# Ask about test generation
gen_t... | Python | 1 |
import math
def asgd(opfunc, x, config, state=None):
""" An implementation of ASGD
ASGD:
x := (1 - lambda eta_t) x - eta_t df/dx(z,x)
a := a + mu_t [ x - a ]
eta_t = eta0 / (1 + lambda eta0 t) ^ 0.75
mu_t = 1/max(1,t-t0)
implements ASGD algorithm as in L.Bottou's sgd-2.... | Python | 1 |
// Access arbitrary elements
let second = fruits.get(1);
if let Some(second) = second {
println!("Second fruit: {}", second);
}
// Access arbitrary elements without bounds checking
let second = fruits[1];
println!("Second fruit: {}", second);
// Initialize the vector with a v... | Rust | 0 |
ems():
self.log.info(f" 📈 {table_suffix.replace('_', ' ').title()}: {count} records")
for row in sample_results:
self.log.info(
f" 📋 CVR: {row[0]} | Name: {row[1]} | Type: {row[2]} | "
f"Founded: {row[3]} | Sources: {row[4]} |... | Python | 1 |
\xa3\x97\x96\xe5\x93+s\xe6\xd9\
\xbf\xff\x0c\x9b\x1f\xae\xa3\x0d\xc0\xe5\x1f\x92|\x8d\x01\xc4\
\x10\xb8c}0g\x10\x03\x00\x22\xa2\xd9\x99\xe5r\xf0\
S2\x22\xbd_6\xfd\xce)\xa0.\xb7eo\x03\xef\
]\xb7vo\xac\x22\xb4\x02k\x01\x15\x0f#\x10#*\
\x06>6\xf0\x9d\xc0h+4h\x1b\xf8N\xc5j\xab\
\x16Hc.Ds\xb9\xa2\x1b\x00\xd6\xd7\x9a~_\xc4\
... | Python | 1 |
-' may be used to hide all unnamed columns")
.takes_value(true),
)
.arg(
Arg::new("alignment")
.short('a')
.long("alignment")
.default_value("l")
.validator(|s| {
if s.chars().all(|c| super::A... | Rust | 0 |
"""草稿文件夹管理器"""
import os
import shutil
from typing import List
from . import assets
from .script_file import ScriptFile
class DraftFolder:
"""管理一个文件夹及其内的一系列草稿"""
folder_path: str
"""根路径"""
def __init__(self, folder_path: str):
"""初始化草稿文件夹管理器
Args:
folder_path (`str`): ... | Python | 1 |
i
# 定子齿宽最小值 = 1
# 定子齿宽最大值 = tan(2*pi/self.spec.Qs*0.5)*self.spec.Radius_OuterRotor * 2 # 圆(半径为Radius_OuterRotor)的外接正多边形(Regular polygon)的边长
# # print(定子齿宽最大值, 2*pi*self.spec.Radius_OuterRotor/self.spec.Qs) # 跟弧长比应该比较接近说明对了
# 转子齿宽最小值 = 1
# 内接圆的半径 = self.spec.Radius_OuterRotor - (... | Python | 1 |
ipt!(
&format!("{}", command),
&vec![],
&options
).unwrap();
(code, output, error)
}
pub fn rmfile(password: &str, filepath: &str) -> (i32, String, String){
let options = ScriptOptions::new();
let _command = r#"echo password | sudo -S rm -f filepath"#;
let _command = _com... | Rust | 0 |
gc_Image_header),
"::",
stringify!(empty)
)
);
assert_eq!(
unsafe { &(*(::core::ptr::null::<gui_gc_Image_header>())).buff_size as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(gui_gc_Image_header),
"::",
stringify!(buff_size)
)
);
assert_eq!(
unsafe { &(*(::cor... | Rust | 0 |
curities, time_serial, fields_balance_sheet)
if result is not None:
return result
df['净资产'] = df['资产总计'] - df['负债合计']
df['商誉/净资产'] = df['商誉'] / df['净资产']
df['商誉/总资产'] = df['商誉'] / df['资产总计']
df['在建工程/总资产'] = df['在建工程'] / df['资产总计']
df['固定资产/总资产'] = df['固定资产'] / df['资产总计']
# df['税前利润... | Python | 1 |
101, 0x0102, 400)
ChrTalk(
0x0101,
(
'#0010031022V#000F嗯,明~白。',
TxtCtl.Enter,
),
)
CloseMessageWindow()
Jump('loc_61B1')
def _loc_6170(): pass
label('loc_6170')
ChrTalk(
0x0102,
(
'#0020031023V#010F这边是街道。',
... | Python | 1 |
"""
Provide the Command Line Interface.
"""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, ParamSpec, TypeAlias, TypeVar, final
from typing_extensions import override
from betty import about
from betty.locale.locali... | Python | 1 |
w = w[None, :]
try:
all_pcs[i, :, c] = pca_model[chan_ind].transform(w)
except:
# this could happen if len(wfs) is less then n_comp for a channel
pass
def _init_work_all_pc_extractor(recording, sorting, all_pcs_args, nbef... | Python | 1 |
ines = hough_lines(img = masked_img, rho = 1, theta = np.pi/180, threshold = 20, min_line_len = 20, max_line_gap = 180)
print("Applying weighted image")
output = weighted_img(img = houghed_lines, initial_img = image, α=0.8, β=1., γ=0.)
print("Lane finding pipeline complete")
return output
def... | Python | 1 |
.abs(), sq.2.abs()])
.max()
.unwrap_or(0) as usize
+ 1
}
// Nothing to see here 🧙
pub fn get_piece_dim(_model: &Model) -> (f32, f32) {
let h = 50.0;
(h * RATIO, h)
}
pub fn get_piece_pos(_model: &Model, (x, y): (f32, f32)) -> (f32, f32) {
// _think_ * 8 because board is 800 * 800... | Rust | 0 |
# Regular expression is used to search and match particular patterns of text.
# r"string" is for raw string which kills the power of escape characters like back slash \. Not to handle back slashes in any special way.
import re
text_to_search = '''
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H ... | Python | 1 |
config.hidden_size,
quant_config=quant_config,
prefix=f"{prefix}.lm_head")
if self.config.tie_word_embeddings:
self.lm_head.weight = self.model.embed_tokens.weight
self.logits_processor = LogitsProcesso... | Python | 1 |
ction")
xml_docs.append("/// </summary>")
# Add param documentation
for param in params:
xml_docs.append(f"/// <param name=\"{param}\">Description of {param}</param>")
# Add returns documentation if it looks like the function returns... | Python | 1 |
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
import logging
from ..database import get_db
from ..models.digital_human_voice import DigitalHumanVoice
from ..schemas.digital_human_voice import DigitalHumanVoice as DigitalHumanVoiceSchema, DigitalHumanVoiceCreate, Digital... | Python | 1 |
let CustomOption::Some(test) = &test {};
while let CustomOption::Some(Test { a, b }) = &test {};
while let CustomOption::Some(Test { a: x, b: y }) = &test {};
while let CustomOption::Some(Test { a: CustomOption::Some(x), b: y }) = &test {};
while let CustomOption::Some(Test { a: CustomOption::None, b: ... | Rust | 0 |
r, Tab};
use super::engine::{glsp, Sym};
use super::gc::{Allocate, Gc, Slot, Root};
use super::val::{Val};
/*
this module is only present when the "serde" crate feature is enabled. it contains manual
Serialize and Deserialize implementations for various glsp types.
it pulls in the `serde` crate as a depend... | Rust | 0 |
(get_z_order_count_min: (display_id: DisplayId) => (z: i64));
ipc_interface_define_command!(get_z_order_count_max: (display_id: DisplayId) => (z: i64));
ipc_interface_define_command!(set_layer_position: (x: f32, y: f32, id: LayerId) => ());
ipc_interface_define_command!(set_layer_size: (id: LayerId, width: ... | Rust | 0 |
if isinstance(pipeline, str):
pipeline = tvm.tir.get_tir_pipeline(pipeline)
else:
# default pipeline depends on the target
pipeline = tvm.tir.get_default_tir_pipeline(target)
mod = pipeline(mod)
# Step 5: Get host and device modules
host_mod, device_mod_dict = split... | Python | 1 |
ommunity are able to achieve, too. “When I first saw we had a million tokens in context, my first question was, ‘What do you even use this for?’” says Machel. “But now, I think people’s imaginations are expanding, and they’ll find more and more creative ways to use these new capabilities.Long-context question answering... | Python | 1 |
@pytest.mark.parametrize("radius", [1, 1.])
@pytest.mark.parametrize("center", [None, (1, 2, 3), (1., 2., 3.)])
def test_attribute_types(self, radius, center):
points = radius * self.points
if center is not None:
points += center
sv = SphericalVoronoi(points, radius=radius... | Python | 1 |
bindings()
.map(|name| name.to_string())
.collect::<HashSet<String>>();
pipeline.dynamic_bindings_generation =
render_pipelines.bindings.dynamic_bindings_generation();
for (handle, _) in render_pipelines.bindings.iter_assets() {... | Rust | 0 |
n_ty = self.monomorphize(fn_ty);
trace!("reify-fn-pointer cast: {:?}", fn_ty);
visit_fn_use(self.tcx, fn_ty, false, self.output);
},
mir::Rvalue::Cast(
mir::CastKind::Pointer(PointerCast::ClosureFnPointer(_)), ref operand, _
) => {
let source_ty = operand.ty(self.mir, s... | Rust | 0 |
metrics['rewloss'] = rewloss.item()
metrics['rewacc1'] = lacc1.item()
metrics['rewacc2'] = lacc2.item()
metrics['rewacc3'] = lacc3.item()
full_loss += model.module.langweight * rewloss
t5 = time.time()
## Within Video TCN Loss
if model.module... | Python | 1 |
#!/usr/bin/env python3
"""
Абсолютно минимальный Spark тест - без аргументов
"""
import sys
import logging
from pyspark.sql import SparkSession
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def main():
try:
logger.info("🚀 ... | Python | 1 |
/// # Ok(())
/// # }
/// ```
fn read_datetime(&mut self) -> IonCResult<IonDateTime>;
/// Reads a `string`/`symbol` value from the reader.
///
/// ## Usage
/// ```
/// # use std::convert::*;
/// # use ion_c_sys::*;
/// # use ion_c_sys::reader::*;
/// # use ion_c_sys::res... | Rust | 0 |
attr_parse() {
assert!("".parse::<MakeMroAttr>() == Ok(MakeMroAttr::default()));
assert!("foo".parse::<MakeMroAttr>().is_err());
assert!("mem_gb".parse::<MakeMroAttr>().is_err());
assert!("mem_gb=f".parse::<MakeMroAttr>().is_err());
assert!(
"mem_gb=10".parse::<MakeMr... | Rust | 0 |
----------
path: str
远程路径
pattern: str
模糊匹配字段
Returns
-------
list
返回远程路径下的文件或文件夹
'''
files = self.ftp.listdir(path, pattern)
files.sort()
return files
def getFileList(self, srcpath, pattern=None):
... | Python | 1 |
# Copyright (c) Meta Platforms, Inc. and 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.
from fvcore.common.benchmark import benchmark
from tests.test_cubify import TestCubify
def bm_cubify() -> Non... | Python | 1 |
ld Blob.from_path(path)
def _yield_paths(self) -> Iterable[Path]:
"""Yield paths that match the requested pattern."""
if self.path.is_file():
yield self.path
return
paths = self.path.glob(self.glob)
for path in paths:
if self.exclude:
... | Python | 1 |
er the MIT License.
use fixedbitset::FixedBitSet;
use iced_x86::{Decoder, DecoderOptions, FlowControl, Instruction, OpKind};
fn process_near_branch(instruction: &Instruction, blocks: &mut FixedBitSet) {
match instruction.op0_kind() {
OpKind::NearBranch16 => {}
OpKind::NearBranch32 => {}
Op... | Rust | 0 |
status', 'Unknown')}\n"
result += f"- Last Reported: {status.get('lastReportedAt', 'Unknown')}\n"
# Performance
result += "\n## Performance\n"
result += f"- CPU: {status.get('cpu', 'Unknown')}%\n"
result += f"- Memory: {status.get('memory', 'Unkno... | Python | 1 |
import click
from flask.cli import AppGroup
from app.models import Sub, SubSubscriber
recount = AppGroup("recount", help="Re-count various internal counters")
@recount.command(help="Rebuilds all sub's subscriber counters")
@click.option(
"--save/--dry-run",
default=True,
help="Use --save (the default) to... | Python | 1 |
))]
pub(crate) fn set_index(&mut self, index: usize) {
self.index = index
}
pub(crate) fn can_read(&self) -> bool {
self.index < self.data.len()
}
pub(crate) fn read_u8(&mut self) -> usize {
let b = self.data[self.index] as usize;
self.index += 1;
b
}
pub(crate) fn read_compressed_u32(&mut self) -> ... | Rust | 0 |
import numpy as np
import openpyxl
from scipy.optimize import root
import random
from data import *
'''
def adjust_rounded_ps(rounded_ps):
total = sum(rounded_ps)
diff = round(1.00 - total, 2)
if diff == 0:
return rounded_ps
tolerance = 1e-9
indices = sorted(range(5), key=lambda i: rounded_... | Python | 1 |
position is determined by the skinning
//! equation
//!
//! (vertex final pos) =
//! ∑_{influence}
//! (weight) (pose local-to-world) (rest world-to-local) (vertex rest pos)
//!
//! See eg. section X in the COLLADA 1.4 spec for more details.
//!
//! In NSBMD models, this skeleton data has been compil... | Rust | 0 |
ile will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML hel... | Python | 1 |
or("記憶體使用率檢查失敗: %s", e)
return HealthCheckResult(
name="memory",
status=HealthStatus.CRITICAL,
score=0.0,
message=f"記憶體使用率檢查失敗: {str(e)}",
details={"error": str(e)},
duration=duration,
)
def che... | Python | 1 |
self.env.set_assoc(&other.env),
env_phaseless: self.env_phaseless.set_assoc(&other.env_phaseless),
q_lev: self.q_lev,
}
} else {
self
}
}
pub fn q_more(&self, by: u8) -> Ren {
Ren { q_lev: self.q_lev + i16::from(by), ..self.clone()... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.