text
string
label_name
string
labels
int64
to have an idle() callback called by the host rapidly to update the UI. */ #[repr(C)] pub struct LV2UIIdleInterface { /** Run a single iteration of the UI's idle loop. This will be called rapidly in the UI thread at a rate appropriate for a toolkit main loop. There are no precise timing g...
Rust
0
def hej(namn): return f"Hej {namn}! Välkommen till den trevligt resa! Vill du fortsätta?"
Python
1
""" Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ import datetime import functools import os import torch import torch.distributed as dist import t...
Python
1
# 启用DDP策略 max_epochs=200, precision=16, callbacks=[ ModelCheckpoint(save_weights_only=True, monitor='val_csi', save_top_k=3, mode='max'), LearningRateMonitor("epoch"), GenerateCallback(input_img, every_n_epochs=1), EarlyStopping(monitor='val_csi_16...
Python
1
__doc__) def _get_name(self): return self.userinfo["name"] def _set_name(self, val): if self.user_id: raise AttributeError(_("This comment was posted by an authenticated "\ "user and thus the name is read-only.")) self.user_name = val n...
Python
1
e_while(|c| c.is_digit(16)) { suggestion.push(c); suggestion_len += c.len_utf8(); } if suggestion_len > 0 { suggestion.push('}'); let hi = char_span.lo() + BytePos(suggestion_len as u32); diag.span_suggestion( ...
Rust
0
_root + 'test/img/', pipeline=test_pipeline)) evaluation = dict(interval=5, metric='bbox') # optimizer optimizer = dict(type='SGD', lr=0.015, momentum=0.9, weight_decay=4.0e-5) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='CosineAnnealing', warmup='linear', wa...
Python
1
# Copyright (c) 2016-2018, The University of Texas at Austin # & University of California--Merced. # Copyright (c) 2019-2020, The University of Texas at Austin # University of California--Merced, Washington University in St. Louis. # # All Rights reserved. # See file COPYRIGHT for details. # # This file is part of th...
Python
1
prop_size=data.cat_property_embedding.shape[-1]).to(device) elif mode == 'GCN': model = BotGCN(hidden_dim=hidden_dim, dropout=dropout, num_prop_size=data.num_property_embedding.shape[-1], cat_prop_size=data.cat_property_embedding.shape[-1]...
Python
1
JTAG access remains disabled until the chip is reset by any source."] DISABLE_JTAG_DEBUG, } impl M0SUBTAPSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { M0SUBTAPSELW::NO_EFFECT => false, M0SUBTAPSELW::DISABLE_JTAG_DE...
Rust
0
: &[Ident], struct_types: &[Type]) -> (Vec<Ident>, Vec<Type>) { let mut optionals = vec![]; let mut types = vec![]; for (id, ty) in struct_fields.iter().zip(struct_types.iter()) { if let Type::Path(type_path) = ty { if type_path.qself.is_some() { continue; } ...
Rust
0
= [0f64; 3]; vst3_lane_f64::<0>(r.as_mut_ptr(), core::ptr::read_unaligned(a[1..].as_ptr() as _)); assert_eq!(r, e); } #[simd_test(enable = "neon")] unsafe fn test_vst3q_lane_f64() { let a: [f64; 7] = [0., 1., 2., 2., 3., 2., 3.]; let e: [f64; 6] = [1., 2., 2., 0., 0., 0.]; ...
Rust
0
"""Script for extracting best hyperparams from HPS.""" import json from pathlib import Path import click import pandas as pd import yaml @click.command() @click.option( "--input_dir", help="Path to directory with HPS logs", type=click.Path(exists=True, path_type=Path), ) @click.option( "--select_by_m...
Python
1
device: Box<B::Device>, pub(crate) factory: Box<B::Factory>, pub(crate) encoder: gfx::Encoder<B::Resources, B::CommandBuffer>, pub(crate) screen_render_target: gfx::handle::RawRenderTargetView<B::Resources>, #[allow(dead_code)] pub(crate) depth_view: gfx::handle::RawDepthStencilView<B::Resources>, ...
Rust
0
orkloads predictions = y_binner.transform(predictions) dists = np.sqrt(np.sum(np.square( np.subtract(predictions, y_target)), axis=1)) scores[workload_id] = np.mean(dists) # Find the best (minimum) score best_score = np.inf best_workload_id = None best_workload_name ...
Python
1
"true"): try: d = difflib.context_diff(open("output/" + t.attrib['name'] + ".stderr", "rt").readlines(), open(tempfile.gettempdir() + "/" + t.attrib['name'] + ".stderr", "rt").readlines()) if list(d): print ''.join(list(d...
Python
1
MIT license <LICENSE-MIT // or http://opensource.org/licenses/MIT>, at your option. All files in the // project carrying such notice may not be copied, modified, or distributed // except according to those terms. use math; use math::{Point2, Point3, Point4}; use noise_fns::{MultiFractal, NoiseFn, Perlin, Seedable}; ...
Rust
0
ral Gas Fired Combustion Turbine", "nggt": "Natural Gas Fired Combustion Turbine", "ngic": "Natural Gas Internal Combustion Engine", "ngst": "Natural Gas Steam Turbine", "ngot": "Other Natural Gas", "ngcas": "Natural Gas with Compressed Air Storage", "other_gas": "Other Gases", "petroleum_co...
Python
1
"asdf", BlobMetaRequest::file("bing.txt").with_meta("some_field", "b"), "admin", ) .await?; assert_eq!(node.id, "beta"); } Ok(()) } #[tokio::test] async fn add_blob_routing_key_unknown_value() -> Result<()> { let node = mock::node...
Rust
0
print("[-] unable to find uid in range(1, {})".format(str(uid_range))) # brute force project id print("[*] getting project id...") project_id_range = 1000 for i in range(1, project_id_range): data = json.dumps({"id": i, "token": self.encrypted_token}) ...
Python
1
def setup(): ''' This will import modules config_default and config and move their variables into current module (variables in config have higher priority than config_default). Thanks to this, you can import settings anywhere in the application and you'll get actual application setti...
Python
1
in_prog = locked.in_progress.remove(&piece_id).unwrap(); // let _ = in_prog.completion.send(Ok(CompletionEvent { // info_hash, // piece_id, // })); // if sha[..] == piece_sha.0[..] { // locked.completion.set(pi...
Rust
0
IPE@?$AAr?$AA?$AA@", "`string'"); expect("??_C@_13KHDBCPJB@?$AAs?$AA?$AA@", "`string'"); expect("??_C@_13DKOGBHCI@?$AAt?$AA?$AA@", "`string'"); expect("??_C@_13ICFKHAEN@?$AAu?$AA?$AA@", "`string'"); expect("??_C@_13JAOPNPKD@?$AAv?$AA?$AA@", "`string'"); expect("??_C@_13CIFDLIMG@?$AAw?$AA?$AA@", "`st...
Rust
0
ssage) raise Exception(message) message = f"{message}, Success." print(message) def deleteStorageTriggerForWorkflow(workflowname, bucketname, context): message = f"deleteStorageTriggerForWorkflow Bucket: {bucketname}, workflowname: {workflowname}" ret = context.deleteStorageTriggerForWorkflow...
Python
1
&[ Semitones(0), Semitones(2), Semitones(3), Semitones(5), Semitones(7), Semitones(8), Semitones(10), Semitones(12), ]; // MINOR-ISH pub const LOCRIAN_INTERVALS: &[Semitones] = &[ Semitones(0), Semitones(1), Semitones(3), Semitones(5), Semitones(6), Semitones(8)...
Rust
0
, comment_id); let req = GitHubRequest { uri: request_uri, body: Some(PatchGistsUpdateComment::from_json(body)?), method: "PATCH", headers: vec![] }; let request = GitHubRequestBuilder::build(req, self.auth)?; // -- let github_...
Rust
0
#!/usr/bin/env python # Copyright Jim Bosch & Ankit Daftery 2010-2012. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import unittest import numpy import indexing_ext class TestIndexing(unittest.Test...
Python
1
import tkinter as tk from openai import OpenAI import os # 环境变量中获取 API 密钥 openai_api_key = os.environ.get("OPENAI_API_KEY") if not openai_api_key: raise ValueError("未在环境变量中找到 API 密钥,请设置 OPENAI_API_KEY。") # 创建 OpenAI 客户端 client = OpenAI( api_key=openai_api_key, base_url="https://api.chatanywhere.tech/v1" ...
Python
1
ption_type=DisruptionType.GEOPOLITICAL, epicenter_nodes=["SHANGHAI_PORT", "SINGAPORE_PORT"], initial_impact=70, duration_days=60, propagation_model=PropagationModel.SIGMOID, propagation_speed=0.5, recovery_rate=0.2 ), Scenario( ...
Python
1
) } fn load_tif(&self) -> Result<Surface, String> { let raw = unsafe { ffi::IMG_LoadTIF_RW(self.raw()) }; to_surface_result(raw) } fn load_png(&self) -> Result<Surface, String> { let raw = unsafe { ffi::IMG_LoadPNG_RW(self.raw()) }; to_surface_result(raw) } fn loa...
Rust
0
def get_package_version(): with open(Path(this_dir) / PACKAGE_NAME / '__init__.py', 'r') as f: version_match = re.search('^__version__\\s*=\\s*(.*)$', f.read(), re.MULTILINE) public_version = ast.literal_eval(version_match.group(1)) local_version = os.environ.get('MAMBA_LOCAL_VERSION') ...
Python
1
import heapq def dijkstra(graph, start, goalNode): distances = {node: float('inf') for node in graph} distances[start] = 0 visited = set() priority_queue = [(0, start)] while priority_queue: current_distance, current_node = heapq.heappop(priority_queue) if current_node in visited:...
Python
1
import sys import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from robot.mode import ControllMode from smbus import SMBus arduino = 0x8 i2cbus = SMBus(1) # 前に進むときの両輪に流すパワー (0〜255) front_power = 125 right_power = 0 left_power = 0 # ジョイスティックの値をパワーの増減に変換する倍率 # 完全に倒した (1 or -1)の時に...
Python
1
_canvas) # Call the draw function output_text = sendToAI(model, canvas_combine, fingers) # Send the drawing to the AI model # Combine the original image with the drawing canvas and display it canvas_combine = cv2.addWeighted(img, 0.75, draw_canvas, 0.40, 1) FRAME_WINDOW.image(imag...
Python
1
: E, } /// Static methods. impl<'e, E> Rkv<E> where E: BackendEnvironment<'e>, { pub fn environment_builder<B>() -> B where B: BackendEnvironmentBuilder<'e, Environment = E>, { B::new() } /// Return a new Rkv environment that supports up to `DEFAULT_MAX_DBS` open databases. ...
Rust
0
import os from dotenv import load_dotenv from pinecone import Pinecone # Load API key dari .env load_dotenv() pineconeApiKey = os.getenv("PINECONE_API_KEY") # Inisialisasi client pc = Pinecone(api_key=pineconeApiKey) # Nama index dan namespace index_name = "sicupang-rag-small" namespace = "recipes" # Connect ke ind...
Python
1
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from typing import Any, Mapping from airbyte_cdk.sources.streams.http.requests_native_auth import TokenAuthenticator class WebflowAuthMixin: """ Mixin class for providing additional HTTP header for specifying the "accept-version" """ def ...
Python
1
# -*- coding: utf-8 -*- # *********************************** # Author: Pedro Jorge De Los Santos # E-mail: delossantosmfq@gmail.com # License: MIT License # *********************************** import numpy as np from nusa import * import itertools import matplotlib.pyplot as plt def pairwise(iterable): #...
Python
1
vec\":[]}"; let f: Foo = json::from_str(j).unwrap(); // This fails, unless 'vec' is optional // let j = "{\"opt\":null,\"req\":0}"; // let f: Foo = json::from_str(j).unwrap(); #[derive(Default, Serialize, Deserialize)] struct Bar { #[serde(rename = "snooSnoo...
Rust
0
// appears to be pixels on my machine if mouse_grabbed { viewer.mouse_drag(delta); } } _ => (), }, _ => (), } }); if should_close { break; } ...
Rust
0
}) .collect(); let mut c = std::process::Command::new(&cmds[0]); c.args(&cmds[1..]); c } } <filename>gstreamer-rtsp/src/auto/rtsp_auth_param.rs // This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::translate::*; ...
Rust
0
<char>, std::allocator<char>>>>```</span>. #[repr(C)] pub struct SetBasicStringCCharCharTraitsCCharRefAllocatorCCharRefRefLessBasicStringCCharCharTraitsCCharRefAllocatorCCharRefRefRefAllocatorBasicStringCCharCharTraitsCCharRefAllocatorCCharRefRefRef { _buffer: [u8; 48], } impl ::NewUninitialized for SetBas...
Rust
0
shape[1:])) if net_output.shape == gt.shape: # if this is the case then gt is probably already a one hot encoding y_onehot = gt else: y_onehot = torch.zeros(net_output.shape, device=net_output.device) y_onehot.scatter_(1, gt.long(), 1) tp = net_outpu...
Python
1
whitespace, excluding 0x20 '\u{00a0}' | '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | // newline (excluding <= 0x20) '\u{0085}' | '\u{2028}' | '\u{2029}' )) .map_err(|e: Error<S>| e.with_expected_kind("letter")) } fn id_sans_sign_dig<S: S...
Rust
0
from typing import List from bisect import bisect_left, bisect_right class Solution: def isArraySpecial(self, nums: List[int], queries: List[List[int]]) -> List[bool]: # Determine if the first element is even or odd is_even = nums[0] % 2 == 0 consecutive_errors = [] # Identify indi...
Python
1
_file.write("\nid:{}\n{}\n".format(sent_id, sentence)) print("\nid:{}\n{}".format(sent_id, sentence)) sub_sentences = split_sentence(sentence) for split_id, sub_sentence in enumerate(sub_sentences): sub_count += 1 phone_pairs = trans.get_phone_pairs( sub_sentence, change_eng...
Python
1
ages. Args: kpts0, kpts1: corresponding keypoints of size (N, 2). colour: color of each match, string or RGB tuple. Random if not given. lw: width of the lines. ps: size of the end points (no endpoint if ps=0) indices: indices of the images to draw the matches on. a: ...
Python
1
.GetDataTypeByName def GetColorInterpretationName(*args): """GetColorInterpretationName(GDALColorInterp eColorInterp) -> char""" return _gdal.GetColorInterpretationName(*args) GetColorInterpretationName = _gdal.GetColorInterpretationName def GetPaletteInterpretationName(*args): """GetPaletteInterpretationName(G...
Python
1
)) c = boto.connect_s3(access_key, secret_key) b = c.get_bucket(bucket, validate=False) k = b.new_key(key) try: k.set_contents_from_string(data, policy='public-read', reduced_redundancy=True) return True except (bo...
Python
1
import os from moviepy import ImageClip, CompositeVideoClip, concatenate_videoclips, AudioFileClip, TextClip, concatenate_audioclips,CompositeAudioClip,afx import uuid from config import get_user_data_dir # 加载json数据(这里直接用字典代替) def trans_video_tax_news_introduction(data:dict)->str: project_id=str(uuid.uuid1()) ...
Python
1
self.noise_level == 3: r = torch.zeros_like(r) r[:, :, :, 0, 0] = 1.0 r[:, :, :, 1, 1] = 1.0 r[:, :, :, 2, 2] = 1.0 ori_synth = torch.matmul(ori_synth, r) marker_normals = ori_synth[..., 2] # Order is already correct since we load...
Python
1
use std::fmt; use std::str::FromStr; use crate::utils::intcode::CPU; #[allow(dead_code)] fn diagnostic_code<T>(input: &str, system_id: T) -> T where T: PrimInt + Signed + FromStr + fmt::Display, { CPU::from_source(input).outputs_with(|| system_id).last().unwrap() } #[cfg(test)] mod tests { use super::*;...
Rust
0
"created_at", ) ) valid, ret_val = await fields_are_valid(required_fields, user_info) if not valid: return ret_val # otherwise, create a new user user_id = f"user-{uuid.uuid4().hex}" # append our fields to what is returned by GitHub ...
Python
1
r, &header_checker, ); assert_error_eq!( result.unwrap_err(), OutPointError::InvalidHeader(invalid_block_hash), ); } #[test] fn resolve_transaction_should_reject_incorrect_order_txs() { let out_point = OutPoint::new(h256!("0x2").pack(), 3); let tx1 = TransactionBuilder::de...
Rust
0
import pygame from Constants import config class Mouse(): """ Represents the mouse input and its interaction with the grid in the game. """ def __init__(self): """ Initializes the Mouse object with default values. Sets map_grid_x and map_grid_y to None, representing no ...
Python
1
main() { // rerun if wrapper header is changed println!("cargo:rerun-if-changed=src/wrapper.h"); println!("cargo:rerun-if-changed=src/wrapper.c"); println!("cargo:rerun-if-changed=allowed_bindings.rs"); let out_dir = env::var_os("OUT_DIR").expect("Failed to get OUT_DIR"); let out_path = PathBu...
Rust
0
aryExpr::parse(s)?; Ok(( s, Unary { op, expr: Box::new(expr), }, )) } } #[derive(Debug, PartialEq)] pub enum UnaryExpr<'a> { PrimaryExpr(PrimaryExpr<'a>), Unary(Unary<'a>), } impl<'a> ASTable<'a> for UnaryExpr<'a> { //...
Rust
0
>::new(1.2)); println!( "KatalPerCubicMetre: {}.", Measure::<f64, KatalPerCubicMetre>::new(1.2) ); println!("JoulePerMole: {}.", Measure::<f64, JoulePerMole>::new(1.2)); println!( "MolePerCubicMetre: {}.", Measure::<f64, MolePerCubicMetre>::new(1.2) ); println!( ...
Rust
0
let id_offset = offset_for_column(&cols, product["id"].id); col_id.mut_val().encode_i64(id_offset).unwrap(); // "3x" will be truncated. let mut value = Expr::default(); value .mut_field_type() .as_mut_accessor() ...
Rust
0
le data frames. """ df1 = pd.DataFrame({ 'ParentID': ['P1', None], 'ParentName': ['Entity A Inc.', 'Entity B LLC'] }) selected_fields1 = {'parent_id': 'ParentID', 'parent_name': 'ParentName'} df2 = pd.DataFrame({ 'ParentName': ['Entity C Corp....
Python
1
, # and we no longer need to call load_checkpoint_in_model() if load_checkpoint_in_model and backend not in [BACKEND.MARLIN, BACKEND.MARLIN_FP16, BACKEND.BITBLAS]: load_checkpoint_in_model_then_tie_weights( model, dtype=torch_dtype, # This is v...
Python
1
) ) pool5 = self.pool(conv5_3) fc6 = self.dropout( self.relu( self.fc6(pool5) ) ) fc7 = self.dropout( self.relu( self.fc7(fc6) ) ) # SEMANTIC SEGMENTATION PART # first scores = self.scoring_layer( fc7 ) upscore2 = self.upscore2(scores) ...
Python
1
ad=arad, origin=origin, rgcoeff=1.2, slivercut=0.5)) if imgo is None: print("Discarding narrow image") continue imgo_arr = np.asanyarray(imgo) assert imgo_arr.sum() > 0, ("Sum of imgo is zero! There likely was " "an error in projecti...
Python
1
_json::from_value(file_value) .expect("Config file in the wrong format"); Some(config_file) } else { None } } pub fn save_config(&self) { let path = config_path(); let file = File::create(path) .expect("Unable to create confi...
Rust
0
""" Evaluate an end-to-end compression model on an image dataset. """ import time import torch.nn.functional as F import torch import torch.nn as nn torch.backends.cudnn.deterministic = True torch.set_num_threads(1) @torch.no_grad() def inference(model, x, patch): x = x.unsqueeze(0) h, w = x.size(2), x...
Python
1
); } extern "C" { pub fn UploadMesh(mesh: *mut Mesh, dynamic: bool); } extern "C" { pub fn UpdateMeshBuffer( mesh: Mesh, index: ::std::os::raw::c_int, data: *mut ::std::os::raw::c_void, dataSize: ::std::os::raw::c_int, offset: ::std::os::raw::c_int, ); } extern "C" { ...
Rust
0
return True else: self.log(f"❌ 碰牌失败: {result['message']}") return False else: self.log(f"❌ 碰牌请求失败: {response.text}") return False else: # 其他玩家碰牌:...
Python
1
#!/usr/bin/env python import rospy from geometry_msgs.msg import * from mavros_msgs.srv import CommandBool, CommandBoolRequest from mavros_msgs.srv import SetMode, SetModeRequest from mavros_msgs.msg import State def state_cb(msg): global current_state current_state = msg if __name__=="__main__": current_state = ...
Python
1
ot': future_signal_dict[strategy_name] = data # strategy_name -> data # write your logic code here. if __name__ == '__main__': future_signal_dict = {} spot_signal_dict = {} future_strategy_order_dict = {} cancel_orders_timer = 0 # 撤单的timer. query_orders_timer = 0 # 查询订单的tismer...
Python
1
from unittest.mock import patch, MagicMock import csle_common.constants.constants as constants from csle_common.dao.emulation_config.vulnerability_type import VulnType from csle_common.controllers.vulnerabilities_controller import VulnerabilitiesController class TestVulnControllerSuite: """ Test Vulnerabiliti...
Python
1
@Cog.listener("on_reaction_clear_emoji") async def on_reaction_clear_emoji_updater(self, reaction: discord.Reaction) -> None: if reaction.message.id in self.bot.message_cache: self.bot.message_cache[reaction.message.id] = reaction.message @commands.group(name="message", aliases=["msg"], inv...
Python
1
result = _raw_keccak_lib.keccak_absorb(self._state.get(), c_uint8_ptr(data), c_size_t(len(data))) if result: raise ValueError("Error %d while updating %s state" % (result, sel...
Python
1
FileMap<'s>, func_records: BreakpadFuncRecords<'s>, } impl<'s> BreakpadFunctionIterator<'s> { fn convert(&self, record: BreakpadFuncRecord<'s>) -> Result<Function<'s>, BreakpadError> { let mut lines = Vec::new(); for line in record.lines() { let line = line?; let filenam...
Rust
0
ECDSA_P256_SHA256_FIXED_SIGNING, secret_key.as_ref(), )?)) } } impl GeneratePkcs8 for P256Signer<nistp256::Asn1Signature> { /// Randomly generate a P-256 **PKCS#8** keypair fn generate_pkcs8() -> Result<pkcs8::SecretKey, Error> { let keypair = EcdsaKeyPair::generate_...
Rust
0
K线 2 30分钟K线 3 1小时K线 4 日K线 5 周K线 6 月K线 // 7 1分钟 // 8 1分钟K线 9 日K线 // 10 季K线 // 11 年K线 // market -> 市场代码 0:深圳,1:上海 // stockcode -> 证券代码; // start -> 指定的范围开始位置; // count -> 用户要请求的 K 线数目,最大值为 800 // // 如: 9,0,000001,0,100''', get_security_bars, '9,0,000001,0,100']), /// 查询股票日线。对应于 pytdx 中的 hq.get_securi...
Rust
0
plane.plane_idx), ); return false; } Some(e) => e, }; if let Ok(size) = ::nix::unistd::lseek(plane.fd, 0, ::nix::unistd::Whence::SeekEnd) { // reset the seek point let _ = ::nix::unistd::lseek(plane.fd, 0, ::nix::unistd::Whe...
Rust
0
pub const MOD8: usize = 5; //pub const BASEBITS: usize = 29; //pub const AES_S: usize=0; // GOLDILOCKS //pub const MODBITS usize=448; //pub const MOD8 usize=7; //pub const BASEBITS usize=29; //pub const AES_S: usize= 0; // BN254 Curve //pub const MODBITS:usize = 254; /* Number of bits in Modulus */ //pub const MOD8:...
Rust
0
prompt_mask_img = prompt_mask_res.reshape(h, w, 1) * color.reshape(1, 1, -1) prompt_mask_res = self.prompt_res_g * 0.5 + prompt_mask_img * 0.5 h, w = tar1_mask_res.shape[-2:] tar1_mask_img = tar1_mask_res.reshape(h, w, 1) * color.reshape(1, 1, -1) tar1_mask_res = self.t...
Python
1
} } fn extract_result_ty(ty: &syn::Type) -> BindgenResult<Option<syn::Type>> { match ty { syn::Type::Path(syn::TypePath { qself: None, path }) if path.segments.len() == 1 => { let segment = path.segments.first().unwrap(); if segment.ident != "Result" { Ok(None) } else { match...
Rust
0
* 1_000 / COIN } bitcoind.generate_blocks_censor(1, unvaults) wait_for(lambda: cpfp_txid not in bitcoind.rpc.getrawmempool()) wait_for(lambda: len(bitcoind.rpc.getrawmempool()) == len(unvaults) + 1) new_cpfp_txid = next( txid for txid in bitcoind.rpc.getrawmempool() if txid not in unvaults ...
Python
1
_to_token(b"EB"), /// TODO. EC = Self::letters_to_token(b"EC"), /// TODO. ED = Self::letters_to_token(b"ED"), /// TODO. EE = Self::letters_to_token(b"EE"), /// Unassigned for use by World Intellectual Property Organisation Standard ST.3. /// /// Union of Countries under the European Community Patent Co...
Rust
0
#!/usr/bin/env python """ ZetCode wxPython tutorial In this example, we create two horizontal toolbars. author: Jan Bodnar website: www.zetcode.com last modified: July 2020 """ import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) ...
Python
1
Point, pub t_a: f64, pub t_b: f64, pub a_seg_index: i32, pub b_seg_index: i32, // TODO: remove the `quality` field pub quality: f64, } impl Intersect { pub fn new(point: Point, t_a: f64, t_b: f64, a_seg_index: i32, b_seg_index: i32) -> Self { Intersect { point, t_a, t_b, a_seg_index, b_seg_ind...
Rust
0
import os import jsonpickle from settings import PROJECT_ROOT from utils.config_util import get_config json_file = os.path.join(PROJECT_ROOT, "config/url_constants.json") with open(json_file) as jfile: jsonList = jsonpickle.decode(jfile.read()) def get_urls(endpoint): """ Get needed urls for service us...
Python
1
roj > a_max_proj || b_max_proj < a_min_proj { return Relation::Out; } // If B is not inside A wrt that axis, the only choice is between Cross and Out. if a_min_proj > b_min_proj || b_max_proj > a_max_proj { rel = Relation::Cross; } } rel } fn project_on_a...
Rust
0
sub_video_dir = os.path.join(sub_video_root, camera_id) os.makedirs(sub_video_dir, exist_ok=True) # mp42img(video_path, img_dir, num_frame, res_prefix = camera_id + '_') args = (video_path, sub_video_dir, num_frame, original_num_frame, cnt2frame_id...
Python
1
i8); } } /// Executes a closure. The first parameter is the Zval with the closure. The second parameter /// is an array containing the parameters. It returns the closure return. /// /// This method does not checks if the closure is an actually closure. If you pass a Zval that is /// not a closure PHP may throw an...
Rust
0
elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.reinitialiser() jeu_termine = False elif event.key == pygame.K_ESCAPE or event.key == pygame.K_F11: en_co...
Python
1
else: raise ValueError('Missing required ConfigProperty {}'.format(attr_name)) def reload(self): """Reload all ConfigProperty values (reading from loader sources again, if applicable)""" for loader in self._loaders: loader.reload() self.varz = {} # re...
Python
1
class Solution: def GCDString(self, str1:str, str2:str) -> str: len1, len2 = len(str1), len(str2) def isDivisor(l): if len1 % l or len2 % l: return False f1, f2 = len1 // l, len2 // l return str1[:l] *f1 == str1 and str2[:l] *f2 == str2 for l in range(min(len1, len2), 0, -1): if isDivisor(l): ...
Python
1
# SPDX-License-Identifier: GPL-2.0 "Adjust a damon monitoring result with new attributes" import _damo_records def main(args): file_path = args.input output_permission, err = _damo_records.parse_file_permission_str( args.output_permission) if err != None: print('wrong --output_permis...
Python
1
in.0, key, )))) } } impl rustls::server::ResolvesServerCert for AlwaysResolvesChain { fn resolve( &self, _client_hello: rustls::server::ClientHello, ) -> Option<Arc<rustls::sign::CertifiedKey>> { Some(Arc::clone(&self.0)) } } pub mod futures; pub use self::futures::spawn...
Rust
0
import pytest import goo import bpy @pytest.fixture def setup_blender(): bpy.ops.wm.read_factory_settings(use_empty=True) # Reset to empty scene cellsA = goo.CellType("A") cellsA.homo_adhesion_strength = 100 cell = cellsA.create_cell( "A1", (0, 0, 0), color=(0.5, 0, 0), size=2, target_volume=...
Python
1
{ if (*seat).pointer_state.button_count != 1i32 as libc::c_ulong || (*seat).pointer_state.grab_serial != serial { _wlr_log(WLR_DEBUG, b"[%s:%d] Pointer grab serial validation failed: button_count=%zu grab_serial=%u (got %u)\x00" as *const u8 as *const libc::...
Rust
0
# ============================================================================== # Binaries and/or source for the following packages or projects # are presented under one or more of the following open source licenses: # io.py The OpenLane-V2 Dataset Authors Apache License, Version 2.0 # # Contact wanghuijie@pjla...
Python
1
a dN)@sddlZddlZddlmZddlTddlmZddlZGdddejZ edGdd d e Z Gd d d ejZ e d kre dS) N)support)*) need_symbolc@seZdZeZddZddZddZddZd d Z d d Z d dZ ddZ ddZ ddZddZd...
Python
1
#!/usr/bin/env python3 """ CLI script to visualize the LangGraph workflow with multiple format options """ import sys import argparse def main(): parser = argparse.ArgumentParser(description="Visualize Policy Research Assistant LangGraph Workflow") parser.add_argument("--ascii", action="store_true", help="Sho...
Python
1
/// 200, /// 25, /// |seat, focus| { /// /* This closure is called whenever the keyboard focus /// * changes, with the new focus as argument */ /// } /// ) /// .expect("Failed to initialize the keyboard"); /// ``` pub...
Rust
0
8aa4au32, 0x5b9cca4fu32, 0x682e6ff3u32, 0x748f82eeu32, 0x78a5636fu32, 0x84c87814u32, 0x8cc70208u32, 0x90befffau32, 0xa4506cebu32, 0xbef9a3f7u32, 0xc67178f2u32, ]; } impl Schedule512 for SHA256Schedule { fn new(block: &[u8; 64]) -> ...
Rust
0
get_status() == "draw": deltas = [0.5, 0.5] elif game.get_status() == "win": deltas = [1, 0] else: raise ValueError("Game status error: backpropagation") for i, state in enumerate(reversed(game.get_state_history())): se...
Python
1