text
string
label_name
string
labels
int64
# CLAUDE MODEL SETUP import boto3 from botocore.config import Config from langchain_aws import BedrockLLM, ChatBedrock from browser_use import Agent from browser_use.browser.browser import Browser, BrowserConfig from browser_use.controller.service import Controller import asyncio import os from dotenv import load_dote...
Python
1
rap_vector: wfi j 4b", options(noreturn) ); } #[no_mangle] unsafe fn kernel_main() -> ! { // Kernel has landed test_main(); loop {} } #[panic_handler] fn panic(_info: &PanicInfo) -> ! { uart_println!("[ok]"); qemu_exit_success(); } pub fn test_runner(tests:...
Rust
0
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Wedge def plot_agent_donut( highlight_label=None, save_prefix="donut_top_left", gap_span=90, # size of the cut-out ): # -------- ring definitions -------- layers = [ ("PERSONA", "#FF6F61", 13), ("TOO...
Python
1
webfx.com/tools/emoji-cheat-sheet/ // 2) (NOT YET SUPPORTED) A filename pointing to a file within the project's asset folder, which should be located in the project root. // As for now, the emoji asset must be present in your project in an "assets" folder located in the root of the project itself. // This r...
Rust
0
No mode given for console ParseConsoleInvalidModeGiven, /// Failed parsing device parameters ParseDevice(OptionParserError), /// Missing path from device, ParseDevicePathMissing, /// Failed parsing vsock parameters ParseVsock(OptionParserError), /// Failed parsing restore parameters ...
Rust
0
match args.len() { 4 => process(args), _ => usage() } }<reponame>anopara/country-slice use hotwatch::Event; use hotwatch::Hotwatch; use std::collections::HashSet; use std::sync::Arc; use std::sync::Mutex; use super::shader::ShaderProgram; pub struct ShaderWatch { hotwatch: Hotwatch, pub event_shader_c...
Rust
0
function (arg) { var n = runSumAll(arg); return (n.get = 1), n; }; return bar; }; var bar = foo({}); console.log(bar.baz([1, 2, 3]));"###; let config = r###"{ "reduce_funcs": true, "reduce_vars": true, "unused": true }"###; run_exec_test(src, config, false); } #[test] fn t...
Rust
0
e JSON string data = json.loads(json_string) # Get the latest production model run ID latest_run_id = data["run_id"] return latest_run_id except ClientError as e: if e.response["Error"]["Code"] == "NoSuchKey": print(f"The file '{file_key}' does not exist in the ...
Python
1
import argparse from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord def parse_arguments(): parser = argparse.ArgumentParser(description="Compute a set of representative sequences (RepGen set) using the Stingy Addition algorithm.") parser.add_argument('-k', '--kmer-length', type=in...
Python
1
iguous().to( point_cls_preds.device).view(-1, 1) point_cls_preds_multiclass = point_cls_preds.new_zeros( pts_num * cls_num, cls_num) point_cls_preds_multiclass = point_cls_preds_multiclass.scatter_( 1, point_cls_preds_index, point_cls_preds_src) _, code_size...
Python
1
self.0) } else { Ok(()) } } } impl core::default::Default for StringRecorder { fn default() -> Self { StringRecorder::new() } } impl<S: Subscriber + for<'a> LookupSpan<'a>> Layer<S> for AndroidLayer { fn new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context...
Rust
0
import customtkinter as ctk from tkinter import messagebox import pandas as pd import joblib # Load models and columns reg_model = joblib.load('vehicle_price_model.pkl') cls_model = joblib.load('vehicle_price_classifier.pkl') columns = joblib.load('model_columns.pkl') # Load your dataset to get feature types df = pd....
Python
1
from django.contrib import admin from tweetapp.models import Tweet # Register your models here. class TweetAdmin(admin.ModelAdmin): fields=['message' ,'username'] admin.site.register(Tweet,TweetAdmin)
Python
1
"4"), ("five", "5"), ("six", "6"), ("seven", "7"), ("eight", "8"), ("nine", "9"), ] # First convert the labels into a list of string prompts prompts = [ f"{text_labels[labels[i][0]][torch.randint(0, len(text_labels[labels[i][0]]), size=())]} and {text_labels...
Python
1
the snapshot, so we detect this situation and always compile with //! the snapshot compiler. //! 2. We pass a bunch of `--cfg` and other flags based on what we're compiling //! (and this slightly differs based on a whether we're using a snapshot or //! not), so we do that all here. //! //! This may one day be...
Rust
0
import os import re import json import string from typing import List, Tuple import numpy as np import onnxruntime as ort from razdel import sentenize from razdel.substring import Substring from huggingface_hub import hf_hub_download, snapshot_download from .char_tokenizer import CharacterTokenizer class TextPreproc...
Python
1
FIGURE_FILENAME: &'static str = "reconfigure"; const RUN_FILENAME: &'static str = "run"; const HABITAT_PACKAGE_INFO_NAME: &'static str = "habitat_package_info"; const HABITAT_PACKAGE_INFO_DESC: &'static str = "package version information"; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Package { pub or...
Rust
0
/ /// Returns `true` if new era should be forced at the end of this session. /// This allows preventing a situation where there is too many validators /// disabled and block production stalls. fn disable_validator(validator: &AccountId) -> Result<bool, ()>; /// Get the validators from session. f...
Rust
0
display = "No component with id `{:?}`, needed by `{:?}` when `{}`", id, needed_by, context )] NoSuchComponent { context: &'static str, needed_by: Option<&'static str>, id: Id<()>, }, #[fail(display = "Context {} error", 0)] Context(&'static str), #[fail(display...
Rust
0
, view_get_vli_thunk, view_get_vlu_thunk, ], }; #[no_mangle] fn on_call(index: i32) { ScExports::call(index, &EXPORT_MAP); } #[no_mangle] fn on_load() { ScExports::export(&EXPORT_MAP); } pub struct CallIncrementContext { state: MutableIncCounterState, } fn func_call_increment_thunk(ctx: &ScFuncCont...
Rust
0
_) => NormMeta::Plain, Meta::NameValue(nv) => NormMeta::Lit(nv.lit), Meta::List(ml) => if let Some(nm) = util::match_singleton(ml.nested) { match nm { NestedMeta::Literal(lit) => NormMeta::Lit(lit), NestedMeta::Meta(Meta::Word(word)) => NormMeta::Word(word), ...
Rust
0
t.session_state.messages.append({"role": "user", "content": prompt}) # Display user message with st.chat_message("user"): st.markdown(prompt) # Call API to get response with st.spinner("Thinking..."): try: response = requests.post...
Python
1
_10_iters() { let initial_state = vec![3, 4, 3, 1, 2]; let count = simulate_iters(&initial_state, 10); assert_eq!(count, 12); } #[test] fn correct_list_of_numbers_after_18_iters() { let initial_state = vec![3, 4, 3, 1, 2]; let count = simulate_iters(&initial_state...
Rust
0
let s = self .to_hash_map() .iter() .map(|(k, v)| k.clone() + "=\"" + v + "\"\n") .collect::<String>(); write!(f, "{}", s) } } #[doc = "Reader of register OSC_CONFIG0_CLR"] pub type R = crate::R<u32, super::OSC_CONFIG0_CLR>; #[doc = "Writer for register OSC_CO...
Rust
0
# Copyright 2022 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
1
x2box_transform, pred_class_logits, pred_proposal_deltas, proposals, smooth_l1_beta ) with EventStorage(): # capture events in a new storage to discard them losses = outputs.losses() # Note: the expected losses are slightly different even if # the boxes are essentially the ...
Python
1
straight(); self.throttle_down(); self.send_controls().await } pub fn steer_straight(&mut self) { self.controls.steering = 0.; } pub fn steer_right(&mut self) { if self.controls.steering < 0. { self.controls.steering = 0.; } if self.controls....
Rust
0
import anyio import typing _T = typing.TypeVar("_T") _V = typing.TypeVar("_V") async def map_async( func: typing.Callable[[_T], typing.Awaitable[_V]], items: typing.Iterable[_T], *, max_concurrent: int = 10, ) -> list[_V]: semaphore = anyio.Semaphore(max_concurrent) results = dict[int, _V]() ...
Python
1
class Solution: def checkZeroOnes(self, s: str) -> bool: longestOnes = 0 longestZeros = 0 currentOnes = 0 currentZeros = 0 for c in s: if c == '0': currentOnes = 0 currentZeros += 1 longestZeros = max(longestZeros, currentZeros) else: currentZeros = 0 ...
Python
1
''' Criado por: Gui Castro 26/01/2025 Faça um programa que leia 5 números e os guarde em uma lista. No final mostre o maior e o menor valor e suas posições. Se tiver mais de um mostrar as duas posições ''' ''' print('=====Maior & Menor Na Lista=====') lista = [] maior = menor = 0 for i in range(1, 6): lista.appen...
Python
1
.read() as u32 } pub unsafe fn write_port_u8(port: u32, val: u32, _: &VmCtx) { Port::<u8>::new(port as u16) .write(val as u8); } #[cfg(feature = "vm-wasmtime")] mod wasmtime; #[cfg(feature = "vm-wasmtime")] pub use self::wasmtime::{engine as wasmtime_engine, LunaticLinker as WasmtimeLunaticLinker}...
Rust
0
import pytest import torch from espnet2.layers.utterance_mvn import UtteranceMVN def test_repr(): print(UtteranceMVN()) @pytest.mark.parametrize( "norm_vars, norm_means", [(True, True), (False, False), (True, False), (False, True)], ) def test_forward(norm_vars, norm_means): layer = UtteranceMVN(no...
Python
1
def extract_geometry(self, bound_min, bound_max, resolution, threshold=0.0): return extract_geometry(bound_min, # extract geometry # bound_max, resolution=resolution, threshold=threshold, ...
Python
1
from collections import defaultdict def create_header_table(transactions, min_sup): """ Create a header table for frequent items. """ item_freq = defaultdict(int) for transaction in transactions: for item in transaction: item_freq[item] += 1 header_table = {item: (item_freq[...
Python
1
=> value & 0x0F, } } /// Creates an extended rcode value from its parts. pub fn from_parts(rcode: Rcode, ext: u8) -> OptRcode { OptRcode::from_int(u16::from(ext) << 4 | u16::from(rcode.to_int())) } /// Returns the two parts of an extended rcode value. pub fn to_parts(self) -> ...
Rust
0
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: if len(s1)>len(s2): return False s1Count,s2Count=[0]*26,[0]*26 for i in range(len(s1)): s1Count[ord(s1[i])-ord("a")]+=1 s2Count[ord(s2[i])-ord("a")]+=1 matches=0 for i in r...
Python
1
0, // iters_unscaled ); bench( "10k_bgra", &mut dst[..], include_bytes!("../../../test/data/hat.gif"), i == 0, // warm_up 90 * 112 * 4, // want_num_bytes 100, // iters_unscaled ); bench( "10k_indexed", ...
Rust
0
_si128_from_u32(buf: &[U8x4], index: usize) -> __m128i { let v: i32 = transmute(*buf.get_unchecked(index)); _mm_cvtsi32_si128(v) } #[inline(always)] pub unsafe fn mm_cvtsi32_si128_from_u8(buf: &[U8], index: usize) -> __m128i { let ptr = buf.get_unchecked(index..).as_ptr() as *const i32; _mm_cvtsi32_si1...
Rust
0
ance_edit=True, prompt=args.prompt, guidance_scale=args.guidance_scale, num_inference_steps=args.num_inference_steps ) recon_image_e = pipe( prompt=args.prompt, num_inference_steps=args.num_inference_steps, guidance_scale=args.guidance_scale, latents=inv_r...
Python
1
gentState) # Define the nodes workflow.add_node("triage", _node_question_triage) # retrieve workflow.add_node("retrieve", _node_call_retriever) # retrieve workflow.add_node("grade_recipes", _node_grade_recipes) # grade documents workflow.add_node("generate", _node_generate_response) # generatae...
Python
1
libc::c_float, pub z_bias: libc::c_float, } #[repr(C)] pub struct unknown_1758 { pub x: libc::c_float, pub y: libc::c_float, pub z: libc::c_float, } #[repr(C)] pub struct unknown_1759 { pub azimuth: libc::c_float, ...
Rust
0
(|param| match param { GenericParam::Type(ty) => { let name = &ty.ident; let pred: WherePredicate = parse_quote! { #name: ::std::clone::Clone }; Some(pred) } GenericParam::Lifetime(_) | GenericParam::Const(_) => None, })); ...
Rust
0
e timestamp future_info = { "source": "flare_docs", "timestamp": int(time.time()) + 86400, # 1 day in the future "content": "Future content" } future_score = trust_calculator.calculate_trust_score(future_info) assert 0 <= future_score <= 1, "Future timestamp should return a vali...
Python
1
vec![RAM_BEGIN], vec![0xAB; RAM_BYTE_COUNT], )]); let mut data = [0; RAM_BYTE_COUNT]; rtc.read_ram(0, &mut data).unwrap(); for d in data.iter() { assert_eq!(0xAB, *d); } destroy(rtc); } #[test] fn can_read_last_ram_address() { let mut rtc = new(&[I2cTrans::write_read(...
Rust
0
} #[test] fn test_linked_dynamic_libraries_missing_1() { let linked = LinkedDynamicLibraries::parse(LDD_OUTPUT_MISSING_1); assert_eq!(linked.libraries.len(), 3); assert_eq!(linked.libraries["libmycode.so"], None); assert_eq!( linked.libraries["libpthread.so.0"], Some("/lib/x86_64-linu...
Rust
0
#!/usr/bin/env python3 # pylint: disable=C0301,C0116,C0103,R0903 """ This script was created by Coopydood as part of the ultimate-macOS-KVM project. It will not work outside of this project. https://github.com/user/Coopydood https://github.com/Coopydood/ultimate-macOS-KVM Signature: 4CD28348A3DD016F """ import os ...
Python
1
_nonce[..]), Error::InvalidNonce(MessageNumber::Message1.into()) ); // IEEE Std 802.11-2016, 12.7.2 f) // IEEE Std 802.11-2016, 1172.16.17.32 rsn_ensure!( is_zero(&frame.key_frame_fields.key_iv[..]), Error::InvalidIv(frame.eapol_fields.version, MessageNumber::Message1.into()) ...
Rust
0
import importlib.util from app.portfolio_manager import Portfolio spec = importlib.util.spec_from_file_location("flask_app", "app.py") flask_app = importlib.util.module_from_spec(spec) spec.loader.exec_module(flask_app) manager = flask_app.manager def main(): p = Portfolio("ExportTest", "key", "secret", "https:/...
Python
1
semantics are such that the /// skb has been “consumed” or queued but certainly not “dropped”. /// cf) <https://docs.cilium.io/en/latest/bpf/#tc-traffic-control> Stolen = 4, /// Allow to redirect the skb to the same or another’s device ingress or /// egress path together with the bpf_redirect() hel...
Rust
0
fn get_df(&mut self) -> &mut HashMap<Uint256, Vec<DirEntry>>{ &mut self.duplicate_files } fn show_duplicates(&self) -> () { if self.duplicate_files.len() != 0 { let itr = self.duplicate_files.iter(); for x in itr{ let vec: Vec<DirEntry> = x.1.to_ve...
Rust
0
tchguide/match-rulesets.html">Build a rule /// set</a> /// </p> /// </li> /// <li> /// <p> /// <a href="https://docs.aws.amazon.com/gamelift/latest/flexmatchguide/match-configuration.html">Design a /// matchmaker</a> /// </p> /// </li> /// <li> /// <p> /// <a href="https://docs.aws.amazon.com/gamelift/latest/flexmatchg...
Rust
0
prefer_socket: true, keepalive_timeout: Some(60 * 60), verify_peer: false, ssl_opts: None, } } } #[cfg(not(feature = "ssl"))] impl Default for MyOpts { fn default() -> MyOpts { MyOpts{ tcp_addr: Some("127.0.0.1".to_string()), tcp_port:...
Rust
0
# excludes symlinks of regular files to avoid reporting on the same file multiple times # in the future it would be nice to merge any coverage for symlinks into the real files for target in walk_func(include_symlinks=False): target_path = os.path.abspath(target.path) target_line...
Python
1
class ModelPath(object,IDisposable): """ A path to a file stored on a disk or on a server. """ def Compare(self,otherPath): """ Compare(self: ModelPath,otherPath: ModelPath) -> int Compares this ModelPath with another otherPath: The path to compare against. Returns: A signed integer indicating...
Python
1
Params) # task.start() # # # # lng_lat = ee.Geometry.Point(lng, lat) # naip = collection.filterBounds(polys) # naip_2015 = naip.filterDate('2015-01-01', '2015-12-31') # ppr = naip_2015.mosaic() # # count = naip_2015.size().getInfo() # print("Count: ", count) # # # print(naip_2015.size().getInfo()) # vis = {'b...
Python
1
/// If set, the image is read in any possible color format. pub const IMREAD_ANYCOLOR: i32 = 4; /// If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. pub const IMREAD_ANYDEPTH: i32 = 2; /// If set, always convert image to the 3 channel BGR color image. pub con...
Rust
0
n, |_node, res| { assert!(res); }); } } <gh_stars>0 #![ cfg(all( feature = "async_global", not(target_os = "unknown") )) ] // Tested: // // ✔ pass a AsyncGlobal to a function that takes exec: `impl Spawn` // ✔ pass a &AsyncGlobal to a function that takes exec: `&impl Spawn` // ✔ pass a...
Rust
0
{ pk.save(w); } } if !self.attributes.is_empty() { save8(w, &TAG_ATTR); for cell in &self.attributes { cell.save(w); } } if self.is_delete_marker { save8(w, &TAG_DELETE_ROW_MARKER); } ...
Rust
0
} } impl From<char> for Codepoint { fn from(ch: char) -> Self { Self::Scalar(ch) } } impl Into<u32> for Codepoint { fn into(self) -> u32 { match self { Codepoint::Scalar(ch) => ch.into(), Codepoint::EndOfFile => 0xffffffff, } } } impl TryInto<char> fo...
Rust
0
y_e = 0x05; pub static CSS_DISPLAY_TABLE: css_display_e = 0x06; pub static CSS_DISPLAY_INLINE_TABLE: css_display_e = 0x07; pub static CSS_DISPLAY_TABLE_ROW_GROUP: css_display_e = 0x08; pub static CSS_DISPLAY_TABLE_HEADER_GROUP: css_display_e = 0x09; pub static CSS_DISPLAY_TABLE_FOOTER_GROUP: css_dis...
Rust
0
_guardar_equipos(equipos) _refrescar_listbox() def _eliminar_equipo(): equipo = _seleccionar_equipo() if not equipo: return # Permitir al admin eliminar cualquier equipo if not is_admin and usuario_actual != equipo["creador"]: messagebox.show...
Python
1
use std::collections::HashMap; const DB_DIRECTORY: &str = "./tests/database/milestone_index_to_receipt"; #[tokio::test] async fn milestone_index_to_receipt_access() { let _ = std::fs::remove_dir_all(DB_DIRECTORY); let config = RocksDbConfigBuilder::default().with_path(DB_DIRECTORY.into()).finish(); let...
Rust
0
import streamlit as st from database.db_adapter import get_profile, upsert_profile def render_profile_form(): st.sidebar.markdown("## 👤 个人档案") prof = get_profile() with st.sidebar.form("profile_form"): name = st.text_input("姓名", prof.get("name", "")) gender= st.selectbox("性别", ["男","女","...
Python
1
Less), (Datum::Min, Datum::Min, Ordering::Equal), ( Datum::Json(Json::from_str(r#"{"key":"value"}"#).unwrap()), Datum::Json(Json::from_str(r#"{"key":"value"}"#).unwrap()), Ordering::Equal, ), (Datum::I64(18), Datum::Json(Jso...
Rust
0
from django.urls import include, path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from .views import CommentViewSet, GroupViewSet, PostsViewSet v1_router = DefaultRouter() v1_router.register('posts', PostsViewSet, basename='post') v1_router.register('groups', GroupViewS...
Python
1
")] pub fn x11_device_get_id(device: &X11DeviceXI2) -> i32 { skip_assert_initialized!(); unsafe { ffi::gdk_x11_device_get_id(device.to_glib_none().0) } } #[doc(alias = "gdk_x11_device_manager_lookup")] pub fn x11_device_manager_lookup( device_manager: &X11DeviceManagerXI2, device_id: i32, ) -> Option<X...
Rust
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class StockMove(models.Model): _inherit = 'stock.move' def _should_force_price_unit(self): self.ensure_one() return self.is_subcontract or super()._should_force_price_un...
Python
1
from fluent.syntax import ast from fluentast import FluentAstMessage from fluentastcomparer import FluentAstComparer from fluentastmanager import FluentAstManager class LokaliseFluentAstComparerManager: def __init__(self, sourse_parsed: ast.Resource, target_parsed: ast.Resource): self.sourse_parsed = so...
Python
1
pub fn remote_addr(&self) -> Option<&SocketAddr> { self.remote_addr.as_ref() } pub fn extend(&mut self, other_req_meta: RequestMeta) { if let Some(other_ra) = other_req_meta.remote_addr { self.remote_addr = Some(other_ra) } if let Some(other_pm) = other_req_meta...
Rust
0
asmiBytes(Vec<u8>); impl WasmiBytes { pub fn new(raw_bytes: &[u8], wasm_costs: WasmCosts) -> Result<Self, engine_state::Error> { let mut ret = vec![]; let wasmi_preprocessor: WasmiPreprocessor = WasmiPreprocessor::new(wasm_costs); let module = wasmi_preprocessor.preprocess(raw_bytes)?; ...
Rust
0
", {}).get("summary", "No summary") status = issue.get("fields", {}).get("status", {}).get("name", "Unknown") print(f" - {key}: {summary[:50]}... [{status}]") return True else: print(f"❌ JQL query failed: {response.status_code}") ...
Python
1
TFACE: Self = IndirectStateFlagsNV(0b1); } #[repr(transparent)] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[doc = "<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkDescriptorSetLayoutCreateFlagBits.html>"] pub struct DescriptorSetLayoutCreateFlags(pub(crate) Flags); vk_bitflag...
Rust
0
import pandas as pd from datetime import datetime, timezone, timedelta import sqlite3 br_tz = timezone(timedelta(hours=-3)) tp_ocorrencia_dict = { "1": "Via Pública", "2": "Endereço Residência", "3": "Outro Domicílio", "4": "Estabelecimento Comercial", "5": "Outros", "9": "Ignorado" } data = [...
Python
1
ult=uuid4) date = models.DateTimeField(auto_now_add=True, db_index=True, editable=False) type = models.CharField(max_length=255, choices=PromotionEvents.CHOICES) parameters = JSONField(blank=True, default=dict, encoder=CustomJsonEncoder) user = models.ForeignKey( settings.AUTH_USER_MODEL, ...
Python
1
pub device_display_name: Option<String>, } impl UnsignedDeviceInfo { /// Creates an empty `UnsignedDeviceInfo`. pub fn new() -> Self { Default::default() } /// Checks whether all fields are empty / `None`. pub fn is_empty(&self) -> bool { self.device_display_name.is_none() } } ...
Rust
0
# attempt to make trajectories for Oakley plot without obstacles import numpy as np import matplotlib.pyplot as plt from scipy.integrate import solve_ivp # defining V(x,y) function def V(x,y): return (1-y*x)**2/(x*(np.arctan((x-y)/4)/np.pi+1/2)+y*(np.arctan((y-x)/4)/np.pi+1/2))**2 # setting initial conditions f...
Python
1
ases, &mut failurecases, $f,stringify!($f));)* rsgx_unit_test_end(ntestcases, failurecases) } } } /// A prologue function for Rust SGX unit testing. /// /// To initiate the test environment, `rsgx_unit_tests!` macro would trigger /// `rsgx_unit_test_start` at the very beginning. `rsgx_unit_test...
Rust
0
# -*- coding: utf-8 -*- # # Copyright (c) 2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ SPDX document formatting """ # document level strings spdx_version = 'SPDX-2.2' data_license = 'CC0-1.0' spdx_id = 'SPDXRef-DOCUMENT' document_name = 'Tern report for {image_name}' document_co...
Python
1
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Generate the signal def generate_data(length=2500, t=0, step_size=0.05): for count in range(length): t += step_size signal = np.sin(2*np.pi*t) damper = np.exp(-t/8.0) yield t, signal * damp...
Python
1
store.upsert(&(key as u64), &value, key); } let checkpoint = store.checkpoint_hybrid_log(); assert!(checkpoint.is_err(), "Checkpoint should fail"); match checkpoint.err().unwrap() { FasterError::InvalidType => assert!(true), _ => assert!(false, "Should give InvalidType Error"), ...
Rust
0
{ pub(crate) fn new(bits: bool) -> Self { DATA_TX_WIDTH_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DATA_TX_WIDTH_A { match self.bits { false => DATA_TX_WIDTH_A::VALUE1, true => DATA_T...
Rust
0
= slice( 0, src_nbits ) s.id = DstT(id) NetReq = mk_req_msg ( Req, num_responders ) NetResp = mk_resp_msg( Resp, num_requesters ) # Interface s.minion = MinionIfcRTL( NetReq, NetResp ) s.master = MasterIfcRTL( Req, Resp ) # Logic s.minion.req.rdy //= s.master.req.rdy s....
Python
1
# MIT License # Copyright (c) 2024 The HuggingFace Team # 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 without limitation the rights # to use, copy, modify, ...
Python
1
.unsqueeze(0) .unsqueeze(0) .unsqueeze(0) / 255.0 ) # Generate video video = pipe( ref_image_pil, audio_path, face_mask_tensor, args["W"], ar...
Python
1
age = int(input("Enter your age: ")) if age >= 100: print("You are a centenarian!") elif age >= 18: print("You are now signed up") elif age <= 0: print("You are not born yet") else: print("You are not eligible to sign up")
Python
1
client,available,held,total,locked"); //iterate over hashmap and output result to stdout //this could probably be faster if using something other than println! or format! for (key, val) in accounts { println!( "{},{},{},{},{}", key, if val.available == Decimal::ZE...
Rust
0
= layout.column() col = c.column(align=True) col.label(text="Collision Group Mask:") row = col.row(align=True) for i in range(8): row.prop(obj.mmd_rigid, "collision_group_mask", index=i, text=str(i), toggle=True) row = col.row(align=True) ...
Python
1
ample input PROJECT_DIR: ./results/treble/single_experiments/ # Example folders inside: aes_absorptioncoeffs/, aes_simtypes_scattering/, aes_sdn_treblehybrid/ experiments_by_source, folder_names_by_source = process_all_treble_sources(PROJECT_DIR, is_singular=IS_SINGULAR) # Save processed data b...
Python
1
bose_build) # pylint: disable=protected-access cached_build_dir = os.path.join(build_top_dir, f'{source_digest}-{_get_mangled_gpu_name()}') if not os.path.isdir(cached_build_dir): tmpdir = f'{build_top_dir}/srctmp-{uuid.uuid4().hex}' os.makedirs(tmpdir) ...
Python
1
_header) .use_core() .whitelist_recursively(false) .whitelist_var("SGX_.*") .whitelist_type("_attributes_t") .whitelist_type("_key_request_t") .whitelist_type("_report_body_t") .whitelist_type("_report_t") .whitelist_type("_sgx_cpu_svn_t") .whiteli...
Rust
0
import re import jinja2 import numpy as np from pysisyphus.constants import ANG2BOHR from pysisyphus.Geometry import Geometry from pysisyphus.helpers_pure import file_or_str @file_or_str(".crd") def parse_crd(crd): lines = [l.strip() for l in crd.strip().split("\n") if not l.startswith("*")] expect_line = l...
Python
1
# -*- coding: utf-8 -*- """ Created on Mon Sep 1 14:56:27 2025 @author: kayvon.daie """ gi = 4; cl = np.argsort(stimDist[:,gi])[0] plt.subplot(121) plt.plot(favg[10:55,cl,gi]) cl = np.where((stimDist[:,gi]>30) & (AMP[1][:,gi]>.15))[0] plt.subplot(122) plt.plot(favg2[10:55,cl[0],gi]) plt.plot(favg1[10:55,cl[0],gi]) ...
Python
1
s xml_file: data_dict = xmltodict.parse(xml_file.read()) with open(args.path_to_model[:-3] + "bin", "rb") as bin_file: output_data = get_layers_info(data_dict, bool(args.remove_duplicates), bool(args.sort), bool(args.read_constants), bin_file) with open(ar...
Python
1
from opencompass.openicl.icl_prompt_template import PromptTemplate from opencompass.openicl.icl_retriever import ZeroRetriever from opencompass.openicl.icl_inferencer import GenInferencer from opencompass.datasets import MastermathDatasetv1, MastermathDatasetv1Evaluator from opencompass.utils import first_option_postpr...
Python
1
= "big")] pub struct Udp { pub sport: u16, pub dport: u16, pub length: u16, pub checksum: u16, } impl Udp { pub fn update_checksum_ipv4(&mut self, ipv4: &Ipv4, data: &[Layer]) -> Result<(), LayerError> { let mut data_buf = Vec::new(); for layer in data { data_buf.extend(...
Rust
0
} pub struct StatusJob { pub status: Status, pub commit: Commit, } pub struct PullRequestJob { pub owner: String, pub repo: String, pub number: usize, pub head_sha: String, } impl fmt::Debug for PullRequestJob { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( ...
Rust
0
= 2147483648, } pub use self::_bindgen_ty_9 as VAEncPackedHeaderType; /** \brief Packed header parameter. */ #[repr(C)] #[derive(Debug, Copy)] pub struct _VAEncPackedHeaderParameterBuffer { /** Type of the packed header buffer. See #VAEncPackedHeaderType. */ pub type_: ::std::os::raw::c_uint, /** \brief Si...
Rust
0
ERROR: type should be string, got "https://www.interviewbit.com/problems/variables-and-types/\n\ndef main():\n # Assign values to the following variable as described above\n # Don't change the variable name\n my_string1 = \"InterviewBit\"\n my_string2 = \"Don't change the variable name\"\n my_int = 11\n my_float = 20.0\n \n # Don't change the below code\n print(\"String1: %s\" % my_string1)\n print(\"String2: %s\" % my_string2)\n print(\"Integer: %d\" % my_int)\n print(\"Float: %f\" % my_float)\n return 0\n\nif __name__ == '__main__':\n main()\n"
Python
1
) def label_loss_items(self, loss_items=None, prefix="train"): """ Returns a loss dict with labelled training loss items tensor. Not needed for classification but necessary for segmentation & detection """ keys = [f"{prefix}/{x}" for x in self.loss_names] if l...
Python
1
""" return self._call( f"refresh-tokens/{refresh_token or self.refresh_token}", **options ) def delete_refresh_token(self, refresh_token: Optional[str] = None): """ Deletes a refresh token. You can use this to delete your refresh token if a user uninstalls your ...
Python
1