text
string
label_name
string
labels
int64
import os # Files to exclude from operations EXCLUDED_FILES = { ".DS_Store", ".gitignore", "package-lock.json", "postcss.config.js", "postcss.config.mjs", "jsconfig.json", "components.json", "tsconfig.tsbuildinfo", "tsconfig.json", } # Directories to exclude from operations EXCLUD...
Python
1
} let mut escaped = String::from(""); for (_index,ch) in input.char_indices(){ if ! (ch == '\\'){ escaped.push(ch); continue; } } escaped } pub fn echo (matches : ArgMatches) { let input = matches.values_of("INPUT"); match input { So...
Rust
0
ethod.merge) //! method, you may "push" data to a `Tree` value //! and have the provided merge operator combine //! it with the existing value, if there was one. //! They are set on a per-`Tree` basis, and essentially //! allow any sort of data structure to be built //! using merges as an atomic high-level operation. /...
Rust
0
priv-aes256-sha256.pem", ) .unwrap(); assert_eq!(pkcs8_doc.as_ref(), ED25519_DER_AES256_SHA256_EXAMPLE); } <reponame>AndrewKvalheim/rust-exercises #[derive(Clone, Debug, PartialEq)] pub struct CustomSet<T>(Vec<T>); impl<T> CustomSet<T> { pub fn is_empty(&self) -> bool { self.0.is_empty() } ...
Rust
0
/// Constructs a vector of type `T`, length `len`, and contents `default`. fn default_vec<T: Default>(len: usize) -> Vec<T> { let mut v = Vec::with_capacity(len); v.resize_with(len, Default::default); v } #[cfg(test)] mod tests { use crate::{api::abs::test_helpers, err}; #[test] /// Tests ge...
Rust
0
+1)] = 2.0 * (h[i] + h[i + 1]); } a[(i+1, i)] = h[i]; a[(i, i+1)] = h[i]; } a[(0, 1)] = 0.; a[(nx-1, nx-2)] = 0.; a[(nx-1, nx-1)] = 1.; a } fn __calc_b(h: &Vec<f64>, a: &Vec<f64>)-> na::DVector<f64> { let nx = h.len() +1; ...
Rust
0
et enc_msg = encoder::encode(&msg_packet).unwrap(); assert_eq!(enc_msg.len() % 4, 0); let dec_msg: OscMessage = match decoder::decode_udp(&enc_msg).unwrap().1 { OscPacket::Message(m) => m, _ => panic!("Expected OscMessage!"), }; let msg = match msg_packet { OscPacket::Message(r...
Rust
0
::str::FromStr for ColumnDataType { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ColumnDataType::from(s)) } } impl ColumnDataType { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ...
Rust
0
: {}", utils::ANSI_ESCAPE_SEQUENCE, uptime)); lines[7].push_str(&format!(" Screen Resolutions(s){}0m: {}", utils::ANSI_ESCAPE_SEQUENCE, screen_resolutions)); lines[8].push_str(&format!(" Processor{}0m: {}", utils::ANSI_ESCAPE_SEQUENCE, processor)); lines[9].push_str(&for...
Rust
0
# -*- coding: utf-8 -*- """ Created on Tue Feb 20 16:06:29 2024 @author: Nilesh """ ''' Johnnie Talkers soft drinks division sales manager has been planning to launch a new sales incentive program for theis sales executives.The sales executives felt that adults(>40yr) wont buy,children will hence requested sales mana...
Python
1
()], ) state = BodyState( user_query="clinic", user_query_redacted="clinic", preferences={}, ) ranked_state = places.run(state, es_client=object()) candidates = ranked_state["candidates"] assert len(candidates) == 1 assert "distance_km" not in candidates[0] def t...
Python
1
0 = vec![1, 2, 3] // lldbr-check:(alloc::vec::Vec<i32>) v = vec![1, 2, 3] // lldb-command:print zs // lldbg-check:[...]$1 = StructWithZeroSizedField { x: ZeroSizedStruct, y: 123, z: ZeroSizedStruct, w: 456 } // lldbr-check:(issue_22656::StructWithZeroSizedField) zs = StructWithZeroSizedField { x: ZeroSizedStruct { }, y...
Rust
0
stly calculate apperence cost, then filter by Kalman state. tracks: List[STrack] dets: List[STrack] """ apperance_dist = nearest_embedding_distance(tracks=tracks, detections=dets, metric='cosine') cost_matrix = self.gate_cost_matrix(apperance_dist, tracks, dets, ) return...
Python
1
n = [] p = [] t = 0 m = 0 r = int(input("Digite quantas notas deseja lancar: ")) for i in range (r): n.append(int(input("Digite a sua nota: "))) p.append(int(input("Digite o peso da nota: "))) for i in range (r): t = t + p[i] if t > 10: print("O peso das notas informados é superior a 10, revise o pes...
Python
1
ype::INT64), "INT96" => Ok(Type::INT96), "FLOAT" => Ok(Type::FLOAT), "DOUBLE" => Ok(Type::DOUBLE), "BYTE_ARRAY" | "BINARY" => Ok(Type::BYTE_ARRAY), "FIXED_LEN_BYTE_ARRAY" => Ok(Type::FIXED_LEN_BYTE_ARRAY), other => Err(general_err!("Invalid type {}...
Rust
0
_page,color=c_blue,style=ft.ButtonStyle(shape=ft.RoundedRectangleBorder(radius=0))),alignment=ft.alignment.center,height=30) if self.regime == 'Дневная торговля': # если дневная торговля - значит н ажали из исторической торговли/дневная торговля при выборе монет и загрузке датафреймов re...
Python
1
numbers=[12,2,3,23] print(type(numbers)) print(numbers) numbers[1]=45 print(numbers) numbers=(12,2,3,23) print(type(numbers)) print(numbers) #numbers[1]=45
Python
1
keychain_mask.clone(), &outputs2del, &mut outputs, tip_height, &last_output, &transactions, status_send_channel, )?; } { restore_labels( wallet_inst.clone(), keychain_mask.clone(), &found_parents, status_send_channel, )?; } // Updating confirmed height record. The height at wh...
Rust
0
n)] #[inline] pub fn _bits(&self) -> u8 { match *self { EXTIPSEL3W::PORTA => 0, EXTIPSEL3W::PORTB => 1, EXTIPSEL3W::PORTC => 2, EXTIPSEL3W::PORTD => 3, EXTIPSEL3W::PORTE => 4, EXTIPSEL3W::PORTF => 5, } } } #[doc = r" Pro...
Rust
0
; engine.eval::<()>("let x = 0; while x < 20 { x += 1; }")?; assert!(matches!( *engine .eval::<()>("for x in range(0, 500) {}") .expect_err("should error"), EvalAltResult::ErrorTooManyOperations(_) )); engine.set_max_operations(0); engine.eval::<()>("for x...
Rust
0
se substratee_stf::TrustedOperation; /// RPC Trusted call or hash /// /// Allows to refer to trusted calls either by its raw representation or its hash. #[derive(Debug, Encode, Decode)] pub enum TrustedOperationOrHash<Hash> { /// The hash of the call. Hash(Hash), /// Raw extrinsic bytes. OperationEncod...
Rust
0
from netmiko import ConnectHandler import time devices = { "R0": "172.31.106.1", "R1": "172.31.106.4", "R2": "172.31.106.5", "S0": "172.31.106.2", "S1": "172.31.106.3" } device_params = { 'device_type': 'cisco_ios', 'ip': None, 'username': 'admin', 'use_keys': True, 'key_file'...
Python
1
serialize(&mut bytes)?; bytes.set_position(0); let other_script = Script::zcash_deserialize(&mut bytes)?; prop_assert_eq![script, other_script]; } } } use std::io::stdout; use std::{process, time::Duration}; use crossterm::{ cursor::{Hide, MoveToColumn, Show}, ...
Rust
0
n16k16.mma.{{.*}}.f32.f16 ; M16N16-DAG: m16n16k16.mma.{{.*}}.f16.f16 ; M16N16-DAG: m16n16k16.mma.{{.*}}.f32.f32 ; PTX60 adds support for m32n8k16/m8n32k16 geometries. ; EXTGEOM-DAG: m32n8k16.load.{{[ab].*}}.f16.p ; EXTGEOM-DAG: m32n8k16.{{load|store}}.{{[cd].*\.(f16|f32)}}.p ; EXTGEOM-DAG: m32n8k16.mma.{{.*}}.f16.f32 ...
Python
1
storage::TagTypeId; use crate::storage::Tags; use crate::tuple::TupleEq; use parking_lot::Mutex; use std::cell::UnsafeCell; use std::iter::Enumerate; use std::iter::Fuse; use std::iter::FusedIterator; use std::iter::Peekable; use std::iter::Repeat; use std::iter::Take; use std::marker::PhantomData; use std::ops::Deref;...
Rust
0
>0 use { serde::Serialize, rocket_contrib::templates::Template, crate::models::db, rocket::{ post, FromForm, http::{Status, RawStr}, request::{Form, FormItems, FromFormValue} } }; #[derive(FromForm, Serialize)] pub struct User { name: String } #[derive(Serialize...
Rust
0
iguration dictionary """ verify_local_config(config_dict) write_configuration_file(join(LOCAL_ROOT, "local_config.json"), config_dict) def get_pid_hash(problem, short=False): """ Returns a hash of a given problem. Args: problem: a valid problem object. short: shorten the retur...
Python
1
lw.message.as_ref()), }) } LastWill::V5(lw) => { json!({ "qos": lw.qos.value(), "retain": lw.retain, "topic": lw.topic, "message": base64::encode(lw.message.as_ref()), ...
Rust
0
FF']) ax = plt.subplot(len(datasets), len(classifiers) + 1, i) # Plot the training points ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright) # and testing points ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6) ax.set_xlim(xx.min(), xx.max()) ax.se...
Python
1
# -*- coding: utf-8 -*- import pandas as pd import sys import json import numpy as np import traceback import funciones as Fu import warnings warnings.filterwarnings("ignore") if __name__ == "__main__": if len(sys.argv) < 2: sys.exit() try: data_j = sys.argv[1] data = json.loads(data...
Python
1
"""Get repeat factor for each images in the dataset. Args: dataset (:obj:`CustomDataset`): The dataset repeat_thr (float): The threshold of frequency. If an image contains the categories whose frequency below the threshold, it would be repeated. ...
Python
1
dout. const EXCLUDE_CHARS: &[char] = &['\n', '\r']; let mut exclude_dirs = config::exclude_dirs()?.into_iter(); if exclude_dirs.any(|pattern| pattern.matches(path)) || path.contains(EXCLUDE_CHARS) { return Ok(()); } if !Path::new(path).is_dir() { bail!("no...
Rust
0
fn main() { /// check!() /// .with_type::<(u8, u16)>() /// .for_each(|(a, b)| { /// // implement checks here /// }); /// } /// ``` /// /// The function `with_generator::<Generator>(generator)` will use the provided `Generator`, /// which implements [`generator::ValueGenerator`],...
Rust
0
backs.clone().values() { // We need to keep track of the current request and response indexes because // they need to match the variant index of the Rust side. let (new_req, new_resp) = self.generate_callback(callback, req_index, resp_index, sink)?; req_in...
Rust
0
c.bench_function("encode bundle crc 16", move |bench| { bench.iter(|| bndl.to_cbor()) }); b.set_crc(crc::CRC_32); b.validate().unwrap(); let mut bndl = b; c.bench_function("encode bundle crc 32", move |bench| { bench.iter(|| bndl.to_cbor()) }); } fn criterion_benchmark_bund...
Rust
0
_spread.fragment_name) { ctx.add_error( format!("{} is not known fragment", &fragment_spread.fragment_name), vec![fragment_spread.position], ) } } } #[cfg(test)] mod tests { use crate::{check_fails_rule, check_passes_rule}; use super::*; ...
Rust
0
d be recreated if the column part of it is /// recreated. fn should_recreate_the_primary_key_on_column_recreate(&self) -> bool { false } fn table_names_match(&self, names: Pair<&str>) -> bool { names.previous() == names.next() } /// Return the tables that cannot be migrated wit...
Rust
0
eq!(buffered.next_token(LexContext::default()), T![ident]); assert_eq!(buffered.next_token(LexContext::default()), NEWLINE); assert_eq!(buffered.next_token(LexContext::default()), WHITESPACE); assert_eq!(buffered.next_token(LexContext::default()), T![=]); assert!(buffered.has_preceding_l...
Rust
0
elf.center_pos[0] cy = bbox[1] + self.center_pos[1] # smooth bbox width = self.size[0] * (1 - lr) + bbox[2] * lr height = self.size[1] * (1 - lr) + bbox[3] * lr # clip boundary cx, cy, width, height = self._bbox_clip(cx, cy, ...
Python
1
en_height, bpp); let (dtop, dleft, dwidth, dheight) = self.buffer.get_real_bounds(framebuffer.width() as u32, framebuffer.height() as u32); framebuffer.clear_at(dleft as _, dtop as _, dwidth as _, dheight as _); BUFFERS.lock().retain(|buffer| { if let Some(buffer) = buffer.upgrade() ...
Rust
0
# Copyright (c) Meta Platforms, Inc. and affiliates. # # 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...
Python
1
cipslaTcpConnTmplSrcAddr": cipslaTcpConnTmplSrcAddr, "cipslaTcpConnTmplSrcPort": cipslaTcpConnTmplSrcPort, "cipslaTcpConnTmplTimeOut": cipslaTcpConnTmplTimeOut, "cipslaTcpConnTmplVerifyData": cipslaTcpConnTmplVerifyData, "cipslaTcpConnTmplTOS": cipslaTcpConnTmplTOS, "cipslaTcpConnTmpl...
Python
1
8d\x90D\x8db\xab\xa8\ \xf8\x0e6\x8f\x11c\xf3\x86{\xe1>\xce\xd4\xb7\x8e\xfb\ z8\x9cSU{\xd7\xdeU{W}?k\x1d\xef\ \x15.\xe7V\xd5\xd9\x8f\xef\xfe=+\xc2c\xe6/\xde\ 9V\x0c\x13\x93\xabB\x9c-\x06\xab\x93E\xa52I\ T\xc4\xd8Z\xad6\xb9\x12|\x15\xb5\xe0%*c\x05\ !\x84\x10B\x88OTj\x9b\xf0\xa5V\xabl\x0a4\ \xcd\xae\xda`\xed\xadJep\xd3`M<...
Python
1
imeouted)) if not ref_timeouted.val: save_data(data, filename_2, "ref", lambda: time_function_with_timeout( lambda: sym.edge_based_symmetry(g, sym.SymmetryType.REFLECTIVE), ref_timeouted)) """ if not str_timeouted.val: save_...
Python
1
print("Hello SmartPulse")
Python
1
or BoundingVolumeInterferencesCollector<'a, N, B, BV> where N: Real, B: Clone, BV: BoundingVolume<N>, { #[inline] fn visit_internal(&mut self, bv: &BV) -> bool { bv.intersects(self.bv) } #[inline] fn visit_leaf(&mut self, b: &B, bv: &BV) { if (self.bv as *const BV) != (b...
Rust
0
once. The entire source string is kept in memory and //! parsed at once. This is meant to be changed in upcoming releases. mod errors; mod lexer; mod parser; mod types; pub use crate::parser::Parser; pub use crate::types::BibEntry; pub use crate::parser::BibEntries;<gh_stars>1-10 use adventofcode::search::{bfs, Resul...
Rust
0
rísticas modernas como snapshots, compresión y balanceado.", title="🌿 BTRFS No Disponible", style="yellow" ) if self.console.confirm("¿Deseas instalar BTRFS ahora?", default=True): if s...
Python
1
HAMMER_COOLDOWN_TIME # 清除选择状态 game["selected"] = None # 清除植物预览 if state_manager: state_manager.clear_plant_preview() print(f"锤子击杀了 {zombies_killed} 只僵尸!") return True else: ...
Python
1
ots. TIMETABLE_SLOTS = [ (time(8, 15), time(9, 0)), (time(9, 15), time(10, 0)), (time(10, 15), time(11, 0)), (time(11, 15), time(12, 0)), (time(12, 15), time(13, 0)), (time(13, 15), time(14, 0)), (time(14, 15), time(15, 0)), (time(15, 15), time(16, 0)), (time(16, 15), time(17, 0)), ...
Python
1
tings::ColoredHelp, StructOpt}; use cargo_deps::Config; const USAGE: &str = "\ cargo-deps writes a graph in dot format to standard output. Typical usage is `cargo deps | dot -Tpng > graph.png`."; #[derive(Debug, StructOpt)] #[structopt(bin_name = "cargo")] pub enum Command { #[structopt(name = "deps", usage...
Rust
0
], pub normal: Vec3, pub edges: [Vec3; 2], pub material: Box<dyn RayScattering + Sync>, } impl BasicTriangle { pub fn new(corners: [Vec3; 3], material: Box<dyn RayScattering + Sync>) -> BasicTriangle { BasicTriangle { corners, normal: get_triangle_normal(&corners), ...
Rust
0
T = int(input()) # 구해야 하는 것 # 루트에 저장된 값 # N/2에 저장된 값 for tc in range(1, T+1): N = int(input()) tree = [[0,0] for _ in range(N+1)] for i in range(1, (N)//2+1): tree[i][0] = 2*i if 2*i+1 <= N: tree[i][1] = 2*i + 1 print(tree) in_order = [0] # 중위 순회 ...
Python
1
; fn insert_ek_cert_into_tpm(ctx: &mut Context, pubcert: &[u8]) -> Result<()> { let session = ctx .start_auth_session( None, None, None, SessionType::Hmac, Cipher::aes_128_cfb(), HashingAlgorithm::Sha256, ) .context("Err...
Rust
0
); new_rect.show(); // Because of the derived Debug trait on Rectangle, we can print it with // debug info. println!("Debug new_rect: {:#?}", new_rect); // import for the Display trait. use std::fmt; // This impl is for adding the Display trait to the Rectangle. impl fmt::Display for ...
Rust
0
special="sentence-end">\n') out.write(" <orth>[SENTENCE_END]</orth>\n") out.write(" <synt><tok>&lt;/s&gt;</tok></synt>\n") out.write(" </lemma>\n") # Pronounciations last_word = "" pronounciat...
Python
1
# # build a graph and calculate various graph properties import os import snap import sys if __name__ == '__main__': if len(sys.argv) < 3: print "Usage: %s <file> <column1> <column2>" % (sys.argv[0]) sys.exit(1) fname = sys.argv[1] col1 = int(sys.argv[2]) - 1 col2 = int(sys.argv[3]...
Python
1
i8; exec.ac.set_gpreg(GpReg16::AX, al as u16) } fn cwd(exec: &mut exec::Exec) -> Result<(), EmuException> { let ax = exec.ac.get_gpreg(GpReg16::AX)? as i16; exec.ac.set_gpreg(GpReg16::DX, if ax < 0 { u16::MAX } else { 0 }) } callf_abs!(16, ptr16, imm16); pushf!(16); po...
Rust
0
red. Otherwise no alert will be triggered for that feature. This field is a member of `oneof`_ ``threshold``. """ value: float = proto.Field( proto.DOUBLE, number=1, oneof="threshold", ) snapshot_analysis: SnapshotAna...
Python
1
from django.urls import path from .views import ( student_home, my_courses, checkout, view_profile, reset_password, sign_out, edit_profile, explore_course, add_comment, edit_comment, delete_comment, serve_video, add_review # Import add_review ) urlpatterns = [ path('', student_home, name='student_home...
Python
1
::PKCS_ED25519) { params.alg = &rcgen::PKCS_ED25519; } else if key_pair.is_compatible(&rcgen::PKCS_ECDSA_P256_SHA256) { params.alg = &rcgen::PKCS_ECDSA_P256_SHA256; } else if key_pair.is_compatible(&rcgen::PKCS_RSA_SHA256) { params.alg = &rcgen::PKCS_RSA_SHA256; ...
Rust
0
#!/usr/bin/env python3 """ 影子数据审计脚本:真伪 & 多样性 & 去模板化检测 """ import argparse, json, re, random, statistics, sys from collections import Counter def mask_digits(s): return re.sub(r"\d+", "#", s.lower()) def jaccard_5gram(a,b): A=set([a[i:i+5] for i in range(max(0,len(a)-4))]) B=set([b[i:i+5] for i in range(max(0,len(...
Python
1
edge_ins_cost=edge_ins_cost), 0.23) def test_graph_edit_distance_upper_bound(self): G1 = circular_ladder_graph(2) G2 = circular_ladder_graph(6) assert_equal(graph_edit_distance(G1, G2, upper_bound=5), None) assert_equal(graph_edit_distance(G1, G2, upper_bound=24), 2...
Python
1
inline(always)] pub fn _0000(self) -> &'a mut W { self.variant(GROUP5_A::_0000) } #[doc = "FB_CS3 . You must also write 1b to CSCR\\[AA\\]."] #[inline(always)] pub fn _0001(self) -> &'a mut W { self.variant(GROUP5_A::_0001) } #[doc = "FB_BE_7_0 . You must also write 1b to CSC...
Rust
0
ck_hook = free_rollback_hook; } fn update_hook<F>(&mut self, hook: Option<F>) where F: FnMut(Action, &str, &str, i64) + Send + 'static, { unsafe extern "C" fn call_boxed_closure<F>( p_arg: *mut c_void, action_code: c_int, db_str: *const c_char, ...
Rust
0
import json # lê arquivo JSON e retorna a lista de pacientes def carrega_pacientes(): with open('pacientes.json') as arquivo: pacientes = json.load(arquivo) return pacientes # recebe a lista de pacientes e escreve seus dados no arquivo JSON def escreve_pacientes_no_arquivo(pacientes: list): # abro...
Python
1
[u8; 20]); impl BytesPrimitive<20> for TemplateAddr {} #[cfg(test)] mod tests { use super::*; #[test] fn address_len() { assert_eq!(20, Address::N); assert_eq!(20, TemplateAddr::N); } #[test] fn address_partial_eq() { let addr1 = Address::repeat(0xAB); let ad...
Rust
0
if checksol(unrad_changed, sol)] # Collect together the unsolved polynomials with the non-polynomial # equations. remaining = poly_eqs + nonpolys # to_tuple converts a solution dictionary to a tuple containing the # value for each symbol to_tuple = lambda sol: tuple(sol[s] for s in symbols) ...
Python
1
, str(e)) @stocks_api_bp.route('/watchlist', methods=['GET']) def get_watchlist(): """获取用户关注列表""" try: user_id = session.get('user_id') if not user_id: return error_response("请先登录", "UNAUTHORIZED") service = get_stock_service() watchlist_data = service.get_u...
Python
1
import os import logging from enum import IntEnum from appdirs import user_data_dir DATA_DIR = user_data_dir('xbox', 'OpenXbox') TOKENS_FILE = os.path.join(DATA_DIR, 'tokens.json') CONSOLES_FILE = os.path.join(DATA_DIR, 'consoles.json') if not os.path.exists(DATA_DIR): os.makedirs(DATA_DIR) LOG_FMT = '[%(asctim...
Python
1
import tqdm from joblib import Parallel class ParallelTqdm(Parallel): """joblib.Parallel, but with a tqdm progressbar. Parameters ---------- total : int The total number of tasks to complete. desc : str A description of the task. tqdm_bar : bool, optional Whether to di...
Python
1
, 2, 100, 252] downsampled_rm = self.reg_head(downsampled_fused_feature) # [b_ego, 14, 100, 252] output_dict.update({'downsampled_cls_preds': downsampled_psm, 'downsampled_reg_preds': downsampled_rm}) if self.use_dir: output_dict.updat...
Python
1
= "Clock source is CTIMERB6 OUT. value."] CTMRB6, #[doc = "Clock source is BLE buck converter TON pulses. value."] BUCKBLE, #[doc = "Clock source is Memory buck converter TON pulses. value."] BUCKB, #[doc = "Clock source is CPU buck converter TON pulses. value."] BUCKA, #[doc = r" Reserv...
Rust
0
"; //Lazy static lazy_static! { //runtime with threaded pool static ref RUN_TIME: tokio::runtime::Runtime = tokio::runtime::Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); // HTTP client to share static ref HTTP_CLIENT: reqwest::Client = reqwest::C...
Rust
0
init = tf.global_variables_initializer() saver = tf.train.Saver(tf.trainable_variables()) # Launch the graph. sess = tf.Session() sess.run(init) # Fit the line. for _ in range(201): sess.run(train_op) w_reference = sess...
Python
1
ce_df = pd.Series(data) # DataFrameを2列のインデックスを持つ形に変換 chart_data = source_df.reset_index() chart_data.columns = ["項目", "金額"] chart_data["金額"] = chart_data["金額"].astype(float) # 上記で作成した新規DataFrameをグラフ描画用に加工 chart = ( alt.Chart(chart_data) .mark_bar() .encode( ...
Python
1
res = score_repository.get_by_usershow_id(usershow_id_one_score.value) assert len(res) == 1 class TestGetByAnimalShowId: def test_no_score_error(self, score_repository, animalshow_id_no_score): with pytest.raises(NotFoundRepoError): score_repository.get_by_animalshow_id(animalshow_...
Python
1
5 => Reg(L), 6 => Mem, 7 => Reg(A), _ => unreachable!(), } } fn get_fullreg(idx: u8, sp: bool) -> Reg { use Reg::*; match idx & 3 { 0 => BC, 1 => DE, 2 => HL, 3 => { if sp { SP } else { ...
Rust
0
timesheet_lines(self): """Gets the timesheet_lines of this Timesheet. # noqa: E501 :return: The timesheet_lines of this Timesheet. # noqa: E501 :rtype: list[TimesheetLine] """ return self._timesheet_lines @timesheet_lines.setter def timesheet_lines(self, timesheet_l...
Python
1
import os from tests.utils.runtest import makesuite, run from tests.utils.gc import gcwait from tests.utils.loadassemblies import CPYTHONSTUB_DLL from tests.utils.testcase import TestCase from Ironclad import dgt_getfuncptr, dgt_registerdata, Unmanaged, StubReference from System import IntPtr class StubReferenceTes...
Python
1
if len(classes) > 1: raise ValueError("Sigmoid output possible only with 1 class") class_pred = probas[:, 0] else: class_pred = probas[:, c] errors = (fg - class_pred).abs() errors_sorted, perm = torch.sort(errors, 0, descending=True) per...
Python
1
, 0x5a]` if protected, `[0x00, 0x00]` if not pub copy_protected: [u8; 2], /// Partition 1 pub partition_1: MBRPartitionEntry, /// Partition 2 pub partition_2: MBRPartitionEntry, /// Partition 3 pub partition_3: MBRPartitionEntry, /// Partition 4 pub partition_4: MBRPartitionEntry, ...
Rust
0
from datetime import date, timedelta from typing import ClassVar from pydantic.dataclasses import dataclass from typing_extensions import Self from .. import http from ..utils import camel_to_snake_dict, format_end_date @dataclass class Stats: calendar_date: date _path: ClassVar[str] _page_size: ClassV...
Python
1
info( &compositor, &presentation.stroke, )?)?; sprite_shape.SetStrokeThickness(presentation.stroke_width)?; current_shape.Shapes()?.Append(sprite_shape)?; } "g" => {} "path" => { ...
Rust
0
from openai import OpenAI import config client = OpenAI(api_key=config.OPENAI_API_KEY) question = input("Ask me anything: ") response = client.chat.completions.create( messages=[ { "role": "user", "content": question } ], model="ft:gpt-3.5-turbo-0125:riis-llc::9cabEtl7", temperature=0,...
Python
1
indexes( &token_id, &index, &index.spl_token_owner_index, key_start, key_end, &secondary_indexes, ); } } fn run_test_secondary_indexes_same_slot_and_forks< SecondaryIndexEntryType: Second...
Rust
0
ssl: true, internal_experiment_flags: vec![], consistency_token_jars: vec![], }; let mut params = Vec::with_capacity(20); params.push(AdParam::new("dt", &format!("{}", timestamp))); params.push(AdParam::new("flash", "0")); params.push(AdParam::new("frm", ...
Rust
0
_(self.pos_bias_v) def rel_shift(self, x): """Compute relative positional encoding. Args: x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1). time1 means the length of query vector. Returns: torch.Tensor: Output tensor. """ ...
Python
1
""" Copyright (C) [2024] [Fourier Intelligence Ltd.] This program 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. This program is distribut...
Python
1
) => { assert_eq!(node.key, $key); assert_eq!(***node, $node); assert_eq!(node.canceled_key, $ckey); assert_eq!(node.canceled_node, $cnode); }, _ => panic!("expected not aligned node") } }; } #[test] fn test_track_new()...
Rust
0
file.TemporaryFile(mode="w+b") as f: build_context.write_archive(f) # We use the client api directly here, so we can stream the logs output_stream = docker_client.images.client.api.build( fileobj=f, custom_context=True, tag=image_name,...
Python
1
ata[y][x] = color; } else { // return fail result } } pub fn pixel_at(&self, x: usize, y: usize) -> Color { self.data[y][x] } // scale/clamp color values from 0-1 to 0-255 fn scale_color(&self, rgb: f32) -> u8 { (rgb * MAX_COLOR_VAL as f32) ....
Rust
0
|= 1 << face; // We update that adjacent chunk's sides with the current chunk ! Self::update_side( // It should be the opposite face from the adjacent chunk's POV, so we XOR 1 to flip the last bit face ^ 1, ...
Rust
0
# pma.py --maxTransitions 100 deterministic synchronous msocket # 7 states, 8 transitions, 1 accepting states, 0 unsafe states, 0 finished and 0 deadend states # actions here are just labels, but must be symbols with __name__ attribute def send_return(): pass def send_call(): pass def recv_call(): pass def recv_retu...
Python
1
class Database_commands: relay1_state = 1 relay2_state = 2 relay3_state = 3 ### input_value = 4 input_price = 12 ### asker1_value = 5 asker2_value = 6 asker3_value = 7 ### asker2_price = 8 asker3_price = 9 ### left_bound = 10 right_bound = 11 class da...
Python
1
e': size = self.n_test loader = DataLoader(list(range(size)), batch_size=1, collate_fn=self.collate, shuffle=self.training, num_workers=0) else: size = self.n_views loader = DataLoader(list(range(size)), batch_size=1, collate_fn=self.collate_image, shuffle=self.tr...
Python
1
torch.zeros(batch_quat_tensor.shape[0], 9) batch_rot_tensor[:, 0] = 1 - 2 * (qy**2 + qz**2) batch_rot_tensor[:, 1] = 2 * (qx * qy - qz * qw) batch_rot_tensor[:, 2] = 2 * (qx * qz + qy * qw) batch_rot_tensor[:, 3] = 2 * (qx * qy + qz * qw) batch_rot_tensor[:, 4] = 1 - 2 * (qx**2 ...
Python
1
se=base) ) def exp(self) -> Self: r"""Compute the exponent. Returns: A new expression. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> df_native = pa.table({"values": [-1, 0, 1]}) >>> df = nw.from_native(...
Python
1
}' => continue, ']' | ')' => { range_str.push(c); let range = R::from_text(ty, Some(&range_str))?; ranges.push(range); range_str = String::new(); } ',' => { if range_str.is...
Rust
0
import time import pandas as pd from itertools import permutations max_length = 45 desired_techniques = ['True Method', 'Yin Jin Jing', 'Art of Harmony', 'Lotus in Heart', 'Breathing Skill', 'Diamond Body', 'Wu Dang Harmony', 'Mechanic', 'Poison Proof Spell'] def checksubstring(a, b): if not a or not b: ...
Python
1