text
string
label_name
string
labels
int64
Descriptor { async fn get_id(&self, registry_canister: &RegistryCanister) -> SubnetId { match self { Self::Id(p) => SubnetId::new(*p), Self::Index(i) => { let subnets = get_subnet_ids(registry_canister).await; *(subnets.get(*i) .unw...
Rust
0
/// * The memory referenced by the returned slice must not be mutated for the duration /// of lifetime `'a`, except inside an `UnsafeCell`. /// /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`. /// See the safety documentation of [`pointer::offset`]. /// /// # Cavea...
Rust
0
urce * amount } else { 0.0 }; if source_unit.as_str() == "c" { res += 32.0; } else if source_unit.as_str() == "k" { res -= 459.67; } ...
Rust
0
= input("Provide your answer: ") if user_input.lower() == "quit": print("Exiting the program.") break for chunk in graph.stream({"messages": HumanMessage(content=user_input)}, config=thread_config, ...
Python
1
import torch from zeta.nn.modules.fused_gelu_dense import FusedDenseGELUDense def test_class_init(): model = FusedDenseGELUDense(512, 1024) assert model.dim == 512 assert model.dim_out == 1024 assert model.bias is True assert model.has_fp16_weights is False assert model.threshold == 6.0 de...
Python
1
/// Convert a `wstatus` obtained from `libc::waitpid` into a `WaitStatus`: /// /// ``` /// use nix::sys::wait::WaitStatus; /// use nix::sys::signal::Signal; /// let pid = nix::unistd::Pid::from_raw(1); /// let status = WaitStatus::from_raw(pid, 0x0002); /// assert_eq!(status, Ok(WaitStatus:...
Rust
0
aN axs[0].plot(E, y1, color = 'k', lw = 1.4, alpha = 0.9, label = 'y1') axs[0].plot(E, y2, alpha = 0.7, label = 'y2') axs[0].plot(E, y3, alpha = 0.7, label = 'y3') axs[0].axhline(y = 0, color = 'grey', linestyle = '--') axs[0].set_title('y1, y2, y3') axs[0].set_xlim([0, 20]) axs[0].set_yli...
Python
1
t_xlabel("Step") ax.set_ylabel("Mode") ax.set_title("Selected Modes") fig.tight_layout() fig.savefig(PS.out_dir / PS.info_sel_modes_fig) logger.info(f"Plotted cycle results.") @logger.catch() def main( settings_path: Path, path_abs_structure_init: Path, path_abs_structure_target: Path...
Python
1
), migrations.AddField( model_name='accountactivity', name='data_file', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='parse_m2.m2datafile'), ), migrations.AddField( model_name='accountactivity', name='even...
Python
1
frame_count) @classmethod def IS_CHANGED(cls, video, use_random_video, random_folder, n_videos, seed, sort, loop_sequence): if use_random_video: return seed # Return seed to indicate change when using random videos else: video_path = folder_paths.get_annotated_filepath(...
Python
1
>; pub trait Handle: fmt::Debug { fn spawn(sender: Sender) -> Self where Self: Sized; fn set_config(&mut self, config: Config); fn invalidate(&mut self, path: AbsPathBuf); fn load_sync(&mut self, path: &AbsPath) -> Option<Vec<u8>>; } impl Entry { pub fn rs_files_recursively(base: AbsPa...
Rust
0
255.0, 211.0 / 255.0, 1.0); const COLOR_FLOW: Vec4 = vec4(196.0 / 255.0, 133.0 / 255.0, 190.0 / 255.0, 1.0); const COLOR_LOOPING: Vec4 = vec4(1.0, 140.0 / 255.0, 0.0 / 255.0, 1.0); const COLOR_IDENTIFIER: Vec4 = vec4(212.0 / 255.0, 212.0 / 255.0, 212.0 / 255.0, 1.0); const COLOR_CALL: Vec4 = vec4(220.0 / 255.0, 220.0 ...
Rust
0
''' Tasks : 1. Transfer the data to bronze to silver 2. Update if the different content and if the record is new then insert the record Packages according to requiremnt: 1. Airflow 2. os 3. BigqueryInsertJobOperator 4. Python Opertor 5. Empty Operator 6. Dummy Operator 7. BigqueryCreateEmptyDatasetOperator 8. Bigque...
Python
1
_use] mod fields; #[cfg(feature = "bn254")] pub use curves::*; pub use fields::*; use std::cmp::Ordering; use super::tree::NodeIndex; implement_error! { pub enum TreeMathError { LeafHasNoChildren = "Leaf nodes don't have children.", RootHasNoParent = "Root nodes don't have parents.", Not...
Rust
0
_class_method("android/media/Rating\0", "getStarRating\0", "()F\0"); __jni_env.call_float_method_a(self.0.object, __jni_method, __jni_args.as_ptr()) } } /// [getPercentRating](https://developer.android.com/reference/android/media/Rating.html#getPercentRating()) pub f...
Rust
0
differences = [(h - date_val).days for h in holiday_set] is_holiday = 1 if 0 in differences else 0 pre = 1 if any(1 <= d <= pre_window for d in differences) else 0 post = 1 if any(-post_window <= d <= -1 for d in differences) else 0 effect = max(is_holiday, pre, post) # Op...
Python
1
"discrete": False, "tl_type": "static", 'max_accel': MAX_ACCEL, 'max_decel': MAX_ACCEL, 'safety_device': True, # 'True' needs emission path to save output file }, ), # network-related parameters (see flow.core.params.NetParams and the # networ...
Python
1
Result<Self, gears::renderer::pipeline::PipelineError> { /// // validations filled in /// // like: gears::static_assertions::assert_type_eq_all!() /// Ok(Self { /// 0: gears::renderer::pipeline::factory::Pipeline::builder() /// .vertex_uniform(VERT::load_spirv().map_err(|err| gears::renderer::pipeline::Pi...
Rust
0
` argument representing the /// offset at which the returned `Reader` should resume reading from. pub fn new(factory: F) -> Self { Self::with_retry(factory, Retry::default()) } /// Uses the provided `Reader` factory to construct a `RetryReader` with the passed `Retry` /// settings. See the ...
Rust
0
import re from typing import List class ConceptExtractor: @staticmethod def extract_concepts_from_summary(summary: str) -> List[str]: """ Extracts all [[concept]] mentions from a summary string. Example: "The model extends [[DQN]] and [[Transformer]]" -> ["DQN", "Transformer"] ...
Python
1
ailed to build pool"); let conn = pool.get().await.expect("Failed to connect to DB"); let _ = conn .batch_execute_async(concat!( "CREATE DATABASE my_test; ", "CREATE TABLE my_test.foo (x Integer PRIMARY KEY, y String); ", "DROP DATABASE my_test;" )) .a...
Rust
0
import sqlite3 from database import * from normal import * conn = sqlite3.connect("travel.db") cur = conn.cursor() data = """CREATE TABLE if not exists travel(id varchar(20), name varchar(50),phone int , no_car int, no_day int , bill int)""" cur.execute(data) # database create only one time no_of_car = 20-tot...
Python
1
if let Some(instance) = index .get_mut(&task_id) .and_then(|info| info.instance_mut(instance_id)) { instance.finished = true; } else { anyhow::bail!("Termination of...
Rust
0
#!/usr/bin/env python import glob import sys import os def main(): fn = sys.argv[1] f = open(fn, "r") ln = f.readlines() f.close() out = "" for l in ln: if l.startswith("INSERT "): ff = l.replace("INSERT ", "").strip() raw_rst = "/".join(fn.split("/")[:-1]).str...
Python
1
import os import re from pathlib import Path from funasr import AutoModel import pypinyin import subprocess import shutil # 用户输入 wav_path = input("请输入wav文件或文件夹路径: ") sofa_model_path = input("请输入SOFA模型路径: ") dictionary_path = input("请输入词典路径: ") annotation_format = input("请输入音素标注格式(TextGrid或HTK lab): ") language = input...
Python
1
""" Setup script for Legal Crawl Analyzer with Poetry """ import os import sys from pathlib import Path def setup_directories(): """Create necessary directories""" directories = [ "warc_files", "analysis_output", "logs" ] for directory in directories: Path(directo...
Python
1
l LolStatstonesGameDataStatstone { pub fn new() -> LolStatstonesGameDataStatstone { LolStatstonesGameDataStatstone { bound_champion: None, category: None, content_id: None, description: None, icon_full: None, icon_lit: None, ...
Rust
0
let mut m = MF::<T, ROWS, ROWS>::unit_stack(); m *= diag_val; m } /// Create a diagonal matrix with initial diagonal value `diag_val` on the heap. #[inline] pub fn diag_heap(diag_val: T) -> HMatrix<T, ROWS, ROWS> where T: FromStr, <T as FromStr>::Err: ...
Rust
0
""" Write a python function to count the upper case characters in a given string. assert upper_ctr('PYthon') == 1 """ def upper_ctr(string): count = 0 for i in string: if i.isupper(): count += 1 return count #assert upper_ctr('PYthon') == 1 print(upper_ctr('PYthon'))
Python
1
tes[index..]); } if cond0.colormap() { index += self.colormap.as_bytes(&mut bytes[index..]); } if cond0.cursor() { index += self.cursor.as_bytes(&mut bytes[index..]); } index } #[inline] fn from_bytes(bytes: &[u8]) -> Option<(Self, usiz...
Rust
0
.into_push_pull_output(&mut gpiob.moder, &mut gpiob.otyper), gpiob .pb11 .into_push_pull_output(&mut gpiob.moder, &mut gpiob.otyper), gpiob .pb12 .into_push_pull_output(&mut gpiob.moder, &mut gpiob.o...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the bzip2 decompressor object.""" import unittest from dfvfs.compression import bzip2_decompressor from dfvfs.lib import errors from tests.compression import test_lib class BZIP2DecompressorTestCase(test_lib.DecompressorTestCase): """Tests for the bzip2 ...
Python
1
from Game import PokemonGame if __name__ == "__main__": game = PokemonGame() game.start()
Python
1
from common.params import Params from common.transformations.camera import tici_f_focal_length, tici_e_focal_length, eon_f_focal_length,\ eon_f_frame_size, tici_f_frame_size, tici_e_frame_size import numpy as np def get_intrinsic_matrix(focal_length, frame_size): return np...
Python
1
#! /usr/bin/env python """ Demo script showing how to create network configurations by combining data from CSV files with Jinja templates. """ import csv from jinja2 import Template source_file = "switch-ports.csv" interface_template_file = "switchport-interface-template.j2" # String that will hold final full confi...
Python
1
mer::new()); let scheduler = Scheduler { store, performer, task_store_check_interval: Duration::from_millis(1), }; assert!(scheduler.prepare_batch().await.unwrap().is_none()); } #[tokio::test] async fn test_loop_run_normal() { let mocker...
Rust
0
32, /// The entity's velocity. pub velocity: [i16; 3], } /// Spawns one or more experience orbs. #[derive(Clone, PartialEq, Debug, McRead, McWrite, Packet)] pub struct SpawnExpOrb { /// The experience orb's network ID. #[options(varint = true)] pub net_id: i32, /// The experience orb's position...
Rust
0
# -i https://pypi.tuna.tsinghua.edu.cn/simple import datetime import pandas as pd import numpy import openpyxl from openpyxl.comments import Comment class CalcLast1YearCount: def count(self): # 读取Excel文件 df = pd.read_excel('date.xlsx', sheet_name='Sheet1') book = openpyxl.load_workbook('...
Python
1
, self.player2.ypos); } } fn main() { let opengl = OpenGL::V3_2; let window = Window::new( WindowSettings::new( "Pong Clone", [800, 600] ) .opengl(opengl) .exit_on_esc(true) ); let mut p1 = Paddle { xpos: 0.0, ypos: 250.0, ...
Rust
0
] ); assert_eq!(0, res.messages.len()); // check if state the vote was rejected let state = config_read(deps.as_ref().storage).load().unwrap(); assert_eq!(200000, state.everyBlockTimePlay); // Test can't REpresent the proposal let...
Rust
0
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/Axiom/config.py from __future__ import absolute_import, print_function, unicode_literals from .consts import * from _Axiom.consts import PAD_TRANSLATION TRANSPORT_CONTROLS = {u'STOP': GENERIC_STOP, u...
Python
1
as usize) < 32 { regs.wtsa.set(1 << self.pin as usize); } else { regs.wtsb.set(1 << (self.pin as usize - 32)); } } fn clear(&self) { let regs = self.registers; if (self.pin as usize) < 32 { regs.wtca.set(1 << self.pin as usize); } el...
Rust
0
) => ({ let s = &format!($($arg)*); crate::print::LOG.lock().Print("INFO", &s); }); } #[macro_export] macro_rules! debug { ($($arg:tt)*) => ({ let s = &format!($($arg)*); crate::print::LOG.lock().Print("DEBUG", &s); }); } <gh_stars>1-10 use aoc13::{read_street_map, StreetMap...
Rust
0
: &[&str] = &[ ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n", "x\n", "b\n", "c\n", "================================\n", "y\n", "e\n", "f\n", "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", ]; let mut d = Replace::new(crate::algorithms::Capture::new()); ...
Rust
0
ELTA GAMMA THETA", "TIME") option = EquityAmericanOption(expiry_dt, strike_price, OptionTypes.AMERICAN_CALL) for num_steps in num_steps_list: model = BlackScholes(volatility, BlackScholesTypes.CRR_TREE, num_steps) start = time.time() results = option.value( value_dt, sto...
Python
1
from fastapi import HTTPException class CustomError(HTTPException): def __init__(self, status_code: int, detail: str): super().__init__(status_code=status_code, detail=detail)
Python
1
""" 2 metre dewpoint temperature ============================= The metadata used to detect the styles are : .. list-table:: :widths: 25 25 * - **paramId** - 168 * - **shortName** - 2d Default style: -------------- **Contour shade (Range: -48 / 56)** \[sh_all_fM48t56i4] ...
Python
1
seconds: 5.0, video_fps: 60, selected_scene_idx: 0, known_scene_files: list_scene_files(), wait_for_vblank: Screen::DEFAULT_PRESENT_MODE == wgpu::PresentMode::Fifo, }, } } pub fn handle_event<T>(&mut self, winit_event: &winit::...
Rust
0
r1: Session<End> = include_session(make_receiver(channel.clone()), |receiver| { unfix_session( receiver, choose!( receiver, Next, receive_value_from(receiver, move |val| { println!("[Consumer 1] Receive first value: {}", val); unfix_sessio...
Rust
0
ssert_eq!( unsafe { &(*(::std::ptr::null::<rte_bus>())).dev_iterate as *const _ as usize }, 104usize, concat!( "Offset of field: ", stringify!(rte_bus), "::", stringify!(dev_iterate) ) ); assert_eq!( unsafe { &(*(::std::ptr:...
Rust
0
E> { self.1 .ref_parser() .skip(self.0.ref_parser()) .drop(self.2.ref_parser()) .parse(source, location) } } /// The result of the [`copy_string`](trait.TextParserExt.html#method.copy_string) function in the /// [`TextParserExt`](trait.TextParserExt.html) tr...
Rust
0
'tfd:'): line_match = re.findall(r'(?P<key>\S+):(?:\s+)?(?P<val>\S+s*)', line) if line_match: raw_output.update({'epoll': {k.strip(): v.strip() for k, v in line_match}}) continue # inotify files if line.startswith('inotify'): ...
Python
1
(LogView::core); pub struct LogView { lines: Vec<String>, core: cursive::view::scroll::Core, } impl LogView { pub fn scrollable(buf: &[u8]) -> Self { let lines = parse_lines(&buf); LogView { lines, core: Core::new(), } } fn inner_required_size(&mu...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2023 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
d(&password_string); } let parsed_uuid = Uuid::parse_str(uuid).map_err(OurError::from_uuid_error)?; Ok(binded .bind(parsed_uuid) .fetch_one(connection) .await .map_err(OurError::from_sqlx_error)?) } pub async fn destroy(connection: &mut Pg...
Rust
0
/// Kernel Module events pub const AUDIT_KERN_MODULE: u16 = 1330; /// Fanotify access decision pub const AUDIT_FANOTIFY: u16 = 1331; // ========================================== // 1400 - 1499 SE Linux use // ========================================== /// SE Linux avc denial or grant pub const AUDIT_AVC: u16 = 1400...
Rust
0
ue = Value::parse(string).unwrap(); let expected_value = Value::String("Hello, world!\n".into()); assert_eq!(value, expected_value); } #[test] fn test_four_byte_unicode_value() { let string = "\"\\ud83d\\ude02\""; let value = Value::parse(string).unwrap(); let expected_value = Value::String("😂"....
Rust
0
calar8x64 { pub fn from_bytes(bytes: &[u8; 64]) -> Self { let mut w = [0u64; 8]; for i in 0..8 { w[i] = u64::from_be_bytes(bytes[((7 - i) * 8)..((7 - i) * 8 + 8)].try_into().unwrap()); } Self(w) } #[inline(always)] // only used in Scalar::mul(), so won't cause bi...
Rust
0
from vehicleSerial import * import time minSteerSensorValue = 500 maxSteerSensorValue = 0 minThrottleSensorValue = 500 maxThrottleSensorValue = 0 #connect to autonomous vehicle connectionResult = connect('/dev/ttyUSB0') while connectionResult != "succes": print("arduino failed to connect but trying again...") ...
Python
1
_negative_one, "@use 'sass:math';\na {\n color: math.atan(-1);\n}\n", "a {\n color: -45deg;\n}\n" ); grass_test!( atan_zero, "@use 'sass:math';\na {\n color: math.atan(0);\n}\n", "a {\n color: 0deg;\n}\n" ); grass_test!( atan_point_five, "@use 'sass:math';\na {\n color: math.atan(.5);\n...
Rust
0
import json from bson import ObjectId class MongoJsonEncoder(json.JSONEncoder): """ Un codificador JSON personalizado para extender json.JSONEncoder, permitiendo la serialización de tipos adicionales no soportados por defecto. Este codificador se enfoca en convertir instancias de ObjectId, utiliza...
Python
1
; const TYPE_I64: u8 = 0; const TYPE_F64: u8 = 1; const TYPE_STRING: u8 = 2; const TYPE_TRUE: u8 = 3; const TYPE_FALSE: u8 = 4; #[derive(Clone, Default)] pub struct BInflux {} impl BInflux { pub fn encode(v: &Value) -> Result<Vec<u8>> { fn write_str<W: Write>(w: &mut W, s: &str) -> Result<()> { ...
Rust
0
time: float = 0.0 k1: float = 0.100000000000000 k2: float = 0.150000000000000 p1: float = 2.50000000000000 C: float = 2.50000000000000 S1: float = 1.00000000000000 S2: float = 0.0 S3: float = 0.0 # Initial assignments S4 = S3 / (p1 + 1) S5 = S4 * p1 S1_conc = S1 / C S2_conc = S2 / C S3_conc = S3 / C S4_conc = S4 / C S...
Python
1
eval_F1 = f1_score(y_true=np.array(true_labels), y_pred=np.array(predicted_labels), average='micro') # Calculate the average AUC eval_auc = roc_auc_score(y_true=np.array(true_labels), y_score=np.array(pr...
Python
1
el): """用于描述MongoDB数据库慢日志统计信息 """ def __init__(self): r""" :param _Pattern: 慢日志模式 :type Pattern: str :param _MaxTime: 最大执行时间 :type MaxTime: int :param _AverageTime: 平均执行时间 :type AverageTime: int :param _Total: 该模式慢日志条数 :type Total: in...
Python
1
orted_array; pub mod s1122_relative_sort_array; pub mod s1143_longest_common_subsequence; pub mod s1189_maximum_number_of_balloons; pub mod s1588_sum_of_all_odd_length_subarrays; pub mod s2016_maximum_difference_between_increasing_elements;<filename>src/tests.rs<gh_stars>1-10 extern crate mydht_basetest; extern crate s...
Rust
0
, res == 0 ); cpu.cond_flag ( HALF_CARRY_FLAG , (op1 & 0x0FFF) < (op2 & 0x0FFF) + c ); cpu.cond_flag ( PARITY_OVERFLOW_FLAG , (op1 & 0x8000 != op2 & 0x8000) && (op1 & 0x8000 != res & 0x8000) ); cpu.set_flag...
Rust
0
es = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ["autosplit_train.txt", "autosplit_val.txt", "autosplit_test.txt"] # 3 txt files for x in txt: if (path.parent / x).exists(): (path.parent / x).unlink() # remove existing LOGGER.info(f"Autospli...
Python
1
w += str(nn_added) + ", " coincident_nodes.append((nn, nn_added)) fW.write(line_new[:-2] + "\n") continue # find *ELEMENT card if line[:8].upper() == "*ELEMENT": line_list = line[8:].upper().split(',') for line_part in line...
Python
1
return vec4<f32>(r, g, b, a); } let SDF_SMOOTHING: f32 = 0.0625; [[stage(vertex)]] fn main(in: VertexInput) -> VertexOutput { var out: VertexOutput; out.clip_position = vec4<f32>(in.xyuv.xy, 0.0, 1.0); ...
Rust
0
if not answers_dict['prediction']: return {} bin_acc = accuracy_score(gts_dict['prediction_binary'], answers_dict['prediction_binary']) mse = mean_squared_error(gts_dict['prediction'], answers_dict['prediction']) pros_rouge_scores = calc_rouge_score(gts_dict['positive developments']...
Python
1
# # Copyright (c) Andre Slabber. All rights reserved. # Licensed under the MIT License. See LICENSE file in the project root for full license information. # # the testtoolkit requires the following python3 packages to be installed: # - robotframework (for the nicely formatted output) # - pyautogui (for the automate...
Python
1
the function will adjust the"] #[doc = " data pointers and the width/height fields, and set the crop fields to 0."] #[doc = ""] #[doc = " In all cases, the cropping boundaries will be rounded to the inherent"] #[doc = " alignment of the pixel format. In some cases, such as for opaque hwaccel"] #[do...
Rust
0
""" Утилиты для блокировки сообщений по содержимому """ import logging from typing import List, Optional from app.infra.repo.alias_blocks_repo import AliasBlocksRepo logger = logging.getLogger(__name__) async def check_message_for_blocked_words(message_text: str, blocks_repo: AliasBlocksRepo, mailbox_id: Optional[int...
Python
1
pub fn change_axes( model: &mut TypedModel, change: &AxisChange, locked: &[OutletId], bounds: &[TVec<OutletId>], ) -> TractResult<Option<HashMap<OutletId, AxisOp>>> { debug!("Trying to apply change {:?}", change); let mut todo_changes = vec![(change.clone(), None)]; let mut changed_wires = H...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging from odoo import api, models _logger = logging.getLogger(__name__) class AccountChartTemplate(models.AbstractModel): _inherit = "account.chart.template" def _post_load_demo_data(self, company=Fal...
Python
1
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. 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/LICENS...
Python
1
on directly, but /// to instead call the corresponding function on a `Descriptor`, which /// will handle the segwit/non-segwit technicalities for you. /// /// All signatures are assumed to be 73 bytes in size, including the /// length prefix (segwit) or push opcode (pre-segwit) and sighash /// p...
Rust
0
# Copyright 2025 Robin Müller # # 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
: return self def _root_decomposition( self: Float[LinearOperator, "... N N"] ) -> Union[Float[torch.Tensor, "... N N"], Float[LinearOperator, "... N N"]]: return self.root def _root_decomposition_size(self) -> int: return self.root.size(-1) def _size(self) -> torch.Si...
Python
1
) self.attention_weights = torch.zeros([B, T], device=inputs.device) self.attention_weights[:, 0] = 1.0 def init_attn( attn_type, query_dim, embedding_dim, attention_dim, location_attention, attention_location_n_filters, attention_location_kernel_size, windowing, no...
Python
1
continue # If field is in exclude list, skip if excludes and f.name in excludes: continue if self.should_skip_field(f): continue index_field_class = index_field_from_django_field(f) kwargs = copy.copy(self.extra_field_kw...
Python
1
ip(inputs, nps))) def test_squeeze(self): reset_model(13) nps = [np.random.randn(1, 10, 1, 1).astype(np.float32)] inputs = Input(*nps) Output(Squeeze(inputs[0], np.array(([2, 3])))) self._run(list(zip(inputs, nps))) def test_squeeze_no_axes(self): reset_model(13) nps = [np.random.randn...
Python
1
Ok(()) } } impl MenuOption for SaveName { fn name(&self) -> GString { self.printable.clone() } } /// Path to the saves directory. pub fn path() -> Result<PathBuf> { let dirs = paths()?; let mut path = PathBuf::from(dirs.data_dir()); path.push("saves"); Ok(path) } /// Lists all s...
Rust
0
from selenium import webdriver from selenium.webdriver.common.by import By import pytest import time import allure @pytest.mark.negative @allure.title("Negative Testcase - App.vwo.com - Wrong Email, Password -> Error Message.") @allure.description("Verify that if email/pass is wrong, we will get a message") def test_...
Python
1
_cert(root_ca) .cert(cert, private_key) .build(); let channel = ChannelBuilder::new(env).secure_connect(addr, credentials); DgraphClient::new(channel) } pub fn new_dgraph_client(addr: &str) -> DgraphClient { let env = Arc::new(EnvBuilder::new().build()); let channel = ChannelBuilder::ne...
Rust
0
\ \xab\x1eX\xf4\xa3\xcb\x1e\x94\x98\x10\xe4\xfaQ\x93\xe9\xfa\ \xd4\xdeX\xf4\xa3\xcb\xf6\xa9Z\x03C\x01\xcd-H#\ \x06\x8d\xb5I\x05\x88\x89\xe6\x87b0@\xa9vg\xde\ \x97\xcb\x18\xa4\x09\x10\xe5\xbb\xd1\x93\xe9R\xf9t\x820\ hZ!\xf2\x90\xe7\x14T\xbb=\xa8\xd9\xedB\xd8-\ b<\x1a7T\x98\x14\x9bi\xb4M\x86\xee\xc5\x1b\xb1\ O\xd8h\xd8i\...
Python
1
import os import httpx from typing import Dict, Any NAVER_CLIENT_ID = os.environ.get("NAVER_CLIENT_ID") NAVER_CLIENT_SECRET = os.environ.get("NAVER_CLIENT_SECRET") NAVER_API_HEADERS = { "X-Naver-Client-Id": NAVER_CLIENT_ID, "X-Naver-Client-Secret": NAVER_CLIENT_SECRET, } NAVER_API_ENDPOINT = "https://openapi....
Python
1
Initialize the memory management module pub fn init(dtb: usize) { // allow user memory access unsafe { sstatus::set_sum(); } // initialize heap and Frame allocator init_frame_allocator(); init_heap(); remap_the_kernel(dtb); } pub fn init_other() { unsafe { sstatus::set_...
Rust
0
2, VALUE) def testSessions(self): self.model.logout() key = self.model.login(pwd="TEST") newMod = standardUser(userName=self.userName) newMod.restoreSession(key) self.assertTrue(newMod.loggedin) def testLogout(self): self.model.logout() key = self.model....
Python
1
{ Command::PredictionMode(PredictionModeContextMap{ literal_context_map:pm.literal_context_map.freeze(), predmode_speed_and_distance_context_map:pm.predmode_speed_and_distance_context_map.freeze(), }) }, Command::Dict(ref d) => { ...
Rust
0
q::Message::new().unwrap(), config: config, }) } // Main loop for server fn run(&mut self, rz: mpsc::SyncSender<()>) -> Result<()> { self.sock.bind(INPROC_ADDR)?; rz.send(()).unwrap(); loop { let job = self.recv_job()?; self.send_ack(&job)...
Rust
0
// 因为可以从手中选出 任意一颗, 我们可以不必在意顺序, 只需要统计其数量信息即可 curr_status.insert((board.as_bytes().to_vec(), parse_hand(hand.as_bytes()))); // 然后我们就开始广搜 while !curr_status.is_empty() { step += 1; let mut next_status = HashSet::new(); for (board_info, hand_info) in curr_statu...
Rust
0
gle(orbit.nu)), ) # Perform actual sampling nu_values = sample_open( orbit.ecc, self._min_nu, self._max_nu, self._num_values, nu_limit=nu_limit, ) # Weird units roundtrip because lis...
Python
1
l", "null.blob", "null.clob", "null.struct", "null.list", "null.sexp", "true", "false", }; // The Ion text format supports escape sequences only within quoted strings and symbols. // TODO: Profile if this is actually faster than a linear search of an array. pub(crate) static ESCAPED_CODE_PO...
Rust
0
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 under the L...
Rust
0
175 /// /// Symbol: RVN /// /// Coin: Ravencoin [175], Ravencoin, "Ravencoin", "https://ravencoin.org/", RVN, , ), ( /// Coin type: 176 /// /// Symbol: GBX /// /// Coin: GoByte [176], GoByte, "GoByte", "https://gobyte.netwo...
Rust
0
).$d3d_field)), "size_of {}::{} != {}::{}", stringify!($thin), stringify!($thin_field), stringify!($d3d), stringify!($d3d_field)); assert_eq!( offset_of(thin, addr_of!((*thin).$thin_field)), offset_of(d3d, addr_of!((*d3d).$d3d_field)), "offset_of {}::{} != {}::{}", stringify!($thin), strin...
Rust
0
cated since 2016-08-04 @deprecated_fn("Deprecated, use ``h2o.cluster().show_status(True)``.") def cluster_status(): """Deprecated.""" _check_connection() cluster().show_status(True) # Deprecated since 2016-08-04 @deprecated_fn("Deprecated, use ``h2o.cluster().shutdown()``.") def shutdown(prompt=False): ...
Python
1
user_watched(db: Session, user_id: str, movie_id: str): watched = db.query(models.UserWatched).filter( models.UserWatched.userID == user_id, models.UserWatched.movieID == movie_id ).first() if watched: db.delete(watched) db.commit() return watched # --- USER WATCHLIST CRUD --- d...
Python
1