text
string
label_name
string
labels
int64
::impl_dyn_hash!(GlobalAvgPool); impl Expansion for GlobalAvgPool { fn name(&self) -> Cow<str> { "GlobalAvgPool".into() } op_hir!(); fn rules<'r, 'p: 'r, 's: 'r>( &'s self, solver: &mut Solver<'r>, inputs: &'p [TensorProxy], outputs: &'p [TensorProxy], ) ->...
Rust
0
}); /// ~~~ pub fn with_window_mode<T, F>(&self, f: F) -> T where F: FnOnce(WindowMode<'_>) -> T, { let ptr = unsafe { ffi::glfwGetWindowMonitor(self.ptr) }; if ptr.is_null() { f(WindowMode::Windowed) } else { f(WindowMode::FullScreen(&Monitor { pt...
Rust
0
} MaterialVariants::Lambertian(albedo) => lambertian_scatter(normal, point, albedo), MaterialVariants::Dielectric(ref_idx) => { dielectric_scatter(incoming_ray, normal, point, face, *ref_idx) } } } } <filename>src/test/run-make-fulldeps/std-co...
Rust
0
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" __version__ = "1.82.1" # x-release-please-version
Python
1
def __getattr__(name: str = "") -> None: """Raise an error on import since is deprecated.""" msg = ( "This module has been moved to langchain-experimental. " "For more details: https://github.com/langchain-ai/langchain/discussions/11352." "To access this code, install it with `pip instal...
Python
1
('loc_E6DA') SetScenaFlags(ScenaFlag(0x0888, 0, 0x4440)) def _loc_E6DD(): pass label('loc_E6DD') SetScenaFlags(ScenaFlag(0x0887, 7, 0x443F)) SetScenaFlags(ScenaFlag(0x08A1, 1, 0x4509)) QuestCmd(0x0025, 0x03, 0x01, 0x02) Jump('loc_E6EE') def _loc_E6EE(): pass label('loc_E6EE') ...
Python
1
R(RR&((s xdrlib.pyRyscCs||_d|_dS(Ni(t_Unpacker__buft_Unpacker__pos(RR&((s xdrlib.pyR|s cCs|jS(N(R6(R((s xdrlib.pyt get_positions...
Python
1
# MIT licensed # Copyright (c) 2024 Jakub Ružička <jru@debian.org>, et al. import asyncio import gzip import pathlib import urllib from typing import Set try: from compression import zstd # type: ignore zstd_decompressor = zstd.decompress except ImportError: import zstandard def zstd_decompressor(data): dc...
Python
1
anchor_util::cert_der_as_trust_anchor; static CERT_PATH: &'static str = "/config/ssl/cert.pem"; lazy_static! { // To meet the required lifetime constraints we need to chain together // a series of statics. static ref RAW_DATA: String = { // I could have an environment variable override this, but i...
Rust
0
ptr.USART1; if rcc.apb2enr.read().usart1en().is_enabled() == true { rprintln!("U(S)ART{} is already configured! | UART::new()", core); return Err(ProgError::InvalidConfiguration); } rcc.apb2enr.modify(|_, w| w.usart1en().enabled()); set_baud(core, baud); if co...
Rust
0
from settings import FAIRESEQ_LANGUAGE_MAP class Seq2seqTokenizer: def __init__(self, tokenizer, src_lang, tgt_lang, max_length): self.tokenizer = tokenizer self.set_tokenizer_lang(src_lang, tgt_lang) self.max_length = max_length def set_tokenizer_lang(self, src_lang, tgt_lang): ...
Python
1
def brain_to_ogocode(code:str): braincodelist = list(code) ogocode = "" for i in range(len(braincodelist)): if braincodelist[i] == "[": ogocode += " フンギャロ" elif braincodelist[i] == "]": ogocode += " ふぬんも" elif braincodelist[i] == ",": ogocode += " ...
Python
1
} impl IndexBuffer { pub fn new(context: &Context, indices: &Indices) -> ThreeDResult<Self> { Ok(match indices { Indices::U8(ind) => IndexBuffer::U8(ElementBuffer::new_with_data(context, ind)?), Indices::U16(ind) => IndexBuffer::U16(ElementBuffer::new_with_data(context, ind)?), ...
Rust
0
-> &Self { self.datahu_reg().write(value); self } #[doc="Set the DATAHU register."] #[inline] pub fn set_datahu<F: FnOnce(Datahu) -> Datahu>(&self, f: F) -> &Self { self.datahu_reg().set(f); self } #[doc="Modify the DATAHU register."] #[inline] pub fn with_dat...
Rust
0
) # Force aspect ratio f.show_grayscale() f.hide_grayscale() f.ticks.set_color('black') f.recenter(266.5, -29.0, width=0.1, height=0.1) f.axis_labels.set_xpad(20) f.axis_labels.set_ypad(20) return f # Test overlaying contours @figure_test de...
Python
1
l regression line and log axes. """ all_selected = any(r.lower() == "all" for r in repos) if not all_selected: df = df[df["repo"].isin(repos)] if window and window.lower() != "all": df = df[df["period_type"] == window] # Ensure metrics are numeric df = df.copy() df[metric_x]...
Python
1
pub position: Vec3, pub target: Vec3, pub fov: f32, pub near_clip: f32, pub far_clip: f32, } /* camera* camera_new(); void camera_delete(camera* cam); vec3 camera_direction(camera* c); mat4 camera_view_matrix(camera* c); mat4 camera_proj_matrix(camera* c); mat4 camera_view_proj_matrix(camera* c); void camer...
Rust
0
rt *\n") f.write(f"except Exception as e:\n") f.write(f" print(f'導入 {module_name} 失敗: {{e}}')\n") return str(task_dir) def run_task(task_dir, requires_gpu): def kill_process_tree(pid): try: process = psutil.Process(pid) for child in process.childr...
Python
1
x = [10,20,30] for e in x: if not e: pass print(e) # pass statment does nothing. This statment in # python is used for empty block of statement{s}
Python
1
try_point)] pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::VestingInfo {} => to_binary(&vesting_account(deps, env)?), } } fn vesting_account(deps: Deps, env: Env) -> StdResult<VestingInfoResponse> { let config: Config = CONFIG.load(deps.storage)?; ...
Rust
0
u64::<NetworkEndian>(), expiration: buf.get_u32::<NetworkEndian>(), }) } fn write<T: BufMut>(&self, buf: &mut T) -> io::Result<()> { buf.put_u64::<NetworkEndian>(self.amount); buf.put_u64::<NetworkEndian>(self.initial); buf.put_u32::<NetworkEndian>(self.expiration); ...
Rust
0
ath.exists(parent_dir): if not new_path: if new_file_name: new_abs_path = f"{parent_dir}/{new_file_name}" else: new_abs_path = old_abs_path else: if new_file_name: new_abs_path = f"{new_pa...
Python
1
if let Some(sent_timestamp) = sync_state.broadcast_info.sent_batches.remove(&batch_id) { // track broadcast roundtrip latency let rtt = timestamp .duration_since(sent_timestamp) .expect("failed to calculate mempool broadcast RTT"); counters::SH...
Rust
0
ChangeType::Deleted, ); let files_changed_notification = notification::<DidChangeWatchedFiles>(DidChangeWatchedFilesParams { changes: vec![delete_event], }); send_messages(&client_conn, vec![files_changed_notification]); main_loop(&mut global_state, &server_conn).unwrap(); ...
Rust
0
M.m[1][3] = 0.0; M.m[2][0] = 0.0; M.m[2][1] = 0.0; M.m[2][2] = 1.0; M.m[2][3] = 0.0; M.m[3][0] = Offset.vector4_f32[0]; M.m[3][1] = Offset.vector4_f32[1]; M.m[3][2] = Offset.vector4_f32[2]; M.m[3][3] = 1.0; return M; } #[cfg(any...
Rust
0
nmdCreate(conf) } { val if !val.is_null() => Some(MiniDFS { cluster: val }), _ => None, } } fn stop(&self) { // remove hdfs from global cache HdfsFs::remove(self.namenode_addr().as_str()).ok(); unsafe { nmdShutdownClean(self.cluster); ...
Rust
0
name = ["Jakub", "Tom", "Dan", "Jiří", "Miluška", "Petr", "Matěj", "Lukáš", "Adam", "Kuba"]
Python
1
BITS(1) [ /// Disabled. Buffer disabled (POR reset value). DisabledBufferDisabledPORResetValue = 0, /// Enabled. Buffer enabled. EnabledBufferEnabled = 1 ], /// Write protect. P OFFSET(20) NUMBITS(1) [ /// None. Writes not protected (POR reset value). NoneWrit...
Rust
0
) ); } { let mut shred = shred.clone(); shred.common_header.index = MAX_DATA_SHREDS_PER_SLOT as u32; assert_matches!( shred.sanitize(), Err(Error::InvalidShredIndex(ShredType::Data, 32768)) ); } {...
Rust
0
#!/usr/bin/env python ############################################################################### # Copyright 2018 The Apollo Authors. 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 ...
Python
1
[1, 1]] .iter() .map(|c| c.clone().into()) .collect::<Vec<Coord>>(), ) } fn explore(maze: &Maze, key_doors: &KeyDoor, cursors: &[Coord]) -> Result<u64, String> { println!( "{}", maze.display_with_overlay(|coord| key_doors.get(coord).map(|(c, _)| *c)) ); ...
Rust
0
"""Benchmark the Black-Scholes solver on a standard grid.""" import os import sys import numpy as np import pytest sys.path.append(os.path.dirname(os.path.dirname(__file__))) from src.core.dynamics_black_scholes import ( DynamicsParametersBlackScholes, ) from src.core.market import Market from src.core.vanilla_b...
Python
1
Access); let result = ribosome.run_init(host_access, init_invocation).unwrap(); assert_eq!( result, InitResult::Fail(TestWasm::InitFail.into(), "because i said so".into()), ); } #[tokio::test(threaded_scheduler)] async fn test_init_multi_implemented_fail() { ...
Rust
0
import os from datetime import datetime, timedelta, timezone from fastapi import HTTPException, status from jose import JWTError, jwt class JwtService(object): access_token_expire_minutes = 1 # 30 refresh_token_expire_minutes = 60 * 24 * 30 access_token_key = os.getenv("ACCESS_TOKEN_KEY") refresh_t...
Python
1
import copy from typing import TYPE_CHECKING import interactions.api.events as events from ._template import EventMixinTemplate, Processor if TYPE_CHECKING: from interactions.api.events import RawGatewayEvent __all__ = ("VoiceEvents",) class VoiceEvents(EventMixinTemplate): @Processor.define() async de...
Python
1
import torch.nn as nn from model.conv_sn_chen import conv_spectral_norm from model.bn_sn_chen import bn_spectral_norm class DnCNN(nn.Module): def __init__(self, channels, num_of_layers=17, lip=1.0, no_bn=False): super(DnCNN, self).__init__() kernel_size = 3 padding = 1 features = 64...
Python
1
(candidate): cross_link.adjustRelativeLinks(candidate) candidate.addObject(cross_link) if candidate.ViewObject: cross_link.ViewObject.ShowReal = candidate.ViewObject.ShowReal cross_link.ViewObject.ShowVisual = candidate.ViewObject.S...
Python
1
() || builder_version.is_empty() { failure!("Args java version, builder or builder version is not assigned or format error."); return; } let mut build_json_object = object!{ "java" => java_version, "builder" => object! { "name" => builder, "version" => bui...
Rust
0
.map(|line| parse::completely(parse)(line)) .collect::<io::Result<_>>()?; let mut velocities = Vec::new(); velocities.resize(moon_coordinates.len(), 0); let moons = Moons { positions_x: moon_coordinates .iter() .map(|(x, _, _)| x) .cloned() .c...
Rust
0
()`](Paint::enable()) /// * [`Paint::disable()`](Paint::disable()) /// * [`Paint::is_enabled()`](Paint::is_enabled()) /// * [`Paint::enable_windows_ansi()`](Paint::enable_windows_ansi()) #[derive(Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] pub struct Paint<T> { item: T, style: Style, } m...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
""" Created on Thu Jan 28 23:35:27 2021 @author: Mohamad Sayegh & Elias Rached """ import matplotlib.pyplot as plt from a_star import AStarPlanner import numpy as np def is_inside(circle_x, circle_y, radius, x, y): d = (x-circle_x)**2 + (y-circle_y)**2 if (d <= radius**2): return 1; ...
Python
1
.tutorial_book_id() > 0, "have tutorial again" service.delete_demo_data() assert service.tutorial_book_id() is None, "no tutorial" # Loading. @pytest.mark.dbreset def test_rebaseline(service): """ This test is also used from "inv db.reset" in tasks.py (see .pytest.ini). """ assert servi...
Python
1
import argparse import sillm import sillm.utils as utils if __name__ == "__main__": # Parse commandline arguments parser = argparse.ArgumentParser(description="Test models with the MMLU benchmark.") parser.add_argument("model", type=str, help="The model directory or file") parser.add_argument("--batch...
Python
1
.append("31254") resample.append("average") snw.append([1]) nosnw.append([0]) nodt.append([]) manual.append("") selection.append("closest") calibrate.append(False) eval_target.append(False) eval_cal.append(False) perc_cal.append(0.4) eval_modes.append(["all"]) #"all" and/or "separate" and/or "average" eval_res.append(...
Python
1
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.datasets import load_breast_cancer from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix, classificat...
Python
1
import torch import numpy as np from models.experimental import attempt_load from utils.datasets import letterbox from utils.general import non_max_suppression, scale_coords from utils.torch_utils import select_device class Detector: def __init__(self): self.img_size = 640 self.threshold = 0.3 ...
Python
1
as_ptr().cast(), level as i32, message.as_ptr().cast(), ); } } pub fn echo(message: impl ToString) { let message = ensure_end_with_zero(message); unsafe { zend_write.expect("function zend_write can't be null")( message.as_ptr().cast(), (messag...
Rust
0
from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, path, reverse_lazy from django.views.generic import RedirectView {% if openwisp2_firmware_upgrader %} # When using S3_REVERSE_PROXY feature of django-private-storage, # the storage back...
Python
1
import pytest import pandas.util._test_decorators as td from pandas import ( Interval, Period, Series, Timedelta, Timestamp, ) @pytest.mark.parametrize( "values, dtype, expected_dtype", ( ([1], "int64", int), ([1], "Int64", int), ([1.0], "float64", float), ...
Python
1
import numpy as np import torch from videolocator.constants import VIDEO_TOKEN_INDEX, DEFAULT_VIDEO_TOKEN, PERSON_TOKEN_INDEX import re import random def tokenizer_image_token(prompt, tokenizer, image_token_index=VIDEO_TOKEN_INDEX, return_tensors=None): tags = [DEFAULT_VIDEO_TOKEN, '<person>'] pattern = re.com...
Python
1
from dataclasses import dataclass, field from typing import Optional,List from torchkeras.tabular.config import ModelConfig @dataclass class DeepFMConfig(ModelConfig): input_embed_dim: int = field( default=32, metadata={"help": "The embedding dimension for the input categorical features. Def...
Python
1
# We now make our meta-model more interesting by adding a 'price' attribute to B, and constraints to it. mm_cs = """ # class named 'A': A:Class # class named 'B': B:Class { constraint = ``` # Price must be less than 100 get_value(get_slot(this, "price")) < 100 ...
Python
1
::ROM_PAGE * 0x0E) + 0x19FF; let max_offset = self.rom[offset_base..] .iter() .position(|&r| r == 0x21) .unwrap(); let max_id = self.rom[offset_base..(offset_base + max_offset)] .iter() .filter(|&x| *x == 0x50) .count(); (...
Rust
0
{ *self.inner.get_context() } } impl From<CfiErrorKind> for CfiError { fn from(kind: CfiErrorKind) -> CfiError { CfiError { inner: Context::new(kind), } } } impl From<Context<CfiErrorKind>> for CfiError { fn from(inner: Context<CfiErrorKind>) -> CfiError { C...
Rust
0
"Humi4z"), ("Ocean Water (5)", "Humi5z"), ("HyoiKam", "HyoiKam"), ("Shootable Eye", "Hys"), ("Shootable Eye (2)", "Hys2"), ("Hyuf1", "Hyuf1"), ("Hyuf2", "Hyuf2"), ("ITat00", "ITat00"), ("Ocean Bokoblin Platform", "Ikada"), ("Anchor", "Ikari"), ("Ice", "Ikori"), ("Ji1", "Ji1"...
Rust
0
(ogs_pfcp_pdr_t *pdr); // ogs_pfcp_rule_t *ogs_pfcp_rule_find_by_sdf_filter_id( // ogs_pfcp_sess_t *sess, uint32_t sdf_filter_id); // void ogs_pfcp_rule_remove(ogs_pfcp_rule_t *rule); // void ogs_pfcp_rule_remove_all(ogs_pfcp_pdr_t *pdr); // int ogs_pfcp_ue_pool_generate(void); // ogs_pfcp_ue_ip_t *ogs_pfcp_ue...
Rust
0
abox_vec2() { let a = Vec2::new(1.0, 7.5); let b = Vec2::new(-3.0, 2.5); let aa_box = AABox { pos: a, size: b }; let bb_box = AABox { pos: a + b, size: b, }; assert_eq!(aa_box + b, bb_box); } #[test] fn test_add_assign_aabox_vec2() { let a = Vec2::new(1.0, 7.5); let b =...
Rust
0
(); for ns in child.namespaces() { let name = ns.name().unwrap_or("None"); let uri = if ns.uri().is_empty() { "\"\"" } else { ns.uri() }; ns_list.push((name, uri)); } ...
Rust
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
#1.基于视频序列的表情跟踪 import cv2 # 读取视频文件 cap = cv2.VideoCapture('face_expression_video.mp4') # 创建人脸检测器 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # 创建光流法对象 lk_params = dict(winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS + cv2. TERM_CRITERIA_COUNT, 10, 0.03)) # 初始化特征点 old_frame ...
Python
1
<Property>, offsetfrom: i32, offsetto: i32, } fn parse_icaltimezonetransition( transition: &IcalTimeZoneTransition, ) -> Result<TimezoneTransition, CalendarError> { Ok(TimezoneTransition { properties: transition.properties.to_owned(), offsetfrom: offset_to_seconds( find_prop...
Rust
0
E) trading_data = websocket_manager.get_latest_data(DataType.TRADING_STATUS) with col1: if stock_data and "2330.TW" in stock_data: price = stock_data["2330.TW"].get("price", 0) change_pct = stock_data["2330.TW"].get("change_percent", 0) st.metric("台積電", f"${price:.1f...
Python
1
TOU, old_handler) def reloader_thread(): ensure_echo_on() if USE_INOTIFY: fn = inotify_code_changed else: fn = code_changed while RUN_RELOADER: change = fn() if change == FILE_MODIFIED: sys.exit(3) # force reload elif change == I18N_MODIFIED: ...
Python
1
# ***************************************************************************** # Copyright (c) 2019-2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions o...
Python
1
""" Configuration utilities for ChimeraAI. This module provides functions for loading and managing configuration files. """ import os import yaml from typing import Dict, Any, Optional def load_config(config_path: str) -> Dict[str, Any]: """ Load configuration from a YAML file. Args: config...
Python
1
_x) # b d h w else: B = {t: B_proj[t](task_x[t]) for t in self.tasks} if self.p.MoE_C: C = C_proj(task_x) # b d h w else: C = {t: C_proj[t](task_x[t]) for t in self.tasks} B = {t: rearrange(B[t], " b d h w -> b d (h w)...
Python
1
col_request_t::opcode`], and /// [`xcb_protocol_request_t::ext`] is [`XcbPresent::xcb_present_id()`], then the type of the request is /// [`xcb_present_query_version_request_t`]. pub const XCB_PRESENT_QUERY_VERSION: u8 = 0i32 as u8; /// The `Present::QueryVersion` request. #[derive(Copy, Clone, Debug)] #[repr(C)] pub ...
Rust
0
from pkilint import finding_filter from pkilint.cabf.serverauth import serverauth_subscriber from pkilint.etsi.asn1 import ts_119_495 as ts_119_495_asn1 class Psd2CabfServerauthValidityPeriodFilter(finding_filter.FindingDescriptionFilter): _TARGET_VALIDATIONS = { serverauth_subscriber.SubscriberValidityPe...
Python
1
"""Client library for children of Einhorn.""" import contextlib import json import os import socket class NotEinhornWorker(Exception): pass def is_worker() -> bool: """Return if this process is an Einhorn worker.""" return os.getppid() == int(os.environ.get("EINHORN_MASTER_PID", -1)) def get_socket_c...
Python
1
/// /// [`BishopArt`]: ./struct.BishopArt.html pub struct BishopResult { field: FieldXY, size: PosXY, } /// Visualizer #[derive(Debug)] pub struct BishopArt { field_w: usize, field_h: usize, map: FieldXY, pos: PosXY, } impl BishopArt { /// Creates new BishopArt instance /// /// # Arguments /// + ...
Rust
0
highhash = hash1 if lowhash in DECK_SIMILARITY_CACHE.keys(): if highhash in DECK_SIMILARITY_CACHE[lowhash].keys(): return DECK_SIMILARITY_CACHE[lowhash][highhash] return None def store_similarity(hash1, hash2, sim): if hash1 < hash2: lowhash = hash1 highhash = hash2 ...
Python
1
# # This file is part of the Chemical Data Processing Toolkit # # Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # versi...
Python
1
import os from anthropic import Anthropic from examples.medqa_multimodel.load_env import load_env_vars def test_claude_api(): """Test the Claude 3.7 API directly.""" # Load environment variables load_env_vars() # Check if API key is set api_key = os.getenv("ANTHROPIC_API_KEY") if not api_k...
Python
1
} if !stack.is_empty() { Err(Right(stack)) } else { Ok(()) } } #[aoc(day10, part1)] fn part1(input: &str) -> usize { input .lines() .filter_map(|l| check_line(l).err().and_then(|e| e.left())) .map(|c| match c { b')' => 3, b']' => 57, ...
Rust
0
lf) -> String{ return String::from(self.name) + "\n" + self.exec_path } } fn parse_config(content : &String) -> Config{ let mut conf = Config::new(); for line in content.lines(){ let parts : Vec<&str> = line.split('=').collect(); if parts.len() < 2{ continue } match parts[0]{ "name" => conf.name ...
Rust
0
EOF(fp: *mut BGZF) -> ::std::os::raw::c_int; } extern "C" { pub fn bgzf_compression(fp: *mut BGZF) -> ::std::os::raw::c_int; } extern "C" { pub fn bgzf_is_bgzf(fn_: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } extern "C" { pub fn bgzf_set_cache_size(fp: *mut BGZF, size: ::std::os::raw::c_int);...
Rust
0
_: uint32_t, _: *mut wl_resource, _: *mut wl_resource, _: *mut wl_resource, ...
Rust
0
, INTERNAL_FANOUT, LEAF_FANOUT>); fn next(&mut self) -> Option<(&'a C::Key, ValueMutRef<'a, C, INTERNAL_FANOUT, LEAF_FANOUT>)> { if self.is_empty() { None } else { let (k, v) = unsafe { self.next_unchecked() }; Some((k, v)) // coerce k from `&mut K` to `&K` ...
Rust
0
# This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for # the Earth and Planetary Sciences # Copyright (C) 2012 - 2024 by the BurnMan team, released under the GNU # GPL v2 or later. from burnman.classes.calibrant import Calibrant import numpy as np """ Zhao_2000 ^^^^^^^^^ """ class Mo(Calibra...
Python
1
# ================================================================================================= # This code is part of PyLith, developed through the Computational Infrastructure # for Geodynamics (https://github.com/geodynamics/pylith). # # Copyright (c) 2010-2025, University of California, Davis and the PyLith Dev...
Python
1
ormat::VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16; } impl VkFormat { pub const VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16_KHR: VkFormat = VkFormat::VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16; } impl VkFormat { pub const VK_FORMAT_R12X4_UNORM_PACK16_KHR: VkFormat = VkFormat::...
Rust
0
[0x0c, 0x00, 0x0c, 0x00, 0x58, 0x00, 0x00, 0x00]; let expected_buffer = [ 0x44, 0x00, 0x6f, 0x00, 0x6d, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6e, 0x00, ]; let mut context = Ntlm::new(); context.set_version(NTLM_VERSION); context.state = NtlmState::Authenticate; context.negotiate_message = So...
Rust
0
#1390 @ 778,886: 26x18 #1391 @ 256,801: 23x10 #1392 @ 916,500: 10x13 #1393 @ 856,667: 7x18 #1394 @ 103,682: 24x17 #1395 @ 727,567: 17x25 #1396 @ 52,176: 19x21 #1397 @ 453,308: 19x24 #1398 @ 238,370: 21x18 #1399 @ 724,519: 23x10 "; use test::*; use super::test_zeros_are_not_written_pb::*; #[test] fn test_zeros_are_no...
Rust
0
import math,random import random import smtplib #function to generate otp def generateotp(): return random.randint(100000, 999999) def initialize(): email = get_user_email() otp = generate_random_otp() send_mail(otp,email) print(f"Email has been sent to{otp}") get_user_otp = input("Enter O...
Python
1
ern crate failure; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } #[macro_use] extern crate serde; use futures::TryStreamExt; use pulsar::{ Authentication, Consumer, DeserializeMessage, Payload, Pulsar, SubType, TokioExecutor, }; use std::env; #[derive(Serialize, De...
Rust
0
let result = overlay.download_persistent_state_part( id, master_id, offset, max_size, peer.clone(), peer_attempt ).await; match result { Ok(next_bytes) => { part_attempt = 0; let len =...
Rust
0
ent_player.name} wins!") self.scoreboard[current_player.symbol] += 1 break if self.board.is_draw(): print("\nIt's a draw!") self.scoreboard["Draws"] += 1 break current_player = player1 if current_player == player2 ...
Python
1
f32, name: "falafel", group: "Food & Drink", subgroup: "food-prepared", is_variant: false, variants: &[], annotations: &[ #[cfg(feature = "af")] crate::Annotation { lang: "af", tts: Some("falafel"), keywords: &["falafel", "frikkadel", "keker-er...
Rust
0
lid", False) self._validate = kwargs.pop("_validate", True) self._set_property("angle", arg, angle) self._set_property("color", arg, color) self._set_property("line", arg, line) self._set_property("opacity", arg, opacity) self._set_property("outliercolor", arg, outlierco...
Python
1
observer.updateStats(file, stats) super().updateStats(file, stats) def serializeDetails(self): def tostr(t): if t[1] == 'key': return ' ' * t[0] + '/'.join(t[2]) o = [] indent = ' ' * (t[0] + 1) for item in t[2]: ...
Python
1
from datetime import datetime from mock import MagicMock from lambda_decorators import dump_json_body def test_dump_json_body_ok(): @dump_json_body def hello(example, context): return {"statusCode": 200, "body": {"foobar": 42}} assert hello({}, MagicMock()) == {"statusCode": 200, "body": '{"fooba...
Python
1
import logging import json from tqdm import tqdm from website import mails from django.core.management.base import BaseCommand from osf.models import Node, OSFUser logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def obj_gen(targets): for u_id, n_dict in targets.items(): try...
Python
1
2))], ); let witness = make_witness( &block0_hash, &faucets[0].clone().into(), &tx_builder.get_auth_data_for_witness().hash(), ); tx_builder.set_witnesses(&[witness]); } } use curl::easy::Easy; const CRATES_URL: &'static str = "https://crates.io/...
Rust
0
unit)? }; // After we built the initial `Fingerprint` be sure to update the // `fs_status` field of it. let target_root = target_root(cx); fingerprint.check_filesystem(&mut cx.mtime_cache, unit.pkg.root(), &target_root)?; let fingerprint = Arc::new(fingerprint); cx.fingerprints.insert(*un...
Rust
0
let mut scope_stack = ScopeStack::new(); let expected_last_scope = { let mut scope = VecDeque::new(); let node = Node::<Range<usize>, Vec<Range<usize>>>::LineComment(comment.clone()); scope.push_back(node); scope }; let expected_scopes = { let mut scopes = Vec::new(); scopes.push(expected_last_...
Rust
0
-> Self { Self::JsonError(err) } } impl From<fs_extra::error::Error> for Error { fn from(err: fs_extra::error::Error) -> Self { // we only use `fs_extra` for copying step Self::CopyError(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Res...
Rust
0
a 0c@sfddlmZddlZddlZddlZddlmZmZmZerJddl m Z n ddl m Z erddl Z ddl m Z ddZ ddlmZdd Zd d Zdd lmZd dZeZzddlmZWneyddlmZYn0eZeZeZnVddl Z ddl m Z e j Z e jZe jZe j!Z!e jZe j...
Python
1
from flask import Flask, render_template, request import csv app = Flask(__name__) def sims_cheatlist(): cheats = [] with open('D:\\63947\\Documents\\GitHub\\project_retake\\response_sheet.csv', 'r', newline='') as csvfile: csv_reader = csv.reader(csvfile) for row in csv_reader: ch...
Python
1
, "夊"), (0x2F23, "M", "夕"), (0x2F24, "M", "大"), (0x2F25, "M", "女"), (0x2F26, "M", "子"), (0x2F27, "M", "宀"), (0x2F28, "M", "寸"), (0x2F29, "M", "小"), (0x2F2A, "M", "尢"), (0x2F2B, "M", "尸"), (0x2F2C, "M", "屮"), (0x2F2D, "M", "山"), ...
Python
1