text
string
label_name
string
labels
int64
appearances_by_model_label[model_label] actual_appearances_by_model_label[model_label].add(pk) for model, (min_expected, max_expected) in expected_count_ranges_by_model.items(): model_label = model._meta.label_lower actual_count = len(actual_appearances_by_model_label[model_...
Python
1
from dataclasses import dataclass @dataclass class PocketCastsURL: id: str = None type: str = None @dataclass class PocketCastsDownloadItem: episode_info: dict = None episode_audio_url: str = None
Python
1
import ast from typing import Any from contextlib import suppress def estimate_type(node: Any, none_values=None) -> Any: """ Takes any type and return it's value in a type it estimates it to be based on ast.literal_eval & internal logic, if the result is a list or a dict will recurse to run all internal value...
Python
1
_ => cmark_acc.push(event.to_owned()), } } let mut buf = String::new(); cmark(cmark_acc.into_iter(), &mut buf)?; Ok(buf) } fn table_of_comparison(prql: &str, sql: &str) -> String { format!( r#" <div class="comparison"> <div> <h4>PRQL</h4> ```prql {prql} ``` </div> <di...
Rust
0
#!/usr/bin/env fbpython # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under both the MIT license found in the # LICENSE-MIT file in the root directory of this source tree and the Apache # License, Version 2.0 found in the LICENSE-APACHE file in the root directory # of this source...
Python
1
last_prekey: EncodedPreKey, } #[derive(Serialize)] pub struct MessageRequest<'a, 'b> { pub sender: &'a str, pub recipients: HashMap<&'b str, HashMap<&'b str, String>>, } #[derive(Serialize)] pub struct AssetUploadRequest<'a> { pub public: bool, pub retention: &'a str, } #[derive(Deserialize)] pub str...
Rust
0
import _plotly_utils.basevalidators class RangesliderValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="rangeslider", parent_name="layout.xaxis", **kwargs): super(RangesliderValidator, self).__init__( plotly_name=plotly_name, parent_name=pare...
Python
1
def read_register(self, reg): # # Send the register address with a read command (0x00 is a read command) # send = [reg, 0x00, reg+1, 0x00] # 2-byte array: [register address, dummy byte] # # Perform the SPI transfer # resp = self.spi.xfer(send) # print(resp) # #...
Python
1
oc(req, req_layout); } } let desc_indexes = match self.desc_indexes { Some(ref indexes) => indexes.clone(), None => panic!("desc_indexes must be saved"), }; self.deallocate_desc(&desc_indexes); let pm = unsafe { process_manager() }; p...
Rust
0
"1721 979 366 299 675 1456 " .as_bytes(), ); let result = solve(read_input(buffer).unwrap().as_slice()); assert!(result == 514579); } } use borsh::{BorshDeserialize, BorshSerialize}; use evm::Context; use near_primitives_core::config::VMConfig; use near_primitives_cor...
Rust
0
field `SYSTEM_TIMERS_CLK_EN`"] pub type SYSTEM_TIMERS_CLK_EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SYSTEM_TIMERS_CLK_EN`"] pub struct SYSTEM_TIMERS_CLK_EN_W<'a> { w: &'a mut W, } impl<'a> SYSTEM_TIMERS_CLK_EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(se...
Rust
0
FramedWrite::new(writer, Self::new(formatter)) } } #[derive(Debug, Serialize)] struct JsonOutput<'a> { #[serde(flatten)] common: CommonJson<'a>, #[serde(flatten)] msg: &'a SBP, } impl<F, T> Encoder<T> for JsonEncoder<F> where F: Formatter + Clone, T: Borrow<SBP>, { type Error = Er...
Rust
0
let mut peripherals = gd32vf103_pac::Peripherals::take().unwrap(); init_clock(&mut peripherals); // do something here init_ports(&mut peripherals); // blink_led(&mut peripherals); send_uart(&mut peripherals); loop {} } fn init_clock(peripherals: &mut gd32vf103_pac::Peripherals) { // ...
Rust
0
<'tcx>, self_trait_ref: ty::TraitRef<'tcx>, trait_items: &[hir::TraitItem]) -> Vec<ty::Predicate<'tcx>> { trait_items.iter().flat_map(|trait_item| { ...
Rust
0
fn from(err: io::Error) -> Self { Error::Io(err) } } impl From<r2d2::Error> for Error { fn from(err: r2d2::Error) -> Self { Error::R2d2(err) } } mod density; mod distribution; mod probability; pub use density::{Density, D}; pub use distribution::Distribution; pub use probability::{Probability, P}; <fi...
Rust
0
"{expected} labels {n}+-{delta}", "{expected} labels to be in [{min}:{max}]", ) def assert_has_image_mean_object_size( output_bytes: OutputBytes, channel: Channel = None, slice: Slice = None, frame: Frame = None, labels: Labels = None, exclude_labels: ExcludeLabels = None,...
Python
1
info.tcm_parent = attach_type.parent(); let sock = NetlinkSocket::open()?; sock.send(&bytes_of(&req)[..req.header.nlmsg_len as usize])?; let mut prios = Vec::new(); for msg in sock.recv()? { if msg.header.nlmsg_type != RTM_NEWTFILTER { continue; } let tc_msg = ptr:...
Rust
0
# /*************************************************************************** # Copyright (c) 2019-2021, Saif Sidhik # 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....
Python
1
.zip(ref_iter) { assert_eq!(t, r); } } Restart => { drop(tree); tree = config.tree(); } } } true } #[test] fn quickcheck_tree_matches_btreemap() { QuickCheck::new() .gen(StdGen::new(rand...
Rust
0
disablers: vec![], } } pub fn with_binder(mut self, binder: &'static StaticDetourBinder) -> Self { self.binders.push(binder); self } pub fn with_detour<F: detour::Function>( mut self, detour: &'static detour::StaticDetour<F>, ) -> Self { ...
Rust
0
ing(project_root) except typer.Exit: raise except Exception as e: logger.error(f"Error checking environment file: {e}") console.print(f"❌ [bold red]Failed to check environment: {str(e)}[/bold red]") raise typer.Exit(1) @env_app.command("template") def create_env_template() -> ...
Python
1
"""Tests for the Freebox device trackers.""" from unittest.mock import Mock from freezegun.api import FrozenDateTimeFactory from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.freebox import SCAN_INTERVAL from homeassistant.core import HomeAssistant from...
Python
1
20)) b5 = canvas.bbox(tid3) if b5: r5 = canvas.create_rectangle(b5, fill="black", outline="") canvas.tag_raise(tid3, r5) root.after(50, update_canvas) update_canvas() root.mainloop() def main(): ...
Python
1
/// /// The implementation should decide on order of transactions in the pool. /// Each transaction should also get assigned a `Score` which is used to later /// prioritize transactions in the pending set. /// /// Implementation notes: /// - Returned `Score`s should match ordering of `compare` method. /// - `compare` ...
Rust
0
import sys import time import json import sqlite3 from flask import Flask, g from flask import render_template app = Flask(__name__) SLEEP = None if len(sys.argv) > 2: print("=" * 60) try: SLEEP = int(sys.argv[-1]) print(f"Each request will be delayed by {SLEEP} seconds") except ValueError...
Python
1
#!/usr/bin/env python3 """ 增强版测试脚本:验证直接关节控制的连续指令问题修复 """ import sys import os import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from ros_comms import handler as ros_handler from loguru import logger def test_continuous_commands(): """测试连续关节控制指令""" logger.info("=== 测试连续关节控制指令 ===") ...
Python
1
def encrypt(plaintext, key): alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" encrypted_text = "" for char in plaintext: if char.isalpha(): is_upper = char.isupper() char_index = alphabet.index(char.upper()) encrypted_char = key[char_index] encrypted_text += e...
Python
1
╝':'╝', '╩':'╩', '╦':'X', '╣':'╣', '╠':'╬', '╬':'╬', '╧':'╧', '╤':'╪', '╟':'X', '╢':'╢', '╨':'╨', '╥':'X', '╞':'╪', '╡':'╡', '╓':'X', '╖':'X', '╙':'╙', '╜':'X', '╒':'╡', '╕':'╪', '╘':'╘', '╛':'╧', '╫':'╫', '╪':'╪', } , '╛' : { ' ':'╛', '│':'╞', '─':'┴', '┌':'├', '┐':'X', '└':'└', '┘':'X', '┴':'┴', '┬':'...
Python
1
eth_dev_stop(port_id: u16); } extern "C" { #[doc = " Link up an Ethernet device."] #[doc = ""] #[doc = " Set device link up will re-enable the device rx/tx"] #[doc = " functionality after it is previously set device linked down."] #[doc = ""] #[doc = " @param port_id"] #[doc = " The port i...
Rust
0
se = next((seg for seg in self.segments if seg.id == 'SE'), None) if se and len(se.elements) >= 2: if int(se.elements[0]) != len([seg for seg in self.segments if seg.id not in ['ISA', 'GS', 'GE', 'IEA']]): self.errors.append("SE segment count does not match actual segment count"...
Python
1
0.0, skewness); } #[test] fn test_median() { let median = |x: DiscreteUniform| x.median(); test_case(-10, 10, 0.0, median); test_case(0, 4, 2.0, median); test_case(10, 20, 15.0, median); test_case(20, 20, 20.0, median); } #[test] fn test_mode() { ...
Rust
0
} TIMER_STORE.Trigger(0); return false; } pub fn Fire(&self, SeqNo: u64) { let timer = { let mut t = self.lock(); //error!("Fire {}/{}", t.Id, t.SeqNo); if SeqNo != t.SeqNo || t.State != TimerState::Running { return; //one out of data...
Rust
0
pl crate::Readable for RXTCP_GOOD_FRAMES_SPEC { type Reader = R; } #[doc = "`reset()` method sets RXTCP_GOOD_FRAMES to value 0"] impl crate::Resettable for RXTCP_GOOD_FRAMES_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } } <gh_stars>1-10 use std::collections::HashMap; use std::time:...
Rust
0
, }, } } fn dispatch(&mut self, remote_addr: &SocketAddr) -> Result<IpAddr> { let state = self.select_state(remote_addr)?; let address = &state.addresses[state.address_idx]; let ip = address.ip.clone(); state.count += 1; if state.count == usize::fro...
Rust
0
= input!(); if &inp[..] == "0" { break; } for i in inp.chars().skip(1) { match i { 'A' => { a += 1; } 'B' => { b += 1; } _ => {} } }...
Rust
0
# Problem 34 # Insert Interval # leetcode 57 # intervals = [[1,3],[6,9]] # newInterval = [2,5] # Output = [[1,5],[6,9]] def InsertInterval(intervals, newInterval): res = [] for i in range(len(intervals)): if newInterval[1] < intervals[i][0]: res.append(newInterval) return res +...
Python
1
IntoIterator<Item = &'a mut ColorRGB>> super::ColorIterMut for T { fn fill(self, color: ColorRGB) { self.into_iter().for_each(|p| *p = color); } } // Theory of Operation: // // fade_to_black(u8) - the same as applying rgb.scale(fade); // The optimization is based on scaling 4 bytes at once, rather tha...
Rust
0
wholebody_val_v1.0.json', img_prefix=f'{data_root}/val2017/', test_mode=True, **data_source_cfg), pipeline=val_pipeline), test=dict( type='HandCocoWholeBodyDataset', data_source=dict( ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.j...
Python
1
""" #utils.py Este módulo armazena funções utilitárias, como cálculos de distância, detecção de colisões, ou carregamento de imagens e sons. """ import pygame import webbrowser import os from config import SCREEN_WIDTH, SCREEN_HEIGHT def show_menu(screen): # Carrega o background do menu backgroun...
Python
1
eds"); // results // } // pub fn get_item(id: i32) -> Option<Item> { // use schema::items::dsl::*; // let pool = establish_pool(); // let connection = pool.get().unwrap(); // match items.find(id).first::<Item>(&*connection) { // Ok(item) => Some(item), // Err(_) => None, // } // } // pub fn get_i...
Rust
0
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from fastapi.middleware.cors import CORSMiddleware from typing import List from datetime import datetime from trip_planner import TripPlanner import logging app = FastAPI() # Configure CORS app.add_middleware( CORSMiddleware, allow_orig...
Python
1
cur, limits.max_nice_priority.soft_limit.as_rlim_t()); assert_eq!(libc_lim.rlim_max, limits.max_nice_priority.hard_limit.as_rlim_t()); // Max realtime priority assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_RTPRIO, &mut libc_lim) }, 0); assert_eq!(libc_lim.rlim_cur, limits.max_realtim...
Rust
0
transpose()?; let do_sample_dur = (flags & 0x0100) > 0; let do_sample_size = (flags & 0x0200) > 0; let do_sample_flags = (flags & 0x0400) > 0; let do_sample_comp = (flags & 0x0800) > 0; let mut entries = ArrayUnsized::new(); while entries.len() < sample_count as usize {...
Rust
0
nombre = input("ingrese su nombre: ") apellido = input("ingrese su apellido: ") nombre_completo = "el nombre completo del usuario es:" + nombre + " " + apellido print (nombre_completo) nombre_completo2 = "el nombre completo del usuario es:{} {}".format(nombre, apellido) print (nombre_completo2)
Python
1
tones' if include_recommendations else ''} {' - Resource requirements and ROI analysis' if include_recommendations else ''} {' - Success metrics and KPIs' if include_recommendations else ''} Focus on value creation, competitive positioning, and stakeholder impact. Provide specific, measurable recommendations.""" ...
Python
1
y!(var_from_sexpr(&list[0])); let val = try!(val_from_sexpr(&list[1])); Ok((var, val)) } else { Err(format!("assignment must have 2 elems")) }, _ => Err(format!("assignment must be a list")), } } fn jump_from_sexpr(elem: &sexpr::Elem) -> Result<grit::Jump, String> { match *e...
Rust
0
logger.error(f"Error running scheduler: {e}") raise async def start_background_scheduler(self) -> None: """Start the background scheduler task""" logger.info("Starting background scheduler...") async def scheduler_loop(): while True: ...
Python
1
# Copyright 2024 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
Python
1
ate.add_message_listener(check_message_0); let locker = v8::Locker::new(&isolate); v8::HandleScope::enter(&isolate, |s| { let mut context = v8::Context::new(s); context.enter(); let source = v8::String::new(s, "throw 'foo'", Default::default()).unwrap(); let mut script = v8::Script::compile(s, cont...
Rust
0
::LLVMSetMetadata(r, kind, llvm::LLVMMDNodeInContext(self.llcx, &val, 1)); } true } } impl AsmMethods for CodegenCx<'ll, 'tcx> { fn codegen_global_asm(&self, ga: &hir::GlobalAsm) { let asm = CString::new(ga.asm.as_str().as_bytes()).unwrap(); unsafe { ...
Rust
0
# Static Method (goto_team_outing): Executes a general task unrelated to instance attributes. # Class Method (change_company_name): Updates the shared company name across all employees. # Instance Methods (do_job, intro): Operate on instance-specific attributes like eid, ename, and esalary. # Dynamic Company Name Chang...
Python
1
_i=getattr(self, layer_name_i) x = layer(x) x_i = layer_i(x_i) if i in self.out_indices: outs_i.append(x_i) outs.append(x) if i > 0 and i < 4: max_v_com, max_i_com, avg_v_com, avg_i_com = self.channel_att[i-1](x, x_i) #...
Python
1
*TAG_DEVICE_MANUFACTURER); impl_tag!(DeviceModel, &'a str, *TAG_DEVICE_MODEL); impl_tag!(ApplicationName, &'a str, *TAG_APPLICATION_NAME); impl_tag!(ApplicationData, Sample, *TAG_APPLICATION_DATA); impl_tag!(ImageOrientation, &'a str, *TAG_IMAGE_ORIENTATION); impl_tag!(Publisher, &'a str, *TAG_PUBLISHER); impl_tag!(In...
Rust
0
child in template.children.drain(0..) { let child = expand( world, render_objects, layout_objects, handlers, states, child, debug_flag, ); let _result = world.entity_conta...
Rust
0
en_indices = ( seq_lengths.unsqueeze(-1) - torch.arange(self._num_added_end_tokens, device=device) - 1 ) # Shape: (batch_size, self._num_added_start_tokens, embedding_size) start_token_embeddings = embeddings[:, : self._num_added_start_tokens, :] # Sh...
Python
1
import requests from loguru import logger from typing import Optional, Union from differential.utils.ptgen.base import PTGenData from differential.utils.ptgen.imdb import IMDBData from differential.utils.ptgen.douban import DoubanData from differential.utils.ptgen.parser import parse_ptgen class PTGenHandler: """...
Python
1
import torch import numpy as np import time from infllm_v2 import blockmask_to_uint64, uint64_to_bool def py_uint64_to_bool(uint64_array, last_dim_size): """ 将 uint64 表示转换回布尔掩码,完全向量化实现 (Python版本) 参数: uint64_array: 包含 uint64 值的 PyTorch 张量 last_dim_size: 原始最后一维的大小 返回: ...
Python
1
'secure': cls.MINIO_SECURE } @classmethod def get_celery_config(cls) -> Dict[str, Any]: """Get Celery configuration""" return { 'broker_url': cls.CELERY_BROKER_URL, 'result_backend': cls.CELERY_RESULT_BACKEND, 'task_serializer': cls.CELERY_TASK_S...
Python
1
he<S>, id: &str) -> Result<Self, Error> { cache.load_owned::<A>(id).map(Arc::new) } } /// Mark an asset as not being hot-reloaded. /// /// At the moment, the only use of this trait is to enable `Handle::get` for /// types that implement it. /// /// If you implement this trait, you MUST set [`Asset::HOT_RE...
Rust
0
<Path>>, send_buffer_size_in_bytes: usize) -> Result<StreamingServerListenerSocketFileDescriptor<sockaddr_un>, NewSocketServerListenerError> { let this = SocketFileDescriptor::<sockaddr_un>::new_streaming_unix_domain_socket(send_buffer_size_in_bytes)?; this.bind_unix_domain_socket(unix_socket_address)?; Ok(this....
Rust
0
-line haiku about ocean fog."}, ], ) print(basic.choices[0].message.content) print("\n=== Tool Loop (Weather) ===") messages = await run_tool_loop( client, deployment=deployment_name, system_instructions="You are a weather assistant. Use get_weather to answer location qu...
Python
1
{ "filename": "weixin", "url": weixin }, { "filename": "dy", "url": dy }, { "filename": "sph", "url": sph }, { "filename": "ks", "url": ks }, { ...
Python
1
bincoded file. /// ## Errors /// - If the wordlist can not be read. /// - If the contents can not be deserialized pub fn deserialize_from(wordfile: &str) -> Result<Wordlist, Error> { use std::fs::File; use std::io::BufReader; let file = File::open(wordfile).map_err(|source| Erro...
Rust
0
xxx-append-secrets/bin/append-initrd-secrets", "kernel": "/nix/store/xxx-linux/bzImage", "kernelParams": [ "amd_iommu=on", "amd_iommu=pt", "iommu=pt", "kvm.ignore_msrs=1", "kvm.report_ignored_msrs=0", "udev.log_priority=3", ...
Rust
0
en.wikipedia.org/wiki/Julian_day) (*JD*). In our case, that date is //! `2451545.0`. //! //! We first calculate the VSOP87 elements: //! //! ``` //! let vsop87_elts = vsop87::mercury(2451545.0); //! //! assert!(vsop87_elts.a > 0.3870982121 && vsop87_elts.a < 0.3870982123); //! assert!(vsop87_elts.l > 4.4026057778 && vs...
Rust
0
t_file_path, 'w') as f: json.dump(best_combination, f, indent=4) print(f"Best combination for {model_name} across all iterations saved (Iteration {best_lag})") return best_combination if __name__ == "__main__": print('----------------------- START----------------------') df = pd.read_exc...
Python
1
how_many_snakes = 1 snake_string = ("\n" "Welcome to Python3!\n" "\n" " ____\n" " / . .\\\n" " \ ---<\n" " \ /\n" " __________/ /\n" "-=:_____...
Python
1
from fastapi.testclient import TestClient from sqlalchemy.orm import Session from app.crud import crud_patient, crud_document, crud_admin from app.schemas import ResponsablesInfo, PatientAll, UserCreate from app.tests.utils.user import create_random_user from app.tests.utils.utils import random_document, random_passw...
Python
1
wallet_rpc("watch_wallet") watch_wallet.importaddress(self.wallet.get_address()) # DEFAULT_ANCESTOR_LIMIT transactions off a confirmed tx should be fine chain = self.wallet.create_self_transfer_chain(chain_length=DEFAULT_ANCESTOR_LIMIT) ancestor_vsize = 0 ancestor_fees = Decimal...
Python
1
e"] impl crate::Writable for CTLBASE {} #[doc = "DMA Channel Control Base Pointer"] pub mod ctlbase; #[doc = "DMA Alternate Channel Control Base Pointer\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields s...
Rust
0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # main if __name__ == "__main__": args = sys.argv[1:] if len(args) == 0: print("ERROR: No addon specified (use -h for help or -g for graphic menu)") sys.exit(1) if args[0][0] == "-": if args[0] in table: ...
Python
1
体对齐 - 实体消歧 - 知识合并 ### 3. 知识推理 基于已有知识推导新知识: - 基于规则的推理 - 基于统计的推理 - 基于深度学习的推理 ## 应用场景 知识图谱在多个领域有广泛应用: - 智能搜索和问答系统 - 推荐系统 - 金融风控 - 医疗诊断辅助 """ # Create chunks chunker = MarkdownChunker(chunk_size=300, chunk_overlap=50) chunking_result = chunker.chunk(markdown_text) # Enha...
Python
1
= GlEnum(Context::RG16UI), Rg32f = GlEnum(Context::RG32F), Rg32i = GlEnum(Context::RG32I), Rg32ui = GlEnum(Context::RG32UI), Rg8 = GlEnum(Context::RG8), Rg8i = GlEnum(Context::RG8I), Rg8SNorm = GlEnum(Context::RG8_SNOR...
Rust
0
let (idx, non_null) = row?; if idx != fidx as i32 { return Err( protocol_err!("missing field from query, field: {:?}", column).into(), ); } Ok(Column { name: column.name...
Rust
0
_debug!("Voxel size is {}", self.voxel_size); /* World space mid point of the grid. */ let mid_offset = (((self.resolution as f32) / 2.0) * self.voxel_size); log_debug!("Midpoint offset is {}", mid_offset); /* Create 3D array of states. */ self.states = Some(vec::with_capacity(((self.resolution +...
Rust
0
ps[8], kernel_size=3, stride=1, padding=1)) sq.add_module('conv10', builder.Conv2dBNReLU(in_channels=deps[8], out_channels=deps[9], kernel_size=3, stride=1, padding=1)) sq.add_module('maxpool4', builder.Maxpool2d(kernel_size=2)) sq.add_module('conv11', builder.Conv2dBNReLU(in_channels=deps[9], o...
Python
1
BLACK = (0, 0, 0) # WHITE = (255, 255, 255) # RED = (255, 0, 0) # # # 字体 # font = pygame.font.Font(None, 36) # # class Scene: # def __init__(self): # self.next_scene = self # # def handle_events(self, events): # pass # # def update(self): # pass # # def render(self, screen): # ...
Python
1
from os.path import join from pythonforandroid.recipe import PyProjectRecipe class PillowRecipe(PyProjectRecipe): """ A recipe for Pillow (previously known as Pil). This recipe allow us to build the Pillow recipe with support for different types of images and fonts. But you should be aware, that in ...
Python
1
name__.lower()}/jobs", data ) ) start = end if end >= limit: break if end + 100 > limit: end = limit else: end += 100 if wait_to_complete: WAIT_TIMEOUT = 120 # pylint: disab...
Python
1
d13dcc3e8fd9f7970a3.ttf", "\u{11C8D}\u{11CA1}\u{11CAA}\u{11C71}", "", ), "u11C8D.11CA1.11CAA=0+2400|\ u11C71=3+1600" ); } #[test] fn use_marchen_026() { assert_eq!( shape( "tests/fonts/in-house/85414f2552b654585b7a8d13dcc3e8fd9f7970a3.ttf", ...
Rust
0
import romtools as rt ''' Closed-interval range object suitable for defining regions in a ROM file. ''' class Range: def __init__(self, begin, end=None): self.begin = 0 self.end = 0 if isinstance(begin, int): # begin parameter is an int self.begin = begin ...
Python
1
# Copyright (C) 2008-today The SG++ project # This file is part of the SG++ project. For conditions of distribution and # use, please see the copyright notice provided with SG++ or at # sgpp.sparsegrids.org import pysgpp ''' In this example we create a B-spline based surrogate for a function with vectorial output. W...
Python
1
play("met EOF before a list was closed"), } UnclosedString { description("met EOF before a string was closed"), display("met EOF before a string was closed"), } UnexpectedEOF { description("met EOF before finished parsing"),...
Rust
0
if quit { break 'l }; }, Err(e) => println!("{}", e) }, ["!h"] => commands(), ["!q"] => return, _ => println!("can't do that, disconnected!") } } } println!("Quitting"); } fn stdin_loop(...
Rust
0
dients_list = array_ops.unstack( grads, num=self._logits_dimension, axis=1) for row, row_grads in enumerate(gradients_list): # If current row is i, K is number of classes,each row returns a tensor of # size batch_size x K representing for each example dx_i dx_1, dx_1 dx_2 # etc dx_i dx_K ...
Python
1
tput_uncond) + output_uncond latents = sampler.step(latents, output) to_idle(diffusion) del diffusion decoder = models.get('decoder') or model_loader.load_decoder(device) decoder.to(device) images = decoder(latents) to_idle(decoder) del decoder ...
Python
1
Default::default() }, nlas, }; netlink_call( RtnlMessage::NewAddress(message), Some(NLM_F_REQUEST | NLM_F_ACK | NLM_F_REPLACE | NLM_F_CREATE), )?; Ok(()) } pub fn add_route(interface: &InterfaceName, cidr: IpNetwork) -> Result<bool, io::Error> { let if_index = if_nam...
Rust
0
= Transcript::new(b"Store Circuit"); let mut prover = Prover::new(&pc_gens, &mut transcript); let mut com_input = "".to_string(); com_input.push_str(v); com_input.push_str(pk_server); com_input.push_str(p); //commitment for hiding v let (com, _) = prover.commit(s...
Rust
0
import numpy as np from scipy import signal import matplotlib.pyplot as plt from scipy.interpolate import interp1d # open loop num = [4.0] den = [1.0,6.0,11.0,6.0] sys = signal.TransferFunction(num, den) t1,y1 = signal.step(sys) # closed loop Kc = 1.0 num = [4.0*Kc] den = [1.0,6.0,11.0,4.0*Kc+6.0] sys2 = signal.Trans...
Python
1
x: &mut [f32], size: i64, cells_type: &[ContainerWall], i: i64, j: i64, ) { if cells_type[idx!(i, j, size)] == ContainerWall::DefaultWall { return; } let up_point_coordinates = (i, (j - 1).clamp(0, size - 1)); let down_point_coordi...
Rust
0
, 71, 6, 214, 239, 212, 109, 72, 252, 205, 84, 128, 248, 5, 72, 147, 194, 111, 244, 208, 56, 44, 177, 152, 173, 43, 179, 196, 110, 155, 20, 95, 71, 59, 173, 30, 211, 29, 102, 91, 57, 199, 119, 126, 15, 169, 25, 148, 32, 96, 170, 244, 139, 172, 7, 89, 1, 234, 160, 255,...
Rust
0
).sublime-color-scheme" "Rust" #[derive(Debug)] // ^^^^^ fg=#83a598 fs= // ^^^^^^^^ fg=#ebdbb2 fs= pub enum State { // ^^^^ fg=#fb4934 fs= // ^^^^^ fg=#b8bb26 fs= // ^ fg=#ebdbb2 fs= Start, // ^^^^^^ fg=#ebdbb2 fs= Transient, // ^^^^^^^^^^ fg=#ebdbb2 fs= Closed, // ^^^^^^^ fg=#...
Rust
0
; match &val["data"]["result"][0]["value"][1] { Value::String(value) => { self.metric.observe(value.parse()?); } _ => { return Err(Box::new(CheckError::new( "error while parsing prometheus response", ))); ...
Rust
0
lette: String, max_dots: i32, } fn model(app: &App) -> Model { let args = ArgParser::new(); let radius = args.get_f32("radius", 15.); let padding = args.get_f32("pad", 0.); let x_padding = args.get_f32("x-pad", padding); let y_padding = args.get_f32("y-pad", padding); let max_dots = args.get_i32("max-dot...
Rust
0
), ("u", 1), ("v", 4), ("w", 4), ("x", 8), ("y", 4), ("z", 10), ]); assert_eq!(expected, etl::transform(&input)); } fn input_from(v: &[(i32, Vec<&str>)]) -> BTreeMap<i32, Vec<String>> { v.iter().fold(BTreeMap::new(), |mut acc, &(n, ref v)| { acc.insert(n, v.iter().map(|s| s.to...
Rust
0
rsect_a_world_with_a_ray() { let w = World::default().generate(); let r = Ray::new(Point::new(0.0, 0.0, -5.0), Vector::new(0.0, 0.0, 1.0)); let xs = w.ray_intersects(r); assert_eq!(xs.len(), 4); assert_eq!(xs[0].t(), 4.0); assert_eq!(xs[1].t(), 4.5); assert_eq!(xs[2].t(), 5.5); assert_e...
Rust
0
""" Hypothesis data generator helpers. """ from datetime import datetime from hypothesis import strategies as st from hypothesis.extra.dateutil import timezones as dateutil_timezones from hypothesis.extra.pytz import timezones as pytz_timezones from pandas.compat import is_platform_windows import pandas as pd from ...
Python
1
''' Sum of non-adjacent numbers Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. Input: [2, 4, 6, 2, 5] Output: 13 Output explanation: We pick 2, 6, and 5. Input: [5, 1, 1, 5] Output: 10 Output explanation: We pick 5 and 5. ==============...
Python
1
Verb::MoveTo => PathCommand::MoveTo(self.points.next().unwrap()), // Verb::LineTo => PathCommand::LineTo(self.points.next().unwrap()), Verb::QuadraticTo => PathCommand::QuadraticTo(self.points.next().unwrap(), self.points.next().unwrap()), Verb::Close => ...
Rust
0
3, }, Vector { _handler: DMA2_STREAM4, }, Vector { _handler: ETH }, Vector { _handler: ETH_WKUP }, Vector { _handler: CAN2_TX }, Vector { _handler: CAN2_RX0 }, Vector { _handler: CAN2_RX1 }, Vector { _handler: CAN2_SCE }, Vector { _handler: OTG_FS }, Vector { ...
Rust
0