text
string
label_name
string
labels
int64
SrcLoc::new(1, 1), )]); assert_eq!(expected, root); } #[test] fn test_ast_parse_string_list() { let input = "\"hello $name\n\"\n"; let root = ast::parse(lex(input)); let part1 = Ast::ConstStr(Lstr::from("hello ")); let part2 = Ast::Localid(Lstr::from("na...
Rust
0
from easydict import EasyDict from copy import deepcopy halfcheetah_dt_config = dict( exp_name='dt_log/d4rl/halfcheetah/halfcheetah_expert_dt_seed0', env=dict( env_id='HalfCheetah-v3', collector_env_num=1, evaluator_env_num=8, use_act_scale=True, n_evaluator_episode=8, ...
Python
1
""" Comment Model This module defines the Comment model for project comments functionality. """ from sqlalchemy import Column, String, DateTime, ForeignKey, Integer from sqlalchemy.orm import relationship from datetime import datetime from app.models.shared_base import SharedBase as Base class Comment(Base): ""...
Python
1
selected operations') btn.grid(row=4, column=1, sticky='sw', padx=0, pady=5) photo = PhotoImage(file=gui.findResource(Icon.DELETE_OPERATION)) btn = Label(helpFrame, image=photo) btn.photo = photo btn.grid(row=5, column=0, sticky='sw', padx=10, pady=5) btn = Label(helpFr...
Python
1
lta_pos, joint5_delta, joint6_delta): log_message(f"Movement: pos={delta_pos}, j5={joint5_delta:.3f}, j6={joint6_delta:.3f}", "info", "Gamepad") def on_grip(toggle): log_message(f"Gripper toggle: {toggle}", "info", "Gamepad") def on_record_start(): log_message("📹 Start recordi...
Python
1
ate_dict(checkpoint['optimizer_he_estimator']) return checkpoint['epoch'] def load_cpk_mapping(self, checkpoint_path, mapping=None, discriminator=None, optimizer_mapping=None, optimizer_discriminator=None, device='cpu'): checkpoint = torch.load(checkpoint_path, map_location=t...
Python
1
_service![request::SetState, response::SetState]; impl_mock_service![request::GetState, response::GetState]; impl_mock_service![ request::HereNow<presence::respond_with::OccupancyOnly>, response::HereNow<presence::respond_with::OccupancyOnly> ]; impl_mock_service![ request::HereNow<presence::respond_with::O...
Rust
0
problem_id = problem_id.zfill(3) os.makedirs(os.path.join(case_path, problem_id), exist_ok=True) with open(os.path.join(case_path, problem_id, "prompt.txt"), "w", encoding="utf-8") as f: f.write(preprocess(prompt)) with open(os.path.join(case_path, problem_id, "reference_code.p...
Python
1
password, expect_pass, extra): pulp_href = extra["local_ee"].get_namespace()['pulp_href'] list_roles_common(user, password, expect_pass, pulp_href) def ee_namespace_add_role(user, password, expect_pass, extra): pulp_href = extra["local_ee"].get_namespace()['pulp_href'] add_role_common(user, password, ...
Python
1
micBool::new(false), x)) .collect::<Vec<_>>(); let creator = LazyCreator::new(&lazy, &entities); ( &entities, &shots, &transforms, &circles, &in_screens, &colors, ) // Let's use multiple threads becau...
Rust
0
ages the resource will be accessed in. pub stages: PipelineStages, /// The type of memory access that will be performed. pub access: AccessFlags, /// Whether the resource needs exclusive (mutable) access or can be shared. pub exclusive: bool, } fn main() { enum Void {} std::rc::Weak::<Void>:...
Rust
0
to) /// Where the first element (name of the action template) is typically constant while /// the remaining elements are typically variable representing the parameters of the action. pub name: Sv, /// Task achieved by the chronicle, if different from its name. pub task: Option<Task>, pub conditi...
Rust
0
d write your own /// system that sends [`NavRequest`](crate::NavRequest) events pub fn default_gamepad_input( mut nav_cmds: EventWriter<NavRequest>, has_focused: Query<(), With<Focused>>, input_mapping: Res<InputMapping>, buttons: Res<Input<GamepadButton>>, axis: Res<Axis<GamepadAxis>>, mut ui_i...
Rust
0
Some(Username::new(String::from("username Pass")).unwrap()), //none usr: Some("username"), pas: Some("<PASSWORD>"), allocations: None, max_lifetime: 30, // this value must be greater than the lifetime_check value in tests.rs client_lifetime: None, realm: Some(Realm::new(...
Rust
0
e self.inputs.sort(); self.outputs.sort(); Ok(TransactionEssence { inputs: self.inputs.into_boxed_slice(), outputs: self.outputs.into_boxed_slice(), payload: self.payload, }) } } <filename>src/errors.rs // Copyright 2017 -2018 Maskerad Developers...
Rust
0
om_group), keyword) or not self.check_description(str(to_group), keyword): return False raw_teams: list[dict] = get_group_settings(str(from_group), "opening") goal_teams: list[dict] = get_group_settings(str(to_group), "opening") for each_team in raw_teams: if str(each_tea...
Python
1
background_img = r'assets\photo-1669216369761-b861ee60a827 1.png' icone_img = r'assets\Icone.png'
Python
1
-> String { misc::random_data(job::TITLE).to_string() } pub fn descriptor() -> String { misc::random_data(job::DESCRIPTOR).to_string() } pub fn level() -> String { misc::random_data(job::LEVEL).to_string() } #[cfg(test)] mod tests { use crate::job; use crate::testify::exec_mes; #[test] ...
Rust
0
[object_id] as [varname] %} {% get_comment_form for [app].[model] [object_id] as [varname] with [parent_id] %} """ return CommentFormNode.handle_token(parser, token) @register.tag def render_comment_form(parser, token): """ Render the comment form (as returned by ``{% render_comment_form %}``)...
Python
1
. Exit") print('--------------------------------') choice = input("Choose an option: ") if choice == '1': sync_games() print("Games synced from Steam!") elif choice == '2': add_new_game() elif choice == '3': display_games() elif choice == '4...
Python
1
json.dump(results, f, indent=2) logger.info(f"Speed benchmark results saved to {output_file}") elif args.mode == 'comparative': # Comparative evaluation if not args.baseline_model_path: logger.error("Baseline model path required for comparative evaluation") ...
Python
1
"""Add discovery fields to pools table Revision ID: 005_add_pool_discovery_fields Revises: 004_discovery_metadata_table Create Date: 2025-09-13 12:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import sqlite # revision identifiers, used by Alembic. revision = '005' down_revi...
Python
1
import orjson import pytest from shared.reports.resources import Report from shared.utils.sessions import Session from services.report import raw_upload_processor as process from services.report.parser.legacy import LegacyReportParser # The intention of these tests is to easily reproduce production problems with real...
Python
1
.as_str()); } #[allow(unused_mut)] let mut scope_3735 = writer.prefix("VpcId"); if let Some(var_3736) = &input.vpc_id { scope_3735.string(var_3736); } #[allow(unused_mut)] let mut scope_3737 = writer.prefix("DryRun"); if let Some(var_3738) = &input.dry_run { scope_3737.bo...
Rust
0
mut erasures = Vec::with_capacity(self.n_parties as usize); for i in 0..self.n_parties { if !root_map.contains_key(&i) { erasures.push(i as i32); } } // Don't need messages after this, can simply take the contents let fragments = std::mem::take...
Rust
0
e_y = center[pre_ind][1] pre_z = center[pre_ind][2] next_x = center[next_ind][0] next_y = center[next_ind][1] next_z = center[next_ind][2] curr_c = [center_x_...
Python
1
swm_handle, //! ); //! //! #[cfg(feature = "82x")] //! let clock = &(); // I2C is always powered by system clock on LPC82x //! #[cfg(feature = "845")] //! let clock = &syscon.iosc; //! //! let mut i2c = p.I2C0 //! .enable( //! clock, //! i2c0_scl, //! i2c0_sda, //! &mut syscon.handle...
Rust
0
three files, train.doc.txt, dev.doc.txt, and test.doc.txt . Each line in these files is a document ID. """ print('Splitting the dataset into train/dev/test sets') train_docs, dev_docs, test_docs = set(), set(), set() # load doc ids with open(os.path.join(split_path, 'train.do...
Python
1
"""OpenBB Core App Abstract Model."""
Python
1
ring::new(); while let Some(ch) = iter.next() { match ch { '\\' => match iter.next() { Some(pch) => match iter.peek() { Some(_) => cur_state.push(pch), None => cur_symbol.push(pch), }, None => return Err(()),...
Rust
0
from godot import exposed, signal, export, Node2D SCORE_TO_WIN = 2 @exposed class Pong(Node2D): game_finished = signal() def _ready(self): self.score_left = 0 self.score_right = 0 # let each paddle know which one is left, too p1 = self.get_node("player1") p2 = self.g...
Python
1
_WORD_TEXT: &str = "Words."; const EMPTY_TEXT: &str = ""; pub(crate) fn get_method<T, CS>( pivot: usize, variant: Variant, charset: CS, rng: T, ) -> ExtendedLineMethod where T: RngCore + 'static, CS: GetCharacterSet + 'static, { ExtendedLineMethod::builder() .with_pivot(pivot) ...
Rust
0
import FWCore.ParameterSet.Config as cms # L1 Trigger client DQM sequence # # used by DQM GUI: DQM/Integration/python/test/l1t_dqm_sourceclient-*_cfg.py # # standard RawToDigi sequence must be run before the L1T module, labels # from the standard sequence are used as default for the L1 DQM modules # any configuration...
Python
1
from Menu import Burger, Drinks, Menu, Pizza from Order import Order from Restaurant import Restaurant from Users import Chef, Customer, Manager, Server def main(): menu = Menu() pizza_1 = Pizza('Shutki Pizza', 600, 'large', ['shutki', 'onion']) menu.add_menu_item('pizza', pizza_1) pizza_2 = Pizza('Al...
Python
1
} } } <reponame>ebfull/hsdfiugjhasdifgujhsdkfjg #![feature(test)] extern crate ff; extern crate pairing; extern crate rand; extern crate subtle; extern crate test; extern crate typenum; use test::Bencher; use rand::SeedableRng; extern crate hsdfiugjhasdifgujhsdkfjg; use hsdfiugjhasdifgujhsdkfjg::fp::Fp...
Rust
0
await bot.send_message(user['user_id'], post[2], reply_markup = markup, disable_web_page_preview=True) else: await bot.send_photo( chat_id=user['user_id'], photo=event[0], caption=event[1]) #event[4] if event[4] else None) #.send_...
Python
1
// should be i8 let fail31 = 240_8; // should be u8 let ok32 = 360_8; // doesnt fit in either, should be ignored let fail33 = 0x1234_16; let fail34 = 0xABCD_16; let ok35 = 0x12345_16; let fail36 = 0xFFFF_FFFF_FFFF_FFFF_64; // u64 // issue #6129 let ok37 = 123_32.123; let ok38 = 124...
Rust
0
OSCEN OFFSET(16) NUMBITS(1) [], STARTUP OFFSET(8) NUMBITS(4) [ Cycles64 = 1, Cycles1024 = 14 ], AGC OFFSET(3) NUMBITS(1) [], GAIN OFFSET(1) NUMBITS(2) [ G0 = 0, G1 = 1, G2 = 2, G3 = 3, G4 = 4 ], MODE OFFSET(0) NUMBITS(1) [ E...
Rust
0
t from the end of the header. And done. let mut reader = BufReader::new(File::open(&compressed_path)?); let mut footer_offset = vec![0; 4]; reader.seek(SeekFrom::Start(12))?; reader.read_exact(&mut footer_offset)?; let c...
Rust
0
ed features: `\"Win32_Graphics_Direct3D12\"`*"] pub type D3D12_PREDICATION_OP = i32; #[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"] pub const D3D12_PREDICATION_OP_EQUAL_ZERO: D3D12_PREDICATION_OP = 0i32; #[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"] pub const D3D12_PREDICATION_OP_NOT_...
Rust
0
dc_util::DisplayHint::ArrayString => 4, dc_util::DisplayHint::ArrayByte => 5, dc_util::DisplayHint::MatrixDouble2D => 6, dc_util::DisplayHint::None => -1, }; self.writer.write_i32::<BigEndian>(hint)?; Ok(()) } } impl<W: 'static + Write + Send> Sink ...
Rust
0
import requests import pandas as pd # Your Facebook access token access_token = 'EAAOKF5vwULwBO3cZBfEoy1t9P7rlI1fgyIDZBmTOpbChhgaSIcnFLuA9EKkTiVZBAKA5bP2MTsYRDB0UW1jfXO2JC082pvQq666ZB38jKg3CC70yQrkiYGmMrOkMvrG7fzIfNR12vcYJeqyHV8WZA5VOU4cZAgMqKvn6jMfNgQiJgQkRHSZBBE3LMrVuRsbs3GvYsFtdZBEyZAlUKlPmIYjgOAtNk' # The ID of th...
Python
1
missing_url; mod sources; const DEFAULT_DAYS_BACK: i64 = 2; fn main() { if let Err(e) = run() { println!("error: {}", e); let mut err = &*e; while let Some(cause) = err.source() { println!("caused by: {}", cause); err = cause; } ::std::process::e...
Rust
0
import socket import logging from typing import Optional from ldn_healthcheck.ryuldn.header import PacketHeader from ldn_healthcheck.ryuldn.packet import Packet from ldn_healthcheck.ryuldn.packet_id import PacketId from ldn_healthcheck.ryuldn.packets.initialize import InitializePacket class RyujinxLdnClient: def...
Python
1
use_checkpoint=use_checkpoint, # True use_scale_shift_norm=use_scale_shift_norm, # False ), SpatialTransformer( ch, # 4*320 num_heads, # 8 dim_head, # 160 ...
Python
1
def __init__(self): self.best_val_f1 = 0. def on_epoch_end(self, epoch, logs=None): f1, precision, recall = evaluate(valid_data) if f1 >= self.best_val_f1: self.best_val_f1 = f1 model.save_weights('best_model.weights') print( 'f1: %.5f, precis...
Python
1
import sys import traceback from glimps_malware_connector import GLIMPSMalwareConnector from glimps_malware_connector.config_loader import GLIMPSMalwareConfig from pycti import OpenCTIConnectorHelper if __name__ == "__main__": """ Entry point of the script - traceback.print_exc(): This function prints th...
Python
1
t): model_path = self.model_path.lower() if 'mistral' in model_path: template = '[INST] PLACEHOLDER [/INST]' elif 'vicuna' in model_path: template = ( 'A chat between a curious human and an artificial intelligence assistant. ' "The assistan...
Python
1
here. pub trait HasBoundingSphere<N, P, M> { /// The object bounding sphere. fn bounding_sphere(&self, m: &M) -> BoundingSphere<N, P>; } /// A Bounding Sphere. #[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)] pub struct BoundingSphere<N, P> { center: P, radius: N } impl<N, P> Boundin...
Rust
0
ining: usize = 0; let mut within_run = false; let mut run_value: u8 = 0; for channel in 0..3 { for pixel in 0..num_pixels { if remaining == 0 { let next: u8 = *iter.next().ok_or_else(rle_error)?; if next < 128 { remaining = (next as usi...
Rust
0
ialize, Deserialize)] pub struct AppConf { pub n: ProcessId, //number of processes fanout: i8, //number of echos to send cycles: u16, //number of echo cycles to run period: Time //time between cycles } //hols the application configuration, read from the yaml file impl AppConf { pub fn new(n: Proces...
Rust
0
args.build_arg("PRETTY_NAME", getenv("BUILDSYS_PRETTY_NAME")?); args.build_arg("IMAGE_NAME", getenv("BUILDSYS_NAME")?); args.build_arg( "IMAGE_FORMAT", match image_format { Some(ImageFormat::Raw) | None => "raw", Some(ImageFormat::Qcow2) => "qcow2"...
Rust
0
// Range check(&vec[i..j], &set[i..j], &slice[i..j]); } for j in i..10 { // RangeInclusive check(&vec[i..=j], &set[i..=j], &slice[i..=j]); } } } } /* Copyright (c) 2020-2021 <NAME> (<EMAIL>) * * Permiss...
Rust
0
fmt(f)?; self.0.fmt(f)?; f.write_char('\n')?; } Ok(()) } } #[allow(missing_debug_implementations)] struct SseId<T>(T); /// Identifier field ("id:<identifier>") pub fn id<T>(id: T) -> impl ServerSentEvent where T: Display + Send + Sync + 'static, { Ss...
Rust
0
_balance(&mut app, &astro_token_instance, &user1, 0); check_token_balance(&mut app, &mirror_token_instance, &user1, 0); check_token_balance(&mut app, &astro_token_instance, &user2, 6_000000); check_token_balance(&mut app, &mirror_token_instance, &user2, 60_000000); // Distributed Astro are 7 + 2 (for ot...
Rust
0
e.into(), ht_cap.into(), vht_cap.into(), ) .into_raw_zx_status() } #[no_mangle] pub extern "C" fn client_sta_handle_data_frame( sta: &mut Client, mlme: &mut ClientMlme, data_frame: CSpan<'_>, has_padding: bool, controlled_port_open: bool, ) -> i32 { // TODO(42080): Do no...
Rust
0
import re import pandas as pd import numpy as np term_pat = re.compile('(.+?):(.+)') pat = re.compile( '(.+)_([a-z][a-z]\.)?((?:wikipedia\.org)|(?:commons\.wikimedia\.org)|(?:www\.mediawiki\.org))_([a-z_-]+?)$') # Debug output to ensure pattern still works # print(pat.fullmatch('BLEACH_zh.wikipedia.org_all-access...
Python
1
let diff = i16::from(rate) - i16::from(last_rate); if diff > UP_DRAG { debug!("{} > {}", diff, UP_DRAG); u8::try_from(i16::from(last_rate) + diff - UP_DRAG).unwrap() } else if diff < -DOWN_DRAG { debug!("{} < -{}", diff, DOWN_DRAG); ...
Rust
0
# 큐 import sys from collections import deque inputf = sys.stdin.readline def main(): que = deque([]) N = int(inputf()) for _ in range(N): command = inputf().split() # print(command) if len(command) == 2: num = int(command[1]) que.append(nu...
Python
1
.1.clone(), info.2.clone())), registry.field::<&String>("cursor", &()), ]; registry .build_object_type::<Edge<C, S>>(&info, &fields) .into_meta() } fn resolve_field( &self, info: &Self::TypeInfo, field_name: &str, _args: &Argu...
Rust
0
bspec::{ USB_30_HUB_DESCRIPTOR, USB_CONFIGURATION_DESCRIPTOR, USB_DEVICE_DESCRIPTOR, USB_DEVICE_SPEED, USB_ENDPOINT_DESCRIPTOR, USB_HUB_DESCRIPTOR, }; use um::winioctl::{FILE_ANY_ACCESS, FILE_DEVICE_USBEX, METHOD_BUFFERED, METHOD_NEITHER}; pub const IOCTL_INTERNAL_USB_SUBMIT_URB: DWORD = CTL_CODE!(FILE_DEVI...
Rust
0
6 t: tkttvttttttttsbf 12-16 k: jkkkkkkkqkkkkfkkk 12-15 d: hdpgdjbktdbsdtpjq 2-10 v: vbvhvvvvvvwrsvvvv 2-6 v: vzvvvvvvvvv 8-11 q: qqqqkqqnqqv 3-5 h: dcrhp 6-7 b: bbpbbbrb 2-17 q: qqqqqqqqqqqqqqqqqq 11-12 h: hhhvhgzhhhxh 12-14 p: pppppppppppppnp 3-4 r: rlrrb 4-9 s: zsskkscxs 1-9 k: kkwkkkkgk 7-10 q: dqnqqqpkqqqqsgbl 11-1...
Rust
0
svm_log(offset, len, code as u32) } } use crate::io::modification::CapacityGraphContainer; use rust_road_router::datastr::graph::{EdgeId, EdgeIdGraph, Graph, NodeId, UnweightedFirstOutGraph}; use rust_road_router::datastr::rank_select_map::{BitVec, RankSelectMap}; use std::collections::HashMap; pub fn filter_inval...
Rust
0
sco_IOS_XE_cdp_oper.CdpYesNo>` **config**\: False .. attribute:: spare_pair_pd_config Spare pair PoE TLV is a one octet long this field represents Powered Device(PD) Spare Pair Desired State **type**\: :py:class:`CdpEnableDisable...
Python
1
# # Vector class # from __future__ import annotations from typing import Any import numpy as np import numpy.typing as npt import pybamm from pybamm.type_definitions import AuxiliaryDomainType, DomainsType, DomainType class Vector(pybamm.Array): """ node in the expression tree that holds a vector type (e.g...
Python
1
import tensorflow as tf from trainers.trainer import Trainer from utils.logger import get_callbacks from data.input_pipeline import get_datasets from utils.seed import set_seed import os import yaml from models.build_vgg_19 import simple_cnn_tiny_imagenet # Load configurations config = yaml.safe_load(open("configs/res...
Python
1
nwbfile_kwargs={ "session_description": "test session", "identifier": "subj0", }, processing_module_kwargs={ "description": "processed behav for test session", }, subject_kwargs={"age": "P90D", "subject_id": "subj0"}, pose_estimation_series_k...
Python
1
.format(config::FileFormat::Toml), )?; Ok(loader) } pub fn from_toml_string<S: AsRef<str>>(cfg_string: S) -> Result<Config> { let mut loader = Config::default_loader()?; loader .merge(File::from_str(cfg_string.as_ref(), config::FileFormat::Toml).required(false))?; ...
Rust
0
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab import os import aws_cdk as cdk from aws_cdk import ( Stack, aws_apigatewayv2_alpha as aws_apigwv2, aws_lambda, ) from aws_cdk.aws_apigatewayv2_integrations_alpha import HttpLambdaIntegration from constructs...
Python
1
card!("Llanowar Elves")); assert_eq!(obs.cmc, runs); assert_eq!(obs.mana, runs); assert_eq!(obs.play, runs); } // on the draw, always draw all 8 cards #[test] fn small_deck_2() { let deck = decklist!( " 1 Llanowar Elves 7 Forest " ); let draws = 1; let runs = 10; ...
Rust
0
from AttributeGathering.Controllers.BasicNodeController import * from AttributeGathering.Controllers.BasicListController import * from AttributeGathering.Controllers.CustomListControllers import * from AttributeGathering.Controllers.SystemNotesController import * from AttributeGathering.Controllers.WebcamController im...
Python
1
""" Реализуйте класс ValueDict, наследника класса dict, описывающий словарь c дополнительным функционалом. Процесс создания экземпляра класса ValueDict должен совпадать с процессом создания экземпляра класса dict. Класс ValueDict должен иметь два метода экземпляра: key_of() — метод, принимающий в качестве аргумента о...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class DeliveryCarrier(models.Model): _name = 'delivery.carrier' _inherit = ['delivery.carrier', 'website.published.multi.mixin'] website_description = fields.Text(related='p...
Python
1
), Err(why) => println!("Command '{}' returned error: {:?}", command_name, why), }) // Command exception .unrecognised_command(|_, _, unknown_command_name| { println!("Could not find command named '{}'", unknown_command_name); }) ...
Rust
0
oragon() } // 大三元 fn is_daisangen(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[DW] + yc[DG] + yc[DR] == 3 } // 小四喜 fn is_shousuushii(ctx: &YakuContext) -> bool { let yc = &ctx.yakuhai_check; yc[WE] + yc[WS] + yc[WW] + yc[WN] == 3 && ctx.pair_tile.is_wind() } // 大四喜 fn is_daisuushii(ct...
Rust
0
import asyncio import re import time from typing import Any, Union, cast from playwright.async_api import Page from typing_extensions import deprecated from src.classes import AIOHTTPClientSession, Billing, CRResource, TimeSheetUpdateKeys from src.services.api import is_auth_id_in_billing, set_billing_timesheets from...
Python
1
from comfy import sd1_clip import os class SD2ClipHModel(sd1_clip.SDClipModel): def __init__(self, arch="ViT-H-14", device="cpu", max_length=77, freeze=True, layer="penultimate", layer_idx=None, dtype=None, model_options={}): if layer == "penultimate": layer="hidden" layer_idx=-2 ...
Python
1
request after peer B closed connection let res = send_request(&sys_a, &communication_actor_a, peer_b_id); assert!(res.is_err()); } #[test] fn firewall_rules() { // Actor A let sys_a = ActorSystem::new().expect("Failed to create actor system."); let blank_actor = sys_a.actor_of::<BlankActor>("blank...
Rust
0
mut().gen_range::<u32, _>(0..100); if tmp < 40 { None } else if tmp < 10 { Some(false) } else { Some(true) } } // 40/100 chance: data hash-type // 60/100 chance: type hash-type pub(crate) fn is_data_hash_type(&self) -> bool { s...
Rust
0
from django.contrib.auth import get_user_model def make_user(username: str = "bob", is_staff: bool = False): user_model = get_user_model() user, _ = user_model.objects.get_or_create(username=username, password="pass", is_staff=is_staff) return user
Python
1
put channel MAX-3"] #[inline(always)] pub fn adc14ch1map(&self) -> ADC14CH1MAP_R { ADC14CH1MAP_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 26 - Controls internal channel 2 selection to ADC input channel MAX-4"] #[inline(always)] pub fn adc14ch2map(&self) -> ADC14CH2MAP_R { ...
Rust
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Layer norm done in fp32 (for fp16 training) """ import torch.nn as nn import torch.nn.functional as F class Fp32InstanceNorm(nn.Instance...
Python
1
import numpy import opengm import time dimx=1000 dimy=1000 numVar=dimx*dimy numLabels=2 numberOfStates=numpy.ones(numVar,dtype=opengm.index_type)*numLabels vis2Order=opengm.secondOrderGridVis(dimx,dimy) numFac = len(vis2Order) randf = numpy.random.rand(numFac,numLabels,numLabels).astype(numpy.float64) print rand...
Python
1
Codec)] #[asn(type = "OPEN")] pub enum CellTrafficTraceProtocolIEs_EntryValue { #[asn(key = 10)] Id_AMF_UE_NGAP_ID(AMF_UE_NGAP_ID), #[asn(key = 43)] Id_NGRAN_CGI(NGRAN_CGI), #[asn(key = 44)] Id_NGRANTraceID(NGRANTraceID), #[asn(key = 256)] Id_PrivacyIndicator(PrivacyIndicator), #[asn...
Rust
0
from ...constants import * # NOQA from . import cmd, create_regular_file, generate_archiver_tests, RK_ENCRYPTION pytest_generate_tests = lambda metafunc: generate_archiver_tests(metafunc, kinds="local,remote,binary") # NOQA def test_delete_options(archivers, request): archiver = request.getfixturevalue(archive...
Python
1
ey=input_key, return_messages=return_messages, human_prefix=human_prefix, ai_prefix=ai_prefix, memory_key=memory_key, ) def save_context( self, inputs: Dict[str, Any], outputs: Dict[str, str], ...
Python
1
"""This is a script for the backend of the TreeModel.predict_proba() method.""" import numpy as np # II Main methods def monte_carlo_predict_proba(X=None, list_models=None, is_selected=None): """Obtain Monta Carlo estimate of prediction probability of positive class""" # Initialize array to store predictions f...
Python
1
incompatible_module_ids.push((m.self_id(), compatibility)); } } } if !incompatible_module_ids.is_empty() { eprintln!( "Modules {} is incompatible with remote chain: {}!", incompatible_module_ids .into_iter() .map(|(module_id, ...
Rust
0
import numpy as np from LogSumExp import log_sum_exp from GaussLogProb import gauss_log_prob def discrim_analysis_predict(model, X_test): """使用类条件概率为多维高斯分布的贝叶斯公式 计算 post[i,c]=p(y=c|x[i,:],parms) yhat[i] = argmax_c post[i,c] Input: model : 已经训练好的DiscrimModel 类 X_test : 测试样本, shape = (n...
Python
1
te_fn, batch_sampler=batches[offset:], num_workers=self.num_workers, ), start=offset, ) class GroupedIterator(object): """Wrapper around an iterable that returns groups (chunks) of items. Args: iterable (iterable): iterable to wrap ...
Python
1
start_day: 15, end_day: 84, } }, recombinant: VaccineSettings { complete: Interval { start_day: 0, end_day: 180, }, no...
Rust
0
_flags: UsedFlags, used_idx: u16, used_ring: [UsedEntry; 8], buffers: [Buffer; 8], } fn make_virtqueue() -> Box<VirtQueue> { let mut v = Box::new(VirtQueue { descriptors: [DescriptorEntry { addr: 0, len: 0, flags: Descr...
Rust
0
import logging from time import time from itertools import chain from adhocracy import config from sources import watchlist_source, vote_source, instance_source from sources import delegation_source, tag_source, comment_source from filters import self_filter, duplicates_filter, comment_filter from filters import hidde...
Python
1
PC_BEGIN + 4); // Should not skip if there is no press machine.reset(); machine.register_set(0xB, 0xD); machine.key.key_down(0xC); machine.test_opcode(0xEB9E); assert_eq!(machine.pc, PC_BEGIN + 2); } #[test] fn test_exa1_skip_if_not_pressed() { let mut machine = Machine::new(TestContext::...
Rust
0
Build a [`blocks::Input`] /// /// # Attributes /// |Attribute|Type|Optional|Available as child| /// |-|-|-|-| /// |[`label`](blocks::input::build::InputBuilder::label())|[`text::Plain`], [`text::Mrkdwn`], or [`text::Text`] ([`<text>`](super::text()))|❌|❌| /// |[`element`](blocks::input::build::InputBuilder...
Rust
0
page.parent_site_id, page.pk, page.plugin.type_name, translation.language_code, translation._cached_url, ), "WILL CHANGE...
Python
1
( "inner_test_items", Kserd::new(Value::Seq(vec![])), ), ] ...
Rust
0
ard_state: self.reward_state.clone(), state_hash: self.state_hash.clone(), } } } <filename>src/count_and_sum.rs /* * Copyright 2019 DTAI Research Group - KU Leuven. * License: Apache License 2.0 * Author: <NAME> */ #[cfg(target_arch = "x86_64")] use std::arch::x86_64::*; use crate::bitblock...
Rust
0
Returns value /// New object of type [`FrequencySpectrum`]. /// /// ## Examples /// ### Scaling via dynamic closure /// ```rust /// use spectrum_analyzer::{samples_fft_to_spectrum, FrequencyLimit}; /// // get data from audio source /// let samples = vec![0.0, 1.1, 5.5, -5.5]; /// let res = samples_fft_to_spectrum( ///...
Rust
0
ll = PowerCell(1, 1, 1); // Indexing starts at 1 for size in 1..=300 { let optimal = optimal_power(&grid, size); if optimal.0 > max { max = optimal.0; max_fuel_cell = optimal.1; } } max_fuel_cell } fn cell_power(x: usize, y: usize, serial_num: isize) -> isi...
Rust
0