text
string
label_name
string
labels
int64
ier 24h # et envoie sous forme JSON @login_required def chart_data_jour(request): dht = Dht11.objects.all() now = timezone.now() # Récupérer l'heure il y a 24 heures last_24_hours = now - timezone.timedelta(hours=24) # Récupérer tous les objets de Module créés au cours des 24 dernières heures ...
Python
1
3 = RenderResourceHandle::new(1234, RenderResourceType::Texture, 12345); let handle4 = RenderResourceHandle::new(123, RenderResourceType::Buffer, 12345); let handle5 = RenderResourceHandle::new(123, RenderResourceType::Texture, 1234); assert_eq!(handle1, handle1); assert_eq!(handle1, handle2); asse...
Rust
0
ny bytes on disk, since the File Allocation Table /// cannot more granularly allocate the disk space. pub fn bytes_per_cluster(&self) -> u32 { u32::from(self.bytes_per_sector) * u32::from(self.sectors_per_cluster) } /// Returns the starting address of the first File Allocation Table. pub fn...
Rust
0
return ShapeTracker(self.views[:-2] + (new_view,)).simplify() return self # *** under this line are the movement ops *** def pad(self, arg: tuple[tuple[sint, sint], ...]) -> ShapeTracker: return ShapeTracker(self.views[0:-1] + (self.views[-1].pad(arg), )) def shrink(self, arg: tuple[tuple[sint, sint]...
Python
1
# Import necessary libraries import os from dotenv import load_dotenv # For loading environment variables from .env file from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel # AI agent framework from agents.run import RunConfig # Configuration for running agents import asyncio # For asynchronou...
Python
1
self.p_sample_model_type = 'v2i' conditioning = c_vision unconditional_conditioning = uc_vision else: raise ValueError # shouldn't reached index = total_steps - i - 1 ts = torch.full((bs,), step, device=device, dtype=torch.long) ...
Python
1
from gym.utils import EzPickle import numpy as np from magical import geom from magical.base_env import BaseEnv, ez_init import magical.entities as en SMALL_POS_BOUND = 0.05 DEFAULT_ROBOT_POSE = ((0.058, 0.53), -2.13) DEFAULT_GOAL_COLOUR = en.ShapeColour.BLUE DEFAULT_GOAL_XYHW = (-0.62, -0.17, 0.76, 0.75) class Mov...
Python
1
# Copyright 2024 Leonin League # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
Python
1
self) { fs::remove_file(self.file_name.as_str()).unwrap_or_else(|_| { warn!( "File {} can't be removed after work. Remove the file in order to save disk space.", self.file_name.as_str() ) }); } } impl MMapMatrix { #[inline] fn update_...
Rust
0
option::Option<u32>, #[prost(uint64, optional, tag="3")] pub file_size: ::core::option::Option<u64>, #[prost(uint32, optional, tag="4")] pub file_width: ::core::option::Option<u32>, #[prost(uint32, optional, tag="5")] pub file_height: ::core::option::Option<u32>, } #[derive(Clone, PartialEq, ::p...
Rust
0
VOffsetT = 14; pub const VT_HASTM: flatbuffers::VOffsetT = 16; pub const VT_COLUMNS: flatbuffers::VOffsetT = 18; pub const VT_FEATURES_COUNT: flatbuffers::VOffsetT = 20; pub const VT_INDEX_NODE_SIZE: flatbuffers::VOffsetT = 22; pub const VT_CRS: flatbuffers::VOffsetT = 24; pub const VT_TITLE: fl...
Rust
0
n_words, self.pred_test.ids], feed_dict=fd) if self._config.decoding == "greedy": ids_eval = np.expand_dims(ids_eval, axis=1) elif self._config.decoding == "beam_search": ids_eval = np.transpose(ids_eval, [0, 2, 1]) n_words += n_words_eval ...
Python
1
expected_operational_timpoints_by_project = sorted( get_project_operational_timepoints(expected_disp_no_commit_gen_set) ) actual_operational_timepoints_by_project = sorted( [(g, tmp) for (g, tmp) in instance.GEN_SIMPLE_OPR_TMPS] ) self.assertListEqual( ...
Python
1
""" Interpolation helpers for timm layers RegularGridInterpolator from https://github.com/sbarratt/torch_interpolations Copyright Shane Barratt, Apache 2.0 license """ import torch from itertools import product class RegularGridInterpolator: """ Interpolate data defined on a rectilinear grid with even or uneven ...
Python
1
let (tx, rx) = Stream::pair(); tx.send(1) .and_then(|tx| tx.send(2)) .and_then(|tx| tx.send(3)) .and_then(|tx| tx.fail(())) .fire(); let reduced = rx.reduce(0, move |sum, v| sum + v); assert_eq!(Err(AsyncError::Failed(())), reduced.await()); } #[test] #[ignore] pub fn t...
Rust
0
discontiguous1_ix2", benchmark); } fn pairwise_sum_equal_lengths_discontiguous0_ix3(c: &mut Criterion) { let axis_lens = vec![1, 5, 20, 80, 320]; let benchmark = ParameterizedBenchmark::new( "ndarray", |bencher, &axis_len| { let arr = Array3::<f32>::random([axis_len ...
Rust
0
def fetch_ami_catalog(): return { "Ubuntu 18.04 LTS": "ami-07c5ecd8498c59db5", "Amazon Linux 2": "ami-07c5ecd8498c59db5" } def fetch_instance_types(): return ["t2.micro", "t2.small", "t2.medium"]
Python
1
US/docs/Web/API/KeyframeEffect/composite)"] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `CompositeOperation`, `KeyframeEffect`*"] pub fn composite(this: &KeyframeEffect) -> CompositeOperation; #[cfg(feature = "CompositeOperation")] # [ wasm_bindgen ( structu...
Rust
0
count kernel - each thread processes one element. """ # Each thread processes exactly one element tid = tl.program_id(0) if tid >= N: return # Load single element bin_idx = tl.load(input_ptr + tid) # Check bounds if bin_idx < 0 or bin_idx >= num_classes: ...
Python
1
_order: self.poly_order, ζ_zeros: self.ζ_zeros.clone(), hint_λ: self.hint_λ, } } pub fn hint_λ(&mut self, hint_λ: f64) -> &mut Self { self.hint_λ = hint_λ; self } pub fn poly_order(&mut self, poly_order: usize) -> &mut Self { self.poly_order = po...
Rust
0
import json import cv2 import matplotlib.pyplot as plt from path import Path from htr_pipeline import read_page, DetectorConfig, LineClusteringConfig, ReaderConfig, PrefixTree with open('../data/config.json') as f: sample_config = json.load(f) with open('../data/words_alpha.txt') as f: word_list = [w.strip(...
Python
1
SecretKey::agree`]. /// /// [`SecretKey::agree`]: trait.SecretKey.html#tymethod.agree pub struct SharedSecret(pub [u8; 32]); /// Error returned by [`SecretKey::agree`] when the public key of the other party is invalid. /// /// [`SecretKey::agree`]: trait.SecretKey.html#tymethod.agree #[derive(Debug)] pub struct Invali...
Rust
0
r(diffProps, type) # get the max twin length. twinMaxLen = _TwinMaxLen_ if (twinMaxLen > _DiffMaxLen_) else twinMaxLen # get the mapping for feature data and labels. twinData, twinLabels = GetTwinMapping(twinProps, twinMaxLen, diffDict, type) # change the tokentypes into one-hot vector. twinData...
Python
1
"a2a_wrapper" in final_state_dict: del final_state_dict["a2a_wrapper"] return final_state_dict # --- Main Execution --- async def main(): """Parse arguments and run the pipeline.""" args = parse_args() logging.basicConfig(level=getattr(logging, args.log_level.upper()), format='%(asctime)s - %(name)s ...
Python
1
l.predict(obs, deterministic=True) # RL 获得的动作 rl_agent.update_rl_traffic_phase(new_phase=rl_action) # 更新当前 RL 推荐的动作 # ########## # 新建文件夹 (存储每一个 step 的信息) # ########## time_step += 1 # 记录 timestep _save_folder = path_convert(f"./{SCENARIO_NAME}/{time_step}/") crea...
Python
1
ctor // In a handler, add "cache: Cache" param for auto extraction .configure(add_cache) // Adds a Database Pool for use in the Actix Data Extractor // In a handler, add "pool: Data<PoolType>" param for auto extraction .configure(add_pool) // Pull ...
Rust
0
/ alice.send_to(bob); //! // alice.send_to(carol); //! // bob.send_to(alice); //! // bob.send_to(carol); //! // carol.send_to(alice); //! // carol.send_to(bob); //! // //! // NOTE: They should only send the `alice`, `bob`, and `carol` structs, *not* //! // the `alice_coefficients`, etc. //! // //! // Bob and Caro...
Rust
0
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import numpy as np import os import pandas as pd from utils import process_jigsaw_1 from utils impo...
Python
1
# -*- coding: utf-8 -*- import os import base from datetime import datetime singularity_cmd = "singularity" timestamp = datetime.now().strftime(r'%m%s') def set_singularity_login_env(user, password): os.environ.setdefault('SINGULARITY_DOCKER_USERNAME', user) os.environ.setdefault('SINGULARITY_DOCKER_PASSWORD...
Python
1
# 1071. Greatest Common Divisor of Strings class Solution(object): def gcdOfStrings(self, str1, str2): """ :type str1: str :type str2: str :rtype: str """ if str1 + str2 != str2 + str1: return "" if len(str1) == len(str2): return str1 ...
Python
1
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import llnl.util.tty as tty import spack.cmd import spack.cmd.common.arguments as arguments description = 'add a spec to...
Python
1
e) or ((epoch + 1) % config.train.eval_interval != 0): continue # evaluate model logger.info(f"Start evaluating model at epoch {epoch}.") model.eval() errors = [] for _, batch in enumerate(val_dataloader): with torch.no_grad(), torch.autocast("cuda", dtyp...
Python
1
#!/usr/bin/env python # pylint: disable=W0212 from agate import utils def distinct(self, key=None): """ Create a new table with only unique rows. :param key: Either the name of a single column to use to identify unique rows, a sequence of such column names, a :class:`function` that takes...
Python
1
#!/usr/bin/python # # Copyright 2018 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Python
1
**Image Support**: JPG, PNG, GIF, SVG, WebP, BMP, TIFF\n" # "- 📄 **Documents**: PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT\n" # "- 🎥 **Media**: MP4, AVI, MOV, MP3, WAV, FLAC, etc.\n" # "- 🤖 **Smart AI**: I understand context and generate appropriate content\n" # ...
Python
1
e(buf)?; self.inception.compose(buf)?; self.key_tag.compose(buf)?; self.signer_name.compose_canonical(buf)?; buf.append_slice(self.signature.as_ref()) }) } } //--- Scan and Display #[cfg(feature = "master")] impl Scan for Rrsig<Bytes, Dname<Bytes>> { fn ...
Rust
0
from typing import Union, List, Optional from omegaconf import DictConfig import hydra from torch.utils.data import DataLoader import pytorch_lightning as pl class ConsecDataModule(pl.LightningDataModule): def __init__(self, conf: DictConfig): super().__init__() self.conf = conf self.tr...
Python
1
Squid Proxy Manager") parser.add_argument('hostname', help="IP address of the Squid proxy server") parser.add_argument('port', type=int, help="Port number for SSH connection") parser.add_argument('username', help="SSH username") parser.add_argument('password', help="SSH password") parser.add_argumen...
Python
1
print(" 🗙 Test messages vides...") empty_tests = ["", " ", "\n\n", "\t\t", " \n \t "] empty_success_count = 0 for i, empty_msg in enumerate(empty_tests): response = chatbot.obtenir_reponse(empty_msg, f"edge_empty_{i}") if response ...
Python
1
, 500 @app.route('/health') def health_check(): """健康检查端点""" try: # 检查存储是否可用 storage.get_all_groups() return jsonify({ "status": "healthy", "storage": "connected", "timestamp": datetime.utcnow().isoformat(), "environment": "vercel" if os.g...
Python
1
sm.sendSay("When you are finished, you will find that the true Empress of Maple World is not Cygnus, but Hilla.") sm.flipDialoguePlayerAsSpeaker() sm.sendSay("(Gaston should be ready about now. Time to take the plunge!)") sm.showFieldEffect("phantom/phantom", 0) sm.forcedInput(0) sm.sendDelay(1500) sm.sendNext("Jum...
Python
1
DisjointFromClause::new(cls.into_py(py))).map(TypedefClause::DisjointFrom) } TransitiveOver(r) => { Py::new(py, TransitiveOverClause::new(r.into_py(py))).map(TypedefClause::TransitiveOver) } EquivalentToChain(r1, r2) => Py::new(py, EquivalentToChainClause...
Rust
0
default="", nargs='?', action="store", help='name of the model to download') args = parser.parse_args() models = [] save_dir = args.save_dir selected_model_name = args.model_name models.extend(parseMetalinkFile('face_detector/weights.meta4', save_dir)) models.extend(pars...
Python
1
Give the ownership of the mutex to `task`. /// /// The task must be in Running or Waiting state. #[inline] fn lock_core<Traits: KernelTraits>( mutex_cb: &'static MutexCb<Traits>, task: &'static task::TaskCb<Traits>, mut lock: klock::CpuLockTokenRefMut<'_, Traits>, ) { debug_assert_matches!( tas...
Rust
0
] [dependencies] whizzo = "0.1.0" parse-generics-poc = { version = "0.1.0", optional = true } parse-generics-shim = "0.1.0" parse-macros = "0.1.0" ``` Then, add the following to your crate's root module: ```ignore #![cfg_attr(feature="parse-generics-poc", feature(plugin))] #![cfg_attr(feature="parse-generics-poc", p...
Rust
0
C: 'a + FormatConvert> NodeLoaderCommon for VideoLoader<'a, C> { type Target = Option<Video<C::ImageResult>>; fn on_finish(mut self) -> Result<Self::Target> { let defaults = self.definitions.templates.templates.get(&("Video".to_owned(), "FbxVideo".to_owned())).map(|t| &t.properties); let path ...
Rust
0
# -*- coding: utf-8 -*- from pandas_ta.overlap import ma from pandas_ta.utils import get_drift, get_offset, verify_series def efi(close, volume, length=13, mamode='ema', drift=None, offset=None, **kwargs): """Indicator: Elder's Force Index (EFI)""" # Validate arguments length = int(length) if length and l...
Python
1
et counter = Arc::new(AtomicUsize::new(0)); let mut handles = Vec::new(); for _ in 0..100 { let key_handle = key_handle.clone(); let counter = counter.clone(); let handle = tokio::spawn(async move { let _guard = key_handle.dagger().await; ...
Rust
0
_EE.RBDOCK_S, str(_EE.RBDOCK_S_DEFAULT), _EE.RBDOCK_P, _EE.RBDOCK_P_DEFAULT] execution_result = self._rDock_executor.execute(command=_EE.RBDOCK, arguments=arguments, check=T...
Python
1
""" Assignment lifecycle management. This module provides high-level assignment lifecycle helpers and management operations. """ from ..utils import get_logger logger = get_logger("assignments.manage") class AssignmentManager: """Manage assignment lifecycle operations.""" def __init__(self, config_path=No...
Python
1
index_array_helper::IndexBuffer; use super::vertex_array_helper::FloatBuffer; use crate::hal::{Font, Shader, WgpuLink}; use crate::prelude::{RenderSprite, SpriteSheet}; use crate::BResult; use bracket_color::prelude::RGBA; use wgpu::{BufferUsages, RenderPipeline}; /// Mapping between a sparse console and wgpu renderin...
Rust
0
""" 4) Al terminar un día en un colegio secundario se hace una estadística de faltas sabiendo de cada curso:  Curso (1-5)  Presentes  Ausentes Calcular  Por cada curso el porcentaje de presentes sobre el total  Cantidad de ausentes en el colegio  Curso con mayor cantidad de ausente """ try: cantausent = 0 ...
Python
1
rng=model.rng, steps=self.nsteps) # compute negative phase updates sampler_updates = self.sampler.updates() # Compute SML cost pos_v = data neg_v = self.sampler.particles ml_cost = (model.free_energy(pos_v).mean() - model.free_en...
Python
1
logits=logits_strong) pseudo_mask = tf.to_float(tf.reduce_max(pseudo_labels, axis=1) >= confidence) tf.summary.scalar('monitors/mask', tf.reduce_mean(pseudo_mask)) loss_xeu = tf.reduce_mean(loss_xeu * pseudo_mask) tf.summary.scalar('losses/xeu', loss_xeu) # L2 regu...
Python
1
Err(JsError::new_str( "Unknown error while creating getter setter", )) } } else { Ok(()) } } /// get a property from an object by name pub fn get_property_q( q_ctx: &QuickJsRealmAdapter, obj_ref: &JSValueRef, prop_name: &str, ) -> Result<JSValueRef, ...
Rust
0
self.model = tf.keras.models.load_model(CFG.checkpointDir() + model_name) self.optimizer = tf.keras.optimizers.Adam(learning_rate=CFG.lr) callbacks, initial_epoch = self.init_model() self.train_on_list(callbacks, initial_epoch) ignored_fg = np.sum(self.gen_percent['gen_sp']) to...
Python
1
NodeId<ast::ClassCon>, Vec<PremiseClassConstraint>>, } impl Premise { pub fn new() -> Self { Self { class_constraints: HashMap::new(), } } pub fn add_class_constraint( &mut self, id: ConstraintId, path: Vec<ConstraintId>, class: ast::NodeId<ast::...
Rust
0
, false, 0, 0, ); }); }); // set the length of the buffer to match the length of the source data (this will be a // no-op unless the array is uninitialised) self.len = src.len(); // hold a re...
Rust
0
from typing import Any, Dict, Union class StarletteAdminException(Exception): pass class FormValidationError(StarletteAdminException): def __init__(self, errors: Dict[Union[str, int], Any]) -> None: self.errors = errors def has(self, name: str) -> bool: return self.errors.get(name, None...
Python
1
let mut want = want.to_vec(); want.sort_unstable(); let mut got = neighbors3(coord, 5); got.sort_unstable(); assert_eq!(want, got); } fn d((x, y): Coord2) -> Coord3 { (-1, x, y) } fn z((x, y): Coord2) -> Coord3 { (0, x, y) } fn u((x, y): Coord2) -> Coord3 { (1, x, y) } ...
Rust
0
, seed) } ShapeType::QuadraticBezier => { QuadraticBezier::random(self.width(), self.height(), BORDER_EXTENSION, seed) } ShapeType::Rectangle => { Rectangle::random(self.width(), self.height(), BORDER_EXTENSION, seed) } ...
Rust
0
let p5_x_lc = p5_x.lc(&mut cs); let p5_y_lc = p5_y.lc(&mut cs); cs.enforce_zero(p5_x_lc - (Coeff::Full(five_x), CS::ONE)); cs.enforce_zero(p5_y_lc - (Coeff::Full(five_y), CS::ONE)); Ok(()) } } assert_eq!( is_satis...
Rust
0
# Modified script to read Maddison's 'Full data' sheet and save it to a CSV file import pandas as pd # Define a function to process and save the 'Full data' sheet to CSV def save_maddison_data_to_csv(excel_path, sheet_name, csv_file_path): # Read the specified sheet from the Excel file data_df = pd.read_excel...
Python
1
Name of the interface to inject packets to") .required(false), ) .arg(clap::arg!(-l --loop "Loop pcap file")) .arg(clap::arg!(-F --fullspeed "Write packets as fast as possible")) .arg( clap::arg!(-L --low <VALUE> "Minimum watermark for packet buffe") ...
Rust
0
if os.path.exists('texts.json'): with open('texts.json', 'r', encoding='utf-8') as file: texts = json.load(file) # Создаем новый текст new_text = { 'id': len(texts) + 1, 'user_id': user_id, 'content': text_data.tex...
Python
1
l = msg.author.bot && msg.embeds.iter().any(|embed| { embed .title .as_ref() .map(|x| x.starts_with("Poll")) .unwrap_or(false) }); if is_poll { // This is rather imperfect, but discord API sucks :/ // we're ...
Rust
0
SHEY_SIMPLEX, 1, (255, 255, 255), 2 ) # Save target heatmap target_path = os.path.join(epoch_dir, f"target_heatmap.png") cv2.imwrite(target_path, target_colored) # Create a comparison image (side by side) h...
Python
1
tf = release_gate_time + 0.4; let dt = args.flag_dt; let total_steps = (tf / dt) as u64; let mut t = 0.; let mut step_no = 0; let total_output_file = 100; let pfreq = if total_steps < total_output_file { 1 } else { total_steps / total_output_file }; // let pfreq = 10...
Rust
0
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from dotenv import load_dotenv import os load_dotenv() EMAIL_HOST = os.getenv("EMAIL_HOST") EMAIL_PORT = int(os.getenv("EMAIL_PORT")) EMAIL_USERNAME = os.getenv("EMAIL_USERNAME") EMAIL_PASSWORD = os.getenv("EMAIL_PASSWO...
Python
1
forms=[ dict(type='Blur', p=0.1), dict(type='MedianBlur', p=0.1), dict( type='CoarseDropout', max_holes=1, max_height=0.4, max_width=0.4, min_holes=1, min_height=0.2, min_w...
Python
1
import requests from requests_oauthlib import OAuth1 import os consumer_key = os.environ.get("CONSUMER_KEY") consumer_secret = os.environ.get("CONSUMER_SECRET") access_token = os.environ.get("ACCESS_TOKEN") access_token_secret = os.environ.get("ACCESS_TOKEN_SECRET") def random_fact(): fact = requests.get("https...
Python
1
, 0x15); /// ``` pub const fn dev_id(&self) -> u8 { (self.uid & 0xFF) as u8 } } impl From<u64> for Uid64 { fn from(uid: u64) -> Self { Uid64 { uid } } } impl From<Uid64> for u64 { fn from(uid: Uid64) -> Self { uid.uid } } impl Display for Uid64 { fn fmt(&self, ...
Rust
0
# # This application showcases how UI components can be placed # to create a more complex layout. The position of all components # is determined by a (x,y) pair prodived by the developer. # # Take a look at the "row-column" application to see how to use # automatic positioning by leveraging the begin*()/end*() API. # ...
Python
1
#!/usr/bin/env micropython import json from ev3dev2.motor import Motor, LargeMotor, OUTPUT_B, OUTPUT_C from ev3dev2.sensor import INPUT_4 from ev3dev2.sound import Sound # import os # import sys # sys.path.append(os.path.expanduser('~')) from util.drive_util_ev3dev2 import IRBeaconRemoteControlledTank HAPPY_BIRTH...
Python
1
an use the coordinate as an offset? let square_size = 400.0; let padding = 100.0; //set color for button A let mut color = [0.2, 0.1, 0.5, 0.2]; let mut hover_color = [0.7, 0.1, 0.0, 0.5]; let button_a = make_our_button( world, (-1.0 * square_size...
Rust
0
(&self) -> &gtk::Widget { self.0.widget() } } pub fn box_add_padding<T: BoxableWidget>(widget: &T, padding: u32) -> AddPadding<'_, T> { AddPadding(widget, padding) } pub fn box_vertical(widgets: &[&dyn BoxableWidget]) -> gtk::Box { let bx = gtk::Box::new(gtk::Orientation::Vertical, 5); for wid...
Rust
0
-> Either<i32, Box<T>> { match self.0.get() { Left(i) => Left(i as i32), Right(b) => Right(b), } } pub fn get_ref(&self) -> Either<i32, &T> { match self.0.get_ref() { Left(i) => Left(i as i32), Right(br) => Right(br), } } } <g...
Rust
0
#assignment operators num = 10 num = num+10 #10+10=>20 print("num:",num)
Python
1
, moved pub fn set_result(&mut self, v: UseItemEggIncubatorResponse_Result) { self.result = ::std::option::Option::Some(v); } pub fn get_result(&self) -> UseItemEggIncubatorResponse_Result { self.result.unwrap_or(UseItemEggIncubatorResponse_Result::UNSET) } // optional .POGOProtos....
Rust
0
def f(x, y): if x == y: return 1 if x < y or x==24: return 0 return f(x - 1, y) + f(x - 6, y) + f(x // 2, y) print(f(34, 29) * f(29, 19) * f(19, 6))
Python
1
ING: Type = 2u64 as u32; pub const eRESTITUTION: Type = 4u64 as u32; pub const eKEEPBIAS: Type = 8u64 as u32; pub const eOUTPUT_FORCE: Type = 16u64 as u32; pub const eHAS_DRIVE_LIMIT: Type = 32u64 as u32; pub const eANGULAR_CONSTRAINT: Type = 64u64 as u32; pub const eDRIVE_ROW: Type = 128u64 as u32; } pub mod PxActorFl...
Rust
0
from typing import List # a divide function def _merge_like(lst : List[int], low : int, high : int) -> int: if (low >= high): return 0 mid = low + (high - low) // 2 left = _merge_like(lst, low, mid) right = _merge_like(lst, mid + 1, high) mergeResult = merge_like(lst, low, mid, high) ...
Python
1
.add_usize("", 5).is_err()); Ok(()) } <gh_stars>1-10 extern crate wordnet; fn print_indent(indent : u32) { for _ in 0..indent { print!(" "); } } fn print_tree(indent : u32, ptr : &wordnet::PointerRef) { if ptr.relationship != wordnet::Relationship::Hypernym { return; } let sense = ptr.read(...
Rust
0
{ let start = match range.start_bound() { std::ops::Bound::Included(x) => *x, std::ops::Bound::Excluded(x) => unsafe { char::from_u32_unchecked((*x as u32) + 1) }, std::ops::Bound::Unbounded => panic!("The range must have a lower bound"), }; let end = match ...
Rust
0
&js_sys::Object) -> bool { !obj.is_null() && { let proto = js_sys::Reflect::get_prototype_of(obj.as_ref()).unwrap(); proto.is_null() } && impl_is_empty_object(obj) } pub fn is_empty_object(obj: &js_sys::Object) -> bool { is_empty_object_with_object_proto(obj) ||...
Rust
0
# -*- coding: utf-8 -*- from odoo import models, fields, api class material(models.Model): _name = 'material.material' _description = 'material.material' code = fields.Char() name = fields.Char() material_type = fields.Selection([ ('Fabric', 'Fabric'), ('Jeans', 'Jeans'), ...
Python
1
_pending_dangling_drawing_objects_during_release: None, approver_required_during_release: None, note_required_during_release: None, require_all_approvers: None, allow_release_items_from_other_documents: None, automatically_obsolete_previous_released_revisions:...
Rust
0
gle array image_points_depth = np.hstack((image_points.reshape(-1, 2), depth[:, None])) # print min max of depth # print(np.min(image_points_depth[:, 2]), np.max(image_points_depth[:, 2])) # Ensure all elements are floats image_points_depth = image_points_depth.astype(np.float3...
Python
1
.into_iter() .filter(|coord| match direction { 'x' => coord.x < line, 'y' => coord.y < line, _ => true, }) .collect::<HashSet<Coord>>(); let right = paper .clone() .into_iter() .filter(|coord| match direction { 'x' => c...
Rust
0
from pathlib import Path import torch from einops import rearrange from structured_kernels import cauchy_mult_sym_fwd, cauchy_mult_sym_bwd # try: # from cauchy_mult import cauchy_mult_sym_fwd, cauchy_mult_sym_bwd # except ImportError: # from torch.utils.cpp_extension import load # current_dir = Path(__fil...
Python
1
0]; let exit = handle_keys(&mut tcod, player); if exit { break; } } } <gh_stars>0 // 首先定义好两个栈 struct MinStack { // 一个栈叫做 stack,负责栈的正常操作 stack: Vec<i32>, // 一个栈叫做 min_stack,负责获取 stack 中的最小值,它等价于遍历 stack 中的所有元素,把升序的数字都删除掉,留下一个从栈底到栈顶降序的栈 min_stack: Vec<i32>, } /** * `&sel...
Rust
0
Err; throw_emitter!(LocalSubscription, 'a); } impl<Err> SharedEmitter for ThrowEmitter<Err> { type Item = (); type Err = Err; throw_emitter!(SharedSubscription, Send + Sync + 'static); } /// Creates an observable that produces no values. /// /// Completes immediately. Never emits an error. /// /// # Examples...
Rust
0
# -*- coding: utf-8 -*- # this file is used by jobman to generate jobs import numpy import os from jobman import DD home = os.getenv('HOME') default_config = DD({ # theano profiling, 0 not printing 'profile': 1, # specify the correct data path # cifar10.npz # curves.npz # mnist_6k_1k_1k.npz ...
Python
1
color_map = [[0, 0, 0], [123, 23, 45]] expected = '["rgb(0, 0, 0)", "rgb(123, 23, 45)"]' self.assertEqual(to_dygraph_colors(color_map), expected) class TestBarPlot(unittest.TestCase): def setUp(self): self.dfr = pd.DataFrame({"foo": [1, 2, 3], "bar"...
Python
1
"""Script to create a snapshot of the UNU-WIDER Government Revenue Dataset. Steps to obtain the data: - Go to https://www.wider.unu.edu/project/grd-government-revenue-dataset - Click on `Access full and additional datasets here` - Fill the form and submit - Download the Full dataset (Stata format). The name of the fil...
Python
1
ntedError for t in i_transforms: t.inverse = True i_transforms = torchvision.transforms.Compose(i_transforms) return i_transforms(x) def get_spectrogram(audio_path, save_dir, length, folder_name='melspec_10s_22050hz', save_results=True): wav, _ = librosa.load(audio_path, sr=None) # this ca...
Python
1
""" The following predicates can be used in the traversal functions directly. """ from ..atomic import AtomicElement from ..metadata import PunctuationElement, CommentElement, NewlineElement, WhitespaceElement from prettytoml import tokens from .. import common atomic = lambda e: isinstance(e, AtomicElement) ...
Python
1
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing_extensions import Literal, Required, TypedDict __all__ = ["FileSearchToolParam", "FileSearch", "FileSearchRankingOptions"] class FileSearchRankingOptions(TypedDict, total=False): ...
Python
1
=debug,runtime=debug"); let _ = pretty_env_logger::try_init(); let pool = RedisPool::builder() .connect_to_node("redis://127.0.0.1:6379") .desired_pool_size(10) .reservation_limit(1_000_000) .default_checkout_mode(Immediately) //.task_executor(runtime.executor()) no expl...
Rust
0
from fastapi import Request, HTTPException def get_api_keys_from_headers(request: Request) -> dict[str, str]: """ Extract API keys from request headers. Args: request: FastAPI Request object Returns: dict: Dictionary containing the API keys Raises: HTTPException: If any ...
Python
1