text string | label_name string | labels int64 |
|---|---|---|
= rs.req;
if req.get_from() == NONE || req.get_from() == self.id {
let s = ReadState {
index: rs.index,
request_ctx: req.take_entries()[0].take_data(),
};
self.read_states.push(s);
} else {
let mut m = Message::new();
m.set_to(req.get_from());
m.set_msg_type(MessageType::MsgReadI... | Rust | 0 |
"There should be exactly one '%s' in dir(excel)" % str(x))
#ex.Visible = True
global selection_counter
selection_counter = 0
# we need all temps/locals allocated for worksheets to be in a separate function
# in order to be collected by GC
excel_... | Python | 1 |
from 助手 import *
分镜序号 = 0
片段列表 = 列表()
分镜文档 = '文档集合/分镜.txt'
工厂实例 = 视频工厂()
总视频序号 = 0
for 分镜 in 阅读分镜文档(分镜文档):
台词 = 分镜.获取('文案')
# 过滤特殊符号
标题 = 自动断句(台词).连文('')
纯图片名 = f'{分镜序号}-{标题}'
视频素材文件名 = 纯图片名 + '.mp4'
视频素材文件路径 = f'视频/{视频素材文件名}'
视频 = 抓取视频(视频素材文件路径)
片段列表.添加(视频)
分镜序号 += 1
#每60个视... | Python | 1 |
lowercase. Quotes must be single quotes.
For example, the previous call could also be written as `run('c c g -20, +0 c')`.
The character commands and their equivalents are here:
`c` => `click(button=PRIMARY)`
`l` => `click(button=LEFT)`
`m` => `click(button=MIDDLE)`
`r` => `click(button=RIGHT... | Python | 1 |
on_off(2):
direct = True
downloaded_file = await loop.run_in_executor(None, video_dl)
else:
proc = await asyncio.create_subprocess_exec(
"yt-dlp",
"-g",
"-f",
"best[height<=?720][w... | Python | 1 |
tattr(settings, setting)
#
# Realtime.
#
if nav_category == Category.MY:
context['category_channel'] = [cat.posts_channel.sync() for cat in following]
else:
context['category_channel'] = [nav_category.posts_channel.sync()]
context['flag_channel'] = ''
if user.is_authentica... | Python | 1 |
),
'subjectAltName': [
('DNS', value)
for value in get_subj_alt_name(x509)
]
}
def _verify_callback(cnx, x509, err_no, err_depth, return_code):
return err_no == 0
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
... | Python | 1 |
let mut lines = self.list()?;
let len_before = lines.len();
lines.push(entry_str);
lines.sort();
lines.dedup();
if lines.len() == len_before {
trace!("no new entries for meta");
return Ok(());
}
self.entries = lines;
self.sa... | Rust | 0 |
= job;
handbrake(&config, &job.src, &job.dest).await?;
}
info!("exiting handbrake process");
Ok(())
});
(HandbrakeProcess { tx }, handle)
}
pub async fn queue(&self, src: PathBuf, dest: PathBuf) -> Result<(), Error> {
self.tx.send... | Rust | 0 |
t & yield every event encountered"""
...
def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
"""Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
...
def is_stream_class_type(typ: type) -> TypeGuard... | Python | 1 |
/// Removes our finalizer from a resource object.
///
/// # Arguments
/// `name` - is the name of the resource we want to patch
/// `namespace` is the namespace of where the resource to patch lives
pub async fn remove_finalizer<T>(client: Client, resource: &T, finalizer: &str) -> OperatorResult<T>
where
T: Clone ... | Rust | 0 |
() -> Self {
Cipher {
algorithm: SymmetricAlgorithm::Aes,
mode: Some(EncryptionMode::Cfb),
key_bits: Some(128),
hash: None,
}
}
/// Constructor for 256 bit AES in CFB mode.
pub fn aes_256_cfb() -> Self {
Cipher {
algorithm:... | Rust | 0 |
le`] <br>
//! * [`ID3D11FunctionLinkingGraph::SetInputSignature`](https://docs.microsoft.com/en-us/windows/win32/api/d3d11shader/nf-d3d11shader-id3d11functionlinkinggraph-setinputsignature) → [`d3d11::FunctionLinkingGraph::set_input_signature`] <br>
//! * [`ID3D11FunctionLinkingGraph::SetOutputSignature`](https://... | Rust | 0 |
map.next_entry::<Cow<'de, str>, Value>()? {
// if k.as_ref() == "href" {
// href = Some(k);
// } else {
// meta.insert(k, v);
// }
// }
// match href
// {
// Some(href) => {
// Ok(CibouletteLinkSelector::Obj(CibouletteLinkObj {
// ... | Rust | 0 |
NewDhcpAckReceived:
*mut BOOLEAN,
NewProxyOfferReceived:
*mut BOOLEAN,
NewPxeDis... | Rust | 0 |
handle integer overflow.
lhs_val * rhs_val
}
MOpcode::OpDiv => lhs_val / rhs_val,
MOpcode::OpMod => lhs_val % rhs_val,
MOpcode::OpAnd => lhs_val & rhs_val,
MOpcode::OpOr => lhs_val | rhs_val,
MOpcode::OpXor => lhs_val ^ rhs_val,
... | Rust | 0 |
C)]` or `#[repr(transparent)]`
/// attribute, and that all of its fields have the same types. It stays on the
/// conservative side and will show an error if any of those requirements are
/// not fulfilled. If some fields have different types, but the same memory
/// layout, or are zero-sized, they can be marked with a... | Rust | 0 |
ario we give
# up on storing the total list of devices and only handle the
# delta instead.
if len(devices) > 1000:
logger.warning(
"Ignoring device list snapshot for %s as it has >1K devs (%d)",
user_id,
len(devices),
)
... | Python | 1 |
},
"html_url": {
"type": "string",
"order": 7
},
"followers_url": {
"type": "string",
"order": 8
},
"following_url": {
"type": "string",
"order": 9
},
"gists_url": {
"type": "string",
... | Python | 1 |
romSqlRow};
use crate::expression::AsExpression;
use crate::mysql::{Mysql, MysqlValue};
use crate::serialize::{self, IsNull, Output, ToSql};
use crate::sql_types::{Date, Datetime, Time, Timestamp};
// This is a type from libmysqlclient
// we have our own copy here to not break the
// public API as soon as this type ch... | Rust | 0 |
::ProtobufResult<()> {
if !self.locale.is_empty() {
os.write_string(1, &self.locale)?;
}
if !self.message.is_empty() {
os.write_string(2, &self.message)?;
}
os.write_unknown_fields(self.get_unknown_fields())?;
::std::result::Result::Ok(())
}
... | Rust | 0 |
import numpy as np
def distance_vector(x,y,total0_or_increment1=0):
"""
% (C) Nick Holschuh - Amherst College - 2022 (Nick.Holschuh@gmail.com)
% This function takes in x and y coordinates and calculates either the
% cumulative distance along the line or the incremental distance between
% points.
... | Python | 1 |
notes about this function.
pub fn stderr() -> StdWriter {
let stream = unsafe {
let io: *mut IoFactoryObject = Local::unsafe_borrow();
(*io).fs_from_raw_fd(libc::STDERR_FILENO, false)
};
StdWriter { inner: stream }
}
/// Prints a string to the stdout of the current process. No newline is e... | Rust | 0 |
&used, &mut sources, &mut rng)
}
Mode::UniformFreeTarget => choose_square_extend_target(
&board,
size,
&used,
&non_used,
&mut neighbors,
&mut rng,
),
Mode::BiasedToOrigin | Mo... | Rust | 0 |
lan(plan):
"""Generate markdown for the fixed 125-day plan."""
markdown = "# NeetCode 250 - Complete 125-Day Study Plan (All 250 Problems)\n\n"
markdown += "**Enhanced Study Strategy:**\n"
markdown += "- 2 problems per day for 125 days (both from the same category when possible)\n"
markdown += "- AL... | Python | 1 |
/// assert_eq!(id.to_string(), "10000000000000002");
/// assert_eq!("10000000000000002".parse::<TraceId>().unwrap(), id);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub struct TraceId {
pub high: u64,
pub low: u64,
}
impl TraceId {
/// Makes a randomly... | Rust | 0 |
azy queue which is run only after the
/// normal defer queue has been completely exhausted. This can be
/// used to run something at the end of this batch of processing, for
/// example to flush buffers after accumulating data.
///
/// Note that in the examples below, in general there can be any
/// number of argument... | Rust | 0 |
(reg_loc))
result.metric_values[metric_name][reg_name] = value
cocotb.logging.info(f"Metric {metric_name}/{reg_name}={value}")
return result
def stop(self):
self.finish_event.set()
def _create_test(function, name, mod, *args, **kwargs):
async def _my_test(dut)... | Python | 1 |
e(), msg.hashes).await?;
let resp_msg = MsgPushTxs { sig_txs };
self.network
.response::<MsgPushTxs>(ctx, END_RESP_PULL_TXS, resp_msg, Priority::High)
.await
}
}
//! Virtualize the Alarm interface to enable multiple users of an underlying
//! alarm hardware peripheral.
use ... | Rust | 0 |
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\RunOnce"),
(winreg.HKEY_LOCAL_MACHINE, r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce"),
# Устаревшие ключи:
(winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\RunService... | Python | 1 |
, CurrencyId, Price, Rate};
pub use module::*;
use orml_traits::MultiCurrency;
use pallet_traits::{
ControllerManager, CurrencyConverter, LiquidityPoolStorageProvider, MntManager, PoolsManager, PricesManager,
};
use sp_runtime::{
traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero},
DispatchResult, Fi... | Rust | 0 |
"""Very basic example of using a sprite image to draw a shape more similar
how you would do it in a real game instead of the simple line drawings used
by the other examples.
"""
__version__ = "$Id:$"
__docformat__ = "reStructuredText"
import math, random
import pygame
from pygame.locals import *
from pygame.color... | Python | 1 |
atch_bands = [patch_B02, patch_B03, patch_B04, patch_B08]
if check_arrays_same_size(list_patch_bands):
new_3D_array = np.zeros((patch_B02.shape[0], patch_B02.shape[1], len(list_patch_bands)))
for i, patch_for_band_i in enumerate(list_patch_bands):
... | Python | 1 |
core/tutorials/netcore-hosting)
//!
//! ## License
//! Licensed under the MIT license ([LICENSE](https://github.com/OpenByteDev/netcorehost/blob/master/LICENSE) or <https://opensource.org/licenses/MIT>)
/// Module for constants related to the coreclr hosting components or useful for interacting with them.
mod consts;
... | Rust | 0 |
from django.urls import path
from . import views
app_name = "core"
urlpatterns = [
path("sources/", views.log_sources, name="log_sources"),
path("source/<id>/", views.log_source, name="log_source"),
path("add-source/", views.add_log_source, name="add_log_source"),
path("delete-source/", views.delete_l... | Python | 1 |
IGN_METHODS: HashMap<&'static str, ForeignMethodFn> = {
let mut map = HashMap::new();
map.insert("mainMathsin(_)s", wren_foreign_method_fn!(sin));
map.insert("mainMathcos(_)s", wren_foreign_method_fn!(cos));
map
};
}
fn sin(vm: &mut VM) {
let value = vm.get_slot_double(1).unwrap... | Rust | 0 |
pixels = targets[0].numel()
for i in range(3): # ET, TC, WT
p = preds[i].bool()
t = targets[i].bool()
tp = (p & t).sum().item()
tn = (~p & ~t).sum().item()
fp = (p & ~t).sum().item()
fn = (~p & t).sum().item()
sens = tp / (tp + fn) if... | Python | 1 |
ow = df['low'].rolling(window=wr_period, min_periods=1).min()
williams_r = (highest_high - df['close']) / (highest_high - lowest_low) * -100
# 趋势过滤 (可选)
if use_trend_filter:
trend_ma = df['close'].rolling(window=trend_ma_period, min_periods=1).mean()
uptrend = df['close'] > trend_ma
... | Python | 1 |
00':
print('Invalid file signature')
sys.exit(1)
# Get body size
size = get_remaining_size(f)
# Don't count signature
size -= 0x100
cipher = AES.new(AES_KEY, AES.MODE_CTR, nonce=AES_IV[:12])
sha256 = hashlib.sha256()
while size > 0:
to_read = min(size, 0x10000)
... | Python | 1 |
"""
The parse command. Accepts a pcap file containing a PPTP capture.
Parses a packet capture for CHAPv2 handshakes, and prints details
of the handshake necessary for cracking. These include the client
and server IP addresses, the username, and the plaintext/ciphertext
pairs.
"""
import base64
import sys
from chapc... | Python | 1 |
from basicsr.utils.registry import ARCH_REGISTRY
from torch import nn as nn
from torch.nn import functional as F
from torch.nn.utils import spectral_norm
@ARCH_REGISTRY.register()
class UNetDiscriminatorSN(nn.Module):
"""Defines a U-Net discriminator with spectral normalization (SN)
It is used in Real-ESRGAN... | Python | 1 |
64),
("Rdx", DWORD64),
("Rbx", DWORD64),
("Rsp", DWORD64),
("Rbp", DWORD64),
("Rsi", DWORD64),
("Rdi", DWORD64),
("R8", DWORD64),
("R9", DWORD64),
("R10", DWORD64),
("R11", DWORD64),
("R12", DWORD64),
("R13", DWORD64),
... | Python | 1 |
>,
) -> Option<Conflict> {
debug!("trait_ref_is_knowable(trait_ref={:?})", trait_ref);
if orphan_check_trait_ref(tcx, trait_ref, InCrate::Remote).is_ok() {
// A downstream or cousin crate is allowed to implement some
// substitution of this trait-ref.
// A trait can be implementable for... | Rust | 0 |
rint username, passw, captcha
if """username is already""" in source_resp:
cj.clear()
return "Username taken, please resubmit form with a more unique username."
if """preferences""" in source_resp:
return """Oh, did you think that you were registering on my website? Too bad, I used you to solve captchas!
... | Python | 1 |
rofile for %r due to unhandled exception",
user_id,
)
await self.store.set_remote_user_profile_in_user_dir_stale(
user_id,
calculate_time_of_next_retry(
self.clock.time_msec(), ret... | Python | 1 |
def main() -> None:
print("Lucidia monitor demo placeholder")
if __name__ == "__main__":
main()
| Python | 1 |
Generate an APK set for all device configurations your app supports from your app
/// bundle
pub fn build_apks(self, bundle: &Path, output: &Path) -> BuildApks {
BuildApks::new(bundle, output)
}
/// Generate AAB file from generated zip modules to specified path.
/// Notice, that zip module... | Rust | 0 |
draw_batch : draw_batch,
horiz_offset : -(screen_size.0 as i32/8),
vert_offset : 0,
screen_size : screen_size,
}
}
}
impl <'a> System<'a> for RenderSystem {
type SystemData = (
ReadStorage <'a, Position>,
ReadStorage <'a, Renderable>,
... | Rust | 0 |
command })?;
trace!("stdout: {}", String::from_utf8_lossy(&output.stdout));
trace!("stderr: {}", String::from_utf8_lossy(&output.stderr));
ensure!(
output.status.success(),
error::CommandFailureSnafu { bin_path, output }
);
Ok(())
}
/// Dumps the memory image in `/proc/vmcore`, w... | Rust | 0 |
r"""
:param _EnvironmentId: 环境(命名空间)名称。
:type EnvironmentId: str
:param _RoleName: 角色名称。
:type RoleName: str
:param _Permissions: 授权项,最多只能包含produce、consume两项的非空字符串数组。
:type Permissions: list of str
:param _ClusterId: 必填字段,集群的ID
:type ClusterId: str
... | Python | 1 |
from flask import request
from flask_restful import Resource
from pydantic import ValidationError
from app.serializers.book import BookSchema
from app import db
class BookList(Resource):
def get(self):
books = Book.query.all()
return [BookSchema.from_orm(book).dict() for book in books]
# Resource ... | Python | 1 |
is not present in model '{modelName}'")
modelData["textures"]["shadow_" + key] = shadowTextures[modelName][key]
patched = True
if not "parent" in modelData:
if not "textures" in modelData: modelData["textures"] = {}
modelData["textures"]["marker"] = "custom/marker"
p... | Python | 1 |
len(dataloader), dice_score
def infer(model, dataloader, device):
model.eval()
result = []
with torch.no_grad():
for images in dataloader:
images = images.float().to(device)
outputs = model(images)
masks = torch.sigmoid(outputs).cpu().numpy()
masks =... | Python | 1 |
self) {}
}
impl std::fmt::Debug for dyn UserData {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", "user data")
}
}
/// Logically there are 4 types of pointers, they point to:
/// - local
/// - slice member
/// - struct field
/// - package member
/// and for pointers t... | Rust | 0 |
is.io/commands/dump>
fn dump<K>(&self, key: K) -> AsyncResult<RedisValue>
where
K: Into<RedisKey>,
{
into!(key);
async_spawn(self, |inner| async move { commands::keys::dump(&inner, key).await })
}
/// Create a key associated with a value that is obtained by deserializing the provided serialized v... | Rust | 0 |
"""
EquipmentManager クラス - EquipmentOperationHandler統合版
装備ロジックと管理
Fowler式リファクタリング:Extract Class パターン
EquipmentOperationHandlerへの委譲による重複解消
"""
from typing import Dict, List, Any, Optional, Tuple
from src.ui.window_system.equipment_types import (
EquipmentSlotType, EquipmentSlotInfo, EquipmentActionType,
Char... | Python | 1 |
from __future__ import print_function, division
import numpy as np
import imgaug as ia
from imgaug import augmenters as iaa
from imgaug import parameters as iap
def main():
nb_rows = 8
nb_cols = 8
h, w = (128, 128)
sample_size = 128
noise_gens = [
iap.SimplexNoise(),
iap.Frequen... | Python | 1 |
: *mut DWORD,
asAuthSvc: *mut *mut SOLE_AUTHENTICATION_SERVICE,
) -> HRESULT;
pub fn CoSwitchCallContext(
pNewObject: *mut IUnknown,
ppOldObject: *mut *mut IUnknown,
) -> HRESULT;
}
pub const COM_RIGHTS_EXECUTE: DWORD = 1;
pub const COM_RIGHTS_EXECUTE_LOCAL: DWORD = 2;
pub const COM_... | Rust | 0 |
]
new_clust=[1.085,0.131,0,0]
add17=[0.7,0.36,1,0]
new_design_input=[img_mem]+[clust_mem]+all_design_input[:7]+[add17]+all_design_input[7:15]+[add17]+[all_design_input[15]]+[contorl]+[sum_mem]+[ave_div]+[new_clust]
return torch.tensor(new_design_input)
def graph_link(path):
with open(path,"r") as fi... | Python | 1 |
"
super().__init_subclass__(state=state, **kwargs)
@staticmethod
def mapping_account(current_state):
"""Соотносит сцену с техническим именем услуги (UtilityName)."""
mapping = {
SceneName.ELECTRICITY.save: UtilityName.ELECTRICITY.value,
SceneName.GAS.save: Utilit... | Python | 1 |
ransfers 50 PONT to bank.
let to_spent = to_unit(50, currency_id);
RuntimeBuilder::new()
.set_balances(vec![(
Accounts::BOB.account(),
CurrencyId::PONT,
initial_balance,
)])
.build()
.execute_with(|| {
// Get initial supply.
... | Rust | 0 |
import pytest
from gusty import create_dag
##############
## FIXTURES ##
##############
@pytest.fixture(scope="session")
def leaves_from_dag_dir():
return "tests/dags/leaves_from"
@pytest.fixture(scope="session")
def dag(leaves_from_dag_dir):
dag = create_dag(
leaves_from_dag_dir,
leaf_task... | Python | 1 |
.run(
inferencer,
feed={
feed_target_names[0]: first_word,
feed_target_names[1]: second_word,
feed_target_names[2]: third_word,
feed_target_names[3]: fourth_word
},
fetch_list=fetch_targets,
retur... | Python | 1 |
limits#rate-limits):** `Medium`<br>
*
*
*
*
*
* **Parameters:**
*
* * `webinar_id: &str` -- Unique identifier of the webinar. You can retrieve the value of this field by calling the [list webinars](https://marketplace.zoom.us/docs/api-reference/zoom-api/webinars/webinars) API.
... | Rust | 0 |
i32>,
memory: Vec<i32>,
pub prog_bytecode: Vec<u8>,
}
// All of the fields beeing pub is not very good
// Maybe move this in runtime.rs?
#[derive(Debug, Default, Clone)]
pub struct StackFrame {
pub id: u32,
pub locals: Vec<i32>,
// The index of the first op in the op_stack that should be kept
p... | Rust | 0 |
_metadata()?;
let file_type = metadata.file_type();
if file_type.is_symlink() {
rename_symlink_fallback(&from, &to)?;
} else if file_type.is_dir() {
// We remove the destination directory if it exists to match the
// behavior of `fs::rename`. As far as I can ... | Rust | 0 |
t_'+str(gamma)+'_'+ str(startepoch) + '.pt'
# model_save_path = model_save_path +'(cont)'
# else:
# load_model_path = None
# if load_model_path is not None:
# model.load_state_dict(torch.load(load_model_path))
maxacc=0
for epochidx in range(1,200):
# fit(triplet_train_l... | Python | 1 |
_ = get_input_location(chat.full_chat.chat_photo)
except Exception:
dc_id = "غير معروف"
description = chat.full_chat.about
members = getattr(chat.full_chat, "participants_count", getattr(chat_obj_info, "participants_count", None))
admins = getattr(chat.full_chat, "admins_count", None)
bann... | Python | 1 |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import CourseViewSet, ModuleViewSet, LessonViewSet
router = DefaultRouter()
router.register(r'courses', CourseViewSet)
router.register(r'modules', ModuleViewSet)
router.register(r'lessons', LessonViewSet)
urlpatterns = ... | Python | 1 |
"""add_connection_id_to_source_connection
Revision ID: a8b2c3d4e5f6
Revises: 210e475985ae
Create Date: 2025-05-06 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "a8b2c3d4e5f6"
down_revision = "210e475985ae"
branch_labels = None
depends_on = No... | Python | 1 |
**self == ADC12SHT0_A::ADC12SHT0_0
}
#[doc = "Checks if the value of the field is `ADC12SHT0_1`"]
#[inline(always)]
pub fn is_adc12sht0_1(&self) -> bool {
**self == ADC12SHT0_A::ADC12SHT0_1
}
#[doc = "Checks if the value of the field is `ADC12SHT0_2`"]
#[inline(always)]
pub... | Rust | 0 |
}
}
thread_local! {
static FOO: Foo = Foo;
}
thread::scope(|scope| {
scope.spawn(|_| {
// Initialize `FOO` and then `HANDLE`.
FOO.with(|_| ());
super::pin();
// At thread exit, `HANDLE` gets dropped... | Rust | 0 |
#!/usr/bin/python
import argparse
import cookielib
import datetime
import itertools
import os
import re
import time
import urllib
import urllib2
langcodes = {
"asm": "13",
"cc": "41",
"py": "4",
"c": "11",
"java": "10",
"rb": "17",
"hs": "21",
"bf": "12",
"txt": "62",
"pl": "3",
"go": "114"
}
l... | Python | 1 |
xtern),
Function(Function),
Struct(Struct),
}
peg::parser!(pub grammar parser() for str {
pub rule module() -> Vec<(String, Item)>
= [' ' | '\t' | '\n']* items:((_ i:item() { i }) ** ([' ' | '\t' | '\n']*)) [' ' | '\t' | '\n']* { items }
rule item() -> (String, Item)
= i:extern() { (i... | Rust | 0 |
, values) = A.csc_data();
let mut atx = vec![0.0; A.nrows()];
svd_opa(A, x, &mut atx);
y.fill(0.0);
for (i, yval) in y.iter_mut().enumerate() {
for j in col_offsets[i]..col_offsets[i + 1] {
*yval += values[j] * atx[row_indices[j]];
}
}
}
// constant times a vector plus... | Rust | 0 |
(CStr::as_ptr).unwrap_or(std::ptr::null()),
);
}
}
/// Commit all the hooks that was previously registered.
///
/// Returns `false` if any error occurs.
pub fn plt_hook_commit(&self) -> bool {
self.inner
.plt_hook_commit
.map(|func| func())
... | Rust | 0 |
.await;
// Act
let newsletter_request_body = serde_json::json!({
"title": "Newsletter title",
"content": {
"text": "Newsletter body as plain text",
"html": "<p>Newsletter body as HTML</p>",
}
});
let response = app.post_newsletters(newsletter_reque... | Rust | 0 |
: V3<f32>) -> V3<f32>;
}
/// Needed to clone trait object, which are implementations of Texture trait, into threads for parralelization.
pub trait TextureClone {
/// Needed to clone trait object, which are implementations of Texture trait, into threads for parralelization.
fn box_clone(&self) -> Box<dyn Texture... | Rust | 0 |
urn response, cost, response.usage.input_tokens, response.usage.output_tokens
def _parse_assistant_tool_calls(
self, assistant_message: Message
) -> list[AssistantToolCall]:
return [
AssistantToolCall(
id=c.id,
type="function",
functio... | Python | 1 |
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
st.set_page_config(page_title="Serie A Trading Dashboard", layout="wide")
# -------------------------------
# CARICAMENTO FILE EXCEL DAL REPO
# -------------------------------
df_all = pd.read_excel("serie a 20-25.xlsx", sheet_n... | Python | 1 |
.critical("plugin_class must be subclass of Plugin")
sys.exit(4)
async def coroutine():
reader, writer = await asyncio.open_connection("127.0.0.1", port)
try:
extra_info = writer.get_extra_info("sockname")
logger.info("Using local address: %s:%u", *extra_info)
... | Python | 1 |
32,
) -> Result<Vec<(IdentityKey, RewardedSetNodeStatus)>, ContractError> {
let start = start_after.map(Bound::exclusive);
let rewarded_set = storage::REWARDED_SET
.prefix(height)
.range(storage, start, None, Order::Ascending)
.take(limit as usize)
.collect::<StdResult<_>>()?;
... | Rust | 0 |
from models.teacher import TeacherModel
from flask import Flask,render_template,jsonify,request,Blueprint
teacher = Blueprint('teacher',__name__)
teacher_model = TeacherModel()
@teacher.route('/')
def get_teachers():
data = teacher_model.get_teachers()
return jsonify(data),200 | Python | 1 |
Momentum update of the key encoder
"""
for param_q, param_k in zip(self.decoder.parameters(), self.decoder_gt.parameters()):
param_k.data = param_k.data * self.m + param_q.data * (1.0 - self.m)
def regroup(self, x, record_len):
cum_sum_len = torch.cumsum(record_len, dim=... | Python | 1 |
"""
Exercício
Peça ao usuário para digitar seu nome
Peça ao usuário para digitar sua idade
Se nome e idade forem digitados:
Exiba:
Seu nome é {nome}
Seu nome invertido é {nome invertido}
Seu nome contém (ou não) espaços
Seu nome tem {n} letras
A primeira letra do seu nome é {... | Python | 1 |
ers_and_parameters(db):
"""Test custom headers and parameters in requests."""
# Test with custom parameters in get request
doc = db.save({'_id': 'custom_params_test', 'data': 'test'})
# Test getting document with custom parameters
# Note: revs_info parameter should be passed to the underlying r... | Python | 1 |
_step: int, flux: flux_models.Flux
):
def sd_saver(ckpt_file, epoch_no, global_step):
sai_metadata = train_util.get_sai_model_spec(None, args, False, False, False, is_stable_diffusion_ckpt=True, flux="dev")
save_models(ckpt_file, flux, sai_metadata, save_dtype, args.mem_eff_save)
train_util.sav... | Python | 1 |
;
((self.bits >> OFFSET) & MASK as u32) as u8
};
AmR { bits }
}
#[doc = "Bits 8:15 - CLUT size"]
#[inline(always)]
pub fn cs(&self) -> CsR {
let bits = {
const MASK: u8 = 255;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u... | Rust | 0 |
csoundStopUDPConsole(self.engine.csound);
}
}
/* Engine Attributes functions implmentations ********************************************************* */
/// # Returns
/// The number of audio sample frames per second.
pub fn get_sample_rate(&self) -> f64 {
unsafe { csound_sys::csound... | Rust | 0 |
# Copyright (c) 2018-2023, NVIDIA Corporation
# 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 condit... | Python | 1 |
ize| *x as f32).collect::<Vec<_>>();
assert_eq!(expected, matrix);
}
#[test]
fn test_unpack_hires_matrix(){
_test_unpack_hires_matrix();
}
fn _test_unpack_hires_matrix(){
let input_spatial = vec![3, 2];
let factors = vec![2, 2];
let output_spatial = input_spatial.iter().zip(factors.iter()).map(|(x, f)| x*f).c... | Rust | 0 |
2EB907C6163BE38C98437"),
&hex!(
"5810E6FD25874022E80361A478E3E9CF48
4AB04F447EFFF6F0A477CC2FC9BF548944"
),
);
}
#[test]
fn test_vector_21() {
test_vector::<U10, [u8; 16]>(
hex!("D7828D13B2B0BDC325A76236DF93CC6B"),
... | Rust | 0 |
("bg_max_count", 5000))
for bar in bars_left:
bg.update(bar)
_sigs = []
cs = CzscSignals(bg, signals_config=signals_config, **kwargs)
cs.cache.update({'gsc_kwargs': kwargs})
for bar in tqdm(bars_right, desc=f'generate signals of {bg.symbol}'):
cs.update_signals(bar)
_sigs.ap... | Python | 1 |
ckServerState, id: usize) -> Result<bool, String> {
let mut mocks = state.mocks.lock().unwrap();
if let Some(m) = mocks.get(&id) {
if m.is_static {
return Err(format!("Cannot delete static mock with ID {}", id));
}
}
let result = mocks.remove(&id);
log::debug!("Deleted m... | Rust | 0 |
})
],
Box::new(SahaType::Void),
print_err
));
fns.push(create_core_function(
"print_err_line",
vec![
("text", FunctionParameter {
name: "text".to_string(),
param_type: Box::new(SahaType::Str),
default: V... | Rust | 0 |
#!/usr/bin/env python3
"""Plots motor data for a 775pro motor."""
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from bookutil import latex
if "--noninteractive" in sys.argv:
mpl.use("svg")
def main():
"""Entry point."""
i_stall = 134
i_free = 0.7
rpm_f... | Python | 1 |
"pre_checkout_query",
"shipping_query",
]
);
}
data => panic!("Unexpected request data: {:?}", data),
}
let method = SetWebhook::new("url").add_allowed_update(AllowedUpdate::Message);
assert_eq!(... | Rust | 0 |
();
let suba = simd_sub(zero, a.as_f64x8());
let subc = simd_sub(zero, c.as_f64x8());
macro_rules! call {
($imm4:expr) => {
vfmadd132pd(suba, b.as_f64x8(), subc, $imm4)
};
}
let r = constify_imm4_round!(rounding, call);
transmute(r)
}
/// Multiply packed double-preci... | Rust | 0 |
from sklearn.linear_model import LogisticRegression
from LogisticRegression import *
import numpy as np
import pandas as pd
import time
trainData = np.array(pd.read_table('../dataset3/train.txt',header=None,encoding='gb2312',delim_whitespace=True))
testData = np.array(pd.read_table('../dataset3/test.txt',header=None,e... | Python | 1 |
import numpy as np
def grassmann_map(x, base_point):
if base_point.shape[0] == 0 or base_point.shape[1] == 0:
return base_point
elif np.isnan(x).any():
# Return an object with the same shape as x filled with nan
return np.full(x.shape, np.nan)
else:
u, s, vt = np.linalg.svd... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.