text
string
label_name
string
labels
int64
number = int(input("Enter a number and I will tell you if it is even or odd: ")) if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd")
Python
1
ctx!(curid, vwctx, vctx)); assert_eq!(ebuf.get_text(), "12345\n67890\nabcq\nfoo\npqrst\nuvwxy\n"); assert_eq!(ebuf.get_leader(curid), Cursor::new(4, 0)); assert_mark!(ebuf, 'a', Cursor::new(0, 4)); assert_mark!(ebuf, 'b', Cursor::new(1, 3)); assert_mark!(ebuf, 'c', Cursor::new(2...
Rust
0
"""用户角色关联路由""" from typing import List from fastapi import APIRouter, Depends, status from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, delete from pydantic import BaseModel from app.core.database import get_db from app.schemas.common import APIResponse from app.schemas.role import RoleRes...
Python
1
# --- # title: "Real-Time Anomaly Detection: identifying brute-force logins using Tumbling Windows" # description: Detecting suspicious login attempts # notebook_export_path: notebooks/tutorials/suspicious_user_activity.ipynb # author: 'przemek' # aside: true # date: '2023-05-30' # thumbnail: # src: '/assets/blog/thu...
Python
1
import logging import threading import unittest from hpfeeds import client from hpfeeds.protocol import readpublish from .fakebroker import FakeBroker, setup_default_reactor class TestClientIntegration(unittest.TestCase): log = logging.getLogger('hpfeeds.testserver') def _server_thread(self): self...
Python
1
::Item> { self.nth_big_uint(BigUint::from(n)) } } impl DoubleEndedIterator for Ipv6CidrU8ArrayIterator { #[inline] fn next_back(&mut self) -> Option<Self::Item> { if self.next < self.back { Some(unsafe { self.next_back_unchecked() }) } else { None } ...
Rust
0
current.list.as_mut().unwrap().push(TOCNode { name: None, level: current_level + 1, list: None, }); } current = current.list.as_mut().unwrap().last_mut().unwra...
Rust
0
e][key].id = key + IMPF_ID_FACT new_impfs.get_func()[self.haz_type][ key + IMPF_ID_FACT ] = new_impfs.get_func()[self.haz_type][key] try: new_exp.gdf[INDICATOR_IMPF + self.haz_type] += IMPF_ID_FACT except KeyError: ...
Python
1
e_weights=None): """Returns ... Parameters ---------- ds : array, shape (n_atoms, n_times_atom) The atoms n_times_valid : int n_times - n_times_atom + 1 method : string If 'full', returns full circulant matrix. If 'scipy', returns scipy linear operator. I...
Python
1
|| self.environment == Environment::Androideabi) } } }, Vendor(ven) => match ven.0.parse::<target_lexicon::Vendor>() { Ok(v) => self.vendor == v, Err(_) => false, }, Point...
Rust
0
nsearch_port PORT, --port PORT Port number of the OpenSearch server. --opensearch-server HOSTNAME, --opensearch_server HOSTNAME, --server HOSTNAME Hostname or IP address of the OpenSearch server. --opensearch-url-prefix URL_PREFIX, --opensearch_url_prefix URL_PREFIX ...
Python
1
import numpy as np import scipy as sp #NO OTHER IMPORTS ALLOWED (However, you're allowed to import e.g. scipy.linalg) def estInitialize(): # Fill in whatever initialization you'd like here. This function generates # the internal state of the estimator at time 0. You may do whatever you # like here, but you...
Python
1
from collections import deque def bfs(matrix, start, end): queue = deque([([start], 0)]) visited = set([start]) while queue: path, length = queue.popleft() x, y = path[-1] if (x, y) == end: return path for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: ...
Python
1
eft_icon" in self.ids: Clock.schedule_once(add_left_icon) def on_text(self, *args) -> None: try: self.ids.label.text = self.text except: pass def add_text(*args) -> None: self.add_widget( CLabel(id="label", text=self.text, sty...
Python
1
return await db.get(Users, id) except SQLAlchemyError as e: logger.error(f"Database error when getting user by id: {e}") raise HTTPException( status_code=500, detail=f'Database error occured: {e}' ) @staticmethod asy...
Python
1
from langchain.chains import TransformChain from langchain_core.messages import HumanMessage from langchain_core.runnables import chain from langchain_core.output_parsers import JsonOutputParser import base64 from langchain.callbacks import get_openai_callback from receiptchat.openai.prompts import VisionReceiptExtract...
Python
1
ons(first_leaf_index, num_leaves)?; Ok(AccumulatorRangeProof::new( self.get_hashes(&left_siblings)?, self.get_hashes(&right_siblings)?, )) } fn get_range_proof_positions( &self, first_leaf_index: Option<u64>, num_leaves: LeafCount, ) -> Result...
Rust
0
n case a later st function call is on one of them. """ from streamlit.delta_generator import DeltaGenerator # Maps originally recorded dg ids to this script run's version of that dg returned_dgs: dict[str, DeltaGenerator] = { result.main_id: st._main, result.sidebar_id: st.sidebar, ...
Python
1
<f64> { input_array_arg!(object_points); input_array_arg!(image_points); input_output_array_arg!(camera_matrix); input_output_array_arg!(dist_coeffs); output_array_arg!(rvecs); output_array_arg!(tvecs); unsafe { sys::cv_ccalib_CustomPattern_calibrate_const__InputArrayR_const__InputArrayR_Size_const__Input...
Rust
0
ed', 7)}-day data") print(f" 🧠 User context incorporated for accurate classification") print(f" 🫂 Root causes addressed, not just symptoms") print(f" 💡 Holistic interventions beyond simple blocking") print(f" ✨ Personalized to your actual work style") def __del__(self): ...
Python
1
(&SI_BASES, false), Unit::Iec(with_i) => (&IEC_BASES, with_i), Unit::Auto => return Err("Unit 'auto' isn't supported with --to options".to_owned()), Unit::None => return Ok((n, None)), }; let i = match abs_n { _ if abs_n <= bases[1] - 1.0 => return Ok((n, None)), _ if a...
Rust
0
encoding = 'utf-8' decode_error_handling = 'utf8_surrogatepass_and_surrogateescape' max_length = 3000 def clean_param_value(self, value): raise TypeError("it's not a param field") class SomeUnicodeListFieldForN6(ResultListFieldMixin, SomeUnicodeFieldForN6): pass class SomeFieldForN6(So...
Python
1
t.extend(i_b.iter()); fixed_part.extend(b_b.iter()); fixed_part.extend(l_b.iter()); fixed_part }, _ => { vec![] } } } } /// Tries to decode a message according to the bittorrent protocol from a slice of byt...
Rust
0
error_str += f'.{e.name}' error_str += ':\n' if isinstance(e.what, ValidationError): for ve in e.what.errors(): field = '.'.join(map(str, ve.get('loc', ['']))) error_str += f" + {field}: {ve.get('msg','')}\n" else: error_str += f' ...
Python
1
""" Created on Dec 19, 2009 @author: barthelemy """ from py4j.java_gateway import JavaGateway if __name__ == "__main__": gateway = JavaGateway() buffer = gateway.getStringBuffer() buffer.append(True) buffer.append(1.0) buffer.append("This is a Python {0}".format("string")) print(buffer.toStrin...
Python
1
<fpowercontrol::AdminMarker>().unwrap(); let node = SystemShutdownHandlerBuilder::new(create_dummy_node()) .with_component_mgr_proxy(setup_fake_component_mgr_service(|| {})) .build() .unwrap(); node.handle_new_service_connection(stream); assert_eq!(proxy.mex...
Rust
0
.arg("-c") .arg("for i in $(seq 1 3); do sleep 1; echo line $i; done") .stdout(Stdio::piped()) .spawn().unwrap(); let child_buf = std::io::BufReader::new(comm.stdout.unwrap()); let (tx_stdin, rx) = sync_channel(1); let tx_child = tx_stdin.clone(); thread::spawn...
Rust
0
lete(sample_copy, locs, axis=1) # Test MCMC test = sample_copy[:, 0].copy() conversion = my_system.basis.to_standard_basis(test) original = my_system.basis.to_xyz_basis(conversion) assert np.allclose(original, sample_copy[:, 0]) # Test OFTI conversions = my_system.basis.to_standard_basis(s...
Python
1
); assert_eq!(attributes["CPTimeout"], "60"); assert_eq!(attributes["DriverODBCVer"], "03.50"); assert_eq!(attributes["FileUsage"], "0"); assert_eq!(attributes["SQLLevel"], "1"); assert_eq!(attributes["UsageCount"], "1"); } } //! Module containing special characters constant ...
Rust
0
2ea3c990d0068700", "<KEY>"), ("<KEY>", "<KEY>"), "e0e91e3812ac029a", "4FgA1BSawG9i4XWQC<KEY>" ), ( "<KEY>", ("<KEY>", "5a224a898a42d48025efccfb14c2062610ec95ddfe02c764e6ababe1ed44780d"), ("ccfc5403e25...
Rust
0
rn Err(StreamError::UnexpectedIdent); } else { buffer.advance(expect.len()); break; } } Ok(()) } pub async fn buffer(&mut self) -> Result<Option<&mut Bytes>, StreamError<E>> { let buffer = match self.buffer.take() { S...
Rust
0
import itertools def get_city(person): return person['city'] people = [ { 'name': 'John Smith', 'city': 'Berlin' }, { 'name': 'Mary Gold', 'city': 'Berlin' }, { 'name': 'Taavi Tamm', 'city': 'Berlin' }, { 'name': 'Piere Cardin', ...
Python
1
, pub texture: *mut wlr_texture, pub surface: *mut crate::src::types::data_device::wlr_data_device::wlr_surface, pub surface_commit: wl_listener, pub surface_destroy: wl_listener, pub events: C2RustUnnamed_2, } #[repr(C)]#[derive(Copy, Clone)] pub struct C2RustUnnamed_2 { pub destroy: wl_signal...
Rust
0
from pydantic import Field from pydantic_settings import BaseSettings class Settings(BaseSettings): # API Configuration api_host: str = Field(default="0.0.0.0", validation_alias="API_HOST") api_port: int = Field(default=8000, validation_alias="API_PORT") # Hugging Face API (for embeddings only) ...
Python
1
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-present Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram 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 F...
Python
1
use crate::connection_worker::Worker; use super::ProxyData; /// The plugin messaging channel used to receive the proxy data. pub const CHANNEL: &str = "velocity:player_info"; /// Matches the version in VelocityConstants.java const FORWARDING_VERSION: i32 = 1; const TAG_LENGTH: usize = digest::SHA256_OUTPUT_LEN; ...
Rust
0
.wait_visibility_button_close() self.wait_presence_button_close() self.find_button_close() self.wait_clickable_button_close() self.click_button_close() @allure.step('Общие шаги для нажатия на кнопку "Личный кабинет" на главной странице') def base_check_click_button_account(self)...
Python
1
""" Allow running mokupdf as a module: python -m mokupdf """ from .server import main if __name__ == "__main__": main()
Python
1
lobal optimization using a //! [Self-Adapting Differential Evolution](http://bit.ly/2cMPiMj) //! for Rust. See Wikipedia's article on //! [Differential Evolution](https://en.wikipedia.org/wiki/Differential_evolution) //! for more information. //! //! ## Usage //! //! Add this to your `Cargo.toml`: //! //! ```toml //! [...
Rust
0
if self.info.get("exif") != original_exif: self._reload_exif() self.tile = [("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])] self.__frame = frame def tell(self): return self.__frame @staticmethod def adopt(jpeg_instance, mpheader=None): """ ...
Python
1
err = exceptions::PyTypeError::new_err("TextInputSequence must be str"); if let Ok(s) = ob.downcast::<PyString>() { Ok(Self(s.to_string_lossy().into())) } else { Err(err) } } } impl<'s> From<TextInputSequence<'s>> for tk::InputSequence<'s> { fn from(s: TextInputSe...
Rust
0
orei32/png2mozjpegd use std::cmp; use std::env; use std::ffi::OsStr; use std::fs::File; use std::io::{BufReader, Write}; use std::path::{Path, PathBuf}; use std::sync::mpsc::channel; use std::time::Duration; use image::GenericImageView; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use once_cell::sync...
Rust
0
update_job_output() { let (_ctx, conn) = init(); let qw = QueueWrapper::with_default_queue(&conn); // can only update jobs if they exist match qw.manager.set_job_output(21, &"foo".into()) { Err(OcyError::NoSuchJob(21)) => (), x => assert!(false, "Unexpected...
Rust
0
|m, xs| { let max = m.max.cast_to_scalar()?; let min = m.min.cast_to_scalar()?; xs.iter_mut().for_each(|x| { *x = x.max(max).min(min) }); Ok(()) }); element_wise!(scalar_min, ScalarMin { min: Tensor }, [f32, f64] => |m, xs| { let min = m.min.cast_to_scalar()?; xs.ite...
Rust
0
. impl<T, const N: usize> IndexMut<usize> for List<T, N> where T: SimpleSerialize, { fn index_mut(&mut self, index: usize) -> &mut Self::Output { let leaf_index = Self::get_leaf_index(index); self.cache.invalidate(leaf_index); &mut self.data[index] } } impl<T, const N: usize> Sized ...
Rust
0
= self.drivers_table.cellWidget(row, 4) if button_widget and button_widget.layout() and button_widget.layout().itemAt(0): color_button = button_widget.layout().itemAt(0).widget() color_button.setStyleSheet(self.get_color_button_style(color)) def refresh_grid...
Python
1
let validator = WHITELISTED_VALIDATORS.load(deps.storage)?; let mut sub_messages: Vec<SubMsg> = vec![]; // Rewards list index = whitelisted validators index, we pass the index as an ID // for the submessages to allow for constant time retrieval in reply let mut rewards_list: Vec<(String, Uint128)...
Rust
0
ways. # Thus we can create a single static attention_mask here, which is more efficient for compilation extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4") if attention_mask is not None: position_ids = attention_mask.cumsum(axis=-1) - 1 extended_atten...
Python
1
for the input images and calculates the similarity with the pre-computed text embeddings to produce classification logits. Args: images (Tensor): Input images to classify. return_image_embeds (bool): Whether to return the image embeddings. return_dict (bool): Whether...
Python
1
from graphiti_core import Graphiti import os from dotenv import load_dotenv from neo4j import GraphDatabase load_dotenv() class KnowldgeGraphDB: def __init__(self): self.neo4j_uri = os.environ.get('NEO4J_URI') self.neo4j_user = os.environ.get('NEO4J_USER') self.neo4j_password = os.envir...
Python
1
# ======================================== # =============== 批量OCR页 =============== # ======================================== from .page import Page # 页基类 from ..mission.mission_ocr import MissionOCR # 任务管理器 from ..utils.utils import allowedFileName from ..platform import Platform # 跨平台 # 输出器 from ..ocr.output.ou...
Python
1
::serialize(params).unwrap(), ), ); rt.verify(); check_state(&rt); } #[test] fn fail_when_current_epoch_is_greater_than_proposal_start_epoch() { let mut rt = setup(); let deal_id = generate_and_publish_deal(&mut rt, CLIENT_ADDR, &MINER_ADDRESSES, START_EPOCH, END_EPOCH); rt.set...
Rust
0
return_value = mock_model # type: ignore[reportFunctionMemberAccess] planning_agent = DefaultPlanningAgent(mock_config) result = await planning_agent.agenerate_steps_or_error( query="Process user addition", tool_list=[AdditionTool()], end_user=EndUser(external_id="123"), plan_i...
Python
1
# flake8: noqa # pylint: skip-file # pylint: disable=too-many-instance-attributes class OCVersion(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, config, debug): ''' Const...
Python
1
ets_up_registers_if_lesser_max_is_passed() { let process = Process::default(); let prototype = FunctionPrototype::new( "my_function", LpcType::Void, FunctionArity::new(4), FunctionFlags::default(), None, ...
Rust
0
_string()); if !meta.is_internal && name.starts_with("__") { ERR.no_double_underscore( meta.name .as_ref() .map(SpanContainer::span_ident) .unwrap_or_else(|| struct_ident.span()), ); } let mut variants = vec![]; emerge_union_va...
Rust
0
doc_id = vector_manager.create_user_vector(user_id, user_data) # return json.dumps( # { # "success": True, # "message": f"✅ User vector created successfully for user {user_id}", # "user_id": user_id, # "vector_doc_id": doc_id, ...
Python
1
P_CODE) def write_stitch(f: BinaryIO, dx, dy): long = GROUP_LONG and -64 < dx < 63 and -64 < dy < 63 write_value(f, dx, long) write_value(f, dy, long) def pec_encode(pattern: EmbPattern, f: BinaryIO): color_two = True jumping = True init = True stitches = pattern.stitches xx = 0 ...
Python
1
arent = matches!( dst.cell_parent().borrow().prototype, ir::CellType::Primitive { .. } ); if dst_parent { Some(dst.canonical()) } else { None } ...
Rust
0
from consumer.ops import Consumer from utils_consumer.envHandler import getenv PREFETCH_COUNT = 5 BATCH_SIZE = 5 BATCH_INTERVAL = 0 queue_name = getenv("RMQ_QUEUE", "gaello_queue") print(f"Queue name: {queue_name}") host = getenv("RMQ_HOST", "amqp-connection") print(f"Host: {host}") if __name__ == "__main__": ...
Python
1
pub trait WeightInfo { fn bond() -> Weight; fn bond_extra() -> Weight; fn unbond() -> Weight; fn withdraw_unbonded_update(s: u32) -> Weight; fn withdraw_unbonded_kill(s: u32) -> Weight; fn validate() -> Weight; fn nominate(n: u32) -> Weight; fn chill() -> Weight; fn set_payee() -> We...
Rust
0
nd = cumulative_sums[idx + 1] q = q_B_scale2_d[:, :, start:end, :] k = k_B_scale2_d[:, :, start:end, :] q_out, k_out = apply_rotary_emb(q, k, freqs_cis=freqs_cis_my[idx]) q_out_list.append(q_out) k_out_list.append(k_out) q_out = torch.cat(q_out_list, 2) k_out = torch.c...
Python
1
import os import shutil # Define the path to the main data folder and the destination dataset folder data_folder = 'data' dataset_folder = 'dataset' # Define the subfolders based on the prefixes subfolders = ['bothFireAndSmoke', 'fire', 'neitherFireNorSmoke', 'smoke'] # Create the dataset folder and the subfolders i...
Python
1
import pygame pygame.init() window_size=(800,600) screen=pygame.display.set_mode((window_size)) pygame.display.set_caption("draw circle") ball_color=pygame.Color('red') bg_color=pygame.Color('white') ball_pos=[400,300] ball_radius=25 speed=20 while True: for event in pygame.event.get(): if event.ty...
Python
1
# -*- encoding:utf-8 -*- """Autogenerated file, do not edit. Submit translations on Transifex.""" MESSAGES = { "%d min remaining to read": "%d min resterende leestijd ", "(active)": "(actief)", "Also available in:": "Ook beschikbaar in:", "Archive": "Archief", "Atom feed": "Atom-feed", "Authors...
Python
1
Ok(()) } fn test(iso: impl AsRef<Path>) -> io::Result<()> { let vm = Vm::build("arch-zfs-iso-test")?; vm.attach_iso(iso)?; vm.run()?; test_zfs_repo_key_is_signed(&vm)?; test_zfs_is_installed(&vm)?; vm.destroy()?; Ok(()) } fn test_zfs_repo_key_is_signed(vm: &Vm) -> io::Result<()> { l...
Rust
0
--- src/mailman/tests/test_configfile.py.orig 2017-11-16 05:50:21 UTC +++ src/mailman/tests/test_configfile.py @@ -161,8 +161,8 @@ class TestConfigFileSearchWithChroot(TestConfigFileBas self.assertEqual(search_for_configuration_file(), config_file) def test_etc_file(self): - # Test /etc/m...
Python
1
term(&self) -> DynNPTerm { DynNPTerm::Type } } impl Stringify for Type { fn stringify(&self) -> String { "Type".into() } } <reponame>amy-keibler/rocket-oauth-github-demo use askama::Template; use std::sync::Arc; use crate::models::{AuthenticatedUser, Repository}; #[derive(Template)] #[tem...
Rust
0
o(device)) matches01 = matcher({"image0": feats0, "image1": feats1}) feats0, feats1, matches01 = [ rbd(x) for x in [feats0, feats1, matches01] ] # remove batch dimension kpts0, kpts1, matches = feats0["keypoints"], feats1["keypoints"], matches01["matches"] m_kpts0, m_kpts1 = kpts0[matches...
Python
1
ontains(Modifier::RAPID_BLINK) { map_error(queue!(w, SetAttribute(CAttribute::NoBlink)))?; } let added = self.to - self.from; if added.contains(Modifier::REVERSED) { map_error(queue!(w, SetAttribute(CAttribute::Reverse)))?; } if added.contains(Modifier::B...
Rust
0
5, "other_income": 15 }, "capital_gains_exemption": False, "tax_residency": "Both", "transfer_pricing": "Yes", "tax_credit": "Yes", "tax_holiday": "No", "treaty_validity": { "start_date": "2001-01-01", "end_date": "Indefinite" ...
Python
1
!(v[0].int_field, 4); assert_eq!(v[1].int_field, 2); assert_eq!(v[2].int_field, 1); assert_eq!(v[3].int_field, 3); let sort = sr.create_sort("barbar").unwrap(); sort.sort_vec(&mut v); assert_eq!(v[0].int_field, 2); assert_eq!(v[1].int_field, 1); assert_eq!(v[2].int_field, 3); assert...
Rust
0
self.value * 100.0) as i32); println!("Stopping pwm handler on {}.", self.pin); } } <gh_stars>1-10 /// Module for miscellaneous instructions use jeebie::core::cpu::CPU; use jeebie::core::registers::Register8::*; use jeebie::core::registers::Register16::*; // 'NOP' 00 4 pub fn nop(cpu: &mut CPU) -> i32 { 4 ...
Rust
0
0.outclr.write(|w| w.pin15().set_bit())) } } <filename>src/zombie/zombie_move.rs use crate::comp::{data_types::*, characters::*, sprite_sheet::*}; use bevy::{prelude::*, sprite::collide_aabb::{collide}}; pub fn zombie_moving( mut sprite_index:Local<SpriteSheet4x3>, mut game_ev:ResMut<GameCoun...
Rust
0
as_raw_mut_LpMotionStabilizer(&mut self) -> *mut c_void { self.inner_as_raw_mut() } } impl crate::videostab::IMotionStabilizerConst for PtrOfLpMotionStabilizer { #[inline] fn as_raw_IMotionStabilizer(&self) -> *const c_void { self.inner_as_raw() } } impl crate::videostab::IMotionStabilizer for PtrOfLpMotionS...
Rust
0
fields: [b_ids], references: [id])  |  "#]]; let dml = with_header(dml, Provider::Mongo, &["mongoDb"]); expect.assert_eq(&datamodel::parse_schema(&dml).map(drop).unwrap_err()); } #[test] fn embedded_many_to_many_fields_must_be_an_array_of_correct_type_postgres() { let dml = in...
Rust
0
#!/usr/bin/python # Copyright 2014 Google Inc. 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
Python
1
import pytest from chaos_lexer import ChaosLexer, TokenType def test_lex_basic_pairs(): src = '[EVENT]: memory\n[CONTEXT]: garden\n' toks = ChaosLexer().tokenize(src) assert any(t.type == TokenType.LEFT_BRACKET for t in toks) assert any(t.value == "EVENT" for t in toks) assert any(t.type == TokenTy...
Python
1
from unittest import mock import warnings from django.test import TestCase from guardian.managers import GroupObjectPermissionManager, UserObjectPermissionManager class TestManagers(TestCase): def test_user_manager_assign(self): manager = UserObjectPermissionManager() manager.assign_perm = mock....
Python
1
from typing import List from prometheus_client import REGISTRY from prometheus_client import CollectorRegistry from prometheus_client import Counter from prometheus_client import Gauge from prometheus_client import Histogram from prometheus_client import multiprocess from prometheus_client import start_http_server fr...
Python
1
max_cwnd <= curr_cwnd_f64 { self.w_max = curr_cwnd_f64; self.k = 0.0; } else { self.w_max = self.last_max_cwnd; self.k = self.calc_k(curr_cwnd_f64); } qtrace!([self], "New epoch"); } } impl WindowAdjustment for Cubic { // This is because o...
Rust
0
oncat!("Size of: ", stringify!(_binary_payload)) ); assert_eq!( ::std::mem::align_of::<_binary_payload>(), 8usize, concat!("Alignment of ", stringify!(_binary_payload)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<_binary_payload>())).payload as *const _ as usize }, 0usize, concat!( ...
Rust
0
cc, self.frequencies[x])?; self.frequencies[x] += 16; self.total_freq += 16; if self.total_freq > (1 << 16) - 17 { self.renormalize(); } let sym = self.symbols[x]; if x > 0 && self.frequencies[x] > self.frequencies[x - 1] { self.frequencies.swa...
Rust
0
eldbus_service_property_changed(iface: *const Eldbus_Service_Interface, name: *const c_char) -> EinaBool; pub fn eldbus_service_property_invalidate_set(iface: ...
Rust
0
erifier: Verifier, env: Arc<Environment>, logger: Logger, ) -> Self { let logger = logger.new(o!("mc.fog.cxn" => uri.to_string())); let ch = ChannelBuilder::default_channel_builder(env).connect_to_uri(&uri, &logger); let grpc_client = view_grpc::FogViewApiClient::new(ch); ...
Rust
0
alues.mean() # Overall mean across all columns std_value = data.values.std() # Overall standard deviation across all columns # Append the results as a dictionary, attaching the key to the CSV file name results.append({ 'CSV File': f"{csv_file} (Key:...
Python
1
from typing import List, Union, Callable, Literal import fnmatch def _match_patterns_helper(element, patterns): for p in patterns: if callable(p) and p(element): return True if fnmatch.fnmatch(element, p): return True return False def match_patterns( item: str, ...
Python
1
.ninja\n"), Include { path: value![reference!("dir"), plain!(b"/rules.ninja"),], new_scope: false, } ); test_parse!( include(b"subninja dir/build.ninja\n"), Include { path: value![plain!(b"dir/build.ninja"),], new_scope: true, ...
Rust
0
ssert_eq!(f64::color_cast_from(0u16), 0.0); assert_eq!(f64::color_cast_from(u16::max_value()), 1.0); assert_eq!(f64::color_cast_from(0u32), 0.0); assert_eq!(f64::color_cast_from(u32::max_value()), 1.0); assert_eq!(f64::color_cast_from(0.0f32), 0.0); assert_eq!(f64::color_cast_fro...
Rust
0
.width, world.height, world.quality); browser::set_layer_size( Layer::TileBg as i32, world.width, world.height, world.quality, ); browser::set_layer_size(Layer::Main as i32, world.width, world.height, world.quality); browser::set_layer_size(Layer::Fps as i32, 200, 70, wor...
Rust
0
if added or dropped: turnovers.append({ "date_from": row['date1'], "date_to": row['date2'], "players_added": len(added), "players_dropped": len(dropped), "total_changes": len(add...
Python
1
import numpy as np from shogunfolio.exceptions import EquationToMatrixError from shogunfolio.utils.equations import _string_to_equation, equations_to_matrix def test_string_to_equation(): string = "-5 - 3.5 * a + b - 2*c + 2 <= -1 + e*2.1 + f +6.5" groups = np.array([["a", "b", "c", "e", "f"]]) left, rig...
Python
1
un_server(repo, requests, stream_parameters, accessor_stats).await { e.close(control); } }) .detach() } self.archive_accessor_stats.global_stats.archive_accessor_connections_closed.add(1); }) ...
Rust
0
= '-' as i32 || *clip_path as i32 == '+' as i32 || *clip_path as i32 == '.' as i32 || *(*__ctype_b_loc()).offset(*clip_path as u8 as i32 as isize) as i32 & _ISdigit as i32 as u16 as i32 != 0 { top += 1; stack[top as usiz...
Rust
0
from cta_api.function import * import numpy as np def signal(df, para=[12, 26, 9], proportion=1, leverage_rate=1): """ MACD指标策略 :param df: 原始数据 :param para: [fast_period, slow_period, signal_period] MACD计算参数 :param proportion: 仓位比例 :param leverage_rate: 杠杆倍数 :return: 包含signal的数据 #...
Python
1
onglong; pub type ISC_DATE = ::std::os::raw::c_int; pub type ISC_TIME = ::std::os::raw::c_uint; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct ISC_TIMESTAMP { pub timestamp_date: ISC_DATE, pub timestamp_time: ISC_TIME, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct GDS_QUAD_t { pub gds_quad_high...
Rust
0
)?; } // Create a new session from the new config and use it to re-encrypt each record. println!("Re-encrypting all records, be patient..."); let session: Session = (&config).try_into()?; for record in records { log::debug!("re-encrypting {}", record.expose_secret().label); session....
Rust
0
from __future__ import annotations import asyncio import logging from pathlib import Path import streamlit as st from chatbot._dictionary import session_keys from chatbot.api.async_api import ( async_file_to_wav, async_get_tts_response, async_play_opus_file, async_write_tts_response, get_openai_r...
Python
1
Flags as Flags; let flags = Flags::USER_SEGMENT | Flags::PRESENT | Flags::LONG_MODE | Flags::DPL_RING_0; Descriptor::KernelSegment(flags.bits()) } /// 用户数据段描述符 Ring3 /// | 63-56 |55|54 |53|52 | 51-48 |47|46-45 |44|43 |42|41|40| 39-16 |15-0 | /// +-----------+--+---+--+---...
Rust
0
n.get("OPENAI_API_KEY") topic = config["topic"] categories = config["categories"] from_email = os.environ.get("FROM_EMAIL") to_email = os.environ.get("TO_EMAIL") threshold = config["threshold"] interest = config["interest"] body = generate_body(topic, categories, interest, threshold) wi...
Python
1