text
string
label_name
string
labels
int64
; for (key, value) in P::to_map().into_iter() { let bool_val = flags.contains(value); map.serialize_entry(&format!("{}{}", &P::PREFIX, key), &Arg::new(bool_val))?; } map.end() } /// Expected JSON layouts for each field that is a valid Hack option #[derive(Deserialize)] #[serde(untagged)] en...
Rust
0
f"{LOCAL_HOST_URL}{web_interface_tests.PORT}/", session ) def _get_all_native_rules(self, web_interface_instance, black_list=None): if black_list is None: black_list = [] full_back_list = self.URL_BLACK_LIST + black_list + web_interface_tests.get_plugins_routes(web_i...
Python
1
lod[i + j * width as usize] = 2.0; } } } let temp_buf = device .create_buffer_mapped(lod.len(), wgpu::BufferUsage::COPY_SRC) .fill_from_slice(&lod); encoder.copy_buffer_to_texture( wgpu::BufferCopyView { buf...
Rust
0
AddError(added_packages::Error), #[fail(display = "Could not operate on local package data. {}", _0)] LocalPackageError(local_package::Error), #[fail(display = "Could not cleanup old artifacts. {}", _0)] CleanupError(removed_lockfile_packages::Error), #[fail( display = "Attempting to ins...
Rust
0
{ let s = "".as_bytes(); let out = CharState::new().utf8_compute(s).output(); assert_eq!(out, 0) } #[test] pub fn test3() { let s = "a".as_bytes(); let out = CharState::new().utf8_compute(s).output(); assert_eq!(out, 1) ...
Rust
0
tructopt(short)] hex_data: String, }, } fn main() { let cli = Cli::from_args(); match cli { Cli::DecodeWorkerMessage { hex_data } => { let data = decode_hex(&hex_data); let msg: phala_types::SignedWorkerMessage = Decode::decode(&mut data.as_slice()).e...
Rust
0
et.ty())?; let ret_pointer = self.ret.value_to_bytes(&mut ret_value).as_mut_ptr(); // Call the function. let ret: u32 = unsafe { (self.jit_fn_ptr)(args_pointer, ret_pointer) }; if ret == u32::MAX { // No error occurred; get the return value from self.out_bytes. ...
Rust
0
import os import numpy as np import glob from joblib import Parallel, delayed import argparse parser = argparse.ArgumentParser(description='Data Preprocessing') parser.add_argument('--num_patch', type=int, default=581) parser.add_argument('--batch_size', type=int, default=48) parser.add_argument('--num_jobs', type=int...
Python
1
, Timestamp}, *, }; use serde::{Deserialize, Serialize}; /// DB Specific struct for ionets table #[derive(Identifiable, Queryable, Debug, Serialize, Deserialize)] #[table_name = "ionets"] pub struct IoNet { pub id: i64, pub interface: String, pub rx_bytes: i64, pub rx_packets: i64, pub rx_errs:...
Rust
0
et mut buf = String::new(); loop { buf.push(char::from_digit((n / fact_base[i]) as u32, 36).unwrap().to_ascii_uppercase()); n %= fact_base[i]; if i == 0 { break; } else { i -= 1; } } buf } fn fact_string_2dec(s: String) -> u64 { s.chars()....
Rust
0
+ 1, param) { error!( "Failed to bind #{} `find` parameter to `{}`: {}", n, sql, err ); return None; } } Some(statement) }, ...
Rust
0
127; for (i, c) in bp.chars().enumerate() { match i { 0..=5 => { let (nl, nu) = compute_range(c, lower, upper); lower = nl; upper = nu; } 6 => { if c == 'F' { row = std::cmp::min(lower, ...
Rust
0
2, PixelFormat::I444 => h, _ => { panic!("Unsupported pixel format"); } }; let u_chroma_stride = match format { PixelFormat::Nv12 => w + u_chroma_fill_bytes, PixelFormat::I420 => (w / 2) + u_chroma_fill_bytes, PixelFormat::I444 => w + u_chroma_fill_b...
Rust
0
_fixed16(convolve.bias)?; for val in &convolve.matrix { self.write_fixed16(*val)?; } self.write_rgba(&convolve.default_color)?; self.write_u8( if convolve.is_clamped { 0b10 } else { 0 } | if c...
Rust
0
BOARD_SIZE = 4 TARGET = 2048 RATE = { 2: 0.8, 4: 0.2 } KEYS = { 'w': 'up', 's': 'down', 'a': 'left', 'd': 'right', 'q': 'quit', }
Python
1
t_to_obj(d): import types if isinstance(d, dict): return types.SimpleNamespace(**{k: dict_to_obj(v) for k, v in d.items()}) elif isinstance(d, list): return [dict_to_obj(v) for v in d] else: return d def get_yaml_object(path_to_type_dir): import os,yaml folder_path = pat...
Python
1
RaftAppendEntriesReq { msg_id: p_msg_id, req: json, } }) .map_err(|e| { anyhow!("could not serialize and convert async_raft::raft::AppendEntriesRequest<memstore::ClientRequest> to json because: {:?}.", e).context(TRACE) }) } /// Convert gr...
Rust
0
tokens. pub struct Tap; impl Tap { pub fn mint(amount: u64) -> ICP { ICP(amount) } } /// A sink is used for burning ICP. In the future, this could be a trait /// where we have different implementations, each offering different /// constraints or be implemented for different types of tokens. pub struc...
Rust
0
tants::CAP_SYS_PACCT, #[cfg_attr(any(feature = "strum", test), strum(serialize = "CAP_SYS_ADMIN"))] #[cfg_attr(any(feature = "serde", test), serde(rename = "CAP_SYS_ADMIN"))] SysAdmin = constants::CAP_SYS_ADMIN, #[cfg_attr(any(feature = "strum", test), strum(serialize = "CAP_SYS_BOOT"))] #[cfg_attr(...
Rust
0
# author : Mr_Topher # darkweb pleyer 127.0.0.1 from __future__ import absolute_import from __future__ import print_function import requests, sys, threading, time, os, random from random import randint from six.moves import input CheckVersion = str(sys.version) import re from datetime import datetime print(''' \0...
Python
1
my == 0); let mut bicubic = !copy_mode && is_luma && self.bicubic; if is_luma && !copy_mode && (self.profile == VP6_ADVANCED_PROFILE) { if !self.autosel_pm { bicubic = true; } else { let mv_limit = 1 << (self.mv_thresh + 1); if (mv....
Rust
0
s = 0 entryPrice_s = 0 #평균 매입 단가. 따라서 물을 타면 변경 된다. leverage = 0 #숏잔고 for posi in balance['info']['positions']: if posi['symbol'] == Ticker.replace("/", "").replace(":USDT", "") and posi['positionSide'] == 'SHORT': amt_s = float(posi['positionAmt']) entryPrice_s= float(...
Python
1
- adding a type layer on top of SIMPLE-TLV's byte slice values //! //! The core idea taken from `der` is to have `Encodable` require an `encoded_length` method. //! By calling this recursively in a first pass, allocations required in other approaches are //! avoided. #![no_std] #![forbid(unsafe_code)] // #![warn(missi...
Rust
0
0][-top:][::-1] print(preds) print(top) return [(class_dict[x], preds[0][x]) for x in top] def preprocess_single_frame(frame): frame = preprocess_input(frame) frame /= 255 return frame if __name__ == '__main__': data_dir = '/home/changan/ActionRecognition/data' list_dir = os.path.joi...
Python
1
while True: try: cidade_a = int(input("Digite o número de habitantes da cidade 'a': ")) taxa_a = float(input("Digite a taxa de crescimento da cidade 'a': ")) cidade_b = int(input("Digite o número de habitantes da cidade 'b': ")) taxa_b = float(input("Digite a taxa de crescimento da c...
Python
1
-lang.org/std/ops/trait.Mul.html /// [`MulAssign`]: https://doc.rust-lang.org/std/ops/trait.MulAssign.html /// [`Math`]: ../type.Math.html /// [`Sample`]: ../type.Sample.html /// [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html /// [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html /// [`fro...
Rust
0
''' UDP TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据。 相对TCP,UDP则是面向无连接的协议。 ''' ''' 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据包。 但是,能不能到达就不知道了。 ''' ''' 虽然用UDP传输数据不可靠,但它的优点是和TCP比,速度快,对于不要求可靠到达的数据,就可以使用UDP协议。 ''' ''' 和TCP类似,使用UDP的通信双方也分为客户端和服务器。 ''' import socket # 服务器首先需要绑定端口: # 创建Socket时,SOCK_DGRAM指定了这个Socket的类型是UDP s = socket.socke...
Python
1
xes[0].set_xlabel("X (normalised)") axes[0].set_ylabel("Y (normalised)") axes[0].set_title( f"Average visits — mean spread = {avg_team_spread:.2f}") fig.colorbar(cont, ax=axes[0], label="Visit count") # 2) Team-spread time-series timesteps = np.arange(team_spread_ts....
Python
1
import json import pytest from django.contrib.auth import get_user_model from mixer.backend.django import mixer from rest_framework.reverse import reverse from rest_framework.status import HTTP_403_FORBIDDEN, HTTP_200_OK from rest_framework.test import APIClient @pytest.fixture() def posts(db): return [ ...
Python
1
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # JMAP_INTERHAND_TO_PANOPTIC = [ 20, # wrist 3, 2, 1, 0, #...
Python
1
expr: self.insert_block(false_expr), if_: if_.offset() as u32, else_: else_.offset() as u32, }), if_.span().extend(false_expr.span()), ); } // FIXME(matthieum): ";" is legal. unimplemented!() } fn pars...
Rust
0
ind OpenSSL development headers. You can try fixing this setting the `OPENSSL_DIR` environment variable pointing to your OpenSSL installation or installing OpenSSL headers package specific to your distribution: # On Ubuntu sudo apt-get install libssl-dev # On Arch Linux sudo pacman -S openssl # On...
Rust
0
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from dvrk import mtm def forward_point_on_trajectory(p, trajectory, forward_steps=5): """ Find a forward point on the trajectory from the nearest point to p. :param p: numpy array, the position vector of the curr...
Python
1
{ PARA_UP_LSCH3_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PARA_UP_LSCH3_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PARA_UP_LSCH3` writer - This bit is used to update register...
Rust
0
from django.shortcuts import render,HttpResponse from apps.interface.services.HTTP_interface_debugService import HTTP_interfaceDebugService from apps.common.func.CommonFunc import * from apps.common.func.LanguageFunc import * from apps.common.helper.ApiReturn import ApiReturn from AutotestWebD import settings import js...
Python
1
# Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available under the Nvidia Source Code License-NC. # To view a copy of this license, visit # https://nvlabs.github.io/stylegan2/license.html import argparse import os import sys import dnnlib import dnnlib.tflib as tflib import pret...
Python
1
} } #[derive(Clone, Serialize, Deserialize)] #[serde(bound(serialize = "<E as ff::ScalarEngine>::Fr: serde::Serialize, \ <E as pairing::Engine>::G1: serde::Serialize, \ <E as pairing::Engine>::G2: serde::Serialize, \ <E as pairing::Eng...
Rust
0
ne in matrix: np.savetxt(f, line[np.newaxis], fmt='%f') def export_poses(self, output_path, frame_skip=1): if not os.path.exists(output_path): os.makedirs(output_path) print('exporting', len(self.frames)//frame_skip, 'camera poses to', output_path) for f in range(0, len(self.frames), frame...
Python
1
<Vec<char>>()};($sc:expr,Usize1)=>{read_value!($sc,usize)-1};($sc:expr,$t:ty)=>{$sc.next::<$t>()};} pub struct Scanner{s:Box<str>,input:std::iter::Peekable<std::str::SplitAsciiWhitespace<'static>>,} impl Scanner{ pub fn new<R:std::io::Read>(mut reader:R)->Self{let mut sc=Scanner{s:{let mut s=String::new...
Rust
0
image_bind, sub_offset, sub_dims, mip_level.to_glint(), data_ptr, data_len, Self::Format::FORMAT, ); } } unsafe impl<C> TextureTypeRenderable<D1> for C where C: ?Sized + ImageFormatRenderable, { type DynRenderable = dyn ...
Rust
0
model def main(): # Inputs from CLI or defaults if len(sys.argv) < 3: train_path = "../PRIMVS/PRIMVS_P_GAIA.fits" test_path = "../PRIMVS/PRIMVS_P.fits" out_file = "xgb_predictions.csv" print("Using default file paths") else: train_path, test_path = sys.argv[1:3] ...
Python
1
n); let mut num_inv = Vec::with_capacity(salen); for i in 0..len { if let Some(n) = names[i] { new_num.push(n); num_inv.push(i); } } // 2-2 let mut lms_sa = Vec::with_capacity(salen); ...
Rust
0
#!/usr/bin/env python import os import subprocess from cffi import FFI import numpy as np gf_dir = os.path.dirname(os.path.abspath(__file__)) subprocess.check_call(["make"], cwd=gf_dir) ffi = FFI() ffi.cdef(""" typedef enum VisionStreamType { VISION_STREAM_RGB_BACK, VISION_STREAM_RGB_FRONT, VISION_STREAM_YU...
Python
1
ect(inspector.root(), "inspect_wrapper") .expect("failed to create TestInspectWrapper inspect node"); assert_data_tree!(inspector, root: { inspect_wrapper: { queue: { "0": { "id": 5 as u64, }, ...
Rust
0
rom_continuing_investing_activities" debt_repayment_field = "repayment_of_debt" common_stock_issued_field = "issuance_of_capital_stock" common_stock_repurchased_field = "repurchase_of_capital_stock" dividends_paid_field = "common_stock_dividend_paid" other_financing_activities_field = "net_other_fin...
Python
1
from armada_backend import consul_config from armada_backend.models.ships import get_ship_name, get_other_ship_ips from armada_backend.utils import get_current_datacenter, is_ship_commander, \ setup_sentry, get_logger from armada_command.dockyard import alias from armada_command.scripts.compat import json def _sa...
Python
1
from mir.io.feature_io_base import * from mir.music_base import get_scale_and_suffix class SalamiIO(FeatureIO): def read(self, filename, entry): f=open(filename,'r') data=f.read() lines=data.split('\n') result=[] metre_up=-1 metre_down=-1 tonic=-1 for...
Python
1
..drm_mode_get_encoder::default() }; cvt_r(|| unsafe { ioctl(fd, DRM_IOCTL_MODE_GETENCODER(), &mut encoder) })?; Ok(encoder) } pub fn drm_mode_get_connector( raw: &impl AsRawFd, id: u32, modes: Option<&mut Vec<drm_mode_modeinfo>>, encoders: Option<&mut Vec<u32>>, ) -> Result<drm_...
Rust
0
from __future__ import annotations from abqpy.decorators import abaqus_class_doc, abaqus_method_doc from ..UtilityAndView.abaqusConstants import DEFAULT_MODEL, SymbolicConstant from .Leaf import Leaf @abaqus_class_doc class LeafFromModelElemLabels(Leaf): """The LeafFromModelElemLabels object can be used wheneve...
Python
1
] if len(password) < 12: recommendations.append("Increase password length to at least 12 characters") if not any(c.isupper() for c in password): recommendations.append("Add uppercase letters") if not any(c.islower() for c in password): ...
Python
1
lines.append("⚠️ ISSUES DETECTED - PR CHECK PASSED WITH WARNINGS ⚠️") lines.append("=" * 80) # Add anti-pattern section if any were detected if self.anti_patterns: lines.append("\n## 🔍 DETECTED ANTI-PATTERNS\n") # Group by severity for display ...
Python
1
create_amenity(self, amenity_data): """Create a new amenity and store it""" try: print(f"Creating amenity with data: {amenity_data}") new_amenity = Amenity( id=str(uuid.uuid4()), name=amenity_data["name"], created_at=datetime.utcnow...
Python
1
[] for x, y in test_samples: output = x for i, layer in enumerate(model): output = layer.forward(output) if i == 0: layer1_fm.append(output.reshape(-1)) elif i == 2: layer2_fm.append(output.reshape(-1)) else: ...
Python
1
example ```python import pulumi import pulumi_gcp as gcp foo = gcp.healthcare.get_hl7_v2_store_iam_policy(hl7_v2_store_id=hl7_v2_store["id"]) ``` :param _builtins.str hl7_v2_store_id: The HL7v2 store ID, in the form `{project_id}/{location_name}/{dataset_name}/{hl7_v2_store_name}...
Python
1
// if code != zk42code { // return Ok(false); // } // let input_hash_addr = machine.registers()[ckb_vm::registers::A0].to_u64(); // let output_hash_addr = machine.registers()[ckb_vm::registers::A1].to_u64(); // let proof_addr = machine.registers()[ckb_vm::registers::A2]....
Rust
0
equest, client: web::Data<sqlx::PgPool>, ) -> HttpResult { let username = get_name_in_token(&req)?; user_model::update_password_by_username(&client, &username, &hash_password(&data.password)?) .await?; Ok(HttpResponse::Ok().json(GeneralResponse::default())) } #[get("/reset_passkey")] async fn r...
Rust
0
%s", thing._path) dut._log.info("length of dut.inst_acs is %d", len(dut.gen_acs)) item = dut.gen_acs[3] item._log.info("this is item") @cocotb.test() async def dual_iteration(dut): """Test iteration over top-level in two forked coroutines.""" async def iteration_loop(): for thing in dut:...
Python
1
5], self.buffer[pos + 6], self.buffer[pos + 7], ]); let offset = u16::from_be_bytes([self.buffer[pos + 2], self.buffer[pos + 3]]) >> 3; let more_fragments = self.buffer[pos + 3] & 0x1 > 0; Some(Ipv6ExtensionHeader::...
Rust
0
ter surface"] pub const _NV_ENC_INPUT_RESOURCE_TYPE_NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR: _NV_ENC_INPUT_RESOURCE_TYPE = 1; #[doc = "< input resource type is a cuda array surface."] #[doc = "This array must be a 2D array and the CUDA_ARRAY3D_SURFACE_LDST"] #[doc = "flag must have been specified when creating it....
Rust
0
signed, LtUnsigned, GtEqUnsigned, LtEqUnsigned, EqSigned, NeqSigned, GtSigned, LtSigned, GtEqSigned, LtEqSigned, Branch, BranchTrue, Call, Ret, PushSlot1, PushSlot2, PushSlot3, PushSlot4, PopSlot1, PopSlot2, PopSlot3, PopSlot4, ...
Rust
0
tadata.write_pkg_file(buffer) msg = buffer.getvalue() # ... when it is read and re-written using stdlib's email library, orig = email.message_from_string(msg) policy = email.policy.EmailPolicy( utf8=True, mangle_from_=False, max_line_length=0, ...
Python
1
wrap(); let result = list_to_device_info(&interpreter, value); crate::utils::assert_invalid_argument_error(&result); } } } <reponame>lukasl93/msp430fr5994<gh_stars>0 #[doc = "Reader of register MPUCTL1"] pub type R = crate::R<u16, super::MPUCTL1>; #[doc = "Writer for register MPUCTL...
Rust
0
from docutils.parsers.rst import roles from docutils.nodes import Text, reference, section, label from sphinx.roles import XRefRole class autonumber(label): pass class autonumber_ref(reference): pass def autonumber_role(name, rawtext, text, lineno, inliner, options={}, content=[]): return ([autonumber(te...
Python
1
apping_add(1) as u32 as u64) .wrapping_mul(::std::mem::size_of::<i8>() as u64) as u32) as *mut i8; strcpy(s, suffix); /* First try converting suffix to feature tag. * agl.c currently only knows less ambiguos cases; * e.g., 'sc', 'superior', etc. */ if let Some(r) = agl_suffix_to_otlta...
Rust
0
"LLVMSupport", "MLIRAnalysis", "MLIRArithmetic", "MLIRCAPIIR", "MLIRCAPIStandard", "MLIRCallInterfaces", "MLIRControlFlowInterfaces", "MLIRIR", "MLIRInferTypeOpInterface", "MLIRPDL", "MLIRPDLInterp", "MLIRPDLToPDLInterp", ...
Rust
0
ial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAI...
Rust
0
rol (0xfffffff) # -1 in the CHU Label.SetText (info["ErrorMsg"]) Button = Window.GetControl (1) Button.SetText (1403) Button.OnPress (Window.Close) Window.ShowModal (MODAL_SHADOW_GRAY) else: GemRB.DisplayString (info["ErrorMsg"], ColorRed) return # special pst death screen for the finale def Open...
Python
1
\t{1}\t{2}\n".format(i, len(members), ", ".join(members))) outfile.close() #--------------------------- Plot dendrogram -----------------------------# fig, ax = plt.subplots(figsize = (3,max(10,len(IDS)/10))) #5 rows per one column width dendro_dat = dendrogram(clustering.linkage_mat, labels=clustering.names, or...
Python
1
elif self.abs_pe == 'none': output = output elif self.abs_pe == 'Eigvecs': output = output + self.eigvecs_embeding(data.Eigvecs) output = self.dropout(output) if self.use_edge_attr and edge_attr is not None: edge_attr = self.embedding_edge(edge_attr) ...
Python
1
if move < NB_AREAS: area = move return f'Abandon {area}' elif move < 2*NB_AREAS: area = move - NB_AREAS return f'Attack {area}' elif move < 3*NB_AREAS: area = move - 2*NB_AREAS return f'Special ppl move {area}' elif move < 4*NB_AREAS: area = move - 3*NB_AREAS return f'Special power {area}' elif ...
Python
1
gameboy.get_tile_data_selection() == 1 { ele as usize } else { ((ele as i8) as i16 + 128) as usize }; let tile_start_idx = tile_idx as usize * BYTES_PER_TILE; let tile_end_idx = tile_start_idx + BYTES_PER_TILE; let tile_bytes ...
Rust
0
sult<HString> { unsafe { let mut out = null_mut(); let hr = ((*self.lpVtbl).get_CapiKdfSha384)(self as *const _ as *mut _, &mut out); if hr == S_OK { Ok(HString::wrap(out)) } else { err(hr) } }} #[inline] pub fn get_capi_kdf_sha512(&self) -> Result<HString> { unsafe { let mut o...
Rust
0
::click_generate_sk) .fix_width(200.); let restore_button = button("Restore") .disabled_if(|data: &AppState, _| data.user.sk.len() != 64) .on_click(ConfigController::click_restore_sk) .fix_width(200.); let forms = Flex::column() .cross_axis_alignment(CrossAxisAlignment:...
Rust
0
edableRng, RngCore}; fn main() { let mut rng = ThreeFry2x64Rng::seed_from_u64(0); loop { println!("{}", rng.next_u32()); } } <filename>src/data/value/literal.rs use { super::{error::ValueError, Value}, crate::result::{Error, Result}, sqlparser::ast::Value as AstValue, std::convert::TryFrom, };...
Rust
0
ribeDBInstanceDetailResponse. # noqa: E501 :return: The nodes of this DescribeDBInstanceDetailResponse. # noqa: E501 :rtype: list[NodeForDescribeDBInstanceDetailOutput] """ return self._nodes @nodes.setter def nodes(self, nodes): """Sets the nodes of this DescribeDBI...
Python
1
__(self, points): ''' :param points: bn, n , 3 :return: ''' if points.is_cuda is True: tmp_rot = self.rot_mats.cuda() else: tmp_rot = self.rot_mats transed_poitns = torch.transpose(torch.matmul(tmp_rot, torch.transpose(points, 1, 2)), 1, 2...
Python
1
>, ) -> ErrorCode { debug!( "vdr_prepare_did > handle {:?} txn_specific_params {:?} submitter_did {:?} endorser {:?}", handle, txn_specific_params, submitter_did, endorser ); check_useful_c_str!(txn_specific_params, ErrorCode::CommonInvalidParam3); check_useful_c_str!(submitter_did, Err...
Rust
0
stringify!(BCD_OutputActiveLow) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<ft_eeprom_4222h>())).BCD_Drive as *const _ as usize }, 63usize, concat!( "Offset of field: ", stringify!(ft_eeprom_4222h), "::", stringify!...
Rust
0
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.model import Job from app.schemas.job_schemas import JobCreate, JobResponse from app.database import get_db from app.utils.utils import process_job_description router = APIRouter(prefix="/jobs", tags=["Jobs"]) @router.po...
Python
1
tdown limpio --- stop_event = asyncio.Event() def _handle_sig(): stop_event.set() loop = asyncio.get_running_loop() for sig in (signal.SIGINT, signal.SIGTERM): try: loop.add_signal_handler(sig, _handle_sig) except NotImplementedError: pass log.info(...
Python
1
); pub const VIDIOC_ENUMINPUT: _IOC_TYPE = _IOWR!(b'V', 26, v4l2_input); pub const VIDIOC_G_CTRL: _IOC_TYPE = _IOWR!(b'V', 27, v4l2_control); pub const VIDIOC_S_CTRL: _IOC_TYPE = _IOWR!(b'V', 28, v4l2_control); pub const VIDIOC_G_TUNER: _IOC_TYPE = _IOWR!(b'V', 29, v4l2_tuner); pub const VIDIOC_S_TUNER: _IOC_TYPE = _IO...
Rust
0
_attribute_t, num_uworkers: u32, num_tworkers: u32) -> SgxResult<sgx_enclave_id_t> { let mut us_config = sgx_uswitchless_config_t::default(); us_config.num_tworkers = num_tworkers; us_config.num_uworkers = num_uworkers; let ...
Rust
0
tem/inventory system */ /*#[cfg(test)] mod tests { #[test] fn asset_loader_resolve_path() { let mut al = AssetLoader::new(format!("{}/assets/", env!("CARGO_MANIFEST_DIR")),"base"); assert_eq!(al.resolve_path("test/test.txt"),"assets/base/test/test.txt") } #[test] fn asset_loader_res...
Rust
0
s = np.where(predictions != -100, predictions, tokenizer.pad_token_id) predictions = tokenizer.batch_decode( predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True ) with open(os.path.join(args.output_dir, 'predictions.jsonl'), 'w') as fout: for i, examp...
Python
1
e, Debug, PartialEq, JsonSchema)] pub struct Holder { pub balance: Uint128, pub index: Decimal, pub pending_rewards: Decimal, } // This is similar to HashMap<holder's address, Hodler> pub fn store_holder( storage: &mut dyn Storage, holder_address: &CanonicalAddr, holder: &Holder, ) -> StdResult...
Rust
0
is not None: accum_gradient.assign_add(gradient) self._accum_steps.assign_add(1) def reset(self): """Resets the accumulated gradients.""" if self._gradients: self._accum_steps.assign(0) for gradient in self._get_replica_gradients(): ...
Python
1
hape,pF,px,py): H, W = range_shape cnt = 0 r = [] # t1 = time.time() for batch,(p_x,p_y) in enumerate(zip(px,py)): image = torch.zeros(size=(H,W,pF.shape[1])).to(px[0].device) image_cumsum = torch.zeros(size=(H,W,pF.shape[1])) + 1e-5 p_x = torch.floor((p_x/2. + 0.5) * W).lon...
Python
1
{ header } => Msg::write_disconnect_bytes(header, dst), } } } pub struct MsgCodec { msg_len: usize, } impl MsgCodec { pub fn new() -> MsgCodec { MsgCodec { msg_len: 0, } } } impl Encoder for MsgCodec { type Item = Msg; type Error = io::Error; fn encode...
Rust
0
hon {sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}")} ''' INPUTNEEDED = ''' ,---,---,---,---,---,---,---,---,---,---,---,---,---,-------, |esc| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 0 | + | ' | <- | |---'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-'-,-----| | ->| | Q | W | E | R | T | ...
Python
1
JsonViewModelItem { summary: vec![], key: String::from("total_commits_by_day"), data: serde_json::to_value(items).unwrap(), }); } } impl GitStat for CommitsByDayCollector { fn process(&mut self, commit: &GitCommit) { let stat = self.total_commits_by_day.entry...
Rust
0
class Solution: def partitionLabels(self, s: str) -> List[int]: d = {} for index, i in enumerate(s): d[i] = index res = [] size, end = 0, 0 for index, i in enumerate(s): size += 1 end = max(end, d[i]) if index == end: ...
Python
1
println!( "All completed in {}.{:03}s.", end.as_secs(), end.subsec_nanos() / 1_000_000 ); } fn write_csv(n: usize, t: Vec<f64>, v: Vec<f64>, x: Vec<f64>, file_path: &str) -> Result<(), Box<dyn error::Error>> { let file_name: String = format!("{}.csv", file_path); let file =...
Rust
0
ywh2xyxy_with_shape( result_dict['gt_bboxes'], shape=result_dict['img_shape'][:2]) return result_dict def get_ann_info(self, idx): """ Get raw annotation info, include bounding boxes, labels and so on. `bboxes` format is as [x1, y1, x2, y2] without normalization. ...
Python
1
from typing import Any, Dict, List from continuous_eval.data_downloader import example_data_downloader from continuous_eval.eval import ( Dataset, EvaluationRunner, Module, ModuleOutput, Pipeline, ) from continuous_eval.eval.result_types import PipelineResults from continuous_eval.metrics.generatio...
Python
1
put == expected_output else: assert actual_output == input_path def test_get_path_datasize(tmpdir): """ Test that get_path_datasize() works correctly when passed excluded patterns. """ # Create a temporary directory for testing test_dir = tmpdir.mkdir("test_dir") test_file = test_d...
Python
1
(ctx, eng, &self.dex); for active in self.player.local.as_ref().unwrap().renderer.iter() { active.pokemon.draw(ctx, Vec2::ZERO, Color::WHITE); } self.closer.draw_battle(ctx); s...
Rust
0
Word, pub ch_size: Elf32_Word, pub ch_addralign: Elf32_Word, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Elf64_Chdr { pub ch_type: Elf64_Word, pub ch_reserved: Elf64_Word, pub ch_size: Elf64_Xword, pub ch_addralign: Elf64_Xword, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct Elf...
Rust
0
ct("bad math") { Tile::Floor => new_map.push(Tile::Floor), Tile::Empty => { if self.num_neighbors_occupied(c, r) == 0 { new_map.push(Tile::Occupied); } else { new_map.push(Tile...
Rust
0
ABLE = 0x40; const MOVEABLE = 0x80; } } binread_flags!(SpriteScoreColor, u8); fn fix_v0_v6_sprite_kind(kind: SpriteKind) -> SpriteKind { match kind { SpriteKind::Bitmap | SpriteKind::Field | SpriteKind::Button | SpriteKind::CheckBox | SpriteKind::RadioButton ...
Rust
0
, 1],[16, 2],[13, 2],[12, 1],[11, 1],[10, 2],[ 7, 2],[ 6, 1],[ 5, 1],[ 4, 2],[ 1, 2],[ 0, 1]], 19, 2), ([[ 0, 1],[ 1, 1],[ 1, 0],[ 2, 1],[ 3, 2],[ 6, 2],[ 7, 1],[ 8, 1],[ 9, 2],[12, 2],[13, 1],[14, 1],[15, 2],[18, 2],[19, 1]], 19, 2), ([[19, 1],[18, 1],[18, 2],[17, 1],[16, 0],[13, 0],[12, 1],[11...
Rust
0