text
string
label_name
string
labels
int64
te dut.lyapunov_derivative_mip_pool_solutions = 1 dut.lyapunov_positivity_mip_pool_solutions = 1 dut.lyapunov_positivity_sample_cost_weight = \ args.lyapunov_positivity_sample_cost_weight dut.lyapunov_derivative_sample_cost_weight = \ args.lyapunov_derivative_sample_cost_weight dut.a...
Python
1
"""ILI9341 demo (color wheel).""" from time import sleep from ili9341 import Display, color565 from machine import Pin, SPI # type: ignore from math import cos, pi, sin ANGLE_STEP_SIZE = 0.05 # Decrease step size for higher resolution PI2 = pi * 2 def hsv_to_rgb(h, s, v): """ Convert HSV to RGB (based on c...
Python
1
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]: depth_map = {} s...
Python
1
, .. for i in 0..NUM_PLAYERS { let player_name: String = i.to_string(); config.player_names[i] = Some(player_name); } config.max_entities = 50; let machine = Machine::new(&config).unwrap(); // assert_eq!(GAME_E_ID, 0); let game_entity = machine.entities.get(GAME_E_ID).unwrap(...
Rust
0
{ match self { Self::U8 => allocator.text("u8"), Self::U16 => allocator.text("u16"), Self::Bool => allocator.text("bool"), Self::Ptr => allocator.text("ptr"), } } } <reponame>baajur/signatory<filename>src/ed25519/seed.rs //! Ed25519 seeds: 32-bit unifo...
Rust
0
1HuX[]1u#ALHuLHAWAV1AUATIUSHXH|$0Hl$0t FAdH %%;A8HtHzɚ;AAGHT$HD$yI?tIGEwHD$AG ASMg LI(IGD$DIoD$@HD$8uIo(H(LE1AHEHD$HDHt$,|$,u 1DD$DD$HL$DT$H|$芁AHD$A9u AtAt[Et^A}uAGA9ƸDEI AG E1=A...
Python
1
impl Drop for Waiter { fn drop(&mut self) { self.inner.get_mut().data.remove(self.token); } } #[cfg(test)] mod tests { use super::*; use futures::future::lazy; #[actori_rt::test] async fn test_condition() { let mut cond = Condition::new(); let mut waiter = cond.wait(); ...
Rust
0
""" .. todo:: WRITEME """ import numpy import theano T = theano.tensor def log_mean_exp(a): """ .. todo:: WRITEME """ max_ = a.max(1) return max_ + T.log(T.exp(a - max_.dimshuffle(0, 'x')).mean(1)) def make_lpdf(mu, sigma): """ Makes a Theano function that allows the evaluti...
Python
1
ine): have_sigaction = 1 if re.search('struct[ \t]+sigevent', line): have_sigevent = 1 if re.search('siginfo_t', line): have_siginfo = 1 if re.search('union[ \t]+sigval', line): have_sigval = 1 if re.search(...
Python
1
a_y1 = second_wire_segment.start[1]; a_y2 = second_wire_segment.end[1]; assert_eq!(a_y1, a_y2); } _ => (), } } _ => (), } assert_ne!(a_x1, -1); assert_ne!(a_x2, -1); assert_ne!(a_y1, -1); asser...
Rust
0
from hiddifypanel_bot import bot, HMessage, Role from hiddifypanel_bot.utils import tghelper import telebot from telebot import types from i18n import t as _ from . import constants as C @bot.message_handler(commands=["start"], role=Role.AGENT) async def send_welcome(msg: HMessage): return await main_menu(msg) ...
Python
1
""" Copyright (c) 2022 Ruilong Li, UC Berkeley. """ from typing import Any, Callable def _make_lazy_cuda_func(name: str) -> Callable: def call_cuda(*args, **kwargs): # pylint: disable=import-outside-toplevel from ._backend import _C return getattr(_C, name)(*args, **kwargs) return c...
Python
1
p=overlap ) # TODO: add tiktoken usage to chunk metadata chunk_metadata = ChunkMetadata( chunk_chars=chunk_chars, overlap=overlap, chunk_type="overlap" ) else: chunked_text = chunk_code_text( parsed_text, doc, chunk_chars=chunk_chars, overlap=overlap ...
Python
1
from pydantic import BaseModel from flask_openapi3 import Info, Tag info = Info(title="alrdmc API", version="0.1.0") semantic_vector_tag = Tag(name="semantic_vectors", description="object containing all semantic vectors") semantic_vector_summary = "get all semantic vectors in DB" class SemanticVectorObject(BaseModel...
Python
1
async fn message_load<T>( ctx: WechatyContext<T>, message_id: String, identity: String, ) -> Result<Option<Message<T>>, WechatyError> where T: 'static + PuppetImpl + Clone + Unpin + Send + Sync, { match ctx.message_load(message_id).await { Ok(message) => { info!("Message sent: {...
Rust
0
# parse datetime robustly dt_raw = row[c_dt] if isinstance(dt_raw, (int, float)): # epoch seconds or ms heuristic val = float(dt_raw) if val > 1e12: dt = datetime...
Python
1
e, program_text ) }); let output_text = tls::set_current_program(&original_program, || { write_program_duplicated_names(&*original_program) }); let output_db = chalk_integration::db::ChalkDatabase::with(&output_text, <_>::default()); let output_program = output_db.progra...
Rust
0
panic!("Client connection failed: {:?}", e); }), ); evtlp.run(run_server).unwrap(); } use std::{mem::swap}; use rand::{Rng, SeedableRng, rngs::StdRng}; /** ## Description Inversion mutation is a mutation only for binary encoded individuals. Given the `individual` it randomly generates two indices and then inve...
Rust
0
data(m.fileName)) { pruned = append(pruned, m) } } t.current = pruned t.contEvaluated = true return len(t.current) > 0, true } func (d *indexData) newMatchTree(q query.Q) (matchTree, error) { if q == nil { return nil, fmt.Errorf("got nil (sub)query") } switch s := q.(type) { case *query.Regexp: // Re...
Rust
0
afe to remove before re-adding # Add new part new_custom_part = CustomBotParts( custom_robot_id=custom_robot_id, robot_part_id=new_part_id, direction=direction, robot_part_amount=amount ) session.add(new_cus...
Python
1
let mut visitor = MyHierVisitor::new(); AcceptHierVisitor::accept(&root, &mut visitor); assert_eq!( vec![ "enter_root", "enter_A", "enter_B", "leave_B", "enter_C", "leave_C", ...
Rust
0
w(-152.0, 456.0); *expected.get_mut(1, 3) = c32::new(-164.0, 492.0); let actual = mat1.dot(&mat2); for row in 0..dim1.0 { for col in 0..dim2.1 { assert_relative_eq!(actual.get(row, col).re, expected.get(row, col).re); assert_relative_eq!(actual.get(r...
Rust
0
yop.write(fileName + '_new') yopPicklable = {} # picklable dict and not object for channel in list(yop.keys()): yopPicklable[channel] = yop[channel] return [yopPicklable, yop.masterChannelList, yop.fileName] def processMDFstar(args): try: return processMDF(*args) excep...
Python
1
::{module, Call, Event, Store}; #[module] pub trait Issue: Core {} #[derive(Clone, Debug, PartialEq, Call, Encode)] pub struct RequestIssueCall<'a, T: Issue> { #[codec(compact)] pub amount: T::Wrapped, pub vault_id: &'a VaultId<T::AccountId, T::CurrencyId>, #[codec(compact)] pub griefing_collatera...
Rust
0
#!/usr/bin/python3 #-*- coding: utf-8 -*- import os, re, sys, json import random, string from urllib import parse # Generate code for block reference # def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) for i ...
Python
1
def is_same_tree(tree1, tree2, test_key_arr, path="root") -> bool: """Helper function to test if two test trees are the same with detailed error logs. `is_same_tree` starts by comparing the root attributes, and then checks if all children are the same. """ # Compare the root. for key in ["path", "n...
Python
1
1:26-1:27 "###); } #[test] fn match2_block_expr() { insta::assert_debug_snapshot!(parse_output("match x { A => { 1 } B => 2, }"), @r###" MATCH scrut: VAR @ 1:7-1:8 var: x @ 1:7-1:8 branch: BRANCH pattern: PATTERN @ 1:11-1:12 constr: A rhs...
Rust
0
{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({},{})", self.i, self.e) } } #[cfg(test)] mod tests { use ::{IdTree,EventTree,Stamp}; use std::str::FromStr; use super::*; #[test] fn id_tree_display() { assert_eq!("0", format!("{}", IdTree::zero())); ...
Rust
0
Some(v) => ChannelValue::Decimal32(v), None => ChannelValue::Disabled, }, ) .collect()) } fn process_output_values(&self, values: &[ChannelValue]) -> Result<Vec<u16>> { if values.len() != 4 { return Err(Error::ChannelValu...
Rust
0
eds,total_correct def evaluate_ByCategory(pred_chunks,true_chunks, class_types): # class_type:PER or LOC or ORG # pred_chunks,true_chunks are one-dim. class2f1_dic ={} for class_type in class_types: pred_chunk_class = [] for pchunk in pred_chunks: if pchunk[0] == class_type: pred_chunk_class.append(pchu...
Python
1
, En, Hi>>, ), ), /// A reference to a function or method. /// /// foo_fun<> /// FooCls::meth<int> FunctionPointer(&'a (FunctionPtrId<'a, Ex, Fb, En, Hi>, &'a [&'a Targ<'a, Hi>])), /// Integer literal. /// /// 42 /// 0123 // octal /// 0xBEEF // hexadecimal /// 0b1...
Rust
0
࿌࿍࿎࿏࿐࿑࿒࿓࿔࿕࿖࿗࿘࿙࿚"; let _a = unicode_is_fun + " really fun!"; //~^ ERROR binary operation `+` cannot be applied to type `&str` } <filename>test/src/types.rs pub struct TestDescAndFn { pub desc: TestDesc, pub testfn: StaticTestFn, } pub struct TestDesc { pub allow_fail: bool, pub ignore: bool, pub...
Rust
0
sub(1); } loop { if 0 == depth_limit { break; } if let Some(Some(bp)) = self.branch_to_parent.get(&branch_id) { depth_limit -= 1; ret.insert(bp.branch_id, bp.version_id); ...
Rust
0
item1 = 10 item2 = 20 item3 = 30 item1 = float(input("Enter the price for item1:")) item2 = float(input("Enter the price for item2:")) item3 = float(input("Enter the price for item3:")) subTotal= item1 + item2 +item3 salesGST = subTotal * 0.15 total = subTotal + salesGST print ("you purchase total is $", total,sep=)
Python
1
()) as usize) } fn soft_len(&self) -> TractResult<TDim> { if let Ok(len) = (self.end.clone() - &self.begin).to_integer() { Ok((((self.stride.abs() as i32 - 1) + len.abs() as i32) / self.stride.abs()).to_dim()) } else if self.stride == 1 { Ok(self.end.clone() - &self.begi...
Rust
0
from web_search import google_search with open("google_config.txt", "r") as file: google_api_key, google_cx = [line.strip() for line in file.readlines()] results = google_search("Regulatory in Medtech", google_api_key, google_cx) for result in results: print(result["title"], result["link"])
Python
1
s={1,2,3,"a","b",} s1={2,4,6,3,8,10,"c","d"} # # 1) add # s.add("f") # print(s) # # 2) clear # s.clear() # print(s) # # 3) copy # c=s.copy() # print(c) # # 4) difference # print(s.difference(s1)) # # 5) discard # s.discard("a") # print(s) ...
Python
1
#!/usr/bin/python3 import pyinotify #import RPi.GPIO as GPIO from gpiozero import LED import os.path from time import sleep #GPIO.setwarnings(False) def handle_change(cb): with open('/sys/class/gpio/gpio12/value', 'r') as f: status = f.read(1) if status == '0': #print("OFF\n") led26....
Python
1
)] #[derive(Copy, Clone, Default)] pub struct __user_cap_data_struct { pub effective: u32, pub permitted: u32, pub inheritable: u32, } assert_eq_size!(kernel::__user_cap_data_struct, __user_cap_data_struct); assert_eq_align!(kernel::__user_cap_data_struct, __user_cap_data_struct); #[repr(C)] #[derive(Copy...
Rust
0
ifted = pos.ins().raw_bitcast(I8X16, shifted); // Then, fixup the even lanes that have incorrect lower bits. This uses the 128 mask // bytes as a table that we index into. It is a substantial code-size increase but // reduces the instruction count slightly. let masks = p...
Rust
0
a=int(input("Enter the amount ")) b=int(input("Enter discount ")) c=a*b/100 d=a-c print("Amount to be paid is ",d) '''pl-ii@plii-HP-Pro-Tower-280-G9-PCI-Desktop-PC:~/B1_22/SEM 2$ python3 p11.py Enter the amount 1000 Enter discount 10 Amount to be paid is 900.0 '''
Python
1
next_word(At::Start, Word::Vi, 1); assert!(ok); assert_eq!(15, s.pos); let ok = s.move_to_next_word(At::Start, Word::Vi, 1); assert!(ok); assert_eq!(17, s.pos); let ok = s.move_to_next_word(At::Start, Word::Vi, 1); assert!(ok); assert_eq!(18, s.pos); ...
Rust
0
a5E\ \xe7(\x1e\x8dH&A\xde\xa1\x09ob_\xbe>\x95\ \x18\xf9M \x9d\x14u\xcd\x1ez7S\x8a\xa1\xdf\xa1\ /Jh\xfc\xe9<\xe4\xf5\xa8\xf7\xaf\xad-P\x13\x8c\ \x1aBs\x8e3Q\x99\x00\xe8\xdf/j<\xd4\xee\xc4\ zb\x9d\x84J\x09\x04\xfam\xe2\x81\xd0TB\xe1{\ \x9c\x9aQ\x22\xf64\x0dhI\x9c\xd1P\xf9\x89\x8eO\ =\xe8\x12&\xe03@\x9e\xe5\x8d\xd4\xda\xa...
Python
1
False, False), # Correctness is visible to learners if due date in the past ('yesterday', False, True), # Correctness is visible to learners if due date in the past (just) ('today', False, True), # Correctness is visible to learners if there is no due date (None, False, T...
Python
1
import numpy as np import pandas as pd import matplotlib.pyplot as plt ## Calculate Mean Squared Error, Mean Error, Max Error, Min Error def compute_measure(predicted_labels, actual_labels): results = [] err = actual_labels - predicted_labels results.append(np.sum(np.power(err, 2)) / len(err)) # Mean Squar...
Python
1
q!(unresolved_shuffle.query_stage_ids, vec![1]); let partial_hash = stages[0].children()[0].clone(); let partial_hash_serde = roundtrip_operator(partial_hash.clone())?; let partial_hash = downcast_exec!(partial_hash, HashAggregateExec); let partial_hash_serde = downcast_exec!(partial_h...
Rust
0
) @_load_runtime_context # type: ignore def get_current() -> Context: """To access the context associated with program execution, the Context API provides a function which takes no arguments and returns a Context. Returns: The current `Context` object. """ return _RUNTIME_CONTEXT.get...
Python
1
) && max_k <= ((u8::MAX - 1) as u32) { return unsafe {levenshtein_simd_core_sse_4x16x8(a, b, max_k, trace_on, costs)}; }else if cfg!(feature = "jewel-8bit") && unit_k <= (Sse8x16x8::static_upper_bound() as u32 - 2) && max_k <= ((u8::MAX - 1) as u32) { return unsafe {levenshte...
Rust
0
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import List from app.database import get_db from app.models import User, Capsule, Transaction # 添加Transaction from app.schemas import UserResponse, CapsuleResponse, CapsuleUpdate from app.utils.security import get_curr...
Python
1
tive_examples = temp_positive_examples negative_examples = temp_negative_examples else: break # Build final examples text system_msg, user_msg = construct_msgs(selected_requirement, positive_examples, negative_examples, extra_context) eval_messages = [ { "role": "system", ...
Python
1
from fastapi import Depends, HTTPException, Query, status from pydantic import UUID4 from sqlalchemy import or_, select from fief.dependencies.pagination import ( GetPaginatedObjects, Ordering, OrderingGetter, PaginatedObjects, Pagination, get_paginated_objects_getter, get_pagination, ) fro...
Python
1
= sess.run([label_name], {input_name: test_input})[0] print("ONNX Model MSE:", mean_squared_error(y_test, onnx_pred)) # Plot actual vs predicted (Sklearn and ONNX) y_test_series = y_test.copy() y_test_series.index = X_test.index plt.figure(figsize=(15, 5)) plt.plot(y_test_series.index, y_test_series, label='Actual'...
Python
1
} => { let (acc_id, _) = self.get_account_by_address(address).unwrap(); self.accounts.remove(&acc_id); } AccountUpdate::UpdateBalance { balance_update: (token, _, new_balance), old_nonce: _, ...
Rust
0
import random import requests import json import base64 from Crypto import Random from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from loguru import logger def rsa_ecb_encrypt(plain_bytes: bytes, public_key_b64: str) -> ...
Python
1
from warnings import warn import bluesky.simulators as _bs def print_summary(plan): """Print summary of plan Prints a minimal version of the plan, showing only moves and where events are created. Parameters ---------- plan : iterable Must yield `Msg` objects """ warn( ...
Python
1
tryType, TimeEntryStatus, OpportunityStatus, OpportunityStage, QuoteStatus, InvoiceStatus, ] for enum_class in enums_to_test: for item in enum_class: assert isinstance( item.value, int ...
Python
1
sual=True) self._up_3 = CasualCT(self._num_hiddens // 2, self._num_hiddens // 4, leaky=True) self._dec_3 = Res_CNR_Stack(self._num_hiddens // 4, self._num_residual_layers, leaky=True, casual=True) self.project = nn.Conv1d(self._num_hiddens//4, out_dim, 1, 1) def forward(self, h, pre_state=N...
Python
1
print(calc.get_history()) input("Press Enter to continue...") continue if option.lower() == "sqrt": result = calc.square_root() print(f"Square Root Result: {result}") input("Press Enter to continue...") ...
Python
1
0) continue # 计算单向匹配距离,迅速想到的有两种办法:(1)和房间重合区域最大的;(2)和房间的IoU最大的 # 实施(2) IoUs = [] FN_flag = True for idx, j_pred in enumerate(values): c_pred = preds == int(j_pred) # 获得pred中,编号为j_pred的连通区域 semantic_pred = pred_arr[c_pred] if seman...
Python
1
} }<gh_stars>1-10 mod clip; mod delay_line; mod delta; mod grain_delay; mod lowpass; mod mix; mod phasor; pub use self::grain_delay::GrainDelay; <filename>src/trainee.rs pub struct Trainee { id : i64, first_name : String, last_name : String, address : String, zip : String, city : ...
Rust
0
.map(|_| make_listening_node(&bootstrap_leader_info)) .collect(); let blob_fetch_stages: Vec<_> = listening_nodes .iter_mut() .map(|(_, _, node, _)| { BlobFetchStage::new( Arc::new(node.sockets.tvu.pop().unwrap()), blob_receiver_exit.clon...
Rust
0
} } } } // Copyright (c) 2017-2021 <NAME> //! Struct values //! //! This module implements array value operations. use crate::{ ty::{struct_ty, Type}, value::Value, }; use std::fmt::{Debug, Display}; /// A struct value. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StructValu...
Rust
0
"""empty message Revision ID: 84100236b6b7 Revises: 0bcd0a93303f Create Date: 2025-02-07 13:38:39.259799 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = '84100236b6b7' down_revision: Union[str, None] = '0bcd0a93303f' bra...
Python
1
= "*Required features: 'Win32_NetworkManagement_Ndis'*"] pub const OID_WWAN_DELETE_MAC: u32 = 234946855u32; #[doc = "*Required features: 'Win32_NetworkManagement_Ndis'*"] pub const OID_WWAN_DEVICE_BINDINGS: u32 = 234946865u32; #[doc = "*Required features: 'Win32_NetworkManagement_Ndis'*"] pub const OID_WWAN_DEVICE_CAPS...
Rust
0
from .game import VGameEnv import gymnasium as gym import re class GameBreakout(VGameEnv): def __init__(self): super().__init__() self.game_name = "Breakout" self.game_prompt = "You are now playing the Breakout game.\n\nAvailable actions are:\n- (0): Stay Still\n- (1): Release the ball (if...
Python
1
} } impl ::std::fmt::Debug for DeleteReply { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for DeleteReply { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::r...
Rust
0
#!/usr/bin/env python # encoding: utf-8 from .fetcher import * from .territory import * class KKBOXFeaturePlaylistCategoryFetcher(Fetcher): ''' List feature playlist categories and list feature playlists for a specific category. See `https://docs-en.kkbox.codes/v1.1/reference#featured-playlist-categories`...
Python
1
basename + '.py' msgs = [] enums = [] filelist = [] for x in xml: msgs.extend(x.message) enums.extend(x.enum) filelist.append(os.path.basename(x.filename)) for m in msgs: if xml[0].little_endian: m.fmtstr = '<' else: m.fmtstr = '>' ...
Python
1
cell_client, SysTimer::new("CELL"), Config::new("").with_apn_info(APNInfo::new("internet.tele2.ee")), ); cell_client.set_socket_storage(unsafe { SOCKET_SET.as_mut().unwrap() }); // spawn serial reading thread thread::Builder::new() .spawn(move || loop { ingres...
Rust
0
import streamlit as st import langchain_helper as lch import textwrap st.title("Youtube Assistant") with st.sidebar: with st.form(key="my_form"): youtube_url = st.sidebar.text_area( label = "What is the Youtube video URL?", max_chars = 50 ) query = st.sidebar.text_...
Python
1
BS1_W { BS1_W { w: self } } #[doc = "Bit 0 - Port x set bit y (y= 0..15)"] #[inline(always)] pub fn bs0(&mut self) -> BS0_W { BS0_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { ...
Rust
0
PathBuf)> = file_paths_and_mimes .into_iter() .map(|(file_path, mime)| (mime, file_path)) .collect(); file_list_to_json(file_list_with_mimes) } fn file_list_to_json(file_list: Vec<(String, PathBuf)>) -> Result<Json> { let mut file_list_json: Vec<Json> = Vec::new(); for file in f...
Rust
0
"""Argon2 Hashing Backend using argon2-cffi.""" from typing import TYPE_CHECKING, Any, Union from advanced_alchemy.types.password_hash.base import HashingBackend if TYPE_CHECKING: from sqlalchemy import BinaryExpression, ColumnElement from argon2 import PasswordHasher as Argon2PasswordHasher # pyright: ignore ...
Python
1
ermine Planck's constant, a metal surface was irradiated with light of different wavelengths. The emitted photoelectron energies were measured by applying a stopping potential. The relevant data for the wavelength (λ) of incident light and the corresponding stopping potential (V₀) are given below: λ (μm) | V₀ (V) 0.3 ...
Python
1
import sut as SUT import random import time import sys import traceback import argparse import os from collections import namedtuple import covertool def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--depth', type=int, default=-1, help='Maximum search dept...
Python
1
(node.rel_skews[ns]), 'rel_p50_ms': None if p50 is None else p50 * 1000.0, 'rel_p95_ms': None if p95 is None else p95 * 1000.0, 'dims': node.dims[ns], } if p95 is None or p95 > node.rel_max_skew_s: rel_ok = False node.get_l...
Python
1
{ return res.primitive.do_exec( name, args, interval, &ContentType::Primitive, data, msg_data, sender, ); ...
Rust
0
4, base: 0.5 }; print_area(&tri); } fn print_area<T: Area>(shape: &T) { println!("The area of given shape is {}", shape.calc_area()); } trait Area { fn calc_area(&self) -> f64; } struct Rectangle { length: f64, width: f64, } impl Area for Rectangle { fn calc_area(&self) -> f64 { self...
Rust
0
ld("a=~~0", "a=0"); fold("a=~~10", "a=10"); fold("a=~-7", "a=6"); fold("a=+true", "a=1"); fold("a=+10", "a=10"); fold("a=+false", "a=0"); fold_same("a=+foo()"); fold_same("a=+f"); // fold("a=+(f?true:false)", "a=+(f?1:0)"); // TODO(johnlenz): foldable } #[test] fn test_unary_ops_2()...
Rust
0
to fulfill HTLC with an incorrect preimage"); } else { assert!(false); } assert!(nodes[0].node.list_channels().is_empty()); check_closed_broadcast!(nodes[0]); } #[test] fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() { //BOLT 2 Requirement: A receiving node: if the BADONIO...
Rust
0
Cs&g|jD]}|j|^q S(N(RORT(R"tident((s symtable.pyt get_symbolslscCs8g|jjD]'}|j|kr t||j^q S(N(R0RIRRR1(R"Rtst((s symtable.pyt__chec...
Python
1
ed = if down { false } else { self.key_pressed(DOWN) }; self.one_pressed = if one { false } else { self.key_pressed(ONE) }; self.two_pressed = if two { false } else { self.key_pressed(TWO) }; self.three_pressed = if three { false } else { self.key_pressed(THREE) }; self.four_pressed = if four { false } ...
Rust
0
# buses.py # # An example of setting up an event handling pipeline with coroutines # and XML parsing. from coroutine import * @coroutine def text_collector(target): while True: while True: event, value = (yield) if event == 'start' or event == 'end': target.send((e...
Python
1
import argparse import logging from sanic import Sanic, response from rasa.core.domain import Domain from rasa.core.nlg import TemplatedNaturalLanguageGenerator from rasa.core.trackers import DialogueStateTracker logger = logging.getLogger(__name__) DEFAULT_SERVER_PORT = 5056 DEFAULT_SANIC_WORKERS = 1 def create...
Python
1
from OpManager import op_manager from img2vec.img2vec import ModelUtil # @op_manager.register(name="resnet101") class resnet101(ModelUtil): def __init__(self): ModelUtil.__init__( self, model_name="resnet101", device="cpu", num_classes=1000, ...
Python
1
""" A file containing all database functions """ import os from pymongo import MongoClient MONGO_URI = os.getenv('MONGO_URI') client = MongoClient(MONGO_URI) db = client.mydatabase tasks_collection = db.tasks tasks_collection.create_index("day_number") def get_events_for_day(day_number): """ A function to get...
Python
1
from __future__ import annotations import os from typing import Final # Earliest fully supported Python 3.x version. Used as the default Python # version in tests. Mypy wheels should be built starting with this version, # and CI tests should be run on this version (and later versions). PYTHON3_VERSION: Final = (3, 8)...
Python
1
xdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest() ) await user.save() # make session cookie: r = web.Response() # 登陆的时候要创建cookie信息 r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True) user.pa...
Python
1
tico = AnalisadorSintatico(tokens) arvore = analisador_sintatico.analisar() if arvore: print("✅ Análise sintática bem-sucedida!") print("\nÁRVORE:") imprimir_arvore(arvore) else: print("❌ Falha na análise si...
Python
1
whose transparency is to be controlled. """ def __init__(self, parent=None, plot=None, legend=None): NamedItemAlphaSlider.__init__(self, parent, plot, kind="image", legend=legend) class NamedScatterAlphaSlider(NamedItemAlphaSlider): """Slider widget to be used in a plot toolbar to control...
Python
1
READ = 0, #[doc = "1: INTD = 0 - Readback will always be zero"] RDZERO = 1, } impl From<GPIO24INCFG_A> for bool { #[inline(always)] fn from(variant: GPIO24INCFG_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `GPIO24INCFG`"] pub type GPIO24INCFG_R = crate::R<bool, GPIO24INCF...
Rust
0
S4 SjrS \S \ S S S\SS4 SjrS#SjrS#SjrS#SjrS#SjrS#SjrS\SS4SjrS\SS4SjrS\SS4SjrS\SS4S jrS \S \ S S SS4S!jrS"rg)$TraceOtInternal dependency holder class. Used to keep together the main dependencies used at the moment of send a sig...
Python
1
on) addr = sb.state.symbols[ExprId(ptr_constr.reg, target_config.arch_context.address_size)] except KeyError: # this implies, the solver relies on a register constrainted to 0 initially (without explicit precondition) logger.error(f"SE: Chain failed to set {ptr_constr.reg} (b...
Python
1
et_rooms: await self.hass.async_add_executor_job(lambda: self._client.vacuums.sweep_rooms(device_mac=self._vac_mac, room_ids=[room.id for room in rooms if room.name in target_rooms])) self.async_schedule_update_ha_state(force_refresh=True) else: await self.async_start() ...
Python
1
(RcDoc::as_string("pub_uint8"), FuncPrefix::Regular), BaseTyp::Int8 => (RcDoc::as_string("pub_int8"), FuncPrefix::Regular), BaseTyp::UInt16 => (RcDoc::as_string("pub_uint16"), FuncPrefix::Regular), BaseTyp::Int16 => (RcDoc::as_string("pub_int16"), FuncPrefix::Regular), BaseTyp::UInt32 =>...
Rust
0
url = get_playlist_url(playlist_id) result=self.common_get_request(url,headers) tracks=result['result']['tracks'] for track in tracks: music = Music() id = track['id'] music.name = track['name'] music.id = id music.album_pic_url ...
Python
1
from pathlib import Path import yaml from huggingface_hub import HfApi, HfFileSystem, hf_hub_download # from mlip_arena.models import MLIP # from mlip_arena.models import REGISTRY as MODEL_REGISTRY try: from prefect.logging import get_run_logger logger = get_run_logger() except (ImportError, RuntimeError): ...
Python
1
r_name = 'train' logger_info(logger_name, os.path.join(opt.expDir, logger_name + '.log')) logger = logging.getLogger(logger_name) logger.info(opt_inst.print_options(opt)) modes = [i for i in opt.modes] stages = opt.stages model = getattr(Model, opt.model) model_G = model(nf=opt.nf, modes=...
Python
1
alid/test dataset/dataloder', 'callback function', 'model and optimizer', 'pretrained checkpoint'], barrier=True) print_rank_0('training ...') # Finetune the model. if args.epochs > 0: _train(model, optimizer, opt_param_scheduler, forward_step, train_dataloader, valid...
Python
1
import os, sys import unicodedata import MMD4Maya.Scripts.Chardet as chardet def ConvertToUnixPath(path = ""): return path.replace("\\", "/") def GetScriptsRootDir(): return ConvertToUnixPath(os.path.split(os.path.realpath(__file__))[0]) + "/" def GetExtraTextureDir(): return GetScriptsRootDir() + "../Te...
Python
1