text
string
label_name
string
labels
int64
MESPACE); assert_eq!( database .get_messages_range(&prefix, Some(&prefix_end)) .unwrap() .messages .len(), 0 ) } } extern crate proc_macro2; extern crate proc_quote; use proc_macro2::{Ident, Span, TokenStream}; ...
Rust
0
22, 1, 1, 0, 0, 0) ), OHLCVRecord( pool_id="test_pool", timeframe="1h", timestamp=1640998800, # Next hour open_price=Decimal("105.0"), high_price=Decimal("115.0"), low_price=Decimal("100.0"), ...
Python
1
soft drop if now.timestamp_millis() - self.now_drop.timestamp_millis() > Self::SOFT_DROP_DELTA { // 1 / 20 秒ごとに self.now_drop = now; //基準をリセット(0から数え直し) return self.grid.next.drop(&self.grid.colors); } } true } fn right_left_check(&mut se...
Rust
0
ff = self.chunk_size - self.returned_bytes; event!( Level::TRACE, "RiakResponseStreamChunk: current chunk len={}, diff={}", chunk.len(), diff ); if diff > chunk.len() { self.returned_bytes += chunk.len();...
Rust
0
cro_export] macro_rules! day_solver { ( $transform:expr, $part_one:expr, $part_two:expr ) => { fn main() -> Result<(), Box<dyn std::error::Error>> { use ::std::io::stdin; use $crate::string_from; let data: String = string_from(stdin())?; let intermediate = $transform(&data); if let Some(part_one) =...
Rust
0
import time from concurrent.futures import ProcessPoolExecutor from multiprocessing import current_process def show(name): print(f'starting {name}') print(f'current_process is {current_process()}') time.sleep(3) print(f'finishing {name}') start = time.perf_counter() with ProcessPoolExecutor(max_wor...
Python
1
(mpi, DropFlagState::Absent)) } let block = &mir[loc.block]; match block.statements.get(loc.statement_index) { Some(stmt) => match stmt.kind { mir::StatementKind::SetDiscriminant{ .. } => { span_bug!(stmt.source_info.span, "SetDiscrimant should not exist during borrowck"...
Rust
0
/// /// `ArenaStorable` is used in `tantivy` to force /// a `Copy` object and a `slice` of data to be stored contiguously. pub trait ArenaStorable { fn num_bytes(&self) -> usize; unsafe fn write_into(self, arena: &mut MemoryArena, addr: Addr); } impl<V> ArenaStorable for V where V: Copy, { fn num_byte...
Rust
0
ror), 0x0A => return Err(error), 0x0B => return Err(error), 0x0C => return Err(error), 0x0D => return Err(error), 0x0E => return Err(error), 0x0F => return Err(error), 0x10 => return Err(error), 0x11 => EmbeddedFunction(OutputEmbeddedFunctionTerminalType::RadioTransmitter), 0x12 => E...
Rust
0
_from_decquad(value: decQuad) -> IonCResult<Self> { let ion_decimal = ION_DECIMAL { type_: ION_DECIMAL_TYPE_ION_DECIMAL_TYPE_QUAD, value: _ion_decimal__bindgen_ty_1 { quad_value: value }, }; Self::try_from_existing(ion_decimal) } /// Binds an existing `ION_DECIM...
Rust
0
rics.counter_spec_decode_num_draft_tokens, self.spec_decode_metrics.draft_tokens, ) self._log_counter( self.metrics.counter_spec_decode_num_emitted_tokens, self.spec_decode_metrics.emitted_tokens, ) ...
Python
1
_ = c.renormalize(); *self = Self::from_matrix_eps(self.matrix(), T::default_epsilon(), 0, c.into()) } } /// # 3D axis and angle extraction impl<T: SimdRealField> Rotation3<T> { /// The rotation angle in [0; pi]. /// /// # Example /// ``` /// # #[macro_use] extern crate approx; //...
Rust
0
import re, math from base import * # Read the input file with open("input3", "r") as file: prog = file.read() # Calculate the multiplication of two values from expression def calculate_mul(expr): return math.prod(map(int, expr[4:-1].split(","))) # Solution 1 - sum all valid multiplication expressions print1(...
Python
1
"""Python bindings for 0MQ""" # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. from __future__ import annotations import os import sys from contextlib import contextmanager @contextmanager def _libs_on_path(): """context manager for libs directory on $PATH Works ...
Python
1
.unwrap(); items .iter() .try_for_each(|f| self._apply_to(&id, f, arena))?; } } Ok(()) } } <filename>libjose/examples/custom_claims.rs // Copyright 2020-2021 <NAME> // SPDX-License-Identifier: Apache-2.0 //! cargo run --example cu...
Rust
0
import tkinter as tk from tkinter import ttk import datetime import time import windCall as pyautogui# type: ignore def get_datetime(): """获取当前日期和时间""" return str(datetime.datetime.now()) def sleep(seconds): """休眠的异常处理""" if seconds < 0: print_log("休眠时间小于0,跳过", "red") return try: ...
Python
1
288988], [0.01160714, 0.02764244, 0.01288988], [0.01075, 0.02764244, 0.01288988], [0.00989286, 0.02764244, 0.01288988], [0.00903571, 0.02764244, 0.01288988], [0.00817857, 0.02764244, 0.01288988], [0.00732143, 0.02764244, 0.0...
Python
1
color == "red": key_name = "Красных" elif color == "blue": key_name = "Синих" elif color == "green": key_name = "Зеленых" else: key_name = color.capitalize() ...
Python
1
eaf_node_cm menu.popup(pos) def closeChildrenViews(self, nodepath, filepath): """Close views being overwritten during node editing. :Parameters: - `nodepath`: the full path of the node that is overwrting other nodes - `filepath`: the full path of th...
Python
1
from .bihyung import * from pathlib import Path # it won't work when package is archived within a package # we might need to create temp files... _server_path = (Path(__file__).parent / "server").absolute().as_posix() def daemon_from_model(model: bihyung.Model) -> bihyung.DaemonHandle: return bihyung._daemon_from...
Python
1
import numpy as np import time class Basic_Problem: """ Abstract super class for problems and applications. """ def reset(self): self.T1=0 def eval(self, x): """ A general version of func() with adaptation to evaluate both individual and population. """ sta...
Python
1
n range(num_pages): if page > 0: print(f"Переход на страницу {page + 1} результатов...") try: # Находим кнопку перехода на следующую страницу next_page_selectors = [ f"a[aria-label='Страница {page + 1}']", f"//a[cont...
Python
1
step.attempts = step.attempts + 1 if result == StepStatus.Pending: # Wait some time before the next run ignore_version_while_saving = True time.sleep(1) except Exception: step.status = "Failure" step.traceback = frappe.get_traceback(with_context=True) step.end = frappe.utils.now_datetim...
Python
1
e() update_multiplier() # Process frame frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGB) boxes = detector.detect(frame_rgb) # Find closest box circle_positions = [] if boxes: closest_box = None min_d...
Python
1
= writer.prefix("Encrypted"); if let Some(var_4014) = &input.encrypted { scope_4013.boolean(*var_4014); } #[allow(unused_mut)] let mut scope_4015 = writer.prefix("Hypervisor"); if let Some(var_4016) = &input.hypervisor { scope_4015.string(var_4016); } #[allow(unused_mut)] ...
Rust
0
um_upgrader") .unwrap_or(Some(0)) .unwrap_or(0); let _num_builder: i32 = screeps::memory::root() .i32("num_builder") .unwrap_or(Some(0)) .unwrap_or(0); let _num_harvester: i32 = screeps::memory::root() .i32("num_harvester") .unwrap_or(Some(0)) .unw...
Rust
0
_params(ctx) # If the last complete arg is an option name with an incomplete # value, the option will provide value completions. for param in params: if _is_incomplete_option(ctx, args, param): return param, incomplete # It's not an option name or value. The first argument without ...
Python
1
let track_name = args.rest(); let track_name_encoded = utf8_percent_encode(&track_name, NON_ALPHANUMERIC).to_string(); let track_search = spotify().search_track(&track_name_encoded, 1, 0, None); let track_result = &track_search.unwrap().tracks.items; let track = track_result.first().unwrap(); let t...
Rust
0
as isize) as *mut opj_image_comp_t; /* Compute the intersection of the area of interest, expressed in tile coordinates */ /* with the tile coordinates */ let mut tcx0 = opj_uint_max( (*tilec).x0 as OPJ_UINT32, opj_uint_ceildiv((*p_tcd).win_x0, (*image_comp).dx), ); let mut tcy0 = opj_uint_max( (*t...
Rust
0
""" Watch over a stream of numbers, incrementally learning their median. Implemented via nested lists. New numbers are added to `lst[i]` and when it fills up, it posts its median to `lst[i+1]`. Wen `lst[i+1]` fills up, it posts the medians of its medians to `lst[i+2]`. Etc. When a remedian is queried for the current m...
Python
1
ction print("End-effector Position:", end_point_position_candidate) joints = None try: joints = baxter_utils.IK(left_arm, end_point_position_candidate, ee_orientation) except Exception as e: print("[ERROR] no joints position returned by the Inverse Kinematic fn") print("end_poin...
Python
1
''' Merge Sorted Linked Lists Input: 1 -> 2 -> 4, 1 -> 3 -> 4 Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4 ========================================= Simple solution with pointers manipulation (just change the pointers of the old nodes, if there is smaller node than the old one). Time Complexity: O(N + M) Space Compl...
Python
1
return _getModel().bottomgates def bottomBarrierGates(): return _getModel().bottomgates[0::2] def get_two_dots(): """ return all possible simple two-dots """ bg = bottomGates() two_dots = [dict({'gates': bg[0:3] + bg[2:5]})] # two dot case for td in two_dots: td['name'] = '-'.join(td...
Python
1
from .user import User, AuthTokens
Python
1
let opts = BobOptions::new_get(None); let result = bob.grinder().get(key, &opts).await?; Ok(Content(infer_data_type(&result), result.inner().to_owned())) } #[post("/data/<key>", data = "<data>")] async fn put_data( bob: &State<BobServer>, key: Result<DataKey, StatusExt>, data: Data<'_>, ) -> R...
Rust
0
from lsdb.catalog import Catalog from lsdb_rubin.tract_patch_search import tract_patch_search Catalog.tract_patch_search = tract_patch_search def test_tract_patch_search_tract(lsst_skymap_reader, small_sky_catalog): """Test the tract_patch_search function with the small_sky catalog.""" tract = 792 result...
Python
1
0, }, flags: flags.bits(), ..unsafe { mem::zeroed() } } } #[doc(hidden)] mod ioctl { use crate::bindings::{v4l2_event, v4l2_event_subscription}; nix::ioctl_read!(vidioc_dqevent, b'V', 89, v4l2_event); nix::ioctl_write_ptr!(vidioc_subscribe_event, b'V', 90, v4l2_event_subscript...
Rust
0
import torch from torch import nn from .facial_recognition.model_irse import Backbone import torchvision from PIL import Image class IDLoss(nn.Module): def __init__(self, ref_path=None, img=None): super(IDLoss, self).__init__() # print('Loading ResNet ArcFace for ID Loss') self.facenet = B...
Python
1
=> { let len = rows.len(); for (key, value) in rows { object.records.insert(key, value); } Ok(Ok(Ok(len))) } None => Ok(Ok(Err(DefinitionError::ObjectDoesNotExist))), }, ...
Rust
0
with a zero fractional part": // https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.1.1 // So if there's an actual fractional part, then only "number" is valid, // but for any other numeric value, then "integer" is als...
Rust
0
import streamlit as st from config import pdf_folder_path, persist_directory from utils.vectors import load_vector_db from utils.flashcards import create_flashcards_on_topic, create_flashcards_generally from langchain.docstore.document import Document vectordb = load_vector_db( pdf_folder_path, persist_directory...
Python
1
# -*- coding: utf-8 -*- import re _元音 = { 'a': 'a', 'i': 'i', 'e': 'ə', 'u': 'u', 'o': 'o', 'aa': 'aː', 'ii': 'iː', 'ee': 'əː', 'uu': 'uː', 'oo': 'oː', } _滑音 = {'w': 'w', 'y': 'j', } _輔音 = { 'p': 'p', 't': 't', 'k': 'k', "'": 'ʡ', '^': 'ʔ', 'c': 'ts', 'f': 'f', 'd': 'ɬ', 's': 's', 'z': 'z', 'x'...
Python
1
1) if mime and clean_mime(mime) not in ['bmp', 'gif', 'jpg', 'jpeg', 'png']: sha1 = default.split('|')[0]; mime = cache.get('%s_mime' % sha1) b64 = cache.get('%s_b64_large' % sha1) if not b64 or not mime: av = None try: av = Avatar.objects.get(sha1=sha1) ...
Python
1
kulize: bool = True, drawer: object = None, **kwargs): """ Convert a molecule to SVG. Parameters ---------- mol: Mol Molecule to convert. molSize: Tuple[int, int] Size of the molecule. kekulize: bool If True, the molecule is kekulized. drawer: object Obje...
Python
1
development segment should sort after those with one. if dev is None: _dev = Infinity else: _dev = dev if local is None: # Versions without a local segment should sort before those with one. _local = NegativeInfinity else: # Versions with a local segment need t...
Python
1
''' 批量下载豆瓣首页的图片 采用伪装浏览器的方式爬取豆瓣网站首页的图片,保存到指定路径文件夹下 ''' #导入所需的库 import urllib.request,socket,re,sys,os #定义文件保存路径 targetPath = "E:\\projects\\Spider\\03_dbImages" def saveFile(path): #检测当前路径的有效性 if not os.path.isdir(targetPath): os.mkdir(targetPath) #设置每个图片的路径 pos = path.rindex('/') t = os...
Python
1
published #[structopt(long, default_value = "surface")] lens: TileLens, /// Hide geographic features such as rivers, lakes, etc? Only relevant for /// rendered output formats, such as SVG. #[structopt(long)] hide_features: bool, /// The logging level to use during world generation. See ...
Rust
0
T>::remove(sale_id); Ok(()) } } } // impl <T: Config> Pallet<T> { // }use std::convert::TryFrom; use std::fmt; use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use std::vec::IntoIter; use crate::errors::NetAddsError; use crate::range::Ipv4AddrRange; use crate::network::{NetworkAddrParseE...
Rust
0
network for inference save_inference_path = './inference_model' input_shapes = [[None, env.observation_space.shape[0]]] input_dtypes = ['float32'] agent.save_inference_model(save_inference_path, input_shapes, input_dtypes, model.actor_model) if __name__ == "__main__": ...
Python
1
s = input() l = len(s) def abc(n): print(n, end=" ") if n == 1: return abc(n-1) print(n, end=" ") abc(l)
Python
1
let mut acc = QA_Account::new( "RustT01B2_RBL8", "test", "admin", 100000.0, false, "backtest", ); acc.init_h(code); acc.buy_open(code, 10.0, "2020-01-20", 3500.0); assert_eq!(acc.get_volume_long(code), 10.0); ...
Rust
0
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. 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 re...
Python
1
import numpy as np import pytest import pandas.util._test_decorators as td from pandas import ( Categorical, DataFrame, ) # _is_homogeneous_type always returns True for ArrayManager pytestmark = td.skip_array_manager_invalid_test @pytest.mark.parametrize( "data, expected", [ # empty ...
Python
1
lse if stripped.startswith(_COMMENT_PREFIXES): return True if any(stripped.startswith(prefix) for prefix in _CODE_PREFIXES): return True if stripped.endswith(("{", "}", ";")): return True if stripped.startswith(("}", "{", "case ", "default:")): return True if "("...
Python
1
let (seconds, overflow1) = self.seconds.overflowing_mul(rhs as _); if overflow1 { if self.seconds > 0 && rhs > 0 || self.seconds < 0 && rhs < 0 { return Self::MAX; } return Self::MIN; } let (seconds, overflow2) = seconds.overflowing_add(ex...
Rust
0
= frame_meta.get("duration", 0) // 10 # Evita KeyError logger.info("Frame %d: Duration %d ms", index, duration) if duration != delay: logger.warning("Frame duration is incorrect: expected %d, got %d", delay, duration) return False exce...
Python
1
ixer.enable_filter(ch.n_3_cmdlo & 0x0f != 0); } fn mt_pattbreak(&mut self) { self.mt_break = !self.mt_break; } fn mt_posjmp(&mut self, chn: usize) { let ch = &mut self.mt_voice[chn]; self.mt_songpos = ch.n_3_cmdlo.wrapping_sub(1); self.mt_break = !self.mt_break; } ...
Rust
0
custom `name` section. pub params: Box< [( Option<ast::Id<'a>>, Option<ast::NameAnnotation<'a>>, ValType<'a>, )], >, /// The results types of a function. pub results: Box<[ValType<'a>]>, } impl<'a> FunctionType<'a> { fn finish_parse(&mut self, al...
Rust
0
hape is None: # Ensure we're only using the first two dimensions for shape calculation if len(img.shape) > 2: shape = img.shape[:2] else: shape = img.shape else: current_shape = img.shape[:2] if len(img.shape) > 2 else img.shape ...
Python
1
# -*- coding: utf-8 -*- from __future__ import annotations from os.path import isfile from typing import TYPE_CHECKING from .core import log from .glossary_utils import Error from .text_utils import ( joinByBar, splitByBar, ) if TYPE_CHECKING: import sqlite3 from collections.abc import Generator, Iterator from...
Python
1
from unittest import TestCase from unittest.mock import Mock import interfaces from core.wl import * from core.wl.object import MockObject class TestUnresolvedObject(TestCase): def test_resolves_to_object_returned_by_db(self): o = UnresolvedObject(7, None) db = Mock(spec=interfaces.Connection) ...
Python
1
nKey("roles.role_id", ondelete="CASCADE"), nullable=False ) granted_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), nullable=False ) class UserORM(Base): """用户ORM模型""" __tablename__ = "users" __table_args__ = ( C...
Python
1
ception`](crate::error::BadRequestException) pub mod bad_request_exception { /// A builder for [`BadRequestException`](crate::error::BadRequestException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) me...
Rust
0
use std::f64::consts::PI; use crate::geometry::build_interpolating_poly; #[test] fn interpolation_test_linear() { let error_margin = 0.00001; let knots = vec![0.0, 1.0]; let values = vec![0.0, 1.0]; let interpolating_poly = build_interpolating_poly(knots.clone(), values.cl...
Rust
0
"""Updated checkconstraint with underscore on username in pom_user Revision ID: 874158ad90c6 Revises: 6d9ebe48cb1e Create Date: 2024-10-02 10:36:06.201604 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = "874158ad90c6" d...
Python
1
a = list(map(int, input().split())) sum_a = (a[0] + a[1])% a[2] sum_b = ((a[0] % a[2]) + (a[1] % a[2])) % a[2] sum_c = (a[0] * a[1]) % a[2] sum_d = ((a[0] % a[2] * a[1] % a[2])) % a[2] print(sum_a) print(sum_b) print(sum_c) print(sum_d)
Python
1
zymatching: bool, /// use custom zlib encoder instead of built in one (default: None) pub custom_zlib: custom_compress_callback, /// use custom deflate encoder instead of built in one (default: null) /// if custom_zlib is used, custom_deflate is ignored since only the built in /// zlib function will...
Rust
0
} } <filename>examples/custom_asset_packfile.rs use bevy_app::prelude::*; use bevy_app::{AppExit, ScheduleRunnerPlugin}; use bevy_asset::importer::text_importer::Text; use bevy_asset::prelude::*; use bevy_ecs::prelude::*; use bevy_log::prelude::*; use bevy_log::LogPlugin; fn main() { App::new() .add_plug...
Rust
0
tencilFuncSeparate({:#X}, {:#X}, {:?}, {:?});", face, func, ref_, mask ); } let out = call_atomic_ptr_4arg( "glStencilFuncSeparate", &glStencilFuncSeparate_p, face, func, ref_, mask, ); #[cfg(all(debug_assertions, feature = "debug...
Rust
0
"""Filters.""" import fnmatch import pathlib def filter_sources( *, sources: tuple[pathlib.Path, ...], include: list[str], exclude: list[str], respect_gitignore: bool, extension: str = "sql", ) -> set[pathlib.Path]: """Filter sources base on include and exclude and either respect gitignor...
Python
1
peline='en_core_web_sm', checkpoint=True, checkpoint_step=30, enable_tqdm=True) familiarity_llm.evaluate(questions + hints + answers) familiarity_llm.release_memory() """""""""""Familiarity""""""""""" """""""""""AnswerLeakage""""""""""" """""""""""AnswerLeakage - Lexical""""""""""" answer_leakage_lexical = Lexical('i...
Python
1
nt(f" 📈 Señal principal: {result['primary_signal']}") print(f" 🎯 Confianza: {result['confidence']*100:.1f}%") print(f" ⏰ Horizonte recomendado: {self.get_recommended_horizon(temporal_predictions)} minutos") # Mostrar estimación de precio si está disponible if current_pri...
Python
1
post_async("/updatelikes", |mut req, ctx| async move { // get value <username>-<time> let mut new_post: Value = req.json::<serde_json::Value>().await?; let kv = ctx.kv("my-app-general_posts_preview")?; let new_post_obj = new_post.as_object_mut().unwrap(); let ...
Rust
0
to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons t...
Rust
0
al_block_hash(), block_hash.pack()); assert_eq!(lock_args.withdrawal_block_number().unpack(), block_number); assert_eq!(lock_args.owner_lock_hash(), owner_lock.hash().pack()); // ## None asset script let (output2, data2) = build_withdrawal_cell_output( &rollup_context, ...
Rust
0
import os import json import re import shutil json_path = 'prompts/VBench2_full_text_info.json' source_video_file = '/mnt/petrelfs/zhengdian/zhengdian/VBench2.0/sample_video/vbench2_videos' # CHANGE target_video_file = '/mnt/petrelfs/zhengdian/zhengdian/VBench2.0/sample_video/Vidu_Q1' # DEFAULT with open(json_path, 'r...
Python
1
= self.read::<u16>(addr); let res = self.cpu().regs.status.has(Status::CARRY) as u16 | (val << 1); self.cpu_mut() .regs .status .set_if(Status::CARRY, val & 0x8000 > 0); self.cpu_mut().update_nz16(res); self.write(addr, res...
Rust
0
# Copyright (c) 2018 Mandar Gogate, All rights reserved. import logging import cv2 import numpy as np from config import img_height, img_width from utils.generic import get_files GRID_TRANSCRIPTION = { 0: dict(b="bin", l="lay", p="place", s="set"), 1: dict(b="blue", g="green", r="red", w="white"), 2: d...
Python
1
import streamlit as st import numpy as np import joblib import os import shap import matplotlib.pyplot as plt # Streamlit config st.set_page_config(page_title="MedGPT – Diabetes Prediction", layout="centered") st.title("🧬 MedGPT: Diabetes Risk Predictor") # Load model and scaler model_path = "app/diabetes_model.pkl"...
Python
1
import allure import pytest import requests import urls import helper from data import TestDataBody @allure.step('Создание данных для уникального пользователя и дальнейшее его удаление') @pytest.fixture(scope='function') def payload_data_new(): payload = helper.TestMethodsHelper.create_random_login_password() ...
Python
1
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # import torch import math import nu...
Python
1
for this "family" of products, such as ``ard``, ``level1`` or ``fc``. It's used for grouping similar products together. They products in a family are usually produced the same way but have small variations: they come from different sensors, or are written in different projections, etc. ...
Python
1
( &self, relation: &mut MirRelationExpr, applied_projections: &HashMap<Id, Vec<usize>>, ) { relation.visit_mut_pre(&mut |e| { if let MirRelationExpr::Project { input, outputs } = e { if let MirRelationExpr::Get { id: inner_id, .. } = &**input { ...
Rust
0
N)r$cGs|jd|g|Rd|iS)Nrr$) call_laterr r!r$r"r%r%r& call_soonszAbstractEventLoop.call_sooncGstdSr9ra)r delayr!r$r"r%r%r&rsszAbstractEventLoop.call_laterc...
Python
1
r = self.stops.at(self.spread.at(offset)); if self.linear_colors { color } else { color.into_linear() } } fn transform(&self) -> Transform { self.tr } fn units(&self) -> Option<Units> { Some(self.units) } } #[cfg(test)] mod tests { ...
Rust
0
import matplotlib.pyplot as plt import pandas as pd # ------------------------------ # 1. Hyperparameter Optimization # ------------------------------ data_opt = { "rsi_period": [10,10,10,10,10], "oversold": [25,25,25,25,25], "overbought": [65,65,65,65,65], "stop_loss": [0.5,0.5,0.5,1.0,1.0], "take...
Python
1
class Solution: def reverseWords(self, s: str) -> str: word=s.split() word.reverse() return ' '.join(word)
Python
1
import os import zlib import sys from deca.file import ArchiveFile in_file = sys.argv[1] with ArchiveFile(open(in_file, 'rb')) as f: magic = f.read(4) version = f.read_u32() aic = f.read(8+16+4) uncompressed_length = f.read_u32() # uncompressed length, whole file section_size = f.read_u32() # un...
Python
1
ic_key + "\nABCD", } self.client.force_authenticate(staff) response = self.client.post( factories.SshPublicKeyFactory.get_list_url(), data=data ) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertFalse(core_models.SshPublicKey.ob...
Python
1
ap(); let mut poly_key = [0u8; 32]; cipher.apply_keystream(&mut poly_key); cipher.seek(64); cipher.apply_keystream(&mut context.unprocessed_part()[LEN_SIZE..LEN_SIZE + len as usize]); // Safety // // Safe because the instance of the cipher is dropped immediatel...
Rust
0
refiner.model) negative_refiner = clip_separate_after_preparation(negative, target_model=current_refiner.model) positive_refiner = encode_model_conds(current_refiner.model.extra_conds, positive_refiner, noise, device, "positive", latent_image=latent_image, denoise_mask=denoise_mask) negative_re...
Python
1
// [notifications](https://docs.microsoft.com/en-us/windows/win32/controls/bumper-date-and-time-picker-control-reference-notifications). /// /// These event methods are just proxies to the /// [`WindowEvents`](crate::gui::events::WindowEvents) of the parent window, who /// is the real responsible for the child even...
Rust
0
('training') self.epoch_logs = [] def log_epoch(self, epoch: int, train_loss: float, val_loss: Optional[float] = None, train_metrics: Optional[Dict[str, float]] = None, val_metrics: Optional[Dict[str, float]] = None): """记录训练轮次""" log_data = { ...
Python
1
eu4 melt failed"); } let out_len = rakaly_melt_data_length(melted); let mut out: Vec<u8> = vec![0; out_len]; let _wrote_len = rakaly_melt_write_data(melted, out.as_mut_ptr() as *mut i8, out.len()); let _ = std::io::stdo...
Rust
0
0]: hor_growth = 'right' target_width = Window.width - c[0] - self.border_margin # if there's more space to the left: else: hor_growth = 'left' target_width = c[0] - self.border_margin if ver_growth == 'down': tar_y = c[1] - target_height else: # should always be 'up' tar_y = c[1...
Python
1
#[allow(unused_variables)] fn layer_benchmark(c: &mut Criterion) { #[cfg(feature = "layer-absolute")] { let mut group = c.benchmark_group("Absolute"); group.bench_function("no match", |b| { let patterns = vec!["rdkafka"]; let absolute_layer = AbsoluteLayer::from_pattern...
Rust
0
nder 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 * distribute...
Rust
0
import FWCore.ParameterSet.Config as cms generator = cms.EDFilter("Pythia8GeneratorFilter", comEnergy = cms.double(8000.0), crossSection = cms.untracked.double(2948), filterEfficiency = cms.untracked.double(1.0), maxEventsToPrint = cms.untracked.int32(0), pythiaHepMCVerbosity = cms.untracked.bool(False), ...
Python
1
import re from datetime import datetime, timedelta, tzinfo ISO8601_RE = re.compile(r""" (?P<YYYY>\d{2,4}) (?:-?(?P<MM>[01]\d))? (?:-?(?P<DD>[0-3]\d))? (?:T (?P<hh>[0-2]\d) (?::?(?P<mm>[0-5]\d))? (?::?(?P<ss>[0-5]\d))? (?:[,.](?P<s>\d+))? )? (?P<TZD>Z| (?...
Python
1
; x = { b = 2; c = { b + a }; c }; y = { a + x }; y").to_yield(4) } <filename>src/merge/tuple.rs use crate::stream::IntoStream; use crate::utils; use crate::Merge as MergeTrait; use futures_core::Stream; use std::pin::Pin; use std::task::{Context, Poll}; impl<T, S0, S1> MergeTrait for (S0, S1) where S0: IntoStrea...
Rust
0