text
string
label_name
string
labels
int64
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch from ..config import DeepSpeedInferenceConfig from .base import BaseOp import deepspeed class LinearOp(BaseOp): def __init__(self, config: DeepSpeedInferenceConfig): super(LinearOp, self).__init__...
Python
1
residual_fn, jacobian_fn, fd_step) delta = self._solve_delta_dense(J, r) try: x_new, r_norm_new, alpha_used = stepper(x, delta, r_norm) except Exception as exc: # Map step strategy failures to convergence errors at backend level raise...
Python
1
) } } /// Mapping of valid jump destination from code. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ValidJumpAddress { first_gas_block: u64, analazis: Vec<AnalazisData>, } impl ValidJumpAddress { pub fn new(analazis: Vec<AnalazisData>, first_gas_block: u64) -> Self { Self { ...
Rust
0
*channel, }; if let Some(ch_m) = get_ch_mgr(manager, &ch_id) { trace!("### Worker[{}]: accept event {:?}", worker_id.1, event); ch_m.update(event); } else { error!("Worker[{}]: Accept event {:?}, channel not found", worker_id.1, event); } } } imp...
Rust
0
-lr: learning rate. """ #paddle.set_device('cpu') ddi = pd.read_csv(args.ddi) rna = pd.read_csv(args.rna, index_col=0) lincs = pd.read_csv(args.lincs, index_col=0, header=None).values lincs = paddle.to_tensor(lincs, 'float32') ##############independent validation############ ...
Python
1
# Copyright 2024 Canonical Ltd. # # 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, s...
Python
1
(), EcGroupId::SecP256R1).unwrap(); let pem1 = key1.write_private_pem_string().unwrap(); let secp256r1 = EcGroup::new(EcGroupId::SecP256R1).unwrap(); let mut key2 = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), secp256r1.clone()) .unwrap(); let ...
Rust
0
t { _unused: [u8; 0], } pub type OnigRegSet = OnigRegSetStruct; pub const OnigRegSetLead_ONIG_REGSET_POSITION_LEAD: OnigRegSetLead = 0; pub const OnigRegSetLead_ONIG_REGSET_REGEX_LEAD: OnigRegSetLead = 1; pub const OnigRegSetLead_ONIG_REGSET_PRIORITY_TO_REGEX_ORDER: OnigRegSetLead = 2; pub type OnigRegSetLead = ::s...
Rust
0
ICACHE_PRELOAD_SIZE register accessor: an alias for `Reg<PRO_ICACHE_PRELOAD_SIZE_SPEC>`"] pub type PRO_ICACHE_PRELOAD_SIZE = crate::Reg<pro_icache_preload_size::PRO_ICACHE_PRELOAD_SIZE_SPEC>; #[doc = "register description"] pub mod pro_icache_preload_size; #[doc = "PRO_ICACHE_AUTOLOAD_CFG register accessor: an alia...
Rust
0
""" This class is going to take a list of words and phrases and scan a folder looking for those words It will return a list of places where these words are found """ from multiprocessing.pool import ThreadPool class FileScanner: def __init__(self, base_directory, word_list): self.base_directory = base_dir...
Python
1
# coding: utf-8 # Copyright (c) 2025 OceanBase. # # 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 agr...
Python
1
WORDS.iter() { EN_US.opportunities(w); } }) }); } fn opportunities_en_us(c : &mut Criterion) { lazy_static::initialize(&EN_US); let w = "antidisestablishmentarianism"; c.bench_function("opportunities, en-US", |b| { b.iter(|| EN_US.opportunities(black...
Rust
0
import cv2 import numpy as np gt_root = '/home/prmct/Database/VOC_PASCAL/VOC2012_test/SegmentationClassAug/' pre_root = './predict/' val_pth = './val.txt' n_class = 21 def fast_hist(a, b, n): k = (a >= 0) & (a < n) return np.bincount(n * a[k].astype(int) + b[k], minlength=n ** 2).reshape(n, n) def compute...
Python
1
ata_file = data_dir.as_ref().join(DATA_FILE); let data = std::io::BufReader::new(std::fs::File::open(&data_file)?); let result = data .lines() .map(|b_res| { b_res .map(|s| s.bytes().map(|b| b - b'0').collect::<Vec<u8>>()) .map_err(|e| e.into()) ...
Rust
0
ent.strftime('%Y-%m-%d'),) current += timedelta(days=1) DateExpander(lit("2023-02-25"), lit("2023-03-01")).show() # +----------+ # | date| # +----------+ # |2023-02-25| # |2023-02-26| # |2023-02-27| # |2023-02-28| # |2023-03-01| # +----------+ def python_u...
Python
1
n::Uri, accountPairwiseId: HSTRING, out: *mut *mut WebAccountClientView) -> HRESULT }} impl IWebAccountClientViewFactory { #[inline] pub fn create(&self, viewType: WebAccountClientViewType, applicationCallbackUri: &foundation::Uri) -> Result<ComPtr<WebAccountClientView>> { unsafe { let mut out = null_mut()...
Rust
0
), } impl FromStr for HardwareError { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "error:hardware:failed-to-open" => Ok(Self::FailedToOpen), "error:hardware:failed-to-remain-open" => Ok(Self::FailedToRemainOpen), "error:hardware:fai...
Rust
0
t D3DDEVINFO_RESOURCEMANAGER; STRUCT!{struct D3DDEVINFO_D3DVERTEXSTATS { NumRenderedTriangles: ::DWORD, NumExtraClippingTriangles: ::DWORD, }} pub type LPD3DDEVINFO_D3DVERTEXSTATS = *mut D3DDEVINFO_D3DVERTEXSTATS; STRUCT!{struct D3DDEVINFO_VCACHE { Pattern: ::DWORD, OptMethod: ::DWORD, CacheSize: ::...
Rust
0
format!("<table {:?}>", ffi::lua_topointer(state, index)).into(), ffi::LUA_TFUNCTION => format!("<function {:?}>", ffi::lua_topointer(state, index)).into(), ffi::LUA_TUSERDATA => format!("<userdata {:?}>", ffi::lua_topointer(state, index)).into(), ffi::LUA_TTHREAD => format!("<thread {:?}>", ff...
Rust
0
import datetime import math from typing import Any from lilya.requests import Request from lilya.templating.controllers import TemplateController from asyncmq.conf import monkay from asyncmq.contrib.dashboard.mixins import DashboardMixin class WorkerController(DashboardMixin, TemplateController): """ Displa...
Python
1
# vim:set et sts=4 sw=4: # # ibus - The Input Bus # # Copyright (c) 2007-2010 Peng Huang <shawn.p.huang@gmail.com> # Copyright (c) 2007-2010 Red Hat, Inc. # # This library 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 Sof...
Python
1
page, cats, archives, }; render(tmpl).map_err(log_error(handler_name)) } // generated file, do not edit use crate::test_utils::{run_output_test, run_parse_test}; use exile::{Declaration, Document, Encoding, Version}; const INPUT_FILE: &str = "exile_cd_catalog.xml"; const OUTPUT_FILE: ...
Rust
0
dispute in your favor. You can do this in your [dashboard](https://dashboard.stripe.com/disputes), but if you prefer, you can use the API to submit evidence programmatically. Depending on your dispute type, different evidence fields will give you a better chance of winning your dispute. To figure out which evi...
Python
1
andle_cancel_search_tiktok(): logger.info("Cancellation requested for tiktok search") cancel_previous_task('/tiktok') io.emit('search_result', {'status': 'cancelled', 'message': 'Search cancelled by user'}, namespace='/tiktok') @io.on('cancel_search_reddit', namespace='/reddit') def handle_cancel_search_re...
Python
1
# Definimos la clase Piloto class Piloto: # Inicializador de la clase Piloto def __init__(self, edad, categoria, peso): self.edad = edad # Edad del piloto self.categoria = categoria # Categoría en la que compite o a la que pertenece el piloto (por ejemplo, Moto GP, Motero, Turismo) sel...
Python
1
upFlags::empty())`, but it's significantly /// more efficient. #[inline] pub fn self_metadata(&self) -> io::Result<Metadata> { util::fstat(self.fd).map(Metadata::new) } /// Retrieve information on the file with the given path. /// /// The specified file must be located within this d...
Rust
0
save_path = getcwd() if not file_name: file_name = d_url.split("/")[-1] response = requests.get(d_url,headers = HEADER,stream = True) save_file_path = join(save_path,file_name) data = bytes() if response.ok: ... else: raise Co...
Python
1
win: None, } } } use itertools::Itertools; use std::collections::HashMap; use std::io; use std::io::BufRead; use std::str::FromStr; #[derive(Debug)] struct Line((i32, i32), (i32, i32)); impl FromStr for Line { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { le...
Rust
0
3 { let mut rec: HitRecord = HitRecord::new(); // ignores hits very close to zero if world.hit(ray, 0.001, std::f64::MAX, &mut rec) { let mut scattered = Ray::new(&Vec3::zeros(), &Vec3::zeros()); let mut attenuation = Vec3::zeros(); //Loop and parallelise this? match rec.mate...
Rust
0
# Symbolic constants for use with sunaudiodev module # The names are the same as in audioio.h with the leading AUDIO_ # removed. from warnings import warnpy3k warnpy3k("the SUNAUDIODEV module has been removed in Python 3.0", stacklevel=2) del warnpy3k # Not all values are supported on all releases of SunOS. # Encodin...
Python
1
* < if condition > * template_block * template_block * ... * < else > * template_block * template_block * ... * < end > */ fn ifelse_block<'a>(c: &'a ParserConfig) -> impl FnMut(&'a str) -> IResult<&'a str, DynDirective> { |i| { // (&str, (&str, Vec<Box<dyn templating::directive::Generato...
Rust
0
from typing import Optional from zencfg import ConfigBase class WandbConfig(ConfigBase): """WandbConfig provides config options for setting up an interface with [Weights and Biases](https://wandb.ai). Parameters ---------- log: bool, default False whether to log outputs to W&B entity:...
Python
1
OR_MESSAGE)]), id='last error') ]) def test_error_in_strategy(self, mocked_otm, mocked_graph, strategies: List[DataflowCreationStrategy]): # GIVEN a mocked OTM with some fake components # AND a mocked graph # AND some strategies which return or not errors # WHEN DataflowCreator...
Python
1
DestroyedError> { if self._device.upgrade().is_some() { let _ = self.take_userdata(); Ok(()) } else { Err(DeviceDestroyedError) } } /// Returns a reference to set userdata, if any. pub fn userdata(&self) -> Result<Option<&T>, DeviceDestroyedError>...
Rust
0
)) } return Err(input.new_error_for_next_token()) } } impl ToCss for EndingShape { fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write { match self { EndingShape::Circle(circle) => circle.to_css(dest), EndingShape::Ellipse(ellipse) => ellipse...
Rust
0
one else 0, "papers": papers } def _parse_paper_entry(self, entry, namespaces) -> Optional[Dict[str, Any]]: """検索された論文ごとのメタ情報を抽出(著者名、所属、PDFリンクなど)""" try: title = entry.find('atom:title', namespaces) id_elem = entry.find('atom:id', namespaces) ...
Python
1
m if hasattr(args, 'use_zero') and args.use_zero: config.TRAIN.OPTIMIZER.USE_ZERO = True # set local rank for distributed training if hasattr(args, 'local_rank') and args.local_rank: config.LOCAL_RANK = args.local_rank # output folder config.MODEL.NAME = args.cfg.split('/')[-1].repl...
Python
1
= true; newFlags.Write = true; let (fd, fstat) = createAt(self.HostFd(), name, newFlags.ToLinux() | LibcConst::O_CREAT as i32, perm.LinuxMode(), owner.UID.0, owner.GID.0)?; let mountSource = dir.lock().MountSource.clone(); let inode = Inode::NewHostInode(&mountSource, fd, &fstat, tru...
Rust
0
hash); let mut valid_fp_hash: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE]; let mut n = 0; let fp; // increment every byte of the hash until we find one that is a valid fingerprint loop { for i in 0..FINGERPRINT_SIZE { valid_fp_hash[i] = fp_hash_arr...
Rust
0
Example JSON: {{ "reason": "The score is <contextual_precision_score> because <your_reason>." }} DO NOT mention 'verdict' in your reason, but instead phrase it as irrelevant nodes. The term 'verdict' are just here fo...
Python
1
// The following blocks until the mutex for this key is acquired. let guard = OwningHandle::new_with_async_fn(mutex, |mutex: *const tokio::sync::Mutex<()>| { let mutex: &tokio::sync::Mutex<()> = unsafe { &*mutex }; mutex.lock() }) .await; ...
Rust
0
} Err(e) => { Err(format!("Could not translate regex - {}", e)) } } } extern crate racer_testutils; use racer_testutils::*; #[test] fn enum_with_type_annotation() { let src = " fn main() { let s: Option<String> = None; if let Some(s) = s{ s.capa~ ...
Rust
0
$ t [s]$',fontsize=18) plt.ylabel('$\psi_{\mathcal{P}r}$',fontsize=18) Tit_string='$\psi_{\mathcal{P}'+str(r)+'}(t_k)$' plt.title(Tit_string,fontsize=17) plt.tight_layout(pad=0.6, w_pad=0.3, h_pad=0.8) Name=FOLDER_POD_RESULTS+os.sep+'POD_Psi_'+str(r)+'R.png' plt.savefig(Name, dpi=200) # plt.show() #%% Plot th...
Python
1
ast(BrowserPort, PlaywrightBrowserAsync()) else: browser = cast(BrowserPort, _NullBrowser()) # FALLBACK: Playwright when CUA not enabled elif config.is_playwright_enabled(): # Use async-compatible version to avoid "Sync API in asyncio loop" error from ..infrastructure...
Python
1
ld cache for "%s"' % dist_name) cache = None try: if not preclean: if not ignore_local: print('- trying to use local cache') yaml_str = None if os.path.exists('%s-cache.yaml.gz' % dist_name): print('- use local file "%s-cach...
Python
1
"""Binding the package attribute without importing the module.""" class submodule: attr = 'origin' class B: attr = 'origin'
Python
1
jni_args.as_ptr()) } } /// [openLogicalChannel](https://developer.android.com/reference/android/se/omapi/Session.html#openLogicalChannel(byte%5B%5D)) /// /// Required features: "android-se-omapi-Channel" #[cfg(any(feature = "all", all(feature = "android-se-omapi-Chan...
Rust
0
import requests import xml.etree.ElementTree as ET from allauth.socialaccount import app_settings from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import NextCloudProvider class NextCloudAdapter(OAuth2Adapter): provider_i...
Python
1
print(f"\nKerr Conjugacy Test:") for a_star in [0.0, 0.5, 0.9]: area_product = list(kerr_results[a_star].values())[0] scatter = kerr_scatter[a_star] print(f" a* = {a_star:.1f}: A_UV × A_IR = {area_product:.6e} m⁴ (stage scatter: {scatter:.2e})") # Spin dependence ratio area_r...
Python
1
import requests from config import START_IMG_URL def gen_image(): try: url = "https://random.imagecdn.app/v1/image?width=1280&height=720&format=json" response = requests.get(url) data = response.json() Z = data.get("url") return Z except Exception: return STAR...
Python
1
class TaskFamily: @staticmethod def get_tasks() -> dict[str, dict]: return { "1": { "art_piece": "Starry Night by Vincent van Gogh", "criteria": "Critique the piece focusing on elements such as color, composition, emotion, and technique." }, ...
Python
1
rint(f"--------------"*25) run.get_miscellaneous() print(f"Finished scrapping THe Category misceoues") for i in range(20): print(f"--------------"*25) run.get_musical_instruments() print(f"Finished scrapping THe Category musical inbtruments") for i in range(20): print(f"--------------"*25) run.get_pet_supplies(...
Python
1
for idx2, sarea in enumerate(self.sections): if sarea[0] ** 2 <= a < sarea[1] ** 2: data_dict[idx2].append(self.max_iou_distribution.data[idx1]) processes = [OneDimPlotter(value, str(key), cdf_pdf, axis_label=['iou', 'normalized numbers'], ...
Python
1
ue if not ai_text: for key, value in ai_response.items(): if isinstance(value, str) and len(value.strip()) > 50: # Substantial text content ai_text = value print(f"✅ Found substantial text in {key}: {ai_...
Python
1
AP: GET_GLYPH_OUTLINE_FORMAT = 1u32; #[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"] pub const GGO_GLYPH_INDEX: GET_GLYPH_OUTLINE_FORMAT = 128u32; #[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"] pub const GGO_GRAY2_BITMAP: GET_GLYPH_OUTLINE_FORMAT = 4u32; #[doc = "*Required features: `\"Win32_Graphics...
Rust
0
r, split, 'calib') new_val_folders['ims'] = os.path.join(curr_folder, split, 'image') new_val_folders['lab'] = os.path.join(curr_folder, split, 'label') # new_val_folders['dep'] = os.path.join(curr_folder, split, 'velodyne') org_train_file = os.path.join(curr_folder, 'ImageSets/train_org.txt') org_val_file = os.path...
Python
1
{ self.bit(variant.into()) } } #[doc = "DOZE instruction will gate all internal EMV SIM clocks as well as the Smart Card clock when the transmit FIFO is empty (default)"] #[inline(always)] pub fn doze_en_0(self) -> &'a mut W { self.variant(DOZE_EN_A::DOZE_EN_0) } #[doc = "DOZE instruction ...
Rust
0
from selene import browser, have, be import allure class WatchlistPage(): def __init__(self, browser): self.browser = browser def open(self, login): with allure.step('Open Watchlist page'): browser.open(f'/{login}/watchlist') def assert_movie_is_present(self, movie_name): ...
Python
1
name, year, need_abs, saved_fn, dblp_req_itv, req_itv, publisher, save_pkl, from_pkl_fn, ) ) if from_pkl_fn is None: collect_conf_metadata( ...
Python
1
3, Some(self.4), None) } } impl IntoOperand for Operand { fn into_op(self) -> Operand { self } } use crate::parser; use crate::util::StatefulList; use std::io; use termion::{event::Key, input::MouseTerminal, raw::RawTerminal, screen::AlternateScreen}; use tui::{ backend::TermionBackend, l...
Rust
0
_empty() && self.previous.is_some() { self.previous_symbol = self.current_symbol; self.skip_symbol(); self.current_symbol = self.iter.peek().cloned(); match self.previous_symbol { Some('A'...'Z') ...
Rust
0
import streamlit as st import yfinance as yf import pandas as pd import pandas as pd import matplotlib.pyplot as plt # plt中文展示 from pylab import mpl mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 def calculate_macd(data, fast_period=12, slo...
Python
1
ree was: // root // / \ // y key3 // / \ // x placeholder // / \ // key1 key2 let key1 = b"aaaaa".test_only_hash(); let key2 = b"bb".test_only_hash(); let key3 = b"cccc".test_only_hash(); assert_eq!(key1[...
Rust
0
def maxPoints(arr, n): if n == len(arr): return sum(arr) elif n == 1: return max(arr[0], arr[-1]) l = -n r = -1 maxSum = sum(arr[l:r] + [arr[-1]]) tempSum = maxSum while r < n - 1: tempSum -= arr[l] l += 1 r += 1 tempSum += arr[r] ...
Python
1
ages_planar_worksurface(self, mesh, ws_disc, render_mode, stable_pose=None, mat_props=None, light_props=None): """ Create ObjectRender objects of the given mesh around a viewsphere and a planar worksurface, where translated objects project into the center of the camera. Parameters ...
Python
1
#!/usr/bin/env python #coding:utf-8 import sys def base64_encode_(in_data, padding=False): in_len = len(in_data) out_data = [] for i in range(0, in_len, 3): out_data.append(in_data[i] >> 2) if i+1 < in_len: out_data.append(((in_data[i] << 4) | (in_data[i+1] >> 4)) & 63) ...
Python
1
ch.autocast("cuda", enabled=False): atom_to_token = feats["atom_to_token"].float() atom_to_token = atom_to_token.repeat_interleave(multiplicity, 0) a_to_q = self.a_to_q_trans(a.float()) a_to_q = torch.bmm(atom_to_token, a_to_q) q = q + a_to_q.to(q) atom_...
Python
1
import numpy as np from sklearn.metrics import confusion_matrix, cohen_kappa_score, precision_score, recall_score, f1_score import matplotlib.pyplot as plt import seaborn as sns def overall_accuracy(y_true, y_pred): return np.sum(y_true == y_pred) / len(y_true) def average_accuracy(y_true, y_pred): cm = confu...
Python
1
23, [0x2abfbf3f6b20c8d0, 0xc2f80241a12f5184], [0x666b059fe4da912f, 0x09b8e5d19777377b]), "b7e0f6c7f5aa56b7331aeab31e82054ea4e2bc5d28fd409893429d2125ee8ae4b5f23b7a212bc488d73b56ad92c46d1639e3e8e4e7f2c7b8d0c83f257c4fad12" ), ( // Len = 1016 "<KEY>", (64, 62, [0x720f99d72960f86c, 0xb2fce59cb96b79f5], [0x1e46e9d...
Rust
0
proto::UpdateKeyGenerationResult> for DelegatorKeyGenStoreItem { type Error = anyhow::Error; fn try_into( self, ) -> Result<crate::actor_delegate_proto::UpdateKeyGenerationResult, Self::Error> { Ok(crate::actor_delegate_proto::UpdateKeyGenerationResult { task_id: base64::decode(...
Rust
0
urrent_commit_num: i64, ) -> QueryResult<()> { update(product::table) .filter( product::product_address .eq(address) .and(product::end_commit_num.eq(MAX_COMMIT_NUM)), ) .set(product::end_commit_num.eq(current_commit_...
Rust
0
") .map_err(|_| UErr::Relative)?, ), prefix, cwd, output: output.to_owned(), ..GCRoots::default() }) } } impl Register for GCRoots { fn register_loop(&mut self, rx: GCRootsRx) { for sp in rx { self.outpu...
Rust
0
/ let dist: MvNormal = MvNormal::new_unchecked(vec![0.0, 1.0], cov); /// ``` pub fn new_unchecked<M, S>(mu: M, Sigma: S) -> Self where M: Into<Vector<f64>>, S: Into<Matrix<f64>>, { let params = Params { mu: Loc(mu.into()), Sigma: Covariance(Sigma.into()), ...
Rust
0
import torch from torch import nn from torchsummary import summary class Residual(nn.Module): def __init__(self, input_channels, num_channels, use_1conv=False, strides=1): super(Residual, self).__init__() self.ReLU = nn.ReLU() self.conv1 = nn.Conv2d(in_channels=input_channels, out_channel...
Python
1
CL; use simple_logger::SimpleLogger; use anyhow::Result; // use std::path::{Path, PathBuf}; use std::path::{PathBuf}; use clap::{App, Arg}; use zquery_core::Zq; use zquery_core::config::{InputConfig, OutputConfig, Config}; fn main() -> Result<()> { SimpleLogger::new().init().unwrap(); let matches = App::...
Rust
0
! let lazycell = LazyCell::new(); //! //! assert_eq!(lazycell.borrow(), None); //! assert!(!lazycell.filled()); //! lazycell.fill(1).ok(); //! assert!(lazycell.filled()); //! assert_eq!(lazycell.borrow(), Some(&1)); //! assert_eq!(lazycell.into_inner(), Some(1)); //! ``` //! //! `AtomicLazyCell` is a variant that uses ...
Rust
0
db.commit() # Try to validate token validated_token = APITokenService.validate_token(test_token.token, db) assert validated_token is None def test_validate_token_after_rate_limit_reset( db: Session, test_user, test_subscription, test_token ): # Set rate limit to maximum rate_limit = db.que...
Python
1
=> "SH_LIB", ProgramHeaderType::PhDr => "PH_DR", ProgramHeaderType::Tls => "TLS", ProgramHeaderType::LoOs => "LO_OS", ProgramHeaderType::HiOs => "HI_OS", ProgramHeaderType::LoProc => "LO_PROC", ProgramHeaderType::HiProc => "HI_PROC", P...
Rust
0
.map(|line| line.split(',').map(|x| x.parse().unwrap()).collect()) .collect(); (fields, tickets) } fn day16a() -> u64 { let (fields, tickets) = get_input(); let mut error_rate = 0; for ticket in &tickets { 'check_number: for number in ticket { for field in &field...
Rust
0
sk_new[:, 0] * lks_mask_new[:, 1] lks_mask_new[:, 1] = lks_mask_new[:, 0] * lks_mask_new[:, 1] lks_mask_new[:, 2] = lks_mask_new[:, 2] * lks_mask_new[:, 3] lks_mask_new[:, 3] = lks_mask_new[:, 2] * lks_mask_new[:, 3] lks_mask_new[:, 4] = lks_mask_new[:, 4] * lks_mask_new[...
Python
1
#!/usr/bin/env python from __future__ import print_function from datetime import datetime import ConfigParser import csv import gzip import json import logging import logging.config import os import os.path import paramiko import sys def main(): if (len(sys.argv)) != 2: print('Usage: {0} /path/to/script'...
Python
1
et" ], "Maver" => &[ "Mavine" ], "Midd" => &[ "Madeline" ], "Morr" => &[ "Seymour" ], "Moss" => &[ "Maurice" ], "Nabb" => &[ "Abigail" ], "Napp" => &[ "Napoleon" ], "Nepp" => &[ "Penelope" ], "Ness" => &[ "Agnes" ], "Nibb" => &[ "Isabella" ], "Nic" => &[ "Vernisee" ], "Nikk" ...
Rust
0
import os from unittest import TestCase from os import environ from cate.core.common import initialize_proxy from cate.conf import conf class CommonTest(TestCase): @classmethod def setUp(cls): if environ.get('http_proxy'): os.environ.pop('http_proxy') if environ.get('https_proxy')...
Python
1
TARGET_EXE, &["--color=always", "-e", "exec-target", "Cargo.toml"], ); assert_eq!(oup.stderr, ""); assert_eq!( oup.stdout, "name = \"\u{1b}[01;31m\u{1b}[Kexec-target\u{1b}[m\u{1b}[K\"\n" ); assert_eq!(oup.status.success(), true); } #[te...
Rust
0
d_attrs.iter().cloned())) .map(|attr| attr.clone()) .collect::<Vec<String>>(); let mtilde = get_mtilde(&unrevealed_attrs)?; let aprime = pk.s .mod_exp(&r, &pk.n, Some(&mut ctx))? .mul(&c1.a, Some(&mut ctx))? .modulus(&pk.n, Some(&mut ...
Rust
0
onses["conversation"]) except Exception as e: logger.error(f"Error generating generic response: {str(e)}") return "Desculpe, estou com dificuldades para entender no momento." def generate_contextual_response(self, user_input, context): """ Generate a res...
Python
1
q)): if query_seq[i] != target_seq[i]: obs_mis += 1 if obs_mis > n_mismatch: matching = False break return matching def find_target_sequence_match(query_seq, target_seq, n_mismatch=1): '''Look for the presence of target sequence in query sequence''' asse...
Python
1
# Copyright (c) 2021 - present / Neuralmagic, 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 b...
Python
1
unsafe { GetClassNameW(self.0, PWSTR(buffer.as_mut_ptr()), len as i32); WideCString::from_ptr_str(buffer.as_ptr()).to_string_lossy() } } /// This function returns the size of the window INCLUDING the extend window frame pub fn get_full_size(&self) -> Size { uns...
Rust
0
# Usage: python create_refatoms.py <options> # Emilio Gallicchio, 6/2023 import os, sys, fileinput, re import numpy as np from time import time # following for argument passing tools import argparse # OpenMM components from openmm.app import PDBFile, Topology def list_to_string(alist): s = str(alist[0]) for...
Python
1
4E", symbol_id="/", symbol_code=">", comment="Test standard", time_dhm="011234z", compressed=False, ) frame = self.aprs.kiss_protocol.protocol.written_frames[-1] self.assertIsNotNone(frame) info = frame.info.decode() sel...
Python
1
StoreLocal {index: u16, type_: JavaTypeKind}, // //Arrays // LoadFromArray {type_: JavaTypeKind}, // StoreToArray {type_: JavaTypeKind}, // GetArrayLength, // NewPrimitiveArray {type_: JavaTypeKind}, // NewRefArray {type_: Arc<RwLock<JavaClass>>}, // NewMultiArray {array_type: Arc<RwLock<J...
Rust
0
import requests from bs4 import BeautifulSoup from dataclasses import dataclass URL = r"https://en.wikipedia.org/wiki/Prison_Break" @dataclass class EvadAdat: evad: str epizodok_szama: int def main(): valasz = requests.get(URL) leves = BeautifulSoup(valasz.text, "html.parser") print("Összes kép...
Python
1
/// 全角 JIS 記号 PILCROW_SIGN pub const WIDE_JIS_SYMBOL_PILCROW_SIGN: u32 = 0x00b6; /// 全角 JIS 記号 MIDDLE_DOT pub const WIDE_JIS_SYMBOL_MIDDLE_DOT: u32 = 0x00b7; /// 全角 JIS 記号 CEDILLA pub const WIDE_JIS_SYMBOL_CEDILLA: u32 = 0x00b8; /// 半角 JIS 記号 SUPERSCRIPT_ONE pub const NARROW_JIS_SYMBOL_SUPERSCRIPT_ONE: u32 = 0...
Rust
0
}).collect()); } return observers; } /// Returns all keypaths that are being observed, relative to this subscription as the root pub fn collect_pubsub_patterns(&self, into: &mut Vec<Vec<String>>, root: Vec<String>) -> bool { let mut had_any = self.clients.len() > 0; ...
Rust
0
); } let tmr = stimer!("Calculate project graphs and redundant projects"); let mut individual_graphs = make_project_graphs(&analysis); let individual_graphs = individual_graphs .iter_mut() .map(|(sln, graph)| { let removed_edges = graph.transitive_reduction(); ...
Rust
0
import random def choose_word(): words = ["hangman", "game", "program", "words", "guessing"] return random.choice(words) def show_word(word, guessed): display = "" for letter in word: if letter in guessed: display += letter else: display += "_" return displa...
Python
1
from typing import Any, Dict import torch from invokeai.backend.flux.ip_adapter.xlabs_ip_adapter_flux import XlabsIpAdapterParams def is_state_dict_xlabs_ip_adapter(sd: Dict[str, Any]) -> bool: """Is the state dict for an XLabs FLUX IP-Adapter model? This is intended to be a reasonably high-precision detec...
Python
1
use std::time::Duration; use notify_rust::server::NotificationServer; use notify_rust::Hint; use notify_rust::Notification; use notify_rust::Urgency::*; fn freeze(message: &str) { println!("{}", message); // let mut _devnull = String::new(); // let _ = std::io::stdin().read...
Rust
0
from typing import Dict, Optional from dataclasses import dataclass import pyarrow from enum import Enum from . import evm, svm import cherry_core.cherry_core as cc class ProviderKind(str, Enum): SQD = "sqd" HYPERSYNC = "hypersync" YELLOWSTONE_GRPC = "yellowstone_grpc" RPC = "rpc" class QueryKind(st...
Python
1