text
string
label_name
string
labels
int64
import jittor as jt from jittor import nn from easyvolcap.engine import REGRESSORS from easyvolcap.utils.base_utils import dotdict from easyvolcap.utils.chunk_utils import chunkify from easyvolcap.utils.net_utils import MLP, get_function @REGRESSORS.register_module() class ImageBasedRegressor(nn.Module): def __in...
Python
1
WindowId) { unsafe { SDL_MinimizeWindow(window_id.raw() as *mut SDL_Window); } } fn maximize_window(&mut self, window_id: WindowId) { unsafe { SDL_MaximizeWindow(window_id.raw() as *mut SDL_Window); } } fn get_window_size(&mut self, window_id: Wind...
Rust
0
import os from typing import Optional from .imagelist import ImageList from ._util import download as download_data, check_exits class OfficeHome(ImageList): """`OfficeHome <http://hemanthdv.org/OfficeHome-Dataset/>`_ Dataset. Args: root (str): Root directory of dataset task (str): The task (...
Python
1
import argparse import logging import sys import time import supervision as sv from pi_inference import VideoOutput, VideoSource from pi_inference import functions as f logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s: %(message)s") logger = logging.getLogger(__name__) def extract...
Python
1
Self::Output { self.symmetrical_difference(other.into()) } } impl <T : EnumSetType, O: Into<EnumSet<T>>> SubAssign<O> for EnumSet<T> { fn sub_assign(&mut self, rhs: O) { *self = *self - rhs; } } impl <T : EnumSetType, O: Into<EnumSet<T>>> BitAndAssign<O> for EnumSet<T> { fn bitand_assi...
Rust
0
linux32: "55 89 E5 57 56 53 83 EC 2C 8B 5D 08 8B 45 0C 89 83 ? ? ? ? 8B 03 89 1C 24 FF 90 ? ? ? ? 89 83 ? ? ? ? 8D 43 38 83 E0 0F C1 E8 02 F7 D8 83 E0 03", } sigs! { for: before_init, debug: "MakeLuaNULLEntity", module: "server_dll", win64_x86_64: "48 83 EC 48 48 8D 4C 24 ? E8 ? ? ? ? 48 8B 0D ? ? ? ? 33...
Rust
0
Ep)) I0 = (Is + Ip)[0, whereTheta, :][:, wherePsi] I0stack[ie, :, :] = I0 if ie in imageIndex: intensity_in_transverse_plane(ie, theta, psi, I0) phEs = np.angle(Es[0, whereTheta, :][:, wherePsi]) phEp = np.angle(Ep[0, whereTheta, :][:, wherePsi]) c...
Python
1
('k', |v: &mut TxnTableView, _| { v.on_event(cursive::event::Event::Key( cursive::event::Key::Up, )); None }) .on_event_inner('l', |v: &mut TxnTableView, _| { v.on_event(cursive::event::Event::Key( ...
Rust
0
# Copyright 2020 Alberto Soragna. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
Python
1
teConnection, BoxReadConnection, ConnectionFd), IoError> { let (mut _ws, wsstream) = WsMeta::connect(addr, None) .await .map_err(|e| IoError::new(std::io::ErrorKind::Other, e))?; let wsstream_clone = wsstream.clone(); Ok(( Box::new(wsst...
Rust
0
[test] fn should_write_impl_desc() { let markdown = render( ~"#[doc = \"desc\"] impl int { fn a() { } }"); assert!(str::contains(markdown, ~"desc")); } #[test] fn should_write_impl_method_header() { let markdown = render( ~"impl int { fn a() { } }"); ...
Rust
0
from pathlib import Path class ExperimentVersion: def __init__( self, base_path, naming_scheme_version, pred_model, image_ending, unc_ending, unc_types, aggregations, n_reference_segs, second_cycle_path=None, n_classes=2, ...
Python
1
[derive(ComWrapper, Clone)] #[com(send, sync, debug)] /// Represents an ellipse which can be used anywhere Geometry is needed pub struct EllipseGeometry { ptr: ComPtr<ID2D1EllipseGeometry>, } impl EllipseGeometry { #[inline] pub fn create<R>(factory: &Factory, ellipse: &math2d::Ellipse) -> D2DResult<Ellips...
Rust
0
""" Revision ID: 0321_drop_postage_constraints Revises: 0320_optimise_notifications Create Date: 2020-06-08 11:48:53.315768 """ import os from alembic import op revision = "0321_drop_postage_constraints" down_revision = "0320_optimise_notifications" environment = os.environ["NOTIFY_ENVIRONMENT"] def upgrade(): ...
Python
1
for cur in param: param[cur] = urllib.unquote_plus(param[cur]) return param params = get_params(sys.argv[2]) try: func = params['func'] del params['func'] except: func = None xbmc.log('[%s]: Primary input' % addon_id, 1) mainScreen(params) if func != None: try: pfunc = globals(...
Python
1
v2.copyMakeBorder(vis_map_img, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=(255, 255, 255)) return vis_map_img def remove_small_blobs(image: np.ndarray, min_area: int) -> np.ndarray: """移除图像中小于指定面积阈值的所有轮廓。 参数: image (np.ndarray): 输入图像(二值图像)。 min_area (int): 小于该阈值的轮廓将被移除。 返回: np...
Python
1
#!/usr/bin/python3 """ This script lists all states from the database `hbtn_0e_0_usa`. """ import MySQLdb from sys import argv if __name__ == '__main__': """ Access to the database and get the states from the database. """ db_connect = MySQLdb.connect( host="localhost", user=argv[1], port=...
Python
1
running_sum = 0.5 * self.array[y, x] count = 0.5 if x + 1 < self.width: running_sum += 0.4 * self.array[y, x + 1] count += 0.4 if y + 1 < self.height: running_sum += 0.1 * self.array[y + 1, x] ...
Python
1
lize, Deserialize, PartialEq, Eq)] pub struct SessionProvisionedNotification { /// Unique identifier of the provisioned session pub id: SessionIdentifier, /// Additional metadata, see [`ProvisionedSessionMetadata`] pub meta: ProvisionedSessionMetadata, } impl Notification for SessionProvisionedNotific...
Rust
0
e_title": { "type": "string" }, "critic": { "type": "string" }, "tone": { "type": "string", "enum": ["positive", "negative"] }, "rating": { ...
Python
1
s at the end of the stack. let capacity = markers.data.capacity(); loop { back += 1; if back == capacity { break; } if markers.data.get(back) != ::core::usize::MAX { break; } } markers.back = ba...
Rust
0
] fn build_check() { if !is_nightly() { return; } let foo = project("foo") .file("Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#) .file("src...
Rust
0
context.set_extra_http_headers({"Cache-Control": "max-age=3600"}) page = context.new_page() # 设置简中 民译 武器50级 好感20级 page.add_init_script(path="playwright/fxxkPlaywwright.js") page.goto("https://schaledb.com/student/%s" % name) page.wait_for_load_state() # # 关闭change-log窗口 # model =...
Python
1
th the two oldest commits. let mut commits: Vec<Commit> = commits.iter().cloned().collect(); commits.sort_by(|a: &Commit, b: &Commit| a.committer().timestamp.cmp(&b.committer().timestamp)); commits.reverse(); // Create a copy to pass to the listener let sources = commits.clone(); while commits...
Rust
0
STATIC_DRAW, ) } } /// Creates a new OpenGL VBO. pub fn new() -> Self { let mut ptr = unsafe { mem::uninitialized() }; unsafe { gl::GenBuffers(1, &mut ptr); } GLVBO { ptr } } } impl Drop for GLVBO { fn drop(&mut self) { unsa...
Rust
0
'{}/best_PNN_model_{}.pth.tar'.format(model_save_dir,epoch)) torch.save(dict(model=model, model_state=model.state_dict(), loss1=v_loss1, train_params=PNN_model), '../pretrained_models/'...
Python
1
# SPDX-FileCopyrightText: Red Hat, Inc. # SPDX-License-Identifier: GPL-2.0-or-later from __future__ import absolute_import from __future__ import division import os import pytest from vdsm.common import cmdutils from vdsm.common import commands from vdsm.common.units import MiB @pytest.mark.skipif( "OVIRT_CI" ...
Python
1
fn default() -> Self { unsafe { std::mem::MaybeUninit::zeroed().assume_init() } } } /// The `PIXMAP` type. pub type xcb_pixmap_t = u32; /// An iterator over `PIXMAP` objects. #[derive(Copy, Clone, Debug)] #[repr(C)] pub struct xcb_pixmap_iterator_t { /// The value of the current iteration. pu...
Rust
0
enna 3 is *not* deployed pub ant_3_not_deployed: bool, /// Whether antenna 3's deployment time limit was reached before achieving full deployment pub ant_3_stopped_time: bool, /// Whether antenna 3's deployment system is currently active pub ant_3_active: bool, /// Whether antenna 4 is *not* dep...
Rust
0
from lc import * # https://leetcode.com/problems/two-sum/ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: seen = {} for i,x in enumerate(nums): if target - x in seen: return seen [target - x], i seen[x] = i return False ...
Python
1
assert bus.rdata == 1 yield bus.receive(WE_FCW_ADDR) assert bus.rdata == 100 s.start_receive() yield bus.delay(1) yield bus.transmit(WR_STATUS_ADDR, WRS_RXEN) yield bus.receive(WR_STATUS_ADDR) assert bus.rdata & WRS_RXEN y...
Python
1
Outlet, OutletHolder, Property, SettingsList, }; use crate::widget::cocoa::Cocoa; use crate::widget::WindowOutlet; use crate::PlatingResult; #[derive(Debug, Default, Clone, Hash)] pub struct CocoaWindowOutlet<CHILDREN, MENU> where CHILDREN: ChildrenList, MENU: ChildrenList, { pub children: CHIL...
Rust
0
, writer: aws_smithy_xml::encode::ElWriter, ) -> Result<(), aws_smithy_http::operation::SerializationError> { #[allow(unused_mut)] let mut scope = writer.finish(); if let Some(var_243) = &input.status { let mut inner_writer = scope.start_el("Status").finish(); inner_writer.data(var_243.a...
Rust
0
} } pub fn set_area(&self, rect: Option<&gdk::Rectangle>) { unsafe { gtk_sys::gtk_gesture_multi_press_set_area(self.to_glib_none().0, rect.to_glib_none().0); } } pub fn connect_pressed<F: Fn(&GestureMultiPress, i32, f64, f64) + 'static>( &self, f: F, ...
Rust
0
zf(utra::com::EV_ENABLE_ENABLE, bar); baz |= com_csr.ms(utra::com::EV_ENABLE_ENABLE, 1); com_csr.wfo(utra::com::EV_ENABLE_ENABLE, baz); let mut i2c_csr = CSR::new(HW_I2C_BASE as *mut u32); let foo = i2c_csr.r(utra::i2c::PRESCALE); i2c_csr.wo(utra::i2c::PRESCALE, foo); le...
Rust
0
#[cfg(any(feature = "feature_gtk4", feature = "feature_gtk3"))] use std::sync::Arc; // This is needed for docs so that we include glib only once #[cfg(all(feature = "feature_gtk4", not(feature = "feature_gtk3")))] use gtk4::glib::{self, clone}; #[cfg(feature = "feature_gtk4")] use gtk4::prelude::*; #[cfg(feature = "f...
Rust
0
from policyengine_us.model_api import * class ky_pension_income_exclusion(Variable): value_type = float entity = Person label = "KY Pension Income Exclusion" definition_period = YEAR defined_for = StateCode.KY def formula(person, period, parameters): # Get the KY pension income exclus...
Python
1
# Coding Exercise No.14 # Concatenate def concatenate(str1, str2): return str1 + str2 print("Welcome to the Word Concatenator!\n") # Get input from the user word1 = input("Enter the first word: ") word2 = input("Enter the second word: ") # Call the function and display result result = concatenate(word1, word2) ...
Python
1
from load import load_ad_impressions, load_click_conversions, load_rtb_auctions from transformation import transform_ad_impressions, transform_click_conversions, transform_rtb_auctions from extraction import extract_ad_impressons, extract_click_conversions, extract_rtb_auctions json_filename = 'ad_impressions.json' cs...
Python
1
crosses zero. Leg 1: Buy {qty1}. Pending Leg 2: Buy {qty2}.") await self._execute_trade(qty1, OrderSide.BUY) else: # Standard trade that doesn't cross zero. No splitting is required. await self._execute_trade(quantity, side) # Acknowle...
Python
1
from fastapi import APIRouter, BackgroundTasks, Body, Depends, HTTPException from sqlmodel import Session from turbo.db import psql_db from turbo.services.google import google_api_service from turbo.types import PubsubMessage, SubscriberHistoryResponse, SubscriptionName router = APIRouter(tags=["subscriber"]) SUBSCR...
Python
1
mount = mounts.get("dataset") if training_mount != None: for info in training_mount: self.add_pod_training_home_src(workspace_name=workspace_name, training_name=info["name"], destination=info["destination"]) ...
Python
1
、弾く場合は、False それ以外ならTrueで """ res = [] for mx, my in moves: nx, ny = x + mx, y + my if not coordinate_check(nx, ny, H, W): continue for f in check_funcs: if not f(nx, ny): break else: res.append((nx, ny)) return res ...
Python
1
from PySide6.QtCore import Qt from PySide6.QtGui import QAction, QIcon from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QMenu class VentanaPrincipal(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('Menu Contextual') # Mostramos y conectamos el menu ...
Python
1
from app.backend.db import Base from sqlalchemy import Column, Integer, String, Boolean class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) first_name = Column(String) last_name = Column(String) username = Column(String, unique=True) email = Column(Str...
Python
1
, initial_balance)) .collect::<Vec<_>>(), } .assimilate_storage(&mut t) .unwrap(); orml_tokens::GenesisConfig::<Runtime> { balances: self .endowed_accounts .into_iter() .filter(|(_, currency_id, _)| *currency_id != MNT) .collect::<Vec<_>>(), } .assimilate_storage(&mut t) .unwrap();...
Rust
0
() .write_all("name = \"Блогг\"\n\ \n\ [machine_data]\n\ JSON = \"\"\n" .as_bytes()) .unwrap(); File::create(root.join("header.html")).unwrap(); File::create(root.join("footer.htm")).unwrap(); assert_eq!(BlogueDescripto...
Rust
0
where T: Real, { let end_sweep = normalize_radians(end_angle - start_angle); let mid_sweep = normalize_radians(test_angle - start_angle); mid_sweep < end_sweep + epsilon } /// Same as [angle_is_between_eps] using default epsilon. /// /// Default epsilon is [fuzzy_epsilon](crate::core::traits::FuzzyEq:...
Rust
0
/// `Femtojoule`: FemtoJ, "FemtoJ", /// `Femtometre`: FemtoM, "FemtoM", /// `Femtomoles per kilogram`: FemtoMOL_PER_KiloGM, "FemtoMOL-PER-KiloGM", /// `Femtomoles per litre`: FemtoMOL_PER_L, "FemtoMOL-PER-L", /// `Fiji Dollar`: FijiDollar, "FijiDollar", /// `Flight`: F...
Rust
0
""" dirty fix of raw quad paragraphs are lists directly containing the paragraph data instead of dict with title, paragraph keys """ from src.qa.quad import QUAD from src.tar.translate import Translator raw_broken = QUAD.Raw.TRAIN raw_fixed = QUAD() squad1 = QUAD.Squad1.TRAIN raw_iterator = iter(raw_broken.data._data...
Python
1
#!/usr/bin/env python3 # The MIT License (MIT) # Copyright (c) 2018 - Universidad del Cauca, Juan Ruiz-Rosero # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including...
Python
1
kup.add(button_contact) bot.send_message(call.message.chat.id, "Пожалуйста, подтвердите свою личность, отправив свой контакт.", reply_markup=markup) @bot.message_handler(content_types=['text']) def text_handler(message): if message.chat.id not in verified_users: ...
Python
1
"""Delete all intermediate files. Called by _png_kmz_checker decorator at end of function calls.""" int_files = [*self.intermediate_rasters.values(), os.path.join(self.cache_dir, f"tmp_3857{self.ext}"), os.path.join(self.cache_dir, f"{self.dem_name}_cmap.txt")] ...
Python
1
let tx = runtime.validate_tx(&bytes).unwrap(); let receipt = runtime.exec_tx(&tx, &state, maybe_gas); assert!(receipt.success); let bytes = receipt.returndata.unwrap(); let mut returndata = ReturnData::new(&bytes); let addr: sdk::Address = returndata.next_1(); assert_eq!(addr.as_slice(), &[0x...
Rust
0
x01) != 0) } #[doc = "Bit 2 - SoF expected or not in RX frames"] #[inline(always)] pub fn sof(&self) -> SOF_R { SOF_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 4 - CRC mode for incoming frames"] #[inline(always)] pub fn crcmoderx(&self) -> CRCMODERX_R { CRCMODER...
Rust
0
rsistent_data: &PersistentData, ) -> Result<(), Error> { let data_str = serde_json::to_string(&persistent_data).map_err(|e| format_err!("{}", e))?; stash_node.write_str(POLICY_DATA_KEY, data_str) } /// Load all saved network configs from stash. Will create HashMap of network configs by SSID...
Rust
0
""" Custom fields used by the marshmallow schema """ from collections.abc import Mapping from marshmallow import fields, ValidationError, Schema, pre_load, post_dump, pre_dump from mhdata.util import group_fields, ungroup_fields from mhdata import cfg def choice_check(*items): def validate_fn(check): if ...
Python
1
, #[cfg(feature = "imxrt1010")] 0xF, ); const LPSPI_SEL: Field = Field::new(4, 3); const CBCMR: Register = unsafe { Register::new(LPSPI_PODF, LPSPI_SEL, 0x400F_C018 as *mut u32) }; /// Configure the SPI clock root /// /// Configure will **not** disable peripheral clock gates. You should disable /// clock gates...
Rust
0
ay_source: DisplaySource", racetime_id, racetime_display_name, discord_id AS "discord_id: Id", discord_display_name FROM users WHERE discord_id = $1"#, discord_id as i64).fetch_optional(pool).await } pub(crate) fn display_name(&self) -> &str { mat...
Rust
0
import re from django import template from django.conf import settings from django.utils.html import escape from django.utils.hashcompat import md5_constructor register = template.Library() DEFAULT_GRAVATAR_IMAGE = '%score/img/avatar.png' % settings.MEDIA_URL GRAVATAR_RATING = 'r' PULLQUOTE_RE = re.compile(r'<bloc...
Python
1
Associates, Inc. and # # Pearson Education, Inc. All Rights Reserved. # # # # DISCLAIMER: The authors and publisher of this book have used their # # best efforts in preparing the book. These efforts i...
Python
1
) -> Result<()> where P1: AsRef<Path>, P2: AsRef<Path>, P3: AsRef<Path>, P4: AsRef<Path> { println!("{}", Yellow.bold().paint(format!("» Installing {}", path.as_ref().display()))); let mut archive ...
Rust
0
from opencompass.multimodal.models.minigpt_4 import ( MiniGPT4COCOCaotionPromptConstructor, MiniGPT4COCOCaptionPostProcessor, ) # dataloader settings val_pipeline = [ dict(type='mmpretrain.LoadImageFromFile'), dict(type='mmpretrain.ToPIL', to_rgb=True), dict(type='mmpretrain.torchvision/Resize', ...
Python
1
_roles): self.call_fut(context, [('Allow', 'Admin', 'view')], registry) set_acl_with_roles.assert_called_with(context, [('Allow', 'Admin', 'view')], registry) @mark.parametrize('acl', [([('Allow',), 'Admin',...
Python
1
schema( Origin::signed(account_key(TEST_SENDER)), existing_schema, account_key(TEST_ORGANIZATION), hash.clone(), None ), Error::<Test>::SchemaIdExists ); }) } #[test] fn create_schema_with_too_many_props...
Rust
0
Error::InvalidResult), } } pub fn cache(&mut self) -> crate::dns::DnsMap { self.dns_cache.map() } #[cfg(test)] fn dns_resolve(&mut self, host: &str) -> Option<String> { // FIXME: when something goes wrong here we need to clean up the stack! let result = { ...
Rust
0
(&mut self, key: ChunkKey<N>, chunk: Ch) -> Option<Ch> { self.insert(key, chunk) } #[inline] fn write(&mut self, key: ChunkKey<N>, chunk: Ch) { self.insert(key, chunk); } #[inline] fn delete(&mut self, key: ChunkKey<N>) { self.remove(&key); } #[inline] fn p...
Rust
0
inline] pub fn insert(self, value: V) -> &'a mut V { self.map.entries.insert_vacant(self.key, value) } /// Call the specified closure to compute a value to insert, /// then proceed by calling [VacantEntry::insert] #[inline] pub fn or_insert_with<F>(self, func: F) -> &'a mut V where F: Fn...
Rust
0
_BIT = 1<<2, MUTABLE_FORMAT_BIT = 1<<3, CUBE_COMPATIBLE_BIT = 1<<4, // feature: VK_KHX_device_group #[cfg(feature = "VK_KHX_device_group")] BIND_SFR_BIT_KHX = 1<<6, // feature: VK_KHR_maintenance1 #[cfg(feature = "VK_KHR_maintenance1")] BIT_2D_ARRAY_COMPATIBLE_BIT_KHR = 1<<5, // f...
Rust
0
""" COSMOS-HGP 신규 고급 기능 (4대 기능) - 자가 디버깅 - CSV 분석 - 웹로그 분석 - 도메인 컨설팅 """ import numpy as np import pandas as pd from io import StringIO from typing import Dict, List, Any from datetime import datetime # =============================== # 1. 자가 디버깅 # =============================== def run_selftest() -> Dict[str, An...
Python
1
cb: &block::CompactBlock) -> Vec<Transaction> { debug!( LOGGER, "pool: retrieve_transactions: kern_ids - {:?}, txs - {}, {:?}", cb.kern_ids, self.transactions.len(), self.transactions.keys(), ); let mut txs = vec![]; for tx in self.transactions.values() { for kernel in &tx.kernels { // ...
Rust
0
import jaynes from params_proto.hyper import Sweep from main_street.config import RunArgs machines = [ # dict(ip="visiongpu55", gpu_id=0), # dict(ip="visiongpu55", gpu_id=1), # dict(ip="visiongpu55", gpu_id=2), # dict(ip="visiongpu55", gpu_id=3), # dict(ip="vision42", gpu_id=2), # dict(ip="vis...
Python
1
""" Plugin for ResolveURL Copyright (C) 2016 script.module.resolveurl 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...
Python
1
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from src.books.domain.repositories.BookABS import BookRepository from src.books.domain.entities.Books import Book as BookEntity from src.books.adapters.models.Bookmodel import Book as BookSQL from typing import Optional, List from src.books.a...
Python
1
s = model.predict(X_test) # Compare predictions with actual values for i in range(5): # Print first 5 predictions print(f"Predicted: {predictions[i][0]}, Actual: {y_test[i]}") df = read_and_preprocess() train_model(df) # # import model # import tensorflow as tf # from tensorflow.keras.m...
Python
1
, Default)] pub struct CronControl { pub pre_commit_num: u64, } #[allow(dead_code)] impl CronControl { pub fn require_cron_inactive(&self, h: &ActorHarness, rt: &MockRuntime) { let st = h.get_state(&rt); assert!(!st.deadline_cron_active); // No cron running now assert!(!st.continue_dead...
Rust
0
return Self { Direct: mask & Flags::O_DIRECT as u32 != 0, NonBlocking: mask & Flags::O_NONBLOCK as u32 != 0, Sync: mask & Flags::O_SYNC as u32 != 0, Append: mask & Flags::O_APPEND as u32 != 0, Read: accmode == Flags::O_RDONLY as u32 || accmode == Fla...
Rust
0
drop_all_items(&mut machine); let mut prev_pos = pos; loop { let output = machine.read_string(); if output.contains("ejected back") { pos = prev_pos; } // Update grid update_grid(&output, &mut grid, pos.clone()); // Print the map println!("=...
Rust
0
return running_count, item /// ... else: /// ... return running_count, None /// >>> def remove_none_and_key(key_item): /// ... key, item = key_item /// ... if item is None: /// ... return [] /// ... else: /// ... return [item] /// >>> flow = D...
Rust
0
# Copyright 2020 The KNIX Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
Python
1
sibling representation, /// augmented by last child/previous sibling links. In other words, the children of tree node are /// maintained in doubly linked list, where the head and tail of the list are the first and last /// child values of the children's parent node. /// /// Therefore, no allocations and re-allocations ...
Rust
0
fn remove(&mut self, e: Entity) { debug_assert_eq!(self.inner.data.len(), self.inner.entities.len()); if self.contains(e) { let removed_index = self.entity_idx_to_data[e.idx as usize]; self.entity_idx_to_data[e.idx as usize] = Default::default(); // To keep the ...
Rust
0
import os, json, yaml from flask import Flask, request, jsonify import numpy as np, cv2 from ..orientation.pipeline import analyze_orientation from ..oal_counter.pipeline import measure_oal app = Flask(__name__) CFG_COMMON = {} CFG_O = {} CFG_B = {} def load_cfg(): global CFG_COMMON, CFG_O, CFG_B with open('...
Python
1
#!/usr/bin/env python3 import os import time import json import glob with open("config.json", "r") as f: config = json.load(f) cmdlist = [] liglist = [] os.system("cd indata;tar -xvf {}.tar.bz2".format(config["target"])) liglist = glob.glob("./indata/{}_unique/*.pdbqt".format(config["target"])) if liglist == []:...
Python
1
i = int(input()) print(i * i) print(2)
Python
1
["tool_request_id"], ["id"], ) create_index(job_request_index_name, job_table_name, [request_column_name]) add_column( workflow_request_to_input_dataset_table_name, Column(workflow_input_request_column_name, JSONType, default=None), ) add_co...
Python
1
GistClient, GistContent, UpdateGistPayload}; let temp_dir = tempdir()?; let config_file = make_config_file(&temp_dir)?; let contents_1 = r#"{"description":"test description 1","language":"rust","tags":["tag1","tag2"],"code":"some\ntest\ncode\n"}"#; let contents_2 = r#"{"description":"test desc...
Rust
0
infile, dst, meta, size_mib=args.send_size, max_height=None if args.send_max_height <= 0 else args.send_max_height, max_fps=None if args.send_max_fps <= 0 else args.send_max_fps, ...
Python
1
assert_eq!( [ 141, 218, 31, 8, 166, 217, 124, 67, 35, 218, 36, 255, 84, 11, 232, 80, 192, 9, 224, 176, 153, 221, 25, 11, 162, 255, 170, 63, 235, 130, 95, 198 ], mac ); assert_eq!(32, mac.len()); } } // Copyright (c) Facebook,...
Rust
0
{ let l = Line { start: Position { x: 0, y: 0 }, end: Position { x: 5, y: 5 }, }; assert_eq!( l.to_cells().collect::<Vec<_>>(), vec![ Position { x: 0, y: 0 }, Position { x: 1, y: 1 }, Position { x: ...
Rust
0
from metaflow_test import MetaflowTest, steps, assert_equals class ResumeRecursiveSwitchFlowTest(MetaflowTest): RESUME = True PRIORITY = 2 ONLY_GRAPHS = ["recursive_switch"] @steps(0, ["start"], required=True) def step_start(self): if not is_resumed(): self.count = 0 ...
Python
1
: HDEVINFO, deviceinfodata: *const SP_DEVINFO_DATA, drivertype: u32, memberindex: u32, driverinfodata: *mut SP_DRVINFO_DATA_V2_A) -> super::super::Foundation::BOOL; #[doc = "*Required features: `\"Win32_Devices_DeviceAndDriverInstallation\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pu...
Rust
0
if not. /// /// # Arguments /// /// * `path` - Path to the File or Folder to check the Existance fn does_exist(&self, path: &str) -> bool { let path = Path::new(path); if path.exists() { true } else { false } } /// Returns the List of Folders that got the given Id as Parent...
Rust
0
code. #[cfg_attr(test, mockable)] impl<T: Config> Pallet<T> { fn _request_redeem( redeemer: T::AccountId, amount_wrapped: Wrapped<T>, btc_address: BtcAddress, vault_id: DefaultVaultId<T>, ) -> Result<H256, DispatchError> { let amount_wrapped = Amount::new(amount_wrapped,...
Rust
0
s>, #[clap( short = 'i', name = "proposal-id", long = "proposal-id", help = "proposal id." )] proposal_id: u64, #[clap( name = "dao-token", long = "dao-token", default_value = "0x1::STC::STC" )] /// The token for dao governance, default i...
Rust
0
import os import string import urllib.parse import urllib.request from .compat import WINDOWS def path_to_url(path: str) -> str: """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib.parse...
Python
1
)*)); $crate::LOGGER.display_cyanln(&formatted); }} } #[macro_export] macro_rules! display_red { ($($arg:tt)*) => {{ let formatted = std::fmt::format(format_args!($($arg)*)); $crate::LOGGER.display_red(&formatted); }} } #[macro_export] macro_rules! display_redln { ($($arg:tt)*)...
Rust
0
neighbour_grid, neighbour_tol): """ Each entry of the input array is replaced by the weighted mean of its neighbours. Neighbours are defined by points closer than neighbour_tol in the neighbour_grid. Weights decrease when the point gets closer to the considered position. Parameters -------...
Python
1
import numpy as np import pyclesperanto as cle cle.select_device("TX") def test_greater_or_equal_2d(): test1 = cle.push( np.asarray( [ [0, 0, 0, 0, 0], [0, 1, 2, 3, 0], [0, 3, 3, 4, 0], [0, 4, 4, 5, 0], [0, 0, 0,...
Python
1
factor_code.extend(vec![AsmInstructions::Push("rax".to_string())]); factor_code.extend(factor1_code); factor_code.extend(vec![AsmInstructions::Pop("rcx".to_string())]); match operator { symbols::HigherBinaryOperator::Multiplication => {...
Rust
0