text string | label_name string | labels int64 |
|---|---|---|
bmission_data
os.remove(submission_file)
@pytest.fixture(scope='function')
def submission_empty_value():
submission_data = dict(
database_url='https://www.igdb.com/games/goldeneye-007',
youtube_theme_url='',
)
submission_file = create_submission_file(data=submission_data)
yield ... | Python | 1 |
memory_key="chat_history",
return_messages=True,
output_key="answer"
)
# qa = RetrievalQA.from_chain_type(
# llm=self.llm,
# chain_type="stuff",
# retriever=retriever,
# return_source_documents=True
# )
qa =... | Python | 1 |
) -> i32 {
return a * b;
}extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
use syn::{ parse_macro_input, FnArg, ItemFn, Pat };
#[proc_macro_attribute]
pub fn login_required(_: TokenStream, func: TokenStream) -> TokenStream {
let func = parse_macro_input!(... | Rust | 0 |
(None) });
let b = a.clone().downgrade();
*a.borrow().x.borrow_mut().get() = Some(b);
}
#[start]
fn main(_: int, _: **u8) -> int {
test_live();
test_dead();
weak_self_cyclic();
0
}
use core::ops::Mul;
use crate::vector::*;
pub struct Matrix3x3 {
pub m:[[f32;3];3],
}
impl Matrix3x3 {
pub cons... | Rust | 0 |
_bigint::BigUint;
use functions::*;
use super::CkFrom;
pub const CK_TRUE: CK_BBOOL = 1;
pub const CK_FALSE: CK_BBOOL = 0;
//// an unsigned 8-bit value
pub type CK_BYTE = u8;
pub type CK_BYTE_PTR = *mut CK_BYTE;
/// an unsigned 8-bit character
pub type CK_CHAR = CK_BYTE;
pub type CK_CHAR_PTR = *mut CK_CHAR;
/// an... | Rust | 0 |
if conf & 8 > 0 {uart4.cr1.modify(|_, w| w.m().m9());}
if conf & 4 > 0 {uart4.cr2.modify(|_, w| w.stop().stop2());}
if conf & 3 == 1 {uart4.cr1.modify(|_, w| w.pce().enabled());}
else if conf & 3 == 2 {uart4.cr1.modify(|_, w| {w.ps().odd(); w.pce().enabled()});}
uart4.cr1.modify(... | Rust | 0 |
import os
from django.conf import settings
from celery import Celery
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Planning.settings')
app = Celery('Planning')
# Using a string here means the worker doesn't have to serialize
# the configuration ... | Python | 1 |
tgreSQL test container...")
try:
compose_file = project_root / "docker-compose.test.yml"
subprocess.run(
['docker-compose', '-f', str(compose_file), 'down'],
capture_output=True,
timeout=30
)
print("✅ PostgreSQL test... | Python | 1 |
t_universal_segmentation(mask2former_for_segmentation)
tolerance = 3e-1
high_tolerance_models = [
"mask2former-swin-base-IN21k-coco-instance",
"mask2former-swin-base-coco-instance",
"mask2former-swin-small-cityscapes-semantic",
]
if model_name in hig... | Python | 1 |
j + 1;
}
}
for i in 1..len_pat {
for (j, item) in str_a.iter().enumerate().skip(1) {
if str_pat[i] == ' ' {
if matrix[i - 1][j - 1] == 0 {
matrix[i][j] = matrix[i][j - 1];
} else {
matrix[i][j] = matrix[i - 1][... | Rust | 0 |
a:
return ""
# Remove control characters except tab, newline, carriage return
sanitized = "".join(char for char in data if ord(char) >= 32 or char in "\t\n\r")
# Replace common injection patterns
sanitized = sanitized.replace("\n", "\\n").replace("\r", "\\r").replace("\t", ... | Python | 1 |
for _ in 0..10000 {
let symbol: u8 = rng.gen_range(0, 6);
let position: usize = rng.gen_range(0, data.len()+1);
inserted.push(symbol);
positions.push(position);
data.insert(position, symbol);
println!("RANDOM_DATA: {:?}", data);
println... | Rust | 0 |
# (C) Copyright 2017, 2020-2021 by Rocky Bernstein
"""
CPython 3.3 bytecode opcodes
This is a like Python 3.3's opcode.py with some classification
of stack usage.
"""
from xdis.opcodes.base import (
def_op,
extended_format_CALL_FUNCTION,
extended_format_RAISE_VARARGS_older,
extended_format_RETURN_VALU... | Python | 1 |
#####################################################
#
# 改为WGAN-GP
#####################################################
import os
import sys
import socket
import pickle
from threading import local
import numpy as np
from matplotlib import pyplot as plt
from datetime import datetime, timedelta
from config import get_... | Python | 1 |
::Borrow<Self>
{
/// The type of the iterator
type Iter: Iterator;
/// Constructs an iterator that iterates over every variant in the defined order
fn variants() -> Self::Iter;
}
/// Derive this trait for an enum automatically using `#[derive(EnumVariantName)]`
///
/// # Example with derive
///
/// ```rust,ignore... | Rust | 0 |
ataset_name = "adult"
model_fit_helper.fit_and_validate_dataset(dataset_name=dataset_name, model=DummyModel(), fit_args=fit_args)
def test_dummy_multiclass_model(model_fit_helper):
fit_args = dict()
dataset_name = "covertype_small"
model_fit_helper.fit_and_validate_dataset(dataset_name=dataset_name, m... | Python | 1 |
nickel::router::http_router::HttpRouter;
use nickel::status::StatusCode::{ BadRequest };
use rustc_serialize;
use schedule_gen::contract as lib_contracts;
use schedule_gen;
use std::error::Error;
pub struct ApiController;
impl ApiController{
pub fn initialize(router: &mut Router) {
// GENERATE SCHEDULE
... | Rust | 0 |
"""
The jsonschema CLI is now deprecated in favor of check-jsonschema.
"""
from jsonschema.cli import main
main()
| Python | 1 |
from .. import IconBase
class IconUnplug(IconBase):
class_name = "lucide lucide-unplug"
svg_data = {
"attrs": {
"width": "24",
"height": "24",
"view_box": "0 0 24 24",
"fill": "none",
"stroke": "currentColor",
"stroke_width": "2",
"stroke_linecap": "... | Python | 1 |
# coding: utf-8
# Copyright (c) 2016, 2025, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | Python | 1 |
import pandas as pd
import google.generativeai as genai
import time
import configparser
import streamlit as st
class Sentiment:
def __init__(self):
config = configparser.ConfigParser()
config.read("config.ini")
api_key = config["GeminiAPI"]["bearer_token"]
genai.configure(api_key=ap... | Python | 1 |
mut key_file: File,
passphrase: &str,
) -> Result<(u32, KeyBuffer), OpenDirectoryError> {
let mut iv = [0u8; IV_SIZE];
let mut salt = [0u8; SALT_SIZE];
let mut expected_mac = [0u8; MAC_LENGTH];
let mut version = [0u8; 1];
let mut encrypted_key = vec![];
... | Rust | 0 |
#
# 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, software
# distributed ... | Python | 1 |
ush()
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice]) -> io::Result<usize> {
self.inner.write_vectored(bufs)
}
#[cfg(can_vector)]
#[inline]
fn is_write_vectored(&self) -> bool {
self.inner.is_write_vectored()
}
#[inline]
fn write_all(&mut self, buf: ... | Rust | 0 |
import os
from ament_index_python import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import ComposableNodeContainer, Node
from launch_ros.descriptions import ComposableNode
from launch.actions import DeclareLaunchArgument
# from launch.substitutions import LaunchConfigurat... | Python | 1 |
f term not in excludes]
Miscs.show_removed("filter terms", len(
terms), len(new_terms), time() - st)
terms = new_terms
return terms
@staticmethod
@abc.abstractmethod
def to_expr(term):
pass
@staticmethod
@abc.abstractmethod
def inv_cls(te... | Python | 1 |
;
Ok(())
}
pub fn unschedule_command_args() -> clap::App<'static, 'static> {
clap::SubCommand::with_name("unschedule")
.about("Unschedule a previously scheduled publication, using `atrm`")
.args(&args::get_config_args())
.arg(
clap::Arg::with_name("SLUG")
.re... | Rust | 0 |
identical(left: Iterable[Any], right: Iterable[Any]) -> bool:
"""
Check that the items of `left` are the same objects as those in `right`.
>>> a, b = object(), object()
>>> all_identical([a, b, a], [a, b, a])
True
>>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is ... | Python | 1 |
from datetime import datetime
from typing import Any, Generic, Sequence, TypeVar
from pydantic import ConfigDict
from app.models import ComponentStatus, Organisation, User
from app.schemas.base import BaseSchema
from app.schemas.models import FormSchema, IncidentRoleSchema, OrganisationSchema, StatusPageComponentSche... | Python | 1 |
sqrt_not_squared() {
usize_sqrt(3);
}
}
<filename>client/examples/cli/main.rs
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
mod arguments;
use arguments::*;
use clap::Clap;
use iota_stronghold::{home_dir, naive_kdf, Location, RecordHint, StatusMessage, Stronghold};
use std::{... | Rust | 0 |
min_manhattan_distance = this_manhattan_distance;
}
let this_combined_steps = stored_steps + num_steps;
if this_combined_steps < min_combined_steps || min_combined_steps == 0 {
min_combined_steps = this_combined_steps;
... | Rust | 0 |
inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn encode(&self) -> Vec<u8> {
let mut buf = BytesMut::with_capacity(self.len());
varintbuf::encode(self.len() as u64, &mut buf);
for i in 0..self.len() {
if let Some(bucket) = self.bucket(i) {
... | Rust | 0 |
code_info",
|m: &Code| { &m.code_info },
|m: &mut Code| { &mut m.code_info },
));
fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>(
"code_bytes",
|m: &Code| { &m.code_b... | Rust | 0 |
# Copyright (c) 2021 PaddlePaddle Authors. 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 |
announce new blocks using headers message
pub fn on_sendheaders(&self, peer_index: PeerIndex, _message: types::SendHeaders) {
trace!(target: "sync", "Got `sendheaders` message from peer#{}", peer_index);
self.peers.set_block_announcement_type(peer_index, BlockAnnouncementType::SendHeaders);
}
/// When peer asks... | Rust | 0 |
arse_more_than_one_space_destination_address() {
let text = "PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\n";
assert_eq!(
Header::try_from(text),
Err(ParseError::InvalidDestinationAddress(
"".parse::<Ipv4Addr>().unwrap_err()
))
);... | Rust | 0 |
from __future__ import division, absolute_import, print_function
import os
import math
from numpy.testing import *
from numpy import array
import util
def _path(*a):
return os.path.join(*((os.path.dirname(__file__),) + a))
from numpy.f2py.crackfortran import _selected_int_kind_func as selected_int_kind
from nu... | Python | 1 |
n_method_id,
"prompt_injection_applied": prompt_injection_applied,
"response_corruption_applied": response_corruption_applied,
"injection_insertion_point": injection_insertion_point,
}
append_answer(annotated_example, answers_file)
def get_examples_to_answer(answers_file: str, eval_ds:... | Python | 1 |
Some(Asm::JP(op.into())),
| (0x2, _, _, _) => Some(Asm::CALL(op.into())),
| (0x3, x, _, _) => Some(Asm::SEC(x.into(), op as u8)),
| (0x4, x, _, _) => Some(Asm::SNEC(x.into(), op as u8)),
| (0x5, x, y, 0x0) => Some(Asm::SER(x.into(), y.into())),
| (0x6, x,... | Rust | 0 |
pub(crate) fn peek_type(&self, name: &str) -> Option<EventTypeRef> {
let l_name = name.to_lowercase();
let (_, ret) = self.check_type(l_name.as_str());
ret
}
}
// This file is part of rdma-core. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this... | Rust | 0 |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Base class representing GTest test packages."""
# pylint: disable=R0201
class TestPackage(object):
"""A helper base class for both APK and stand-... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Web指纹识别插件
用于检测Web服务器、框架、CMS等技术栈信息
"""
import re
import json
import logging
import requests
from typing import Dict, List, Any, Optional
from urllib.parse import urljoin
from pathlib import Path
from plugins.base_plugin import WebRiskPlugin
class FingerprintScanner(... | Python | 1 |
> SolverResult {
let arg = match *args {
[arg] => arg,
_ => panic!("Wrong number of arguments"),
};
log::trace!("trying goal {}", vars.dbg(arg, ctx));
let mut new_vars = vars.backtrackable();
let mut state = State {
ctx,
vars: &mut new_vars,
runner: &mut OneS... | Rust | 0 |
rs(log_dir, exist_ok=True)
png_path = os.path.join(log_dir, 'downloaded_image.png')
with open(png_path, 'wb') as f:
f.write(img_bytes)
# 再读取文件转base64
... | Python | 1 |
# 不将html存入数据库 而是存入 磁盘文件中
# data['html'] = r
try:
r_data = DecodeArticle.part_of_html(r_data)
# 提取文档中的html中的文本 并且去掉换行
data['article'] = html_to_text.handle(r_data).replace('\n','')
except Exception as e:
try:
... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# 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... | Python | 1 |
def generate_summary(user_skills, experience):
return "Experienced professional with skills in Python, Flask, and PostgreSQL..."
| Python | 1 |
perator" not in c["name_match"]
):
return candidates
return [best_match] if best_match else candidates
def prefer_railway_station(candidates: list[CandidateDict]) -> list[CandidateDict]:
"""Pick railway station from candidates."""
if len(candidates) == 1:
return candidates
... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2025/4/5 17:00
Desc: 东方财富网-数据中心-经济数据-中美国债收益率
https://data.eastmoney.com/cjsj/zmgzsyl.html
"""
import pandas as pd
import requests
from akshare.utils.tqdm import get_tqdm
def bond_zh_us_rate(start_date: str = "19901219") -> pd.DataFrame:
"""
东方财富网-数据中心-经济... | Python | 1 |
import numpy as np
#creating identity matrix
identity = np.eye(5)
print(f"Identity Matrix: {identity}") | Python | 1 |
"""ゲーム管理システム - リファクタリング版
Fowlerのリファクタリング手法を適用:
- Extract Class: SceneManager, EventBus
- Move Method: シーン固有のメソッドを各シーンに移動
- Replace Data Value with Object: イベント駆動アーキテクチャ
"""
import pygame
import sys
import random
from typing import Dict, List, Any, Optional
from . import dbg_api
from src.core.config_manager import con... | Python | 1 |
several consistency checks on the database for this transaction.
// An error is returned if any inconsistency is found.
//
// It can be safely run concurrently on a writable transaction. However, this
// incurs a high cost for large databases and databases with a lot of subbuckets
// because of cac... | Rust | 0 |
_err(Error::DbError) {
Ok(conn_ref) => conn_ref,
Err(err) => return err.into(),
};
// Memcache supports multiple tokens but to preserve legacy behavior
// we must purge any existing tokens AFTER generating new ones
let access_tokens = match AccountToken::list(account_id, &*conn).map_err... | Rust | 0 |
x = np.concatenate([x, np.zeros(target_length - len(x))])
else:
x = x[:target_length]
assert len(x) == target_length, print(len(x), target_length)
return x
def calculate_maxflen(flist):
max_flen = 0
for h5f in flist:
with h5py.File(h5f, "r") as fp:
if max_flen <... | Python | 1 |
itness, non_member, additions, removals, public_info)
}
#[wasm_bindgen(js_name = generateMembershipProvingKey)]
pub fn generate_membership_proving_key(
label: Option<Vec<u8>>,
) -> Result<js_sys::Uint8Array, JsValue> {
set_panic_hook();
let label = label.unwrap_or_else(|| random_bytes());
let prk = Mem... | Rust | 0 |
Text),
/// [`SB_GETTEXTLENGTH`](crate::msg::sb::GetTextLength) and
/// [`SB_SETTEXT`](crate::msg::sb::SetText) drawing operation (`u16`).
->
NONE, 0
OWNERDRAW, 0x1000
NOBORDERS, 0x0100
POPOUT, 0x0200
RTLREADING, 0x0400
NOTABPARSING, 0x0800
}
const_type! { SC, u32,
/// [`WM_SYSCOMMAND`](crate::ms... | Rust | 0 |
uot;:1744601216,"func_flag":32770,"is_send_all":true,"is_published":0},"sent_status":{"total":78430,"succ":78430,"fail":0,"progress":100,"userprotect":0},"sent_result":{"msg_status":2,"refuse_reason":... | Python | 1 |
.add_argument(
"--options",
nargs="+",
help="override some settings in the used config, the key-value pair "
"in xxx=yyy format will be merged into config file (deprecate), "
"change to --cfg-options instead.",
)
args = parser.parse_args()
return args
if __name__ ==... | Python | 1 |
num.and_then(|len| -> Result<Vec<u8>> {
if len == 0 {
Ok(Vec::new())
} else {
mayfail! {
status =<< result;
header_len =<< status;
let resp_body = &resp[header_len..];
base64 =<< std::str::from_utf8(resp_body);
... | Rust | 0 |
UTF-16LE. This is only"]
#[doc = " modified if |buflen| is longer than the length of the key."]
#[doc = " Optional, pass null to just retrieve the size of the buffer"]
#[doc = " needed."]
#[doc = " buflen - length of the buffer."]
#[doc = " out_bu... | Rust | 0 |
x, k in enumerate(other_classes):
adv_x_i.grad = None
# Only retain graph if not the last class
retain_graph = k_idx < len(other_classes) - 1
logits[0, k].backward(retain_graph=retain_graph)
# Count as one gradient call
self... | Python | 1 |
integer",
},
}
})
);
}
struct DiffMetricPlugin {}
impl Plugin for DiffMetricPlugin {
fn fetch_metrics(&self) -> Result<HashMap<String, f64>, String> {
let mut metrics = HashMap::new();
let now = time::SystemTime::now()
.duration_since(time::UNIX_... | Rust | 0 |
"""Audio signal feature extraction utilitary functions."""
import librosa
import numpy as np
def extract_features(signal, freq=16000, n_mfcc=5, size=512, step=16):
"""Extract MFCC features from an audio signal.
Args:
signal (np.ndarray): audio signal
freq (int, optional): MFCC features sampli... | Python | 1 |
rom the currently active account in multi-session apps.
after_switch_session_url: Full URL or path to navigate to after a successful account change in multi-session apps.
default_open: Controls whether the <UserButton /> should open by default during the first render. Defaults to None.
user_prof... | Python | 1 |
t": "Where are you currently located?"
}}
}}
User message: "I'm in Berlin right now."
JSON:
{{
"Current Location": "Berlin"
}}
---
**Example C**
Previous Turns:
{{
{{
"role": "assistant", "content": "Do you have any dietary restrictions?"
... | Python | 1 |
ext(iter(filtered_map.items()))
new_cards = [
Card(suit, rank) for suit in first_value for rank in [first_key]
]
return (True, new_cards)
return (False, [])
if __name__ == "__main__":
cards_one = [
Card(Suit.Spades... | Python | 1 |
.len() as isize;
let (mut il, mut ir) = (- i_len / 2, i_len / 2);
let (mut jl, mut jr) = (- j_len / 2, j_len / 2);
let (mut kl, mut kr) = (0, 0);
let (mut ll, mut lr) = (0, 0);
for (i, line) in buffer.trim().split('\n').enumerate() {
for (j, cell) in line.trim().chars().enumerate() {
... | Rust | 0 |
from functools import wraps
from time import time
def is_video(ext: str):
"""
Returns true if ext exists in
allowed_exts for video files.
Args:
ext:
Returns:
"""
allowed_exts = ('.mp4', '.webm', '.ogg', '.avi', '.wmv', '.mkv', '.3gp')
return any((ext.endswith(x) for x in al... | Python | 1 |
ype_guid::*;
pub use type_limits::*;
pub use type_name::*;
pub use type_namespaces::*;
pub use type_tree::*;
<gh_stars>1-10
use crate::io::read_lines;
use itertools::Itertools;
use std::{
collections::{HashMap, HashSet},
fmt::Display,
ops::Sub,
};
crate::test::test_part!(test1, part1, 570915);
crate::test::test_par... | Rust | 0 |
def custom_apriori(columns):
tables_with_columns = {}
# Récupérer les tables associées à chaque colonne spécifiée
for column in columns:
cursor = conn.cursor()
cursor.execute(f"SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = '{column}'")
rows = cursor.... | Python | 1 |
Pallet::withdraw_set_fee(&ALICE));
assert_eq!(hdx_balance_before - 1029, Currencies::free_balance(HDX, &ALICE));
});
}
#[test]
fn withdraw_set_fee_should_work() {
ExtBuilder::default().base_weight(5).build().execute_with(|| {
assert_ok!(PaymentPallet::set_currency(
Origin::signed(AL... | Rust | 0 |
safe
match event
{
super::input::Event::MouseMove(x,y, _dx,_dy) => {
S_MOVE_STATE.lock().update( x, y );
},
event @ _ =>
match S_EVENT_QUEUE.push(event)
{
Ok(_) => {},
Err(event) => log_notice!("Dropping event {:?}, queue full", event),
},
}
// > Prod a worker (e.g. the render thread) in an atomic ... | Rust | 0 |
from PyQt6 import QtWidgets
from models.battery_model import BatteryModel
from views.battery_view import BatteryView
from controllers.battery_controller import BatteryController
class PowerBar(QtWidgets.QWidget):
def __init__(self, steps=5, update_interval=8000, use_mock=True, *args, **kwargs):
super()... | Python | 1 |
unchecked {
use crate::{Quaternion, UnitQuaternion};
use glam::{DQuat, Quat};
impl From<Quat> for UnitQuaternion<f32> {
#[inline]
fn from(e: Quat) -> UnitQuaternion<f32> {
UnitQuaternion::new_unchecked(Quaternion::from(e))
}
}
impl From<DQuat> for UnitQuaternio... | Rust | 0 |
device}
# logging to TensorBoard and write checkpoints (in timesteps)
cfg["experiment"]["write_interval"] = 800
cfg["experiment"]["checkpoint_interval"] = 8000
cfg["experiment"]["directory"] = "runs/jax/Ant"
agent = DDPG(models=models,
memory=memory,
cfg=cfg,
observation_space=en... | Python | 1 |
b: usize) -> usize {
return a + b;
}
let results = foo_vec(vec![1,2,3], vec![1,2,3]);
assert_eq!(vec![2,4,6], results);
}
#[test]
#[should_panic(expected = "Input vectors of not the same length to vectorized function foo_vec")]
fn unequal_vector_inputs() {
#[auto_vec]
fn foo(a: usize,... | Rust | 0 |
al_shape_to_tensor(
[3, None])))
self.assertAllEqual([3, -1], sess.run(convert.partial_shape_to_tensor(
constant_op.constant([3, -1], dtype=dtypes.int64))))
self.assertAllEqual([-1, -1], sess.run(convert.partial_shape_to_tensor(
tensor_shape.TensorShape([None, None]))))
... | Python | 1 |
}
// ハッシュを作るのに使う
let mut ss_hash_builder = Movement::default();
ss_hash_builder.destination = ms_dst;
// 移動元の升
let mut mv_src_hashset: HashSet<umasu> = HashSet::new();
// +----------------+
// | 盤上(成らず) |
// +----------------+
// 現局面を読取専用で取得し、ロック。
insert_narazu_src_by_ms_k... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" List translatable projects """
from __future__ import absolute_import
from __future__ import unicode_literals
from __fu... | Python | 1 |
= num1.length, num2.length <= 200
* num1 and num2 consist of digits only.
* Both num1 and num2 do not contain any leading zero, except the number 0 itself.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/multiply-strings/
// discuss: https://leetcode.com/problems/multiply-strings/discuss/?c... | Rust | 0 |
'kv_cache_theoretical': -1,
'activations_theoretical': -1,
'other_theoretical': -1,
'total_theoretical': -1,
'scenario': scenario
}
writer.writerow(error_result)
csvfile.f... | Python | 1 |
:Ap
|| uf == Uf::Df
|| uf == Uf::Pi
|| uf == Uf::Rj
|| uf == Uf::Ro
|| uf == Uf::Se
|| uf == Uf::To)
{
return Err(WebServicesBuilderError::UfSemWebServiceConsultaCadastro);
}
// URL de amb... | Rust | 0 |
{
let q = if l < 0.5 {
l * (1.0 + s)
} else {
l + s - l * s
};
let p = 2.0 * l - q;
r = hue2rgb(p, q, h + 1.0 / 3.0);
g = hue2rgb(p, q, h + 0.0 / 3.0);
b = hue2rgb(p, q, h - 1.0 / 3.0);
};
[
(r * 255.0).round() as u8,
(g * 255.0).round() as u8,
(b * 255.0).roun... | Rust | 0 |
# Этот файл был сгенерирован тНавигатор v23.4-5689-g1082f6c.
# Copyright (C) Рок Флоу Динамикс 2005-2024.
# Все права защищены.
# This file is MACHINE GENERATED! Do not edit.
#api_version=v0_0_117
from __main__.tnav.workflow import *
from tnav_debug_utilities import *
from datetime import datetime, timedelta
de... | Python | 1 |
squash
git checkout master
git merge squashme --squash && git commit --no-edit
git branch -D squashme
# rebaseme
git checkout -b rebase-tmp rebaseme
git rebase master
git checkout master
git merge rebase-tmp --ff-only
... | Rust | 0 |
x: x.url)
return ips_res
def format_host_strings(ip_list: list[URLIPMapping]) -> str:
"""将列表中的字典中的IP地址和URL转换为host格式的字符串 并确保每个URL的开头对齐。
Parameters:
ip_list (List[Dict[str, str]]): 包含URL和IP地址的字典列表。
Returns:
str: 包含host格式的字符串。
"""
host_strings: list[str] = []
max_ip_length =... | Python | 1 |
Some(_) => {
let (db_name, conn) = create_conn(datasource, true).await?;
conn.create_database(&db_name).await?;
Ok(format!("Database '{}' created successfully.", db_name))
}
None => Err(CliError::Other(anyhow::anyhow!(
"Invalid URL or unsupported connector... | Rust | 0 |
::P),8);
assert!(!b.in_check());
}
#[test]
fn move_seq_1() {
let mut b = board::Board::start_pos();
let p = PreMoveInfo {
src: SQ(12),
dst: SQ(28),
flags: MoveFlag::DoublePawnPush
};
let m = BitMove::init(p);
b.apply_move(m);
let p = PreMoveInfo {
src: SQ(5... | Rust | 0 |
from_big_endian(&self.r[..]));
s.append(&U256::from_big_endian(&self.s[..]));
}
}
impl Decodable for EIP2930Transaction {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if rlp.item_count()? != 11 {
return Err(DecoderError::RlpIncorrectListLen)
}
Ok(Self {
... | Rust | 0 |
from research_assist.gsuite.base.GSuiteService import GSuiteService
from googleapiclient.discovery import build
from typing import Any
class GoogleDriveService(GSuiteService):
"""
A service class for interacting with Google Drive API.
Inherits from GSuiteService and implements the methods to retrieve
... | Python | 1 |
x,
prev_trans_ix, &mut team_mdp_states,
&mut team_mdp_transitions, num_agents, num_tasks,
&loc_prod.jacc[..], &loc_prod.acc[..], &loc_prod.dead[..],
... | Rust | 0 |
um_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m... | Python | 1 |
feature.set_value(None)
await dev.update()
assert dev.features["alarm"].value is False
# test set sound
feature = dev.features.get("alarm_sound")
assert feature
new_sound = (
alarm.alarm_sounds[0]
if alarm.alarm_sound != alarm.alarm_sounds[0]
... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This script downloads the tokenizer models of the specified models from Huggingface and
# generates the get_vocab_base_pre() function for convert_hf_to_gguf.py
#
# This is necessary in order to analyze the type of pre-tokenizer used by the model and
# provide the necess... | Python | 1 |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward/blob/main/LICENSE
from __future__ import annotations
import pytest # noqa: F401
import awkward as ak
def test():
y = ak.from_iter([[{"x": 1, "y": 1.1}], [], [{"x": 2, "y": 2.2}]])
y_tt = ak.Array(y.layout.to_typetracer())
x_tt = ak.rave... | Python | 1 |
se:
print(f"❌ Stream down: {cam['name']}")
time.sleep(2) # Small delay between cameras to prevent overload
if __name__ == "__main__":
print("📡 Stream checker scheduler running...")
interval_type = os.getenv("INTERVAL_TYPE", "seconds").lower()
interval_duration = int(os.getenv... | Python | 1 |
).is_dir() {
return Err(ZipError::FileNotFound);
}
let path = Path::new(outer_zip);
let file = File::create(&path).unwrap();
let walkdir = WalkDir::new(outer_dir.to_string());
let it = walkdir.into_iter();
compress::zip_dir(&mut it.filter_map(|e| e.ok()), outer_dir, file, me... | Rust | 0 |
PROPERTY_LIST_SERVICE_E_SUCCESS:
property_list_service_error_t = 0;
pub const property_list_service_error_t_PROPERTY_LIST_SERVICE_E_INVALID_ARG:
property_list_service_error_t = -1;
pub const property_list_service_error_t_PROPERTY_LIST_SERVICE_E_PLIST_ERROR:
property_list_service_error_t = -2;
pub const prop... | Rust | 0 |
(IliaQuest, HORSE_CALL) => ILIAS_CHARM,
(SkyBook, SKY_BOOK_PARTLY_FILLED) => SKY_BOOK_EMPTY,
(SkyBook, SKY_BOOK_FILLED) => SKY_BOOK_PARTLY_FILLED,
_ => EMPTY,
};
inventory.set_by_slot_id(item_slot, new_item_id);
} else if dpad_right {
let new_ite... | Rust | 0 |
dom {
thread_rng().fill(&mut data[..]);
}
if let Some(tg) = transaction_generator.as_mut() {
let tx = tg.generate(payer, &rpc_client);
info!("{:?}", tx);
data = bincode::serialize(&tx).unwrap();
}
let res = s... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.