text
string
label_name
string
labels
int64
Env>> { let device = tch::Device::cuda_if_available(); let qnet = dqn_model::create_dqn_model(DIM_OBS, DIM_ACT, LR_CRITIC, device)?; let builder = DQNBuilder::default() .opt_interval(OPT_INTERVAL) .n_updates_per_opt(N_UPDATES_PER_OPT) .min_transitions_warmup(N_TRANSITIONS_WARMUP) ...
Rust
0
from django.shortcuts import render from .data import ( dashboard_links_top, dashboard_links_bottom, analytics_card, ) from .models import Package, TrackingEvent from accounts.models import User # get a list of a few random packages being traced def get_a_few_packages_traced(): packages = TrackingEv...
Python
1
from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path from pathlib import Path def test_metadata() -> None: from pathlib import Path from ontopy import get_ontology repo_dir = Path(__file__).resolve().parent.parent testonto = get_ontology( str(repo_dir / "tests" / ...
Python
1
Delete share directory """ print("we are deleting samba share directory") smbTools.delete_samba_share(share_path) remove_mount_point = "rm -rf %s" % share_path session_multihost.client[0].run_command(remove_mount_point) for idx in range(1, 3): ad_user = 'idmfoouser%d...
Python
1
#------------------------------------------------------------------------------- # Name: Single Band Gap Filler For Landsat 7 # Purpose: To use cloud masks for three seperate scenes to fill gaps in data # due to SLC-induced gaps and clouds # Author: Quinten Geddes Quinten.A.Geddes<at>na...
Python
1
yers import Dense, Conv2D, MaxPool2D, Flatten, Dropout # from keras.optimizers import Adam # # # 加载数据集 # (x_train, y_train), (x_test, y_test) = mnist.load_data() # # # 数据预处理 # x_train = x_train.reshape(-1, 28, 28, 1)/255.0 # x_test = x_test.reshape(-1, 28, 28, 1)/255.0 # y_train = np_utils.to_categorical(y_train, num_c...
Python
1
self.remove_loaded_pipeline(pipeline_id); } fn remove_queued_pipeline(&mut self, pipeline_id: WeakAssetId<Pipeline>) { if let Some(sources) = self.queued.remove(&pipeline_id) { for source in sources { self.shader_index .remove(&(source, OrderWindow::n...
Rust
0
[:space:]", ",", ";", "|", "'", "\"", "(", ")", "<", "=", ">", "{", "}"]); separators.extend(add_separators); separators.retain(|separator| !remove_separators.contains(separator)); return separators.into_iter().collect(); } fn validate_strftime(format: String) -> Result<(), String> { ...
Rust
0
<Vec<u8>>; TargetOnlineRewardCount get(fn target_online_reward_count): u32; TargetComputeRewardCount get(fn target_compute_reward_count): u32; TargetVirtualTaskCount get(fn target_virtual_task_count): u32; /// Miners must submit the heartbeat in `(now - reward_window, now]` RewardWindow get(fn reward_window):...
Rust
0
llm'] = ret if role: ret = self.role_manager.use(role) rets['role'] = ret return rets def new_task(self): """创建新任务""" # 创建新任务 task = Task(self) self.tasks.append(task) self.log.info('New task created', task_id=task.task_id) ret...
Python
1
ore } } //impl Default for TracebackCell { } impl Eq for TracebackCell {} pub struct Traceback { rows: usize, cols: usize, // store the last visited node in topological order so that // we can index into the end of the alignment when we backtrack last: NodeIndex<usize>, matrix: Vec<Vec<T...
Rust
0
wrapper let python_series_wrapper_a = pypolars.call1("wrap_s", (pyseries_a,)).unwrap(); let python_series_wrapper_b = pypolars.call1("wrap_s", (pyseries_b,)).unwrap(); // call the lambda and get a python side Series wrapper let result_series_wrapper = match lambda.call1(py,...
Rust
0
)(*self)); write!(f, "{}", err.to_string_lossy()) } } } impl std::error::Error for InitError { fn description(&self) -> &str { "init error" } } pub struct VRContext { pub system: VRSystem, pub compositor: VRCompositor, pub render_models: VRRenderModels ...
Rust
0
{ from: '򏿾', to: '򏿿', mapping: Disallowed }, Range { from: '򐀀', to: '򟿽', mapping: Disallowed }, Range { from: '򟿾', to: '򟿿', mapping: Disallowed }, Range { from: '򠀀', to: '򯿽', mapping: Disallowed }, Range { from: '򯿾', to: '򯿿', mapping: Disallowed }, Range { from: '򰀀', to: '򿿽', mapping: D...
Rust
0
let mut mac = HmacSha512::new_from_slice(&self.chaincode.0) .expect("HMAC should take a 32-bytes long chaincode."); mac.update(&public_key_bytes); mac.update(i); let result = mac.finalize(); let bytes = result.into_bytes(); let mut array = [0u8; PRIVATE_KEY_LENG...
Rust
0
not None: self.timing[uidx].append(timing) plt.figure() for idx, (hist, timings, label) in enumerate(zip(self.history, self.timing, self.label_names)): plt.plot(list(range(1, len(hist)+1)) if len(timings) == 0 else timings, hist, linewidth=3, label=label) plt.grid() ...
Python
1
import random import sqlite3 connection = sqlite3.connect('not_telegram.db') cursor = connection.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS Users( id INTEGER PRIMARY KEY, username TEXT NOT NULL, email TEXT NOT NULL, age INTEGER, balance INTEGER NOT NULL ) ''') # for i in range(1, 11): # cursor.execute...
Python
1
assert_eq!(Ok(()), s.clear()); assert_eq!(0, s.len()); } #[test] fn test_clear_empty() { let mut s = DCStack::new(); assert_eq!(Ok(()), s.clear()); assert_eq!(0, s.len()); } #[test] fn test_behavior() { let n = bigint::BigInt::parse_bytes(b"A", 16).expect("BigInt expecting success"); //let n ...
Rust
0
# Creating a Library Application using Classes and Objects (Storing data in lists) import datetime # Function to get current time def get_date(): date = datetime.date.today() full_date = str(date.day) + '/' + str(date.month) + '/' + str(date.year) return full_date # Initial lists to add the data al...
Python
1
+1); } return Ok(params[index].clone()) } pub fn param_int(params: &Vec<String>, index: usize) -> Result<i32, KissError> { let v= param_at(params,index)?; if v.starts_with("0x"){ match i32::from_str_radix(v.trim_start_matches("0x"), 16) { Ok(i) => { return Ok(i); } Err(e...
Rust
0
''' This module provides a simple message encoder that converts messages to and from JSON text. ''' import json from twisted.python import log def _decode_list(data): rv = [] for item in data: if isinstance(item, unicode): item = item.encode('utf-8') elif isinstance(item, list): ...
Python
1
break else: print("Invalid choice. Please try again.") except KeyboardInterrupt: print("\nOperation cancelled by user.") except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": main() """...
Python
1
} #[no_mangle] pub extern "C" fn GDKRPC_destroy_json(ptr: *mut GDKRPC_json) -> i32 { debug!("GA_destroy_json({:?})", ptr); // TODO make sure this works unsafe { drop(&*ptr); } GA_OK } #[no_mangle] pub extern "C" fn GDKRPC_destroy_string(ptr: *mut c_char) -> i32 { unsafe { // re...
Rust
0
::OpenOptionsExt; use std::path::{Path, PathBuf}; #[cfg(unix)] use std::sync::{Arc, Mutex}; const BLOCK_SIZE: usize = 512; const BUF_SIZE: usize = 256 * 1024; const BUF_SIZE_U64: u64 = BUF_SIZE as u64; #[repr(align(512))] struct AlignedBuffer([u8; BUF_SIZE]); trait SliceRange { fn subslice(&self, start: usize, s...
Rust
0
from textnode import text_node_to_html_node, TextType, TextNode from utility import markdown_to_blocks import unittest class TestTextNodeToHTMLNode(unittest.TestCase): def test_text(self): node = TextNode(text="This is a text node", text_type=TextType.TEXT) html_node = text_node_to_html_node(node) ...
Python
1
8265/forwarding_rules", # pylint: disable=line-too-long status=204, ) mock_client.load_balancers.add_forwarding_rules( lb_id="a91a98de-9b5f-4198-91cd-f852e36f8265", body={ "forwarding_rules": [ { "entry_protocol": "https", ...
Python
1
to have support for all operations in this crate /// a must implement the `RealNumber`. pub trait DspNumber: Num + Copy + Clone + Send + Sync + ToSimd + Debug + num_traits::Signed + num_traits::FromPrimitive + rustfft::FFTnum ...
Rust
0
# controllers/generation_controller.py from flask import Blueprint, request, jsonify from app.config import MODEL_ID import json import logging import traceback from app import get_bedrock_client # Create a Blueprint for this controller generation_blueprint = Blueprint('generation', __name__) # Logger setup logger =...
Python
1
ls = [] mp = {} val = { "0": (0,1), "1": (1,0), "2": (1,1), "3": (1,2), "4": (2,0), "5": (2,1), "6": (2,2), "7": (3,0), "8": (3,1), "9": (3,2), "A": (0,2) } res = 0 def pad2(ls): sln = [] s1 = pad1(ls) for i in s1: s2 = pad1(i) sln += s2 retur...
Python
1
ReaderStream { stream } } } fn main() {} <reponame>azaika/mcc use super::mir::*; use id_arena::Arena; type Set = util::Set<BlockId>; fn conv(bid: BlockId, arena: &mut Arena<Block>, arrived: &mut Set) { if arrived.contains(&bid) { return; } arrived.insert(bid); let (mut add_insts, n...
Rust
0
static str = "MyWidget"; type Type = super::MyWidget; type ParentType = gtk::Widget; fn class_init(klass: &mut Self::Class) { klass.bind_template_instance_callbacks(); } } impl ObjectImpl for MyWidget {} impl WidgetImpl for MyWidget {} } glib::wrapper! { pub...
Rust
0
l::Rational(n, d), None => UReal::Integer(n), } } #[allow(unused_variables)] fn __action14< 'input, >( flags: &NumberFlags, (_, loc, _): (usize, usize, usize), (_, d, _): (usize, (Precision, &'input str, &'input str, isize), usize), (_, m, _): (usize, ::std::option::Option<&'input str>,...
Rust
0
/// Returns a human-readable address of the specified raw address /// /// # Safety /// This function is unsafe because of calls to C-library system calls #[cfg(target_os = "linux")] pub unsafe fn get_ip(address: *const sockaddr_in) -> String { assert_not_null!(address); let raw = inet_ntoa(&(*address).sin_addr...
Rust
0
palabra = input() letras = {} for letra in palabra: letras[letra] = True print(len(letras))
Python
1
henticate") # Then assert response.status_code == 401 assert "No expiration date provided" in response.json["msg"] def _create_adage_valid_token(self, valid_user, uai_code: str | None, can_prebook: bool | None = True) -> bytes: return create_adage_jwt_default_fake_valid_token( ...
Python
1
492, 478, 493, 479, 494, 480, 480, 481, 496, 482, 497, 483, 498, 484, 499, 485, 500, 486, 501, 487, 502, 488, 503, 489, 504, 490, 505, 491, 506, 492, 507, 493, 508, 494, 509, 495, 510, 0, 0 ]; #[rustfmt::skip] static mrow_scan_32x16_neighbors : [u16; 513 * MAX_NEIGHBORS] = [ 0, 0, 0, 0, 1, 1, 2,...
Rust
0
mem::replace(guard.as_mut(), vec![]) }; cluster.sim.wl().clear_recv_filters(2); for i in 20..40 { cluster.must_put(format!("k{}", i).as_bytes(), b"v1"); } must_get_equal(&cluster.get_engine(2), b"k39", b"v1"); let router = cluster.sim.wl().get_router(2).unwrap(); // lightlike...
Rust
0
blocked` [31], `sigignore` [32] and /// `sigcatch` [33] fields are included as private fields, but `proc(5)` recommends the use of /// `/proc/[pid]/status` instead. /// /// # Examples /// /// ``` /// psutil::process::Process::new(psutil::getpid()).unwrap(); /// ``` /// /// [array.c:361]: https://github.com/torvalds/lin...
Rust
0
th ) if success: print(" ✅ 文件下载验证成功") # 清理本地文件 for local_file in [temp_file, download_path]: if os.path.exists(local_file): os.unlink(local_file...
Python
1
r'/home/dj/code/mmdetection_DOTA/data/dota1_1024_v2/trainval1024_ms/DOTA_trainval1024_ms.json', # wordname_15) # DOTA2COCOTest(r'/workfs/jmhan/dota15_1024_ms/test1024', # r'/workfs/jmhan/dota15_1024_ms/test1024/DOTA_test1024.json', # wordname_16) # DO...
Python
1
} i += 2; } true } /* cargo test --test e0005 cargo test --test e0005 with_error cargo test --test e0005 without_error1 cargo test --test e0005 without_error2 */ /* Patterns used to bind names must be irrefutable, that is, they must guarantee that a name will be extracted in all cases. */ #[cf...
Rust
0
en(project_de_locale) as fp: po_contents = fp.read() self.assertMsgId("This app has no locale directory", po_contents) self.assertMsgId("This is a project-level string", po_contents) with open(app_de_locale) as fp: po_contents = fp.read() ...
Python
1
000;00000000000000000000000000000000;' \ '1436940126;(none);(none);(none);(none)' all_rpms = [line for line in package_list.splitlines() if line] all_components = parse_rpm_output(all_rpms) flexmock(RemoteHost).should_receive('rpms_installed').and_return(package_list) task_results =...
Python
1
# Copyright 2024 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from unittest.mock import patch from odoo.addons.server_action_mass_edit.tests.test_mass_editing import ( TestMassEditing, ) class TestMassEditingWithOnChange(TestMassEditing): @patch("odoo.addons.base.models.res_par...
Python
1
dllm_mask = batched_outputs.extra_outputs.dllm_mask stop_pos = batched_outputs.stop_pos batch_size = len(running) next_token_ids = next_token_ids.view(batch_size, -1).numpy() dllm_mask = dllm_mask.view(batch_size, -1).numpy() stop_pos = stop_pos.tolist() update_mode = ...
Python
1
taset_dict in model_docs.items(): for dataset, keywords_dict in dataset_dict.items(): for keywords, doc_info in keywords_dict.items(): if indicator not in doc_info['content']: continue keyword_strs = [ ...
Python
1
not find .uns["{neighbors_key}"]. Run `muon.pp.neighbors` first.') from scanpy.tools._utils import _choose_representation from copy import deepcopy from scipy.sparse import issparse # we need a data matrix. This is used only for initialization and only if init_pos=="spectral" # and the graph has ...
Python
1
warn!(log, "Failed to stop thread watcher"; "thread_name" => block_applier_thread_watcher.thread_name(), "reason" => format!("{}", e)); } if let Err(e) = chain_manager_p2p_reader_thread_watcher.stop() { warn!(log, "Failed to stop thread wa...
Rust
0
from copilot_api import Copilot from copilot_api.copilot import Conversation def test_basic_chat(): print("\n=== Testing Basic Chat ===") copilot = Copilot() messages = [ {"role": "system", "content": "You are a helpful AI assistant."}, {"role": "user", "content": "Hello! Tell me a short jo...
Python
1
#token matches current_ac_node = current_ac_node.transition_table[node_token] for fixer in current_ac_node.fixers: if not fixer in results: results[fixer] = [] results[fixer].append(current_ast_node)...
Python
1
#[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`, `\"Win32_Networking_WinSock\"`*"] #[cfg(feature = "Win32_Networking_WinSock")] pub struct Filter_Spec_IPv4 { pub filt_ipaddr: super::super::Networking::WinSock::IN_ADDR, pub filt_unused: u16, pub filt_port: u16, } #[cfg(feature = "Win32_Networ...
Rust
0
age = np.copy(image) # Bruit sel salt_pixels = np.random.rand(*image.shape) < salt_prob noisy_image[salt_pixels] = 1 # Bruit poivre pepper_pixels = np.random.rand(*image.shape) > 1 - pepper_prob noisy_image[pepper_pixels] = 0 return noisy_image # Paramètres de bruit (ajustez selon vos p...
Python
1
""] #[doc = ""] #[doc = " \\param [in] encoder"] #[doc = " Pointer to the NvEncodeAPI interface."] #[doc = " \\param [in] mappedInputBuffer"] #[doc = " Pointer to the NV_ENC_INPUT_PTR"] #[doc = ""] #[doc = " \\return"] #[doc = " ::NV_ENC_SUCCESS \\n"] #[doc = " ::NV_ENC_ERR_INVA...
Rust
0
schema = {"format": "relative-json-pointer"}; valid = "1"; invalid = "/foo/bar"; ); bench!( name = "format_time"; schema = {"format": "time"}; valid = "08:30:06.283185Z"; invalid = "01:01:01,1111"; ); bench!( name = "format_uri_reference"; schema = {"format": "uri-reference"}; valid = "http://foo.bar/...
Rust
0
, |this, touch| { if touch.is_ended() { if this.flaccid { return; } let frame = *this.frame(); this.direction_stick.set_center(frame.size.center()); this.on_change.trigger(Point::default()); } els...
Rust
0
abc:123 -[Item handleSomething]]:" => (test_timestamp(789), Some(LogLevel::Error), test_metadata(123)); "multiple spaces" )] #[test_case( "1234/01/23 12:34:56:789 💛 [Item.abc:123 -[Item handleSomething]] " => (test_timestamp(789), Some(LogLevel::Info), test_metadata(123)); ...
Rust
0
UID"] + " exists" self.log.warning(cmd) self.log_and_raise(http_status_code=500, reason=reasonErr) else: env_dict["KERNEL_PYSPARK_PYTHON"] = ( response["parameters"]["deploy_home"]["value"] + "/anaconda/envs/" + env["KERNEL_ANAC...
Python
1
_follow_burros) .add_system(follow_following) .add_system(update_camera); } } #[derive(Component)] pub struct PanOrbitCamera { pub focus: Vec3, pub radius: f32, pub upside_down: bool, } impl Default for PanOrbitCamera { fn default() -> Self { PanOrbitCamera { ...
Rust
0
import cv2 import numpy as np def make_coordinates(image,line_parameters): slope,intercept=line_parameters y1=image.shape[0] y2=int(y1*(3/5)) x1=int((y1-intercept)/slope) x2=int((y2-intercept)/slope) return np.array([x1,y1,x2,y2]) def average_slope_intercept(image,lines): left_fit=[] ...
Python
1
coords_x[trailing_edge_indices] >= x_gt] # check if we have no trailing edge indices return not len(trailing_edge_indices) <= 1 def calc_area(coords: npt.NDArray[np.float32]) -> float: """Calculates the area of the airfoil. Args: coords (np.ndarray): The coordinates of the airfoil. Retu...
Python
1
n with `malloc_key`. pub unsafe fn realloc_key(ptr: *mut u8, size: usize, align: usize) -> *mut u8 { xrealloc(ptr, size, align, true) } /// Free memory /// /// Provides the same interface than the usual `free` function. This function /// has no effect if `ptr` is a `NULL` pointer or a pointer to a zero-sized /// ...
Rust
0
-> edbn::Value { edbn::Value::Vector((&self.0).into_iter().map(|&(x, ref y)| edbn::Value::Vector(vec![edbn::Value::Integer(x), edbn::Value::Text(y.clone())])).collect()) } } /// Turn MinkowskiType::Ref into MinkowskiType::Keyword when it is possible. trait ToCausetId { fn map_causetId(self, schemaReplica...
Rust
0
import cv2 import numpy as np from pathlib import Path import os from rembg import remove, new_session import time def detect_card(image_path, output_path, border_size=5): """ Detect and crop a card using rembg for background removal. Args: image_path: Path to the input image output_pa...
Python
1
odule"] pub struct CTR_SPEC; impl crate::RegisterSpec for CTR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [ctr::R](R) reader structure"] impl crate::Readable for CTR_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [ctr::W](W) writer structure"] impl crate::Writable for CTR_SPEC { ...
Rust
0
relude: &'static str) -> impl FnOnce(E) -> String { move |e: E| format!("{}: {}", prelude, e.to_string()) } <filename>src/example/outline/remote/proxy_get_menu_badge/init.rs mod proxy_service; mod response_encoder; use actix_web::HttpRequest; use getto_application::infra::ActionStatePubSub; use crate::x_outside_...
Rust
0
tworking_Clustering\"`*"] pub fn ClusterResourceTypeGetEnumCount(hrestypeenum: *const _HRESTYPEENUM) -> u32; #[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"] pub fn ClusterResourceTypeOpenEnum(hcluster: *const _HCLUSTER, lpszresourcetypename: ::windows_sys::core::PCWSTR, dwtype: u32) -> *mu...
Rust
0
sample_counter: 0, }; out.reset(); out } } // Compute the Zero Crossing metric for a signal sampled at twice the symbol rate // // v[0] is previous symbol // v[1] is inter-sample zero // v[2] is most-recent symbol // // output is the timing error estimate // // this is a modified G...
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
(sp, cp) = pitch.sin_cos(); let (sy, cy) = yaw.sin_cos(); return double4x4( double4(cy * cp, sy * cp, -sp, 0.0), double4(cy * sp * sr - sy * cr, sy * sp * sr + cy * cr, cp * sr, 0.0), double4(cy * sp * cr + sy * sr, sy * sp * cr - cy * sr, cp * cr, 0.0), double4(0.0, 0.0, 0.0, 1.0) ...
Rust
0
# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master...
Python
1
.add(StopMutators::<SSProcessEdges<VM>>::new()); // Prepare global/collectors/mutators scheduler.prepare_stage.add(Prepare::new(self)); // Release global/collectors/mutators scheduler.release_stage.add(Release::new(self)); // Resume mutators #[cfg(feature = "sanity")] ...
Rust
0
#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/ATOM/translating_background.py from __future__ import absolute_import, print_function, unicode_literals from ableton.v2.control_surface.components import BackgroundComponent class TranslatingBackgrou...
Python
1
"""Vector storage modules."""
Python
1
}); // Create a directory that will automatically be dropped after the test finishes. let temp_dir = tempfile::tempdir().expect("failed to create temp directory"); let file_path = NamedTempFile::new_in(&temp_dir) .expect("failed to create temp file") .into_temp_path(); let file_stream =...
Rust
0
" Creates a post-processing function that wraps a reranking model to rerank search candidates. This function can be used directly with a search engine to improve the ranking of search results. It takes a reranking model and returns a function that can be applied to a list of EnhancedSearchResults. Arg...
Python
1
ctionCount = params.get("ConcurrentConnectionCount") self._NewConnectionRate = params.get("NewConnectionRate") memeber_set = set(params.keys()) for name, value in vars(self).items(): property_name = name[1:] if property_name in memeber_set: memeber_set.rem...
Python
1
json_response = json_format.MessageToDict(response) return parse_stats_response(json_response) @staticmethod def _parse_non_empty_args(args: List[Tuple[str, Any]]) -> Dict[str, Any]: return {arg_name: val for arg_name, val in args if val is not None} @staticmethod def _parse_spars...
Python
1
("2023-12-20", "Día de Duelo Nacional"), ("2023-12-25", "Navidad"), ) def test_l10n_default(self): self.assertLocalizedHolidays( ("2024-01-01", "Año Nuevo"), ("2024-01-09", "Día de los Mártires"), ("2024-02-12", "Lunes de Carnaval"), ...
Python
1
auth ) ): allowed_scopes = set(roles.roles_to_scopes(oauth_client.allowed_roles)) allowed_scopes.update(access_scopes(oauth_client, db)) oauth_client.allowed_scopes = sorted(allowed_scopes) db.commit() # drop token-role ...
Python
1
main() { use foo::{ Bar, my~fn }; myfn(); } "; let got = get_all_completions(src, None); assert_eq!(got.len(), 1); assert_eq!(got[0].matchstr, "myfn"); } #[test] fn completes_trait_methods_in_trait_impl() { let _lock = sync!(); let src = "...
Rust
0
; 3 -- 4 [pos="39.322,178.76 38.043,189.53 36.424,203.17 35.14,213.98"]; } """ # print("dot representation:", dot_rep) # assert expected == dot_rep def test_drawing_makes_file(self): A = pgv.AGraph(name="test graph") A.add_path([1, 2, 3, 4]) with TemporaryFil...
Python
1
# Last Change: Sat Mar 21 02:00 PM 2009 J # Copyright (c) 2001, 2002 Enthought, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # a. Redistributions of source code must retain the abov...
Python
1
with ( patch.object(env_plugin, "_get_pathext", return_value={".exe", ".bat"}, autospec=True), patch.object(env_plugin, "expand_env", side_effect=mock_expand_env, autospec=True), patch.object(env_plugin, "user_env", side_effect=mock_user_env, autospec=True), ): assert resolver_plu...
Python
1
"""Advent of code 2021 --- Day 17: Trick Shot --- """ import math from common.aoc import file_to_string, aoc_part, get_filename def parse_data(raw_data): """Parse the input""" arr = raw_data.split(",") x_values = arr[0] y_values = arr[1] arr = x_values.split("=") min_x = int(arr[1].split(".....
Python
1
(height), completions.len()), } as u16; let width = completions .iter_mut() .map(|c| c.len()) .max() .expect("There'a at least one completion") as u16; let (rows_above, rows_below) = self::rows_above_below_cursor(lua)?; // The total height of the completion menu, also ...
Rust
0
*const i8, 4, 4); *ilk_info.offset(pre_def_loc as isize) = 6i32; pre_define(b"reverse \x00" as *const u8 as *const i8, 7, 4); *ilk_info.offset(pre_def_loc as isize) = 7i32; pre_define(b"sort \x00" as *const u8 as *const i8, 4, 4); *ilk_info.offset(pre_def_loc as isize) = 8i32; pre_de...
Rust
0
import numpy as np import pandas as pd import lightgbm as lgb import xgboost as xgb import catboost as cbt from pandas import DataFrame as DF import gc from sklearn.preprocessing import LabelEncoder import time import networkx as nx from sklearn.cluster import MeanShift,KMeans # 1. 分别训练A,B榜数据,得到A,B模型,则只需要利用A榜模型预测B榜All...
Python
1
class AlreadyExistsError(ValueError): def __init__(self, entity: str, field: str, value: str) -> None: self._entity = entity self._field = field self.value = value super().__init__(f'{entity} with {field} "{value}" already exists') class UserAlreadyExistsError(AlreadyExistsError): ...
Python
1
_idx, mem_dist_off: shard_mem_off, mem_occ_sz: req_shard_mem_sz, }; splits.push(split); max_shard_mem_sz = max(max_shard_mem_sz, req_shard_mem_sz); } let block_sz = 2 * 1024 * 1024; let rdup_shard_mem_sz = (max_shard_mem_sz + block_sz - 1) / block_sz * block_sz; ...
Rust
0
participating in the current signing protocol pub type Peers = HoleVecMap<SignShareId, TypedUsize<KeygenShareId>>; // This is the set of parties participating in the current signing protocol pub type SignParties = Subset<KeygenPartyId>; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SignShareId;...
Rust
0
import sys # signature(check.func.__dict__["__wrapped__"]).parameters["kind"] import numpy as np import pytest from sklearn.utils.estimator_checks import parametrize_with_checks from sklego.neighbors import BayesianKernelDensityClassifier @parametrize_with_checks([BayesianKernelDensityClassifier()]) def test_sklear...
Python
1
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
1
SERVICE = 3i32; #[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub type KSMETHOD_BDA_ISDB_CAS = i32; #[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub const KSMETHOD_BDA_ISDBCAS_SETREQUEST: KSMETHOD_BDA_ISDB_CAS = 0i32; #[doc = "*Required features: 'Win32_Media_DirectShow'*"] pub const KSMETHOD_BDA...
Rust
0
len() - 1 { if self.jump_state == JumpState::Not { self.mixer.play(self.jump_sound.clone()); self.jump_state = JumpState::BuildUp; self.state = State::AIR; } self.jump_up_timer += 1; ...
Rust
0
data = [ { 'name': 'Elon Musk', 'follower_count': 48, 'description': 'Entrepreneur and CEO of SpaceX, Tesla, and Neuralink', 'country': 'United States' }, { 'name': 'Jeff Bezos', 'follower_count': 31, 'description': 'Entrepreneur and CEO of Amazon', ...
Python
1
hat the player may receive a reward, if there is no collisions collisionModel(t, env.arms, players, choices, rewards, pulls, collisions) # Finally we store the results result.store(t, choices, rewards, pulls, collisions) # Print the quality of estimation of arm ranking for this policy, jus...
Python
1
from celery import Celery import os from backend.tasks import BatchProcessing def make_celery(app_name=__name__): return Celery( app_name, backend=os.environ.get("CELERY_BACKEND", 'redis://localhost:6579/0'), broker=os.environ.get("CELERY_BROKER", 'redis://localhost:6579/0'), ) celer...
Python
1
returns its current state."] #[inline(always)] pub fn setpend31(&self) -> SETPEND31_R { SETPEND31_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - 30:30\\] Writing 0 to this bit has no effect, writing 1 to this bit pends the interrupt number 30 (See EVENT:CPUIRQSEL30.EV for details)....
Rust
0
= match fs::read_dir(dir) { Ok(entries) => entries, _ => continue, }; for entry in entries.filter_map(|e| e.ok()) { let path = entry.path(); let filename = match path.file_name().and_then(|s| s.to_str()) { Some(filename) => filename, ...
Rust
0
ved until this seed ratio is met.', }, { 'name': 'seed_time', 'label': 'Seed time', 'type': 'int', 'default': 40, 'description': 'Will not be (re)moved until this seed time (in hours) is m...
Python
1