text
string
label_name
string
labels
int64
from django.test import SimpleTestCase from django.test.utils import override_settings from django.urls.resolvers import RegexPattern, RoutePattern, get_resolver from django.utils.translation import gettext_lazy as _ class RegexPatternTests(SimpleTestCase): def test_str(self): self.assertEqual(str(RegexPa...
Python
1
found_secret def calculate_work_idxs(args): n_work_full = sum( math.comb(args.bf_dim, hw) for hw in range(args.min_bf_hw, args.max_bf_hw + 1) ) n_work_per_worker = math.ceil(n_work_full / args.work_split_into) assert args.which_worker_am_i < args.work_split_into start = args.which_worker_a...
Python
1
.distance_travelled += 1; } } fn check_end_condition(&self, _num_execd_instructions: usize) -> bool { self.x == self.tx && self.y == self.ty } } let mut agent = Agent{ x: test_case.pos_x, y: test_case.pos_y, tx: test_case.target_x, ...
Rust
0
// Ok(proof) => Ok(serde_wasm_bindgen::to_value(&proof).map_err(|e| JsValue::from(e)).unwrap()), Ok(proof) => Ok(obj_to_uint8array!(&proof, false, "BBS+ProofG1")), Err(e) => Err(JsValue::from(&format!("{:?}", e))), } } #[wasm_bindgen(js_name = bbsVerifyProofOfKnowledgeOfSignature)] pub fn b...
Rust
0
#рекорды 2.0 не работает, нужно найти ошибку!!!!!! #демонстрирует вложенные последовательности scores = [] choice = None while choice != "0": print( """ Рекорды 2.0 0 - Выйти 1 - Показать рекорды 2 - Добавить рекорд """ ) choice = input("Ваш выбор: ") print() #выход if choice =...
Python
1
sage = Message::Add(AddMessage { command: command.into(), path: shared.pueue_directory(), envs: HashMap::new(), start_immediately: false, stashed: false, group: group.to_owned(), enqueue_at: None, dependencies: vec![], label: None, print_ta...
Rust
0
selections = [] for i, row in enumerate(self.selection_rows): algo_name = row["combo"].currentText() hyperparams = {} if row["use_default"]: config_path = get_config_path("config_algorithm.yaml") try: with open(config_path...
Python
1
lag, mode: Mode) -> Result<RawFd> { let ret = try!(name.with_nix_path(|cstr| { unsafe { ffi::shm_open(cstr.as_ptr(), flag.bits(), mode.bits() as mode_t) } })); Errno::result(ret) } pub fn shm_unlink<P: ?Sized + NixPath>(name: &P) -> Result<()> { let ret = try!(name.with_nix...
Rust
0
) -> SetBio { self.inner.clone() } pub fn bio<T: AsRef<str>>(&mut self, bio: T) -> &mut Self { self.inner.bio = bio.as_ref().to_string(); self } } impl AsRef<SetBio> for SetBio { fn as_ref(&self) -> &SetBio { self } } impl AsRef<SetBio> for RTDSetBioBuilder { fn as_ref(&self) -> &SetBio { &self....
Rust
0
USEHOVERWIDTH, 0x0063 GETMOUSEHOVERHEIGHT, 0x0064 SETMOUSEHOVERHEIGHT, 0x0065 GETMOUSEHOVERTIME, 0x0066 SETMOUSEHOVERTIME, 0x0067 GETWHEELSCROLLLINES, 0x0068 SETWHEELSCROLLLINES, 0x0069 GETMENUSHOWDELAY, 0x006a SETMENUSHOWDELAY, 0x006b GETWHEELSCROLLCHARS, 0x006c SETWHEELSCROLLCHARS, 0x006d GETSHO...
Rust
0
#exercise 4 my_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse ci...
Python
1
'] # Dark Pixel Percentage blur = df['Blur Amount'] # Blur Amount # Create a 3D scatter plot fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111, projection='3d') # Plot the scatter points with color mapping based on the blur amount scatter = ax.scatter(cci, dpp, blur, c=blur, cmap='v...
Python
1
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: messages_robocup_ssl_detection.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_po...
Python
1
rib4Nsv", "glVertexAttrib4Nub", "glVertexAttrib4Nubv", "glVertexAttrib4Nuiv", "glVertexAttrib4Nusv", "glVertexAttrib4s", "glVertexAttrib4sv", "glVertexAttrib4ubv", "glVertexAttrib4uiv", "glVertexAttrib4usv", "glVertexAttribPointer", ], enums_removed: &[], commands_removed: ...
Rust
0
ing0fromKtoB::Forward, Branching0fromKtoC::Forward, Branching0fromKtoD::Forward, Branching0fromKtoE::Forward, Branching0fromKtoF::Forward, Branching0fromKtoG::Forward, Branching0fromKtoH::Forward, Branching0f...
Rust
0
//! | | <-- current stack pointer //! +------------------+ //! //! # Differences from Wasm //! //! - There is no `nop` instruction. //! - All control flow structures are flattened to plain gotos. //! - Implicit returns via reaching function scope `End` are replaced with an explicit `return` instructio...
Rust
0
D::Error> where D: de::Deserializer<'de>, { let mut map = BTreeMap::<Value, Value>::deserialize(d)?; let kind = match map.remove(&Value::String("kind".to_owned())) { Some(kind) => kind.deserialize_into().map_err(|e| e.to_error())?, None => "pattern".to_owned(), ...
Rust
0
from django.urls import path from .views import LoginView, CadastroView, ListUsuario urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('cadastro/', CadastroView.as_view(), name='cadastro'), path('usuarios/', ListUsuario.as_view(), name='list-usuarios') ]
Python
1
) => PlayerEvent::Removed, ( PlayerEvent::Updated { delta, registration, active }, PlayerEvent::Updated { delta: new_delta, registration: new_registration, active: new_active, }, ) => Play...
Rust
0
f.map } pub fn extensions_mut(&mut self) -> &mut ShareMap { &mut self.map } /// Take the body from the hyper request. Once taken the body is not longer /// available. This method will return `None` in that case. /// /// For small non-streaming applications, the body access methods ...
Rust
0
Self { pattern_kind } } pub fn of_kind(kind: &'static str) -> Self { Self { pattern_kind: PatternKind::KindPattern(kind), } } pub fn match_node<'tree>(&self, node: Node<'tree>) -> Option<(Node<'tree>, MetaVarEnv<'tree>)> { match &self.pattern_kind { ...
Rust
0
TS: `(` (`$EXPORT`,`?)* `)` /// - $EXPORT: [AtomToken] `/` [IntegerToken] #[derive(Debug, Clone, Span, Parse, Format)] pub struct ExportAttr(AttrLike<Either<ExportAtom, ExportTypeAtom>, ExportItems>); #[derive(Debug, Clone, Span, Parse)] struct ExportItems { open: OpenSquareSymbol, items: Items<ExportItem, Com...
Rust
0
cription": "Date for weather check" } }, "required": ["city"] } }, "user_input": "今天北京的天气怎么样?" }, { "tool_info": { "name": "send_email", "spec": { ...
Python
1
.or_insert_with(|| graph.add_node(name)); } $( { let source = nodes[&stringify!($source)]; let target = nodes[&stringify!($target)]; graph.add_edge(source, target, ()); } )* ...
Rust
0
from django.urls import path from . import views app_name = "inventory" urlpatterns = [ path("", views.index, name="index"), path("new", views.new, name="new"), path("show/<int:id>", views.show, name="show"), path("edit/<int:id>", views.edit, name="edit"), path("delete/<int:id>", views.delete, n...
Python
1
print('{:>5} error for seq_len {}: {:.4f} +- {:.4f}'.format(measure, seq_len, mean_error, se_error)) print('Averaged errors:') for measure in ['trans', 'rot']: e_means = [] e_ses = [] for seq_len in sorted(average_errors[measure].keys()): e = np...
Python
1
ayed_process| &delayed_process.arc_process == value) } pub fn len(&self) -> usize { self.0.len() } pub fn dequeue(&mut self) -> Run { match self.0.pop_front() { Some(mut delayed_process) => { if delayed_process.delay == 0 { Run::Now(delay...
Rust
0
import numpy as np import datetime from matplotlib import pyplot as plt from wotan import flatten from betellib import tweet, build_string, get_mags_from_AAVSO def make_plot(days_ago, dates, mag): print('Making plot...') time_span = np.max(dates) - np.min(dates) min_plot = 0.0 max_plot = 1.75 x_da...
Python
1
} } if self.target.is_dir() { match fs::symlink_dir(&self.target, &dest) { Ok(_) => info!("Creating symlink dir {:?} -> {:?}", dest, self.target), Err(e) => error!("Error -- Creating symlink dir {:?}: {}", dest, e), } } } } ...
Rust
0
from vocabularies import VocabType from config import Config from interactive_predict import InteractivePredictor from model_base import Code2VecModelBase import tensorflow as tf def load_model_dynamically(config: Config) -> Code2VecModelBase: assert config.DL_FRAMEWORK in {'tensorflow', 'keras'} if config.DL_...
Python
1
LTACT_A::LOW, 3 => PFLTACT_A::HIGH, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `UNCHG`"] #[inline(always)] pub fn is_unchg(&self) -> bool { *self == PFLTACT_A::UNCHG } #[doc = "Checks if the value of the field is `TRIS`"] #[i...
Rust
0
# Generated by Django 4.2.20 on 2025-09-17 16:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("ciudadanos", "0005_alter_ciudadano_documento"), ] operations = [ migrations.AddField( model_name="ciudadano", name=...
Python
1
#!/usr/bin/env python3 """ Setup script for VASP DOS Plotter """ from setuptools import setup, find_packages import os # Read the README file def read_readme(): with open("README.md", "r", encoding="utf-8") as fh: return fh.read() # Read requirements def read_requirements(): with open("requirements.t...
Python
1
''' The MIT License (MIT) Copyright (c) 2013 Dave P. ''' # import BaseHTTPServer, SimpleHTTPServer # import ssl # # openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem # httpd = BaseHTTPServer.HTTPServer(('', 443), SimpleHTTPServer.SimpleHTTPRequestHandler) <target> # httpd.socket = ssl.wrap_socket...
Python
1
: &mut Location) -> bool { let sec_name = irdb.get_opnd_as_identifier(&ir, 0).to_string(); self.trace(format!("Engine::iterate_section_end: '{}', img {}, sec {}", sec_name, current.img, current.sec).as_str()); current.sec += self.sec_offsets.pop().unwrap(); // Track that'...
Rust
0
) -> str: """生成PoB2可导入的构筑代码""" try: # 构建PoB2格式的构筑数据 pob2_build = { 'version': build_config.get('version', '3_0'), 'character': build_config.get('character', {}), 'skills': self._convert_skills_to_pob2_format(build_config.ge...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'SMS on Events', 'version': '1.0', 'category': 'Marketing/Events', 'description': """Schedule SMS in event management""", 'depends': ['event', 'sms'], 'data': [ 'data/sms_data.xm...
Python
1
&AttrContext::Module, &Attr::AttrNone, )?; w.write_all(module_def.name.as_bstr())?; w.write_all(b" ")?; print_span(w, &module_def.span)?; w.write_all(b" {")?; newline(w)?; w.write_all(b"}")?; newline(w) } fn print_pos_as_prov_tag( ctx: &Context<'_>, w: &mut dyn Write, ...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017 Baidu, 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/LIC...
Python
1
to be cleared and the data to be appended to the"] #[doc = "base table."] #[doc = ""] #[doc = "This should generally not be used unless you know what you are doing. Instead, call `duckdb_appender_destroy` when you"] #[doc = "are done with the appender."] #[doc = ""] #[doc = " appender: The appe...
Rust
0
'id': 0, 'created_at': 1, 'updated_at': 2, 'title': 3, 'desc': 4, 'location': 5, 'time': 6, 'is_hidden': 7, 'remark': 8 } # 迁移博客数据 blogs_data = await source_conn.execute_query('SELECT * FRO...
Python
1
) result = pytester.runpytest() assert result.ret == pytest.ExitCode.TESTS_FAILED result.assert_outcomes(passed=1, failed=1) result.stdout.fnmatch_lines( [" | *ExceptionGroup: multiple thread exception warnings (2 sub-exceptions)"] ) def test_unraisable_collection_failure(pytester: P...
Python
1
const KEY_PREFIX_ID_TO_SEQ: char = 'I'; /// for getting/scanning the all the seqs pub const KEY_PREFIX_SEQ: char = 'S'; /// number values index pub const KEY_PREFIX_NUMBER: char = 'f'; /// for true values index pub const KEY_PREFIX_TRUE: char = 'T'; /// for false value index pub const KEY_PREFIX_FALSE: char = 'F'; ///...
Rust
0
.0f32) + col("sepal.width")]) .logical_plan; let mut expr_arena = Arena::new(); let mut lp_arena = Arena::new(); let rules: &mut [Box<dyn OptimizationRule>] = &mut [Box::new(SimplifyExprRule {})]; let optimizer = StackOptimizer {}; let mut lp_top = to_alp(plan, &mut expr_arena, &mut lp_are...
Rust
0
", token ) .fetch_optional(&self.pool) .await?; if let Some(x) = character { if let Some(id) = x.character_id { Ok(id.into()) } else { Err(Error::InvalidUser) } } else { Err(Error::Inval...
Rust
0
().transpose((0, 2, 1, 3)).reshape(M, N) np_c = np.matmul(a_np.astype("int32"), b_np.astype("int32").T) print("np result: ", np_c[0][0:10]) print("tvm result: ", c_np[0][0:10]) np.testing.assert_allclose( c_np, np_c, rtol=1e-3, atol=1e-3 ) print("assert_allclose pass!") np.testing.as...
Python
1
te(TYPE_UINT | 27)?; self.put_bytes( unsafe { &mut *(&mut v as *mut u64 as *mut [u8; 8]) }, true ) } } } #[inline] fn serialize_f32(self, mut v: f32) -> Result<()> { self.put_byte(TYPE_MISC | 4)?; se...
Rust
0
N, 1, D] dim = data.size()[-1] priors = torch.unsqueeze(priors, 1) # [B, 1, K] radii = torch.unsqueeze(radii, 1) # [B, 1, K] neg_dist = -torch.sum((data - cluster_centers)**2, 3) # [B, N, K] log_likelihood = 0.5 * neg_dist / (radii) - 0.5*dim*(torch.log(radii) - np.log(2 * np.pi)) l...
Python
1
s sent by the client or browser as the origin of the request. It is set through an `Origin` header. * **Access-Control-Allow-Methods**: This specifies the allowed options for requests from that domain. This will generally be all available methods. * **Access-Control-Expose-Headers**: This will contain the headers t...
Python
1
import json from rich import print from pprint import pprint from rich.console import Console from pycentral.base import ArubaCentralBase from pycentral.workflows.workflows_utils import * # Get central_information from file by calling this module console = Console() def caas_push_configuration(group_name,config_f...
Python
1
.clone(), id, key, } } #[allow(unused)] pub(crate) async fn has_id(&self, id: &I) -> bool { let store = self.store.read().await; store.id_map.contains_key(id) } pub(crate) async fn remove(&self, addr: &SocketAddr) -> Vec<Connection> { let mu...
Rust
0
d('G1 X10 Y10 Z2 F6000') self.gcode.run_script_from_command('G1 Z0.2 F300') self.pheaters = self.printer.lookup_object('heaters') self.heater_hot = self.printer.lookup_object('extruder').heater self.gcode.respond_info("can_break_flag = %d" % (self.pheaters.can_break_flag)) self.g...
Python
1
, WIN_HEIGHT)) # Set the parameter configuration for NEAT local_dir = os.path.dirname(__file__) config_path = os.path.join(local_dir, "parameter.txt") configuration = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation...
Python
1
import time import random def wait(t=1): time.sleep(t) def start_game(): print("🌍 Welcome to PyLand: The Code Quest 🎮🐍") wait() print("✨ You must learn Python magic 🪄 to defeat the Bug Overlord 👹.\n") wait() # -------- level 1 ------------ def village_level(): print("🏡 Level 1 - The Vil...
Python
1
extensions.append(id_ext) patient.extension = extensions # Build photo attachment if hasattr(data_obj, "photo") and data_obj.photo: photo = Attachment.model_construct() photo.contentType = "image/jpeg" # Default to JPEG photo.title = f"Photo of {data_obj....
Python
1
""" We can think of this as a set of simultaneous equations: xbutton1 and yButton2 = endGoal All of these have exactly 2 values, and we know button1, button2 and endgoal n*b1x + m*b2x = endGoalx n*b1y + m*b2y = endGoaly Solvable as a simultaneous equation """ import sympy as sym n, m = sym.symbols("n, m") with o...
Python
1
8().unwrap(); let (width, height) = img_view.dimensions(); let (width, height) = (width as usize, height as usize); let len = width * height; assert!(width.is_power_of_two()); println!("shader setup"); // setup some shaders let context = Context::new().unwrap(); let view = BufferViewBuil...
Rust
0
print(f"💰 總收益率: {returns.get('total_return', 0):.2%}") print(f"📈 年化收益率: {returns.get('annual_return', 0):.2%}") print(f"📊 夏普比率: {risk.get('sharpe_ratio', 0):.2f}") print(f"📉 最大回撤: {risk.get('max_drawdown', 0):.2%}") print(f"🎯 勝率: {trade.get('win_rate', 0):.2%}") print(f"💡...
Python
1
""" https://github.com/pytorch/vision/blob/main/torchvision/models/_utils.py Copyright(c) 2023 lyuwenyu. All Rights Reserved. """ from collections import OrderedDict from typing import Dict, List import torch.nn as nn class IntermediateLayerGetter(nn.ModuleDict): """ Module wrapper that returns intermedi...
Python
1
f.user(UserID::ID(user.id)).mode(m)) .await? .into_iter() .filter(|s| s.mods.contains(mods)) .collect::<Vec<_>>(); scores.sort_by(|a, b| b.pp.unwrap().partial_cmp(&a.pp.unwrap()).unwrap()); if scores.is_empty() { m...
Rust
0
""" CRIAR A V2 DO NOSSO SITEMA BANCÁRIO -> Separar funções existentes de saque, depósito e extrato em funções. -> Criar 2 novas funções : Cadastrar Usuário (cliente) e Cadastrar conta bancária (vinculada ao cliente) -> Criar funções para as operações existentes: Sacar, Depositar e Visualizar extrato SAQUE -> A funçã...
Python
1
Id>> } #[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub struct Replica<AccountId> { // Controller account pub who: AccountId, // The last bloch number when the node reported works pub valid_at: BlockNumber, // The ancho...
Rust
0
process: process.to_owned(), }) } fn parse_inittab<R: BufRead>(mut reader: R) -> Result<BinaryHeap<InittabEntry>> { let mut result = BinaryHeap::new(); let mut line = vec![]; let mut count = 1; while reader.read_until(b'\n', &mut line)? > 0 { if let Some(entry) = parse_entry(&line,...
Rust
0
# Make sure it's a file if not os.path.isfile(full_path): return { "error": f"Not a file: {file_path}", "success": False } try: # Read the file content with open(full_path, 'r', encoding='utf-8') as f...
Python
1
delta_mcap.copy() negative = delta_mcap.copy() positive[positive < 0] = 0 negative[negative > 0] = 0 avg_gain = positive.rolling(window = days).mean() avg_loss = abs(negative.rolling(window = days).mean()) r_strength = avg_gain / avg_loss print(r_strength) print(r_strength.shape) df...
Python
1
rstate = render(rstate, &model).unwrap(); let timer = timer::Timer::new(); loop { let ch = match std::char::from_u32(ncurses::getch() as u32) { Some(ch) => ch, None => '\0' }; model = match ch { 'q' => model.update(Message::Quit), 'r...
Rust
0
max = (t_max * (t_max + 1)) / 2; break SimResult::Success(y_max); } } } } fn simulate_part_a(x_min: i32, x_max: i32, y_min: i32, y_max: i32) -> i32 { let mut ret = 0; // Parameters chosen somewhat arbitrarily 'outer: for dx in (0..x_max).rev() { 'inner: for d...
Rust
0
// > The system User IDs from 100 to 499 should be reserved for dynamic allocation by system // > administrators and post install scripts using useradd. for uid in 150..=499 { if get_user_by_uid(uid).is_none() { hint = format!( "{} with the command:\n sudo useradd '{}...
Rust
0
experiences, with priority and importance sampling.""" if len(self.memory) == self.capacity: priorities = self.priorities else: priorities = self.priorities[:self.position] # Calculate probabilities with prioritization (add epsilon to avoid zero priority) ...
Python
1
, var) in variables.iter().rev().enumerate() { varmap.insert(*var, !bit_at(i, j)); } let eval_results = exprs .iter() .map(|e| evaluate_postfix(e, &varmap)) .collect::<Result<Vec<bool>, String>>()?; // If this row is invalid or not if eva...
Rust
0
um, 'title': chapter_title if chapter_title else f"Capítulo {chapter_num}", 'content': chapter_content, 'word_count': len(chapter_content.split()) }) if update_callback: update_callback(chapt...
Python
1
), doc=attr_value.__doc__, ) return attr_value class TelemetryMeta(type): def __new__( cls, name: str, bases: tuple, attrs: dict[str, Any] ) -> Union[ "snowflake.snowpark.modin.plugin.extensions.groupby_overrides.DataFrameGroupBy", "snowflake.snowpark.mod...
Python
1
return Bounds { center, radius: point_sphere.1, cone_apex: glm::vec3(0.0, 0.0, 0.0), cone_axis: glm::vec3(0.0, 0.0, 0.0), cone_cutoff: 0.0, }; } let mut maxt = 0.0; for tri in triangles.iter() { for p in [tri.p0, tri.p1, tr...
Rust
0
is_ok() } pub fn as_bytes(&self) -> &[u8] { unsafe { core::slice::from_raw_parts( (self as *const DS4Signature) as *const u8, core::mem::size_of::<DS4Signature>(), ) } } } impl fmt::Debug for DS4Signature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writ...
Rust
0
import sys, os, time sys.path.insert(1, os.path.join(sys.path[0], '..')) import instance_loader import numpy as np from util import timestamp, memory_usage def sigmoid( x, derivative = False ): return x*(1-x) if derivative else 1/(1+np.exp(-x)) #end sigmoid def run_and_log_batch( sess, solver, epoch, b, batch, time...
Python
1
dataframe['fastd'])) conditions.append(dataframe['resample_sma'] < dataframe['close']) # Check that volume is not 0 conditions.append(dataframe['volume'] > 0) if conditions: dataframe.loc[ reduce(lambda x, y: x & y, conditions), 'enter_long']...
Python
1
import user_features as ufis_verified(user): import csv import ijson import pandas as pd import time def get_user_vector(user): user_vector = { "user_id": uf.get_user_id(user), "profile_description": uf.has_description(user), "profile_location": uf.has_location(user), "profile_url"...
Python
1
""" Guia 2.3.5. Ejercicio 5 La pizzeria Cesar’s Pizza, contiene una variada gama de pizzas para escoger. La pizzeria se caracteriza por tener una atención rápida y mantener sus precios más bajos que la competencia. La gerencia le solicita realizar un programa que permita calcular los costos del pedido con sus respectiv...
Python
1
ize = a.len() as isize; let ib_len: isize = b.len() as isize; indel_lengths.push(ia_len.wrapping_sub(ib_len).abs()); // number of snps, insertions, deletions if a.len() != 0 && b.len() != 0 { if a.len() == b.len() { snps += 1; ...
Rust
0
from .sd import SD15Wrapper from hcpdiff.utils import pad_attn_bias class PixArtWrapper(SD15Wrapper): def forward_TE(self, prompt_ids, timesteps, attn_mask=None, plugin_input={}, **kwargs): # T5Encoder do not need position_ids (It use relative position embedding for key and query) input_all = dict(...
Python
1
units by sitting next to David.", "Carol would lose 62 happiness units by sitting next to Alice.", "Carol would gain 60 happiness units by sitting next to Bob.", "Carol would gain 55 happiness units by sitting next to David.", ...
Rust
0
class Solution: def rob(self, nums: List[int]) -> int: rob1,rob2 = 0, 0 for n in nums: temp = max(n + rob1 , rob2) rob1 = rob2 rob2 = temp return rob2
Python
1
E=CELL:+55 27 91234-5678 TEL;TYPE=CELL:+55 27 1234-5678 END:VCARD """ # Test case 5: Multiple contacts with different formats vcard5 = """BEGIN:VCARD VERSION:3.0 N:Johnson;Mike;;; FN:Mike Johnson TEL:27912345678 END:VCARD BEGIN:VCARD VERSION:3.0 N:Williams;Sarah;;; FN:Sarah Williams TEL;TYPE=CELL:27123...
Python
1
cp23017); mcp_pin0.set_client(mcp23017); mcp_pin1.set_client(mcp23017); // // GPIO Extenders // // Create an array of the GPIO extenders so we can pass them to an // administrative layer that provides a single interface to them all. let async_gpio_ports = static_init!([&'static capsule...
Rust
0
# TencentBlueKing is pleased to support the open source community by making # 蓝鲸智云 - PaaS 平台 (BlueKing - PaaS System) available. # Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the MIT License (the "License"); you may not use this file except # in compliance with the Licen...
Python
1
from badsecrets import modules_loaded Yii2_SignedCookies = modules_loaded["yii2_signedcookies"] yii2_tests = [ ( "secret", "0bb72f36d041a3a022f231eebe114889ee442092ee350242ffb2d4bb53887a81a%3A2%3A%7Bi%3A0%3Bs%3A4%3A%22lang%22%3Bi%3A1%3Bs%3A7%3A%22English%22%3B%7D", ), ] def test_yii2_valid():...
Python
1
use super::*; #[test] fn unpack_bool() { let bytes: [u8; 1] = [0xFF]; let value = bool::unpack_from(&mut bytes.as_ref()).unwrap(); assert_eq!(value, false); } #[test] fn unpack_u8() { let bytes = [0xFF]; let value = u8::unpack_from(&mut bytes.as_ref()).unwra...
Rust
0
> { self.cache.descriptors.get(&contract_id).and_then(|cache| { cache.used_address_derivations.get(address).cloned() }) } } <filename>src/ext/geom.rs // // GLSL Mathematics for Rust. // // Copyright (c) 2015 The glm-rs authors. // // Permission is hereby granted, free of charge, to any p...
Rust
0
# terrascript/resource/launchdarkly/launchdarkly.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:20:56 UTC) import terrascript class launchdarkly_access_token(terrascript.Resource): pass class launchdarkly_custom_role(terrascript.Resource): pass class launchdarkly_destination(terrascript...
Python
1
import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() AUSTRIA = "\xd6sterreich" # by default, rows are returned as Unicode cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert row[0] == AUSTRIA # but we can make sqlite3 always return bytestrings ... con.text_factory = bytes cur.execute("sel...
Python
1
ate::stdlib::os::_set_thread_local_invalid_parameter_handler( $crate::stdlib::os::silent_iph_handler, ); let ret = $e; $crate::stdlib::os::_set_thread_local_invalid_parameter_handler(old); ret }}; } #[cfg(not(all(windows, target_env = "msvc")))] #[macro_export] macro_rul...
Rust
0
sparse matrix output - tfidf_obj = tf-idf model ''' tfidf_obj = TfidfVectorizer(ngram_range=(1,1), stop_words='english', analyzer='word', max_features = n_features) tfidf_text = tfidf_obj.fit_transform(df.ix[:,column].values) if train_df is not None: ...
Python
1
// MaybeUninit<T> is FromBytes, but never AsBytes since it may contain uninit. // SAFETY: MaybeUninit<T> has no restrictions on its contents. unsafe impl<T> FromBytes for MaybeUninit<T> { fn only_derive_is_allowed_to_implement_this_trait() where Self: Sized, { } } impl_for_primitives!(FromByt...
Rust
0
BitBinary(Vec<u8>, u8), BigInt(BigInt), Atom(String), } <filename>examples/rust/get_started/examples/old/10-routing-to-a-cloud-node.rs // This node routes a message, to a worker on a cloud node, over the tcp transport. use ockam::{route, Context, Result, TcpTransport, TCP}; #[ockam::node] async fn main(m...
Rust
0
from decimal import Decimal from typing import Dict, Any import pytest from pydantic import ValidationError from agenthalo.services.alchemy.alchemy_client import Balance @pytest.fixture def valid_address() -> str: return "0x1234567890123456789012345678901234567890" @pytest.fixture def valid_balance_data(valid...
Python
1
**************************************************************************************** # busquedas def BuscarIDdeActivos(id): try: peticion = requests.get(f"http://154.38.171.54:5501/activos/{id}") return [peticio...
Python
1
iter = raw.clone().into_iter(); let start = iter .next() .map_or(Span::call_site(), |t| TokenTree::span(&t)); let end = iter.last().map_or(start, |t| TokenTree::span(&t)); let part = pull_format(&mut format, &mut cur_format, start, ...
Rust
0
_width: f32, max_height: f32) { if position.x < 0.0 - (constants::BODY_SIZE / 2.0) { position.x += max_width; } else if position.x > max_width + (constants::BODY_SIZE / 2.0) { position.x -= max_width; } if position.y < 0.0 - (constants::BODY_SIZE / 2.0) { position.y += max_heigh...
Rust
0
er { queue, index: buffer.index, num_planes: buffer.planes.len(), timestamp: TimeVal::zero(), fuse, _p: std::marker::PhantomData, } } /// Returns the V4L2 index of this buffer. pub fn index(&self) -> usize { self.index ...
Rust
0
| a.partial_cmp(&b).unwrap()); let mut threshold = 0.0; if self.centrality > 0.0 { let mut always_include = 0; while always_include < point_list_with_distance.len() && distance_list[always_include] == 0.0 { always_include += 1; ...
Rust
0