text
string
label_name
string
labels
int64
# # Copyright 2018-2025 Elyra Authors # # 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 writ...
Python
1
elf)) // } // } <filename>TuringDB/src/crypto/traits.rs use crate::CipherErrors; use secrecy::Secret; pub trait CipherOps { /// FIXME add support for `Payload` and removing `as_ref()` as a result fn encrypt(&self, plaintext: Secret<Vec<u8>>) -> core::result::Result<Vec<u8>, CipherErrors>; fn decrypt(&...
Rust
0
[fp_tmp_len - 1 - i]], axis=0) fp_part = np.append(fp_part, [[0, fp_back, 0, 0, (fp_back - mrange)/1000]], axis=0) """ print("\rProcessing distance complete", end='') len_fp_part = len(fp_part) if len_fp_part > 0 : for i_f in range (len_fp_part - 1) : ...
Python
1
fig.SOLVER.MAX_ITER: logger.info('[Saving] Iter: %d' % iteration) model_path = osp.join(model_dir, '%d.pth' % iteration) solver_path = osp.join(solver_dir, '%d.solver' % iteration) model_opr.save_model(model, model_path) model_opr.save_solv...
Python
1
let value_output = &value_fn._get_pred()[idx * action_dim .. (idx+1) * action_dim]; let argmax_k = argmax(value_output.iter().map(|&v| F32InfNan(v))).unwrap(); self.target_maxs.push(argmax_k); }*/ target_fn.load_diff_param(&mut self.target); target_fn.next_iteratio...
Rust
0
int(f"An error occurred: {e}") # JavaScript function to dispatch a change event async def dispatch_change_event(self, tab , select_element): try: js_dispatch_event = """ function dispatchChangeEvent(element) { var event = new Event('change', { bubbles: true }); ...
Python
1
ext_prop_value_1; const EXT_PROP_VALUE_2: u32 = #ext_prop_value_2; const TA_DATA_SIZE: u32 = #ta_data_size; const TA_DESCRIPTION: &[u8] = #ta_description; const TA_FLAGS: u32 = #ta_flags; const TA_FRAMEWORK_STACK_SIZE: u32 = #ta_framework_stack_size; const TA_STACK_SIZE: ...
Rust
0
<'d> { db: &'d DatabaseReader, matcher: Option<regex::Regex>, prefix: &'d str, range: crate::CowStringRange<'d>, } impl<'d> DatabaseKeyReader<'d> { pub(crate) fn check(&self) { match (self.range.start_bound(), self.range.end_bound()) { (Bound::Unbounded, _) => {} (_, Bound::Unbounded) => {} (Bound::Inc...
Rust
0
comparison = compare(output, output_method) self.assertTrue( comparison, f"torch.{op} result did not match Tensor.{op} result" ) # Compare numerics to Python-side "autocasting" that (we expect) does the same thing # as the C++-si...
Python
1
mal; pub fn main() -> usize { primal::StreamingSieve::nth_prime(10_001) } } pub mod problem08 { pub fn main() -> u64 { let input = "73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ ...
Rust
0
import re def main(): """ Basic text substitution examples using re.sub(). """ print("=== Basic Text Substitution Examples ===\n") # Sample text text = "Python programming language is useful. Python can be used for web development." print(f"Original text: {text}\n") # 1. Simpl...
Python
1
MILL_ROUGH_KEY = "mill_rough" MILL_POLISHING_KEY = "mill_polishing" MICROEXPANSION_KEY = "microexpansion" FIDUCIAL_KEY = "fiducial" NOTCH_KEY = "notch" TRENCH_KEY = "trench" UNDERCUT_KEY = "undercut" SETUP_LAMELLA_KEY = "setup_lamella" SETUP_POLISHING_KEY = "setup_polishing" LIFTOUT_KEY = "liftout" LANDING_KEY = "landi...
Python
1
from django.db import models from .managers import MusicCategoryManager, MovieCategoryManager class HobbyCategory(models.Model): title = models.CharField(max_length=150, verbose_name='Название клуба') description = models.TextField(blank=False, verbose_name='Описание') cover = models.ImageField(upload_to...
Python
1
: BasicContext, _next: impl Fn(BasicContext) -> MiddlewareReturnValue<BasicContext> + Send + Sync) -> Box<Future<Item=BasicContext, Error=io::Error> + Send> { context.body("1"); Box::new(future::ok(context)) }; app.use_middleware("/", middleware![BasicContext => query_params::query_params]); a...
Rust
0
'No image provided' concert_info['Venue'] = date_location.get_text(strip=True) if date_location else 'No date and location provided' concert_info['rank'] = rank concert_info['change'] = change concert_info['site'] = "http://ticket.yes24.com/Rank/All" # 공통 URL로 설정 concerts_data....
Python
1
estingContract = Deserialize::deserialize(&mut &bytes[..]).unwrap(); assert_eq!(contract.balance, 52500000000000.try_into().unwrap()); assert_eq!(contract.owner, Address::from("fd34ab7265a0e48c454ccbf4c9c61dfdf68f9a22")); assert_eq!(contract.start_time, 1); assert_eq!(contract.step_amount, 2625000000000...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class ResCompany(models.Model): _inherit = "res.company" def _get_leaderboard_query(self): return """ WITH A AS ( SELECT aal.employee_id AS id, SUM( ...
Python
1
ener = YOLO_Listener() gui_listener = GUI_Listener() ds4_listener = DS4_Listener() exec.add_node(yolo_listener) exec.add_node(gui_listener) exec.add_node(ds4_listener) exec.spin() # Destroy the node explicitly # (optional - otherwise it will be done automatically # when the garbag...
Python
1
omp(&x_coordinate, &BIG::new_ints(&rom::MODULUS)) >= 0 { return Err(()); } let sign_bit: isize = if sign_bit == 0 { 0 } else { 1 }; let mut ecp = ECP::new_big(&x_coordinate); if ecp.is_infinity() { return Err(()); } ecp.affine(); let x = ec...
Rust
0
m = 0x8CF3; #[allow(dead_code, non_upper_case_globals)] pub const COLOR_ATTACHMENT2: types::GLenum = 0x8CE2; #[allow(dead_code, non_upper_case_globals)] pub const COLOR_ATTACHMENT20: types::GLenum = 0x8CF4; #[allow(dead_code, non_upper_case_globals)] pub const COLOR_ATTACHMENT21: types::GLenum = 0x8CF5; #[allow(dead_co...
Rust
0
pub fn display(&self) { let mut points: Vec<Vector> = self.points_iter().collect::<HashSet<Vector>>().into_iter().collect(); points.sort_by(|a, b| { if a.y == b.y { a.x.cmp(&b.x) } else { a.y.cmp(&b.y) } }); dbg!...
Rust
0
t() -> I, FM: FnMut() -> I> Signal for MapBool<S, TM, FM> { type Item = I; #[inline] fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let MapBoolProj { signal, true_mapper, false_mapper, } = self.project(); sig...
Rust
0
); assert_ok!(Sponsored::withdraw_pool( Origin::signed(account.clone()), pool_id )); assert_eq!(Balances::free_balance(&account), account_balance); }) } #[test] fn withdraw_pool_fail() { ExtBuilder::default().build_and_execute(|| { run_to_block(1...
Rust
0
import argparse import io import json import os from pathlib import Path from tqdm import tqdm parser = argparse.ArgumentParser(description="Merges all manifest files in specified folder.") parser.add_argument("manifests", metavar="m", nargs="+", help="Path to all manifest files you want to merge.") parser.add_argum...
Python
1
ion")]` attribute /// /// This is used to specify a custom function with which custom Components will be creatde and/or inserted. /// This is essentially identical to just simply implementing `ProtoComponent` yourself. /// /// Generates the following code: /// ```rust /// my_function(self, c...
Rust
0
p': (datetime.now() - timedelta(days=7)).isoformat(), 'source': 'document_analysis', 'confidence': 'medium', 'file_metadata': { 'filename': 'Trading_Journal_Q1_2025.pdf', 'size': '15.7MB', 'pages': 47 ...
Python
1
bytes. read_bytes(buffer, reader, bytes_to_read)?; } Ok(()) } fn read_bytes<R: Read>(buffer: &mut Vec<u8>, reader: &mut R, amount: u64) -> Result<usize> { if let Ok(amount_read) = reader.take(amount).read_to_end(buffer) { // If no bytes were read at all purposefully, it shouldn't count as...
Rust
0
or Gene A: [[0, 1], [1, 0]] both of these observations could potentially match the code for GENE_A: [[4, 3], [4, 0]] and [[0, 3], [4, 3]] The first is interpreted as argmax as: [[1, 1], [0, 0]] which fails to match, while the second is interpreted as [[0,...
Python
1
# encoding: utf-8 import serial import Queue import threading import struct import time ser = None def do_imu(data): temp = struct.unpack('h', bytearray(data[4:6]))[0] print(data[4],data[5]) # acc ax = struct.unpack('h', bytearray(data[6:8]))[0] ay = struct.unpack('h', bytearray(data[8:10]))[0] ...
Python
1
single = left1 == NONE_FRAME; let above_single = above1 == NONE_FRAME; let left_intra = left0 == INTRA_FRAME; let above_intra = above0 == INTRA_FRAME; let left_backward = check_backward(left0); let above_backward = check_backward(above0); if avail_left && avail_up { if above_single && lef...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.http import route from odoo.addons.mail.controllers.discuss.binary import BinaryController from odoo.addons.im_livechat.tools.misc import force_guest_env class LivechatBinaryController(BinaryController): @route( "/im_li...
Python
1
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'test.ui' # # Created by: PyQt5 UI code generator 5.15.11 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui,...
Python
1
# Problem: Find Center of Star Graph - https://leetcode.com/problems/find-center-of-star-graph/ class Solution: def findCenter(self, edges: List[List[int]]) -> int: deck=defaultdict(list) for a,b in edges: deck[a].append(b) deck[b].append(a) for i in deck: ...
Python
1
# Copyright (C) 2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import logging from sqlalchemy import create_engine from sqlalchemy.engine.url import URL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker logger = logging.getLogger(__name__) db_us...
Python
1
pected error: {e}") return False def print_usage(): """Print usage information""" print("Usage: python setup_telegram_webhook.py [command]") print("\nCommands:") print(" setup - Set webhook (default)") print(" info - Get webhook info") print(" delete - Delete webhook") ...
Python
1
Size.with_msg(&format!("Argon memory size must be in the range {:?}", ARGON_MEMORY))) } if argon.iterations < ARGON_MIN_COST { return Err(ErrorCode::InvalidArgonCost.with_msg("The cost must be greater than zero")) } Ok(()) } fn validate_bcrypt(bcrypt: &api::BCryptPolicy) -> Result<(), VaultEr...
Rust
0
rses.color_pair(1)) screen.addstr(idx, 0, item) screen.attroff(curses.color_pair(1)) else: screen.addstr(idx, 0, item) screen.refresh() while True: print_menu() key = screen.getch() if k...
Python
1
lone_from_slice(&(self.decompressed_len).to_le_bytes()); buf[CHECKSUM_RANGE].clone_from_slice(&(self.checksum).to_le_bytes()); writer.write(&buf) } } // CompressionLevel #[derive(Debug, Clone, Copy)] pub(crate) struct CompressionLevel { compression_level: u8, } impl CompressionLevel { pub...
Rust
0
a if num_qubits == 1 else None, 'phi': phi if num_qubits == 1 else None } } st.success("State exported successfully!") st.json(state_data) with col2: if st.button("🔄 Random State"): if num_qubits == 1: theta = np.random.uniform(0, np.pi) ...
Python
1
f, "{}", (format!( "D4 {:08x} D5 {:08x} D6 {:08x} D7 {:08x}", self.d[4], self.d[5], self.d[6], self.d[7] )) .red() )?; writeln!( f, "A0 {:08x} A1 {:08x} A2 {:08x} A3 {:08x}", s...
Rust
0
import tkinter as tk import tkinter.font as font from intrusiondetection.JSONReader.methods.ObjectDetection import ObjectDetection from intrusiondetection.JSONReader.methods.MotionDetection import MotionDetection from intrusiondetection.JSONReader.methods.OpticalFlow import OpticalFlow from intrusiondetection.JSONReade...
Python
1
ext.0.as_str(); if iter.peek().is_some() { value.push(';'); } } value } pub(super) fn as_str(&self) -> &str { &self.formatted } } impl fmt::Display for SignedHeaders { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { wri...
Rust
0
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. mod hash_cache; mod hasher; mod processor; pub(crate) use hash_cache::HashCache; pub(crate) use hasher::{HasherWorker, HasherWorker...
Rust
0
bytes[to + 2] = buffer[from + 2]; } } bytes } fn sprite_from_chunk_rgba(buffer: &[u8], col: usize, row: usize, width: usize) -> Sprite { let mut bytes = vec![0; 16 * 16 * 3]; for ty in 0..16 { for tx in 0..16 { let to = ty * 16 * 3 + tx * 3; let from = (row ...
Rust
0
); unsafe { let begin_info = vk::CommandBufferBeginInfo::builder() .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); self.context .device() .begin_command_buffer(cmd, &begin_info) .expect("Begin frame commands."); ...
Rust
0
import logging import os import psutil from easyprocess import EasyProcess from pyvirtualdisplay.util import get_helptext log = logging.getLogger(__name__) def prog_check(cmd): try: p = EasyProcess(cmd) p.enable_stdout_log = False p.enable_stderr_log = False p.call() ret...
Python
1
in32_Media\"`*"] pub fn timeSetEvent(udelay: u32, uresolution: u32, fptc: LPTIMECALLBACK, dwuser: usize, fuevent: u32) -> u32; } pub type HTASK = isize; pub type IReferenceClock = *mut ::core::ffi::c_void; pub type IReferenceClock2 = *mut ::core::ffi::c_void; pub type IReferenceClockTimerControl = *mut ::core::ffi:...
Rust
0
# # SPDX-License-Identifier: MIT # # Copyright (c) 2025 Carsten Igel. # # This file is part of simplepycons # (see https://github.com/carstencodes/simplepycons). # # This file is published using the MIT license. # Refer to LICENSE for more information # """""" # pylint: disable=C0302 # Justification: Code is generated ...
Python
1
* * ``` * use js_source_mapper::consume; * * let cache = consume(r#"{ "version": 3, "file": "foo.js", "sources": ["source.js"], "names": ["name1", "name1", "name3"], "mappings": ";EAACA;;IAEEA;;MAEEE", "sourceRoot": "http://example.com" }"#).unwrap(); * * println!("{:?}", cache.mapping_for_generat...
Rust
0
from django.shortcuts import render from django.http import HttpResponse def students(request): students= [ {'id':1 , 'name': 'john' , 'age': 35} ] return HttpResponse(students)
Python
1
peak is outside of the intensity profile", "Auroral slice at ", "with data", "Removing boundary outliers from", "The polar/equatorward boundary locations are mixed up"] self.alb_kwargs['slice_func'] = self.new_vals['slice_func'] uncert = 12.0 ...
Python
1
write_str("...")); } } else { try!(f .debug_set() .entries(self.ranges_values().map(|x| (&x.0, &x.1))) .finish()); } try!(f.write_str(")")); Ok(()) } } impl<T: Debug + PrimInt, V: Clone + Debug + PartialEq> Rang...
Rust
0
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler import scipy.cluster.hierarchy as sch import matplotlib.pyplot as plt from sklearn.cluster import AgglomerativeClustering from sklearn.decomposition import PCA # Read Excel file...
Python
1
have_money = 2500000 exchange_rate = 1175 #exchange_money = 2127 #left_money = 775 exchange_money = have_money / exchange_rate print(exchange_money) left_money = have_money % exchange_rate print(left_money) print("가진돈:", have_money) print("환율:", exchange_rate) print("환전액:", exchange_money) print("남은돈:", left_money)
Python
1
response = await self._create_subscription(space_id, app_host) if response.get("Id"): logger.info( f"Subscription created for space '{space_id}' with ID {response['Id']}" ) else: logger.error(f"Failed to create subscrip...
Python
1
result_map = {} def __translate(cell: ModuleManageCell): instance_label = to_instance_label(cell.name, cell.kind) # 如果 result 重复就不需要重复创建 if instance_label not in result_map: result = cell.cell_info if len(cell.sub_cells) > 0: ...
Python
1
one); // let inner_rule = Rule { // offset: OffsetKind::Duration(Duration::days(0)), // repetition: Some(RepetitionKind::Duration(Duration::days(4))), // length: Duration::days(2), // }; // let inner_rules = vec![VaRul::from_rule(inner_rule, 1, 1, Some(vec![twelve_hour_day_rule...
Rust
0
logout_user() flash("You have been logged out!", category='info') return redirect(url_for('HomePage')) def run_ollama(prompt, model="llama3"): import subprocess result = subprocess.run( ["ollama", "run", model], input=prompt.encode(), stdout=subprocess.PIPE, stderr=subpr...
Python
1
import numpy as np import lasagne import lasagne.layers import voxnet lr_schedule = { 0: 0.001, 60000: 0.0001, 400000: 0.00005, 600000: 0.00001, } cfg = {'batch_size' : 32, 'learning_rate' : lr_schedule, 'reg' : 0.001, 'momentum' ...
Python
1
# coding: utf-8 from flask import Request from api.auth.permission.permissionresolver import PermissionResolver from api.database.entitymanager import EntityManager from api.database.model.permission import Permission from api.http.request_handlers.requesthandler import RequestHandler from api.http.requesthelper impo...
Python
1
views: Vec::default() } } } impl Server { #[wlroots_dehandle(cursor)] pub fn new(layout_handle: OutputLayoutHandle, cursor_handle: CursorHandle) -> Self { let mut xcursor_manager = XCursorManager::create("default".to_string(), 24).expect("Could not create xcursor \ ...
Rust
0
n: bool, args: Vec<OpIndex>, }, /// A swapstack without an exception clause that is a terminator (i.e. one with KILL_OLD) SwapStackKill { stack: OpIndex, is_exception: bool, args: Vec<OpIndex>, }, /// a multiway branch Switch { cond: OpIndex, def...
Rust
0
tx::default()), vec![Token::Id("a"), Token::Id("+"), Token::Id("b")]) //! ``` //! //! "a+b" will as well: //! //! ``` //! # use rusty_yard::tokenizer::{tokenize, Token}; //! use rusty_yard::Ctx; //! assert_eq!(tokenize("a+b", &Ctx::default()), vec![Token::Id("a"), Token::Id("+"), Token::Id("b")]) //! ``` //! //! # Note...
Rust
0
import os from pathlib import Path from dotenv import load_dotenv from jsonargparse import auto_cli load_dotenv() def run(version: str, publish: bool = False): dist_dir = Path("dist") if not dist_dir.exists(): dist_dir.mkdir() for f in dist_dir.iterdir(): f.unlink() plugins = Path("l...
Python
1
.push(controls); Container::new(content) .width(Length::Fill) .height(Length::Fill) .padding(5) .center_y() .into() } } impl Controls { fn new() -> Self { Self { close: button::State::new(), } } ...
Rust
0
0.SH'] fields = ['current_price', 'volume'] df = await wind_adapter.get_realtime_data( symbols=symbols, fields=fields ) assert isinstance(df, pd.DataFrame) if not df.empty: assert 'symbol' in df.columns assert 'tim...
Python
1
istance(patterns[0], patterns[1]); let one_two_distance = Self::distance(patterns[1], patterns[2]); let zero_two_distance = Self::distance(patterns[0], patterns[2]); let mut point_a: &ResultPointTrait; let point_b: &ResultPointTrait; let mut point_c: &ResultPointTrait; ...
Rust
0
rical(data_y) data_x = normalize(data.values) #define 5-fold cross validation test harness inputDim = len(data_x[0]) print('inputdim = ', inputDim) #Separate out data #X_train, X_test, y_train, y_test = train_test_split(data_x, dummy_y, test_size=0.2) num=0 sss = StratifiedS...
Python
1
this entry point must be a callback is so that this unique lifetime can be /// generated as part of the callback's parameters. Even though this callback API is somewhat /// inconvenient, it has several advantages: /// /// - Inside calls to `Lua::context`, we know that all instances of the 'lua lifetime...
Rust
0
import modelx as mx import pytest def test_update_global_in_space_formula(): """ m-----SpaceA |-x1 | --SpaceA[y]----x3 == m.x1 """ m = mx.new_model() s = m.new_space("SpaceA") def param(y): return {'refs': {'x3': x1}} s.formula = param m.x1...
Python
1
utput = output[:origin_size] output = torch.from_numpy(output) if i < module.get_num_outputs() / 2: cls_score.append(output) else: box_reg.append(output) batch_img_metas = [ data_samples.metainfo for d...
Python
1
extern "C" { pub fn sapp_set_clipboard_string(str_: *const ::std::os::raw::c_char); } extern "C" { pub fn sapp_get_clipboard_string() -> *const ::std::os::raw::c_char; } extern "C" { pub fn sapp_set_window_title(str_: *const ::std::os::raw::c_char); } extern "C" { pub fn sapp_set_icon(icon_desc: *const...
Rust
0
_array_of_vectors() } } impl<T, const M: usize, const N: usize> AsMut<[Vector<T, N>; M]> for Matrix<T, M, N> { fn as_mut(&mut self) -> &mut [Vector<T, N>; M] { self.as_mut_array_of_vectors() } } impl<T, const M: usize, const N: usize> AsRef<[[T; N]; M]> for Matrix<T, M, N> { fn as_ref(&self) -> ...
Rust
0
ths because doing so would produce infinitely many paths of unbounded length -- instead, we only produce the shortest simple paths. See Also -------- shortest_path single_source_shortest_path all_pairs_shortest_path """ method = "unweighted" if weight is None else method if method =...
Python
1
from pathlib import Path from typing import List, Tuple def sample_ids(containing: str = None) -> List[str]: with open(str(Path(__file__).parent / 'index.txt'), 'r') as f: sample_ids = [line for line in f.read().replace('/', '-').split('\n')] if containing is not None: sample_ids = [sa...
Python
1
remoteplayerchat_schema; let db_connection = self.0.get().unwrap(); diesel::insert_into(remoteplayerchat_schema::remoteplayerchat) .values(&( remoteplayerchat_schema::player.eq(db_id), remoteplayerchat_schema::remote_player.eq(&player), remoteplayerchat_schema::remote_server.eq(&re...
Rust
0
import torch import os import time from tqdm import tqdm import numpy as np import pickle import torch.nn.functional as F seq_list = ["05"] count = 0 total_time = 0 for seq in seq_list: feat_root = "/DATA_EDS2/zyp/data_semantic-kitty/multiview_openseg/{}/image_2".format(seq) save_root = feat_root.replace("imag...
Python
1
/// has_dir_missing_size returns false pub fn fetch_some_missing_dir_size(&mut self, tl: &TaskLifetime) { for i in 1..self.lines.len() { if self.lines[i].size.is_none() && self.lines[i].line_type == LineType::Dir { self.lines[i].size = Size::from_dir(&self.lines[i].path, tl)...
Rust
0
{ self.inputctrl_reg().with(f); self } #[doc="Get the CTRLB Register."] #[inline] pub fn ctrlb_reg(&self) -> ::bobbin_mcu::register::Register<Ctrlb> { ::bobbin_mcu::register::Register::new(self.0 as *mut Ctrlb, 0x6) } #[doc="Get the *mut pointer for the CTRLB register."] ...
Rust
0
} let mask = mask as u128; let self_occupied = unsafe { self_occupied.merged_bitboard }; let mut board = !self_occupied & !1; if from < 10 { board &= mask >> (11 - from - 1); } else if from == 10 { board &= mask; } else { board &= mask << (from - 11 + 1); } BitBoard { mer...
Rust
0
fn is_enable(&self) -> bool { *self == TX_TIMEOUT_INT_EN_A::ENABLE } } #[doc = "Field `TX_TIMEOUT_INT_EN` writer - Transmit Timeout Interrupt"] pub type TX_TIMEOUT_INT_EN_W<'a> = crate::BitWriter<'a, u32, EMAC_INT_EN_SPEC, TX_TIMEOUT_INT_EN_A, 3>; impl<'a> TX_TIMEOUT_INT_EN_W<'a> { #[doc = "`0`"] ...
Rust
0
# -*- 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
score_local_max = scores * is_local_max sorted_score = torch.argsort(score_local_max, dim=1, descending=True) # max_num = scores.shape[1] return_idx = sorted_score[:, 0: max_num].detach() return return_idx def seed_sampling(self, src_keypts, tgt_keypts, sampling_num): "...
Python
1
:copy_nonoverlapping(nsstring.UTF8String() as *const u8, bytes.as_mut_ptr(), len); String::from_utf8(bytes).unwrap() } } pub fn nsstr(from: &str) -> id { unsafe { let ns_str = NSString::alloc(nil).init_str(from); msg_send![ns_str, autorelease] } } pub fn nsurl_filename(nsurl: id) -> id { unsafe { l...
Rust
0
t fname = file.to_str().unwrap(); match sce.to_mtx(fname) { Ok(_) => (), Err(y) => panic!("ERROR: {}", y), }; println!("{:?}", fname); let sce_mtx: SingleCellExperiment<f32> = match SingleCellExperiment::from_mtx(fname, b, c) { Ok(x) => x, ...
Rust
0
ServerState { urls_with_active_diagnostics: HashSet<Url>, pub root_dir: PathBuf, } impl ServerState { pub fn new(root_dir: PathBuf) -> Self { ServerState { urls_with_active_diagnostics: HashSet::default(), root_dir, } } pub fn register_url_with_diagnostics(...
Rust
0
from urllib import urlencode as _urlencode from bittrex.constants import BITTREX_BUY_ORDER, BITTREX_DEAL_TIMEOUT from data_access.classes.post_request_details import PostRequestDetails from data_access.internet import send_get_request_with_header from data_access.memory_cache import generate_nonce from utils.debug_u...
Python
1
ces[dst].append(src) ts[dst].append(row['time']) eid[dst].append(idx) for i in tqdm(range(num_nodes)): indptr[i + 1] = indptr[i] + len(indices[i]) indices = np.array(list(itertools.chain(*indices))) ts = np.array(list(itertools.chain(*ts))) eid = np.array(list(itert...
Python
1
mut func: impl FnMut(&[Point]) -> bool, ) -> Result<()> { let mut req = proto::GetPointsInBoxRequest::new(); req.mut_bounding_box().mut_min().set_x(bounding_box.min.x); req.mut_bounding_box().mut_min().set_y(bounding_box.min.y); req.mut_bounding_box().mut_min().set_z(bounding...
Rust
0
pping( data_dir, config.format.time_column ) graph_content = create_dependency_graph( graph_data, column_map ).render_embed() output_path = Path(f"./output/{graph_name}") output_path.mkdir(parents=True, exist_ok=True) ...
Python
1
wrap.set_qdata(*BUILDABLE_GET_INTERNAL_CHILD_QUARK, ret); ret } <reponame>lanPN85/area-cov use std::fs::File; use std::io; use std::io::BufRead; use std::io::prelude::*; use std::path::Path; use models::*; use models::point::Point; pub fn config_from_file(path: &Path) -> Configuration { let mut c = Configuration...
Rust
0
"""Voice transcription dependencies.""" from functools import lru_cache from typing import Annotated from fastapi import Depends from ..core.config import Settings, get_settings from .deepgram_client import ( DeepGramClientProtocol, MockDeepGramClient, ProductionDeepGramClient, ) from .service import Voi...
Python
1
and then synchronize with the other processes self.evidence_embedder_obj.save_shard() torch.distributed.barrier(get_data_parallel_group()) del self.model # rank 0 process builds the final copy if self.is_main_builder: self.evidence_embedder_obj.merge_shards_and_save...
Python
1
h.tail() { Value::Pair(p) => p, _ => panic!("expected pair in obj1.head.tail"), }; assert_eq!(ht.as_mut_ptr(), p5); }); } <filename>src/parser/parse/parser.rs #![allow(unused)] use crate::parser::parse::{ call_node::*, flag::*, operator::*, pipeline::*, token_tree::*, t...
Rust
0
2 will nominate for 10, 20, 30 // assert_ok!(Staking::bond( // Origin::signed(1), // 2, // StakingBalance::RingBalance(1000), // RewardDestination::Controller, // 0 // )); // assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31])); // // 4 will nominate for 10, 20, 40 // a...
Rust
0
#!/usr/bin/env python3 """ 音声情報処理 n本ノック !! """ # MIT License # Copyright (C) 2020 by Akira TAMAMORI # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the Software"), to deal in the Software without restriction, # including without...
Python
1
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models class ResUsers(models.Model): _inherit = "res.users" last_role_line_modification = fields.Datetime( compute="_compute_last_role_line_modification", ) def _compute...
Python
1
rsion_id, revision_id ), ), })?; Ok(PurchaseOrderRevisionSlice::from( purchase_order_revision.ok_or_else(|| { ErrorResponse::new( 404, &format!("Purchase order {} not found", purchase_order_uid), ) })?, ...
Rust
0
PhysicalAddress; use super::{AllocatorError, FrameAllocator}; bitflags! { /// Allocation status of a page. struct PageFlags: u8 { const TAKEN = 1 << 0; const LAST = 1 << 1; } } /// A descriptor for a physical memory page. #[derive(Debug, Clone, PartialEq, Eq)] struct PageDescriptor { ...
Rust
0
); assert_eq!(point.manhattan_distance_from(Point::new(17, -8)), 25); assert_eq!(point.manhattan_distance_from(Point::new(-17, 8)), 25); assert_eq!(point.manhattan_distance_from(Point::new(-17, -8)), 25); } #[test] fn test_point_rotate_around() { let mut point = Point::new(4, 10); let origin ...
Rust
0