text
string
label_name
string
labels
int64
#!/usr/bin/env python3 # Copyright (c) OpenMMLab. All rights reserved. """HuixiangDou binary.""" import argparse import json import os import time from multiprocessing import Pool, Process, Value import pytoml import requests from loguru import logger from .service import ErrorCode, Worker, llm_serve class Task: ...
Python
1
} }); let message_label = LabelBuilder::new().name("events").build(); info_bar.get_content_area().add(&message_label); Self { info_bar, message_label, } } pub(super) fn update(&self, game_state: &GameState) { self.message_label.h...
Rust
0
roles` /// /// * [`organizations.roles.list()`](/iam/reference/rest/v1/organizations.roles/list): /// `organizations/{ORGANIZATION_ID}`. This method lists all /// organization-level [custom roles](/iam/docs/understanding-custom-roles). /// Example request URL: /// `https://iam.googleapi...
Rust
0
import contextlib import functools import pickle from collections.abc import Callable from typing import Any from redis import Redis Serializer = Callable[[Any], bytes] Deserializer = Callable[[bytes], Any] def cached_query( ttl_seconds: int, key_fn: Callable[[Any], str] | None = None, serializer: Serial...
Python
1
"Reference Selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum REFSEL_A { #[doc = "0: Internal Bandgap Reference"] INTREF = 0, #[doc = "2: 1/2 VDDANA"] INTVCC0 = 2, #[doc = "3: VDDANA"] INTVCC1 = 3, #[doc = "4: External Reference A"] AREFA = 4,...
Rust
0
image_analysis_fallback_prompt": IMAGE_ANALYSIS_FALLBACK_PROMPT, "image_analysis_error_message": IMAGE_ANALYSIS_ERROR_MESSAGE, "task_entry_prompt": TASK_ENTRY_PROMPT, "image_generation_user_prompt": IMAGE_GENERATION_USER_PROMPT, "about_text": ABOUT_TEXT, "new_chat_session_message...
Python
1
, r) elif vignetting_polynomial_2d_size > 0: # 2d polynomial xv = x.T / x_dim yv = y.T / y_dim k = meta.vignette_polynomial2D() e = meta.vignette_polynomial2Dexponents() p2 = np.zeros_like(xv, dtype=float) for i, c in enumerate(k): ex = e[2 * i] ...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from aiogram import types, Router from aiogram.types import Message from aiogram.filters import Command from aiogram.fsm.context import FSMContext from bot.keyboards.user_keyboards import start_keyboard, menu_keyboard, add_task_keyboard, new_task_add_keyboard, delete_tas...
Python
1
ef addParentContextMenus(self, item, menu, event): """ Can be called by any item in the scene to expand its context menu to include parent context menus. Parents may implement getContextMenus to add new menus / actions to the existing menu. getContextMenus must accept 1 argument (the eve...
Python
1
# error occurred, in which case it depends on the error. This reminds us that # clean shouldn't be used in production if tmp_write_arg == "fail": assert not localStore.exists(container_id) else: survived = localStore.l...
Python
1
'method': self.allocation_method.value, 'risk_budget_method': self.risk_budget_method.value, 'target_volatility': self.target_volatility, 'num_assets': len(constrained_weights) } ) # 更新歷史和統計 ...
Python
1
pub const XK_3270_AltCursor: u32 = 0xfd10; pub const XK_3270_KeyClick: u32 = 0xfd11; pub const XK_3270_Jump: u32 = 0xfd12; pub const XK_3270_Ident: u32 = 0xfd13; pub const XK_3270_Rule: u32 = 0xfd14; pub const XK_3270_Copy: u32 = 0xfd15; pub const XK_3270_Play: u32 = 0xfd16; pub const XK_3270_Setup: u32 = 0xfd17; pub c...
Rust
0
); } fn create_module_13() -> ResultObject { let module_str = "(module (global (;0;) i32 (i32.const 0)) (export \"a\" (global 0))) "; let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed"); instantiate(wasm_binary, spectest_importobject(), None).expect("WASM ...
Rust
0
<Self, T, E> { Unwrap { iter: self, phantom: PhantomData } } /// Create an iterator which yields the unwrapped value or a default as the next value. fn unwrap_or(self, def: T) -> UnwrapOr<Self, T, E> { UnwrapOr { iter: self, def: def, phantom: PhantomData } } /// Count the number of ...
Rust
0
import sys from pathlib import Path import asyncio sys.path.append(str(Path(__file__).parent.parent.parent)) import g4f g4f.debug.logging = True from g4f.debug import access_token provider = g4f.Provider.OpenaiChat iso = "GE" language = "german" translate_prompt = f""" Translate this markdown document to {language}...
Python
1
# Copyright 2017 Google Inc. 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 applicable law or a...
Python
1
mage, resolution, slider_1=None, slider_2=None, slider_3=None, input_mask=None, **kwargs): if input_mask is None: return input_image H, W, C = input_image.shape raw_color = input_image.copy() raw_mask = input_mask.copy() input_image, remove_pad = resize_image_with_p...
Python
1
# This file is part of OpenHatch. # Copyright (C) 2009 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later v...
Python
1
shm_context = create_coworker_shm_context( sample_batch=sample_batch, shm_data_size=shm_data_size[idx], shm_name_prefix=shm_name_prefix[idx], io_timeout=io_timeout, initialize_timeout=initialize_timeout, ) ...
Python
1
from UQpy.stochastic_process import BispectralRepresentation import numpy as np n_sim = 100 # Num of samples n = 1 # Num of dimensions # Input parameters T = 60 # Time(1 / T = dw) nt = 256 # Num.of Discretized Time F = 1 / T * nt / 2 # Frequency.(Hz) nf = 128 # Num of Discretized Freq. # # Generation of Input Da...
Python
1
r_type == Error::Relative && abs(x_act) > Float::epsilon() { abs((x_act - x_prev)/x_act) } else { abs(x_act - x_prev) } } pub fn load_function(f: String) -> Result<impl Fn(f64) -> f64, Pessimistic>{ let expr: meval::Expr = match f.as_str().parse() { Ok(e) => e, Err(_) => ret...
Rust
0
from myscan.lib.scriptlib.ssti.languages import javascript class Ejs(javascript.Javascript): def init(self): self.update_actions({ 'render' : { 'header': """<%%- '%(header)s'+""", 'trailer': """+'%(trailer)s' %%>""", }, 'write' : { ...
Python
1
1c37, 0x1c90, 0x1c91, 0x1ca8, 0x246f, 0x6a5f, 0x6aee, 0x6aef, 0x6b5a, 0x6b62, 0xbc9a, 0xbc9b, 0xd127, 0xd128, 0xd455, 0xd49d, 0xd4a0, 0xd4a1, 0xd4a3, 0xd4a4, 0xd4a7, 0xd4a8, 0xd4ad, 0xd4ba, 0xd4bc, 0xd4c4, 0xd506, ...
Rust
0
from ScoutSuite.providers.aws.facade.base import AWSFacade from ScoutSuite.providers.aws.resources.base import AWSResources from ScoutSuite.providers.aws.utils import format_arn class Grants(AWSResources): def __init__(self, facade: AWSFacade, region: str, key_id: str): super().__init__(facade) se...
Python
1
nt(f" - Annual Return: {getattr(metrics, 'annual_return', 0):.2%}") if rejected_factors: print(f"\n REJECTED FACTORS:") for factor_name, result in rejected_factors: metrics = result.get('metrics') if metrics: print(f" • {factor_name}") print(f" - IC: {getattr(metr...
Python
1
nsforms to priors """ loss = self.camera_mlp.compute_distance_to_prior() return loss # def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): # self.pos_embedding.update_step(epoch, global_step, on_load_weights=False) # hg_conf = self.pos_encod...
Python
1
outer: { fn adapter(&self) -> &dyn types::Adapter; fn adapter_mut(&mut self) -> &mut dyn types::Adapter; fn len_at(&self, indexes: &[usize]) -> Option<usize> { self.adapter().len_at(indexes) } } inner: { ...
Rust
0
/// ``` /// /// [`Top`]: crate::alignment::VerticalAlignment::Top FitToText, /// If the text does not fill the bounding box, shrink the [`TextBox`] to be as tall as the /// text. /// /// # Example: `ShrinkToText` does not grow the [`TextBox`]. /// /// ```rust /// # use embed...
Rust
0
logo_small.png"), ("sparkylinux", "https://upload.wikimedia.org/wikipedia/commons/thumb/1/16/SparkyLinux-logo-200px.png/110px-SparkyLinux-logo-200px.png"), ("suse linux enterprise desktop", "https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/SLED_15_Default_Desktop.png/300px-SLED_15_Default_Desktop.png")...
Rust
0
import os import platform import subprocess from shutil import which MSG_CANNOT_RUN_NODE = "Cannot run Node.js. Make sure it's in your PATH." # # Linux: it may be "node" or "nodejs" # Mac: need to specify path # NODE_FILE = 'node' pl = platform.system() if pl == 'Darwin': NODE_FILE = '/usr/local/bin/node' else: ...
Python
1
restore_kv=restore_kv, ) steps.append( { BkStep.COMMAND: restore_commands, BkStep.LABEL: restore_label, BkStep.TIMEOUT: test_step["restore"][BkStep.TIMEOUT], "agents": { "instance": restore_instanc...
Python
1
ortErrorInfo { description: String::from("in java_library rule //src/main/java/com/com/example:Example: target '@third_party_jvm//3rdparty/jvm/com/google/api/grpc:proto_google_common_protos' is not visible from target '//src/main/java/com/com/example:Example'. Check the visibility declaration of the former ...
Rust
0
rt traceback traceback.print_exc() if __name__ == "__main__": print("Telegram Channel Monitor - For legitimate cybersecurity research only") print("Ensure you have proper authorization and legal compliance") # Install required packages: # pip install telethon pandas openpyxl rarfile ...
Python
1
Op::FLoad(read_u8!(source)), 0x22 => Op::FLoad(0), 0x23 => Op::FLoad(1), 0x24 => Op::FLoad(2), 0x25 => Op::FLoad(3), 0x6A => Op::FMul, 0x76 => Op::FNeg, 0x72 => Op::FRem, 0xAE => Op::FReturn, 0x38 => Op::FStore(...
Rust
0
addr: SocketAddr, mut expected: Vec<NamedMetric64>, location: &'static str, ) -> Result<(), ()> { let mut listener = TcpListener::bind(&addr).await.map_err(|_| ())?; let (socket, _) = listener.accept().await.map_err(|_| ())?; let codec = CarbonDecoder::new(2048); let...
Rust
0
from ultralytics import YOLO def Train(data_path="", test_name="test1"): # Initialize YOLO model model = YOLO("yolov8n-cls.pt") # Train the model with built-in augmentations model.train( data=data_path, epochs=100, imgsz=512, batch=16, workers=48, name=...
Python
1
IMD algorithm once // they stabilize. let zeros: x86_64::__m256i = x86_64::_mm256_setzero_si256(); let mut c0: x86_64::__m256i; let mut c1: x86_64::__m256i; let mut acc: x86_64::__m256i; let mut data: [u8; 32] = [0; 32]; while bytes.len() >= 32 { let...
Rust
0
#Волк Тимофей from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import time driver = webdriver.Chrome() driver.get('https://ci.nsu.ru/news') time.sleep(3) start_date = driver.find_element(By.CSS_SELECTOR, 'input[name="start_date"...
Python
1
import numpy as np import pandas as pd import os #os.environ['NUMBA_DISABLE_JIT'] = '1' # Disable JIT for testing (we can debug numba functions this way) from finmlkit.feature.core.ma import ewma def test_ewma_against_pandas(): """ Test the ewma function against pandas' ewm function to ensure correctness. ...
Python
1
absoulte_path = os.path.join(out_path, audio_file) os.makedirs(os.path.dirname(absoulte_path), exist_ok=True) i += 1 first_word = True audio = wav[int(sr*sentence_start):int(sr*word_end)].unsqueeze(0) # if the audio is to...
Python
1
".to_string(), ) .set_command_callback(Some(execute_wireguard)), ); } } #[derive(Debug)] enum Error { InvalidArguments(String), ServiceNotFound(String), ServiceAlreadyExists(String), ServiceNotConnectable { service_name: String, reason: String, },...
Rust
0
from flask import Flask, request, jsonify from meta_ai_api import MetaAI import time app = Flask(__name__) ai = MetaAI() @app.route('/search', methods=['GET']) def search_query(): query = request.args.get('q') if not query: return jsonify({"error": "Missing 'q' parameter"}), 400 for attempt i...
Python
1
status = 'failed' yield f"data: {json.dumps({'type': 'file_complete', 'filename': file_path.name, 'status': status, 'result': result})}\n\n" except Exception as e: failed_count += 1 logger.error(f"E...
Python
1
import contextlib import os import time import original_examples # type: ignore import pytest import progressbar # Import hack to allow for parallel Tox try: import examples except ImportError: import sys _project_dir: str = os.path.dirname(os.path.dirname(__file__)) sys.path.append(_project_dir) ...
Python
1
{ let mut app = test::init_service(App::new().service(web::resource("/test").to( |payload: Json<JsonPayload>| { let payload = payload.into_inner(); assert_eq!(payload.age, 24); assert_eq!(payload.page_url, "https://my_page.com"); HttpResponse::Ok().finish() ...
Rust
0
if found { Ok(()) } else { Err("never applied remove-delete-operations-query-parameters fixup".into()) } } // Some watch and watchlist operations (eg `watchCoreV1NamespacedPod` and `watchCoreV1NamespacedPodList`) are deprecated in favor of the corresponding list operation // (eg `listCoreV1NamespacedPod`). T...
Rust
0
code: String, } #[derive(Debug, Clone, Deserialize)] pub struct PFilterFactory { pub input: InputLocation, pub output: Option<String>, pub code: String, } #[derive(Debug, Clone, Deserialize)] pub struct RMapFactory { pub input: InputLocation, pub output: Option<String>, }use derive_new::new; use futures::S...
Rust
0
te("AnimationScene1.AnimationTime = times[-1]\n") return fn searchdirs=map(lambda d: os.path.join(d, 'paraview'), [os.environ['INSIGHT_USERSHAREDDIR']]+os.environ['INSIGHT_GLOBALSHAREDDIRS'].split(':')) if opts.list: avail=[] for d in searchdirs+['.']: if os.path.exists(d): avail+=filter...
Python
1
32x4: Sleef_cospif4_u05sse4); impl_unary!(f32x8: Sleef_cospif8_u05avx); impl_unary!(f64x2: Sleef_cospid2_u05sse4); impl_unary!(f64x4: Sleef_cospid4_u05avx); } else if #[cfg(target_feature = "sse4.2")] { impl_unary!(f32x2[t => f32x4]: Sleef_cosp...
Rust
0
import pandas as pd def parse_bed(log_file, out): print("chrom\tleft_start\tleft_end\tright_start\tright_end", file=out) for data_primers in pd.read_csv( snakemake.input[0], sep="\t", header=None, chunksize=chunksize, usecols=[0, 1, 2, 5], ): for row in data...
Python
1
assert result.exit_code == 0 with open(os.path.join(tmpdir, "splitgraph.yml")) as f: repo_yml = f.read() snapshot.assert_match_dir( { "readmes": {"someuser-somerepo_1.b7f3.md": readme_1}, "splitgraph.yml": repo_yml, }, ...
Python
1
// mod dtoa; // TODO: incomplete // mod pyfpe; // TODO: incomplete // Additional headers that are not exported by Python.h pub mod structmember; #[cfg(not(py_sys_config="Py_USING_UNICODE"))] #[inline(always)] pub fn PyUnicode_Check(op : *mut PyObject) -> libc::c_int { 0 } #[cfg(not(py_sys_config="Py_USING_UNICODE...
Rust
0
self.sizes_len); unsafe { self.map.as_mut_ptr().write_bytes(0, self.map.len()); self.map.set_len(length); } } #[inline] unsafe fn get(&self, index: BitArray) -> bool { let map_index = index as usize >> BIT_SHIFT; debug_assert!(map_index < self.map.le...
Rust
0
pub fn ast(&self) -> &Ast { &self.ast } pub fn assign_var<'other>(&'other self, name: &str, value: &'other Value<'other>) where 'other: 'a, { self.frame.bind(name, value) } pub fn evaluate(&'a self, input: Option<&str>) -> Result<&'a Value<'a>> { let input =...
Rust
0
::Connection::open_in_memory().unwrap(); // Force the schema to a newer version conn.pragma_update(None, VERSION_KEY, DB_VERSION_CURRENT + 1) .unwrap(); // Migration should fail. migrate_database(&mut conn).unwrap_err(); } #[test] fn foreign_keys_are_enforced()...
Rust
0
m_trailing_slashes() { let mut app1 = App::<Request, BasicContext>::new_basic(); fn test_fn_1(mut context: BasicContext, _next: impl Fn(BasicContext) -> MiddlewareReturnValue<BasicContext> + Send + Sync) -> MiddlewareReturnValue<BasicContext> { let body = &context.params.get("id").unwrap().clone(); ...
Rust
0
#!/usr/bin/env python # Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
Python
1
1.0 pub font_scale_aspect: f32, pub color: Color, } impl Default for TextParams { fn default() -> TextParams { TextParams { font: Font(0), font_size: 20, font_scale: 1.0, font_scale_aspect: 1.0, color: WHITE, } } } /// Load f...
Rust
0
, (bssid, "gas_query_tx;gas_query_tx_initial_req") ] for addr,func in tests: with alloc_fail(dev[0], 1, func): dev[0].request("ANQP_GET " + addr + " 258") ev = dev[0].wait_event(["GAS-QUERY-DONE"], timeout=5) if ev is None: raise Exception("N...
Python
1
as u32, top.ceil() as u32, Scale::uniform(font_size), &font, text, ); } for (start, end) in table.table_line_position(padding, canvas_width as f32) { draw_line_segment_mut(&mut image_buf, start, end, GRAY_COLOR); } let dyn_image = Dynamic...
Rust
0
nt as _ } } #[doc = "Field `PART_0` reader - Bits\\[7:0\\] of the 12-bit part number of the component. The designer of the component assigns this part number."] pub struct PART_0_R(crate::FieldReader<u8, PART_0_A>); impl PART_0_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PART_0_R(cra...
Rust
0
simple things //! (e.g., copying text from an SVG) harder than they should be. //! //! - **Self-contained tests.** Unlike generic snapshot files, [`Transcript`]s contain //! both user inputs and outputs. This allows using them as images with little additional //! explanation. //! //! # Limitations //! //! - Termi...
Rust
0
.as_bytes(), ) .unwrap(); } if ref_insertions.len() >= 1 { output_writer .write( format!( "{}\n", serde_json::to_string_pretty(&ref_insertio...
Rust
0
m.add("hello", self.tags[3]) m.add(2, self.tags[1]) m.add(True, self.tags[4]) self.assertEqual(m.size(), 4) def test_erase(self): m = Metadata() for tag in self.tags: self.assertFalse(m.erase(tag)) self.populate_metadata(m) for tag in self.small_t...
Python
1
assert (len(faces_halfedge) in [1, 2]) for face_idx in faces_halfedge: # Get face label. face_lab = face_labels[face_idx] # Update edge soft label. edge_soft_labels[halfedge_idx, face_lab] += 0.5 # Create the output folder if non-...
Python
1
"""Extra coverage for BMI visualization guidance chart branches.""" import pytest import bmi_visualization as vizmod def test_guidance_chart_covers_all_recommendation_branches(): try: import matplotlib.pyplot as plt # Local import to avoid stale references except ImportError: # pragma: no cover - ...
Python
1
# Video - https://youtu.be/p9A5ySU8nWU def to_digits(number): digits = [] for x in str(number): digits.append(int(x)) return digits # 79927398713 # 7 + 9 + 9 + 4 + 7 + 6 + 9 + 7 + 7 + 2 + 3 def is_credit_card_valid(number): result = [] digits = to_digits(number) digits_count = len(...
Python
1
import os ###################### local windows or H800 cluster def get_platform(): if os.path.exists('/public/SothisAI'): platform='H800' elif os.path.exists('/workspace/3ddatasets'): platform='local_docker' else: platform='H800_docker' return platform def base_dir(): if get...
Python
1
}; _pyo3::callback::cb_convert( _pyo3::callback::PyObjectCallbackConverter, _py, _result) } } } /// Generate functiona wrapper (PyCFunction, PyCFunctionWithKeywords) pub(crate) fn impl_wrap_getter(cls: &Box<syn::Ty>, name: &syn::Ident) -> Tokens { quote! { ...
Rust
0
_this.make_stub()))); } // we can't get a token yet, make sure correct context are set, then we will go back to wait. if let Some(pool) = ref_this.pool.as_ref() { // only enqueue to wake up if we're in the preemptive mode; otherwise the owning future // will wake us up ...
Rust
0
/// * `client_cache` - cache with a connection to use for performing all lookups pub fn lookup( names: Vec<Name>, strategy: LookupIpStrategy, client_cache: CachingClient<C>, options: DnsRequestOptions, hosts: Option<Arc<Hosts>>, finally_ip_addr: Option<RData>, ...
Rust
0
.interlace.is_none() } fn perform_backup(input_path: &Path) -> Result<(), PngError> { let backup_file = input_path.with_extension(format!( "bak.{}", input_path.extension().unwrap().to_str().unwrap() )); copy(input_path, &backup_file).map(|_| ()).map_err(|_| { PngError::new(&format!(...
Rust
0
ize, value: Octet) { self.elements.insert(i, value); } } // Stores a matrix in sparse representation, with an optional dense block for the right most columns #[derive(Clone, Debug, PartialEq)] pub struct SparseOctetMatrix { height: usize, width: usize, sparse_elements: Vec<SparseOctetVec>, ...
Rust
0
#[case("local.ron", true)] #[case("remote.ron", true)] #[case("rule_without_geo.ron", true)] #[case("wrong_rule.ron", false)] #[case("multiple_acceptors.ron", true)] #[trace] #[tokio::test] async fn config_file_without_geo(#[case] filename: &str, #[case] success: bool) -> Result<()> { ...
Rust
0
function: {:?}", input); } }; Oxpr { ops, dst: input_dst, } } /* pub fn make_sub_ops(input: &Ixpr) -> Oxpr { match input.src { Source::ConstVal(Val::FuncRef(ref cri, ref cvs, ref typ)) => { let mut ops = Vec::with_capacity(cvs.0.len() + 1); let d...
Rust
0
from django.urls import path from .views import ( delete_award, RsuListView, RsuDetailView, delete_vest, RsuVestDetailView, refresh_rsu_trans, refresh_rsu_vest_trans, show_vest_list, add_vest, update_vest, add_vest_sell_trans, show_vest_sell_trans, delete_vest_sell_t...
Python
1
below. let dispatch_pending_ptr = System::port_state().dispatch_pending.get(); unsafe { asm!(" # Read `dispatch_pending` ldrb r1, [r0] tst r1, r1 bne NotShortcutting # `dispatch_pending` is clear, meaning we a...
Rust
0
let cargo_clippy_path = config .cargodir .join(format!("bin/cargo-clippy{}", EXE_SUFFIX)); assert!(cargo_clippy_path.exists()); }); } #[test] fn install_with_components_and_targets() { clitools::setup(Scenario::SimpleV2, &|config| { expect_ok( config, ...
Rust
0
def ask_for_float(message: str) -> float: while True: try: return float(input(message)) except ValueError: print("Insira um número\n")
Python
1
/// Creates a rectangular prism centered at (0, 0, 0) pub fn rectangular_prism(mut x: f32, mut y: f32, mut z: f32, color: Point3<f32>) -> Mesh { x /= 2.0; y /= 2.0; z /= 2.0; let vertices = vec![ // Bottom Vertex::new(-x, y, -z, Point3::new(0.0, 0.0, -1.0),...
Rust
0
score, config); // best_score = score; // // best_policy = Some(config); // } // } // } // fn find_ok_random_policies() { // loop { // let (policy, config) = mk_random_player(); // let fast_score = eval_policy_against_random_policy(10_000, &policy); // if...
Rust
0
import pytest from upstash_redis import Redis from upstash_redis.typing import JSONValueT @pytest.fixture(autouse=True) def setup_json(redis: Redis): json_key = "json_arrpop" value: JSONValueT = { "int": 1, "array": [1, 2, 3, 4], "object": {"array": [5, 6, 7]}, } redis.json.set...
Python
1
return def Run(self, bot_params, strategy_function, pairs, symbol_datas): sp = self.sp exchange = self.exchange database = self.database pool = Pool(4) func1 = partial(self.EntryOrder, bot_params, strategy_function, pairs) pool.map(func1, symbol_datas) pool.close() pool.join() def Exit(self, bot_p...
Python
1
# don't take empty line if len(line) < 1: continue # ref mark if line.startswith('.. _'): continue return line for package in packages: summary = extract_summary_line(sys.modules[package].__doc__) if summary is None or summary == '': summary...
Python
1
_valid_expression(cls, expr: str) -> bool: """Tries to evaluate the given boolean expression and returns True if it is valid or False if it has syntax or gramatical errors.""" try: evaluator = BooleanExpressionEvaluator(ValidationOnlyTokenEvaluator()) evaluator.evaluate_e...
Python
1
Status, Result<(Uuid, serde_json::Value), Json<ErrorResponse>>, ) { let res_count_r = get_reservation_count(c, wallet_address); match res_count_r { Ok(count) => { if count >= max_reservations { ( Status::new(403), Err(Json(ErrorRe...
Rust
0
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/data/quests/daily_quest.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf ...
Python
1
import cv2 import pywt import numpy as np def compress_video(input_video, output_video): # Définir la fonction de compression DWT def compress_frame(frame): # Appliquer la DWT sur chaque canal de couleur de l'image coeffs_R = pywt.dwt2(frame[:, :, 0], 'haar') coeffs_G = pywt.dwt2(frame...
Python
1
let col = self.0.col; unsafe { let toodee = self.0.toodee.as_mut(); let vec = &mut toodee.data; let mut dest = vec.as_mut_ptr().add(col); let mut src = des...
Rust
0
# This file is part of django-ca (https://github.com/mathiasertl/django-ca). # # django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation, either version 3 of the License, or (at your # option) any later version...
Python
1
._dumps def dump(self, obj: Any) -> Buffer | None: if isinstance(obj, _JsonWrapper): dumps = obj.dumps or self.dumps obj = obj.obj else: dumps = self.dumps data = dumps(obj) if isinstance(data, str): return data.encode() return...
Python
1
tpole'), ('benchmark/dqn/dqn_lunar.json', 'dqn_concat_lunar'), ]) def test_dqn(spec_file, spec_name): run_trial_test(spec_file, spec_name) @pytest.mark.parametrize('spec_file,spec_name', [ ('experimental/dqn/ddqn_cartpole.json', 'ddqn_boltzmann_cartpole'), ('experimental/dqn/ddqn_cartpole.json', 'ddqn...
Python
1
one; } let channel_id = data[0] & 0x3F; let sequence_id = (((data[2] & 0x0F) as u32) << 16) | (((data[3] ) as u32) << 8) | (((data[4] ) as u32) ); let window_parent_lead = ((data[5] as u16) << 8) | ...
Rust
0
use automaton::Automaton; mod events; use events::Event; mod console_renderer; use console_renderer::ConsoleRenderer; mod sdl2_renderer; use sdl2_renderer::Sdl2Renderer; mod rule110; use rule110::Rule110; mod rule30; use rule30::Rule30; mod rule90; use rule90::Rule90; mod rule184; use rule184::Rule184; mod gol; us...
Rust
0
""" Max flow problem in cpmpy. From Taha 'Introduction to Operations Research', Example 6.4-2 Translated from the AMPL code at http://taha.ineg.uark.edu/maxflo.txt This cpmpy model was written by Hakan Kjellerstrand (hakank@gmail.com) See also my cpmpy page: http://hakank.org/cpmpy/ """ from cpmpy import * import...
Python
1
from typing import List def solve(grid: List[List[int]]) -> List[List[int]]: n, m = len(grid), len(grid[0]) def fence_color(): candidates = [] for c in set(x for row in grid for x in row): rows = sum(1 for i in range(n) if sum(1 for v in grid[i] if v == c) > m//2) cols = ...
Python
1
Option<i32>, #[serde(rename = "passwordRequiredType")] #[serde(skip_serializing_if = "Option::is_none")] pub password_required_type: Option<RequiredPasswordType>, #[serde(rename = "passwordPreviousPasswordBlockCount")] #[serde(skip_serializing_if = "Option::is_none")] pub password_previous_pass...
Rust
0
", "rip", "rbp", "rax", "rbx", "x11", "x12", ]; struct TestFrameWalker<Reg> { instruction: Reg, grand_callee_param_size: u32, callee_regs: HashMap<&'static str, Reg>, caller_regs: HashMap<&'static str, Reg>, stack: Vec<u8>, } trait Int { const BY...
Rust
0
ng does /// nothing if `commands` is set to `false`. /// /// `clean_file` /// /// `default: true` /// /// If `true`, `vault` will empty the internal `data` vector used to store raw replay bytes in /// the `Replay` object's `file` `Stream` instance. This is done to prevent vast amounts of /// junk data from being serial...
Rust
0
(vec![3, 4, 6, 7, 1]); let parent = tree_index.get_parent(); assert_eq!(TreeIndex::from(vec![3, 4, 6, 7]), parent); } } mod to_flat_index_tests { use super::*; #[test] fn empty() { let tree_index = TreeIndex::new(); let flat_index...
Rust
0