text
string
label_name
string
labels
int64
"""Configuration for this instance of prysm.""" from .mathops import np class Config(object): """Global configuration of prysm.""" def __init__(self, precision=64, phase_cmap='inferno', image_cmap='Greys_r', lw=3, zorder=3, ...
Python
1
x = 5 print(type(x))
Python
1
play.vkGetDisplayPlaneCapabilitiesKHR(physical_device.handle().to_raw(), mode.handle().to_raw(), plane_index, &mut capabilities); error::check(result, "vkGetDisplayPlaneCapabilitiesKHR", DisplayPlaneCapabilitiesKhr::from_raw(capabilities)) } /// Creates a `SurfaceKhrHandle` stru...
Rust
0
self.resample_kernel[key_str] = self.resample_kernel[key_str].to(self.device) audios_res = self.resample_kernel[key_str](audios) mels = self.mel_extractor(audios_res, center=True) hiddens = self.mel2hidden(mels) f0 = self.decode(hiddens, thred=thred, use_viterbi=use_viterbi) ...
Python
1
import pytest import pandas.util._test_decorators as td from pandas import DataFrame from pandas.tests.plotting.common import ( TestPlotBase, _check_plot_works, _gen_two_subplots, ) pytestmark = pytest.mark.slow @td.skip_if_no_mpl class TestCommon(TestPlotBase): def test__check_ticks_props(self): ...
Python
1
elf._arguments.append(value) def __init__(self, method_type, mandatory: bool = False): self.name = None self.need_code_parameters = False self._arguments = [] self.__method_type: str = method_type self.__mandatory: bool = mandatory def clear(self): """ ...
Python
1
import threading import time import os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../layers"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))) import ui.name_input import ui.leader_yn from layers.application_layer import ApplicationL...
Python
1
# -*- coding: utf-8 -*- """Machine Learning task 3(Areej Mehboob).ipynb Automatically generated by Colab. Original file is located at https://colab.research.google.com/drive/1VOGB4oEZd2Hxjj4SYWaSyji2O82EGNeX """ # Importing necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as pl...
Python
1
raph, causetid: i64) -> Causetid { // topograph.get_ident(causetid).map_or(Causetid::Causetid(causetid), |solitonid| Causetid::Solitonid(solitonid.clone())) // } /// Return the set of causets in the store, ordered by (e, a, v, tx), but not including any causets of /// the form [... :einsteindb/txInstant ...]. pub ...
Rust
0
u32).ok(); } /*! [odoh-rs] is a library that implements [Oblivious DNS over HTTPS (ODoH) protocol draft-06] in Rust. It can be used to implement an ODoH client or server (target). [odoh-client-rs] uses `odoh-rs` to implement its functionality, and is a good source of API usage examples, along with the tests in `odoh...
Rust
0
kAgentConfig; #[derive(Debug, SwimAgent)] #[agent(config = "MockAgentConfig")] struct MockAgent { #[lifecycle(name = "ValueLifecycle")] pub value: ValueLane<i32>, #[lifecycle(name = "MapLifecycle")] pub map: MapLane<String, i32>, } #[value_lifecycle(agent = "MockAgent", event_type = "i32")] struct Val...
Rust
0
from pydantic import BaseModel from datetime import datetime class AppointmentBase(BaseModel): doctor_id: int hospital_id: int patient_id: int appointment_time: datetime class AppointmentCreate(AppointmentBase): pass class Appointment(AppointmentBase): id: int class Config: orm_m...
Python
1
#!/usr/bin/env python3 """ КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ ПЛАНИРОВЩИКА Проблема: Планировщик проверяет время каждые 60 минут, но пропускает точное время 08:01:00 Решение: Изменить логику сна для точной проверки времени Проблемный код в scheduler.py: - Спит ровно 60 минут между проверками - Пропускает окно времени 08:01:00 ...
Python
1
ifies the time of the last logged audit protocol event time on the cluster. #[serde(rename = "protocol_audit_latest_log_time")] pub protocol_audit_latest_log_time: Option<i32>, /// Specifies the time of the oldest protocol audit event consumed by the CEE forwarder on the cluster. #[serde(rename = "proto...
Rust
0
# Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Point of Sale Subscription', 'version': '1.0', 'category': 'Point of Sale', 'sequence': 15, 'summary': "Link between PoS and Sale Subscription.", 'depends': ['pos_sale', 'sale_subscription'], 'installable...
Python
1
Over = False elif json.loads(json.loads(res.text)['data']['list'][0]['msg'])['over_num'] > 0: success = True Signed = False Over = True else: success = False except IndexError: ...
Python
1
t c_char, s2: *const c_char) -> c_int { // relibc has no locale stuff (yet) strcmp(s1, s2) } #[no_mangle] pub unsafe extern "C" fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char { let mut i = 0; loop { let byte = *src.offset(i); *dst.offset(i) = byte; if byte == 0...
Rust
0
# Copyright 2024 Bytedance Ltd. and/or its affiliates # # 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 ...
Python
1
let dist = |x: f64, y: f64, w: f64, h: f64| -> f64 { self.ml.sqrt((x - w / 2.0) * (x - w / 2.0) + (y - h / 2.0) * (y - h / 2.0)) }; let c_mul = 16.5 + sin(time / 2.0) * 15.5; for y in 0..h { for x in 0..w { let fx = x as f64; let fy = y ...
Rust
0
age=int(input("enter age")) if 18<age: print("vote") elif age==18: print("first vote") else: print("not vote")
Python
1
#!/usr/bin/env python3 import argparse import random import sys from pathlib import Path from acn_embed.util.data.transcription import read_tran_utts, TranscriptionWriter from acn_embed.util.logger import get_logger LOGGER = get_logger(__name__) # pylint:disable=too-many-branches def get_isolated_words(tokens, m...
Python
1
; let mut struct_4 = Struct(4); assert_eq!("4 true 1.5", struct_2.ref_mut_method(true, 1.5f32).await); assert_eq!(4, struct_2.0); assert_eq!("8 true abc", struct_4.ref_mut_method(true, "abc").await); assert_eq!(8, struct_4.0); } #[tokio::test] async fn and_continue_...
Rust
0
::AHardwareBuffer>, } impl HardwareBuffer { /// Create a `HardwareBuffer` from a native pointer /// /// # Safety /// By calling this function, you assert that it is a valid pointer to /// an NDK `AHardwareBuffer`. pub unsafe fn from_ptr(ptr: NonNull<ffi::AHardwareBuffer>) -> Self { Self...
Rust
0
requires at least version 1.36.0 of Rust. //! //! [alloc-lib]: https://doc.rust-lang.org/alloc/ //! //! *Note*: to use derive macros in serde you will need to declare `serde` //! dependency like so: //! ``` toml //! serde = { version = "1.0", default-features = false, features = ["derive"] } //! ``` //! //! Serialize a...
Rust
0
elf.delegate).get_ivar::<bool>("should_close") { events.push(WindowEvent::CloseEvent); (*self.delegate).set_ivar("should_close", false); } } return events; } } impl GameWindowImpl for OsxWindow { fn capture_events(&mut self) -> Vec<WindowEvent> { ...
Rust
0
repo.list_objects(None).unwrap().count()); } fn assert_obj_not_exists(repo: &OcflRepo, object_id: &str) { match repo.get_object(object_id, VersionRef::Head) { Err(RocflError::NotFound(_)) => (), _ => panic!("Expected object '{}' to not be found", object_id), } } fn assert_staged_obj_not_exist...
Rust
0
class Model(RootModel): root: list[Union[BModel, RModel]] choices = [b_schema, r_schema] elif order == 'RB': class Model(RootModel): root: list[Union[RModel, BModel]] choices = [r_schema, b_schema] s = SchemaSerializer( core_schema.model_schema...
Python
1
ed_generation: resource.meta().generation, reason, status: status.to_string(), type_: condition_type, } } <reponame>synthizer/synthizer-rs<filename>synthizer/examples/basic_file.rs<gh_stars>1-10 //! Play a file by loading it into a buffer. use synthizer as syz; fn main() -> syz::Result<()> ...
Rust
0
ample_per_pixel = 5; //ought to be 100 可以做的更大比如500// let max_depth = 50; //an bo modifyed to lessen the time let mut backgroud = Vec3::new(0.0, 0.0, 0.0); let mut lookfrom = Vec3::new(278.0, 278.0, -800.0); //13 2 3 let mut lookat = Vec3::new(278.0, 278.0, 0.0); let mut vfov = 40.0; let number ...
Rust
0
().unwrap() { oled_display.draw_right_display(&pressed_keys[..]).ok(); } } } } #[exception] fn SysTick() { cortex_m::interrupt::free(|cs| { let mut timer_ref = TIMER_SHARED.borrow(cs).borrow_mut(); if timer_ref.is_none() { return; } ...
Rust
0
map_unfolded, state_unfolded) = parse_diagram(&lines_unfolded); let cost_folded = dijkstra_search(&map_folded, &state_folded); let cost_unfolded = dijkstra_search(&map_unfolded, &state_unfolded); println!("{}", cost_folded.expect("cost")); println!("{}", cost_unfolded.expect("cost")); } fn unfold_dia...
Rust
0
{ let $var = avail_sub; { $abody} } , )* $( $sub.sub_id() == avail_sub => { $cbody } , )* else { ::core::unreachable!("Select returned unknown alternative"); } ) ...
Rust
0
ainer.hub_controller]): """ Update a hub --- tags: - Hubs summary: Update a hub description: Update a hub by ID. parameters: - name: hub_id in: path type: integer required: true description: The ID of the hub to update. - name: body i...
Python
1
e_cols.discard(j) B = basis_from_allocation(X) B = ensure_tree_basis(m, n, C, B) return Solution(x=X, basis=B) # ---------- MODI (метод потенциалов) ---------- def find_cycle_in_basis(m: int, n: int, basis: Set[Tuple[int,int]], enter: Tuple[int,int]) -> List[Tuple[int,int]]: # базис — дерево; добавим...
Python
1
from amaranth import * from amaranth.lib import io, wiring from amaranth_stdio.serial import AsyncSerial __all__ = ["LoopbackUART"] # TODO
Python
1
] .iter(), ) .is_err()); // externval vector is shorter than import count. assert!(ModuleInstance::with_externvals(&module_with_single_import, [].iter(),).is_err()); // externval vector has an unexpected type. assert!(ModuleInstance::with_externvals( &module_with_single_import,...
Rust
0
import envtest from raytracing.utils import deprecated def simpleDecoratorReturnsTuple(func): def wrapper(*args, **kwargs): return func(*args, **kwargs), func(*args, **kwargs) return wrapper def decoratorWithOneArgument(arg): def simpleDecoratorReturnsTuple(func): def wrapper(*args, **k...
Python
1
= 'Imputer': imputers.append(method) elif method_type == 'Feature_selector': feature_selectors.append(method) elif method_type == 'Duplicate_detector': duplicate_detectors.append(method) elif method_type == 'Outlier_detector': ...
Python
1
tric_name, metric_value in val_metrics.items(): if metric_name != 'reward': if metric_name not in metrics['validation'][label_name]['metrics']: metrics['validation'][label_name]['metrics'][metric_name] = [] m...
Python
1
let mut receiver_commitment = ReceiverCommitmentKOutOfN::default(); let c_id = blinding_a * blinding_b; let point_x = RistrettoPoint::multiscalar_mul(&[blinding_a], &[*BASEPOINT_G1]); let point_y = RistrettoPoint::multiscalar_mul(&[blinding_b], &[*BASEPOINT_G1]);...
Rust
0
#!/usr/bin/env python import mozdevice import logging import unittest from sut import MockAgent class TestGetIP(unittest.TestCase): """ class to test IP methods """ commands = [('exec ifconfig eth0', 'eth0: ip 192.168.0.1 ' 'mask 255.255.255.0 flags [up broadcast running multicast]\n' ...
Python
1
shows", id, "stats"))) } pub fn show_watching(&self, id: impl Display) -> Result<Vec<User>> { self.get(api_url!(("shows", id, "watching"))) } pub fn show_next_episode(&self, id: impl Display) -> Result<Option<Episode>> { self.get(api_url!(("shows", id, "next_episode"))) } pub ...
Rust
0
since libbacktrace can't track // down that executable this is. We at one point used env::current_exe but // it turns out that there are some serious security issues with that // approach. // // Specifically, on certain platforms like BSDs, a malicious actor can cause // an arbitrary file to be placed at the path retur...
Rust
0
import os import ray.utils from ray.rllib.agents.mock import _MockTrainer from ray.tune import DurableTrainable from ray.tune.sync_client import get_sync_client from ray.tune.syncer import NodeSyncer MOCK_REMOTE_DIR = os.path.join(ray.utils.get_user_temp_dir(), "mock-tune-remote") + os...
Python
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
Python
1
n New",20)) entry_book_id.grid(row=0, column=1, padx=10, pady=10, sticky="nsew") #ช่องกรอกข้อมูลชื่อผู้ยืม,คืนหนังสือ tk.Label(root, text="ชื่อผู้ยืม:",font = ("TH Saraban New",20)).grid(row=1, column=0, padx=10, pady=10, sticky="e") entry_user = tk.Entry(root,font = ("TH Saraban New",20)) entry_user.grid(row=1, colum...
Python
1
class Solution: def findNumbers(self, nums: List[int]) -> int: n = len(nums) res = 0 for i in range(n): if len(str(nums[i])) % 2 == 0: res += 1 return res
Python
1
import logging import azure.functions as func from jinja2 import Environment, FileSystemLoader app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS) environment = Environment(loader=FileSystemLoader("templates/")) # Landing page containing the html that loads htmx.js @app.route(route="index", auth_level=fu...
Python
1
match *self { PINPOLR::_0 => false, PINPOLR::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> PINPOLR { match value { false => PINPOLR::_0, true => PINPOLR::_1, } } #[doc = "Ch...
Rust
0
import os import os.path import cv2 import sys, getopt from Katna.video import Video from Katna.writer import KeyFrameDiskWriter import multiprocessing import ntpath #from icecream import install #install() class CustomDiskWriter(KeyFrameDiskWriter): """ :param KeyFrameDiskWriter: Writer class to overwrite ...
Python
1
''' WikiLinks Extension for Python-Markdown ====================================== Converts [[WikiLinks]] to relative links. See <https://Python-Markdown.github.io/extensions/wikilinks> for documentation. Original code Copyright [Waylan Limberg](http://achinghead.com/). All changes Copyright The Python Markdown Pro...
Python
1
# Get source code source_info = self.get_contract_source(address) # Create output directory if not provided if output_dir is None: output_dir = tempfile.mkdtemp(prefix="eth_vuln_scanner_") else: output_dir = Path(output_dir) ...
Python
1
chrome/browser/canary.html) or /// [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested. /// > /// > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for /// video playback. See /// [this article](htt...
Rust
0
""" " service name """ SPORT_SERVICE_NAME = "sport" """ " service api version """ SPORT_API_VERSION = "1.0.0.1" """ " api id """ SPORT_API_ID_DAMP = 1001; SPORT_API_ID_BALANCESTAND = 1002; SPORT_API_ID_STOPMOVE = 1003; SPORT_API_ID_STANDUP = 1004; SPORT_API_ID_STANDDOWN ...
Python
1
loat<F> { fn cmp(&self, other: &Self) -> cmp::Ordering { self.partial_cmp(other).unwrap() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_nonnanfloat() { let mut v = [NonNaNFloat(5.1), NonNaNFloat(1.3)]; v.sort(); assert_eq!(v, [NonNaNFloat(1.3), NonNaNF...
Rust
0
/// but this field is still false, discard the response and perform a limited /// number of retries. #[prost(bool, tag="3")] pub verified_data_crc32c: bool, /// Integrity verification field. A flag indicating whether /// \[MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_cr...
Rust
0
Body::empty()) .map_err(|e| e.into()) } }, } }) .await } _ => chain(...
Rust
0
have a shape of (1, B, L), now we just need to re-order the data back to (B, 1, L) x_gates = x_tmp.view(B, 1, -1) # Now we effectively apply σ(x_t^T tanh(W c)) gates = torch.sigmoid(x_gates) x = x * gates return x def forward(self, x): if self.low_...
Python
1
f::Instance { ph: UpperReversalSignal::new(cfg.left, cfg.right, candle.high())?, pl: LowerReversalSignal::new(cfg.left, cfg.right, candle.low())?, window: Window::new(cfg.right, HLC::from(candle)), hprice: 0., lprice: 0., cfg, }) } fn validate(&self) -> bool { self.left >= 1 && self.right >= 1 ...
Rust
0
pub fn cleanup_system<T: Component>( mut commands: Commands, q: Query<Entity, With<T>>, ) { for e in q.iter() { commands.entity(e).despawn_recursive(); } } pub enum Corners { TopLeft, TopRight, BottomLeft, BottomRight, } pub fn text_bundle_at_corner(corner: Corners, values: Vec...
Rust
0
elf.temporal_embedding(x_mark) + self.position_embedding(x) return self.dropout(x) class DataEmbedding_wo_pos(nn.Module): def __init__(self, c_in, d_model, embed_type='fixed', freq='h', dropout=0.1): super(DataEmbedding_wo_pos, self).__init__() self.value_embedding = TokenEmbedding(c_in=c...
Python
1
urn_on(max_x, max_y); } fn turn_on(&mut self, x: usize, y: usize) { self.set_to(true, x, y); } fn turn_off(&mut self, x: usize, y: usize) { self.set_to(false, x, y) } fn set_to(&mut self, new_state: bool, x: usize, y: usize) { if self.grid[y][x] == new_state { ...
Rust
0
pName: LPSTR, Level: DWORD, pProvidorInfo: LPBYTE, ) -> BOOL; pub fn AddPrintProvidorW( pName: LPWSTR, Level: DWORD, pProvidorInfo: LPBYTE, ) -> BOOL; pub fn DeletePrintProvidorA( pName: LPSTR, pEnvironment: LPSTR, pPrintProvidorName: L...
Rust
0
s": options.trademarks, "OriginalFilename": ofn, "ProductName": options.product, "ProductVersion": ver, } vdata = { "Translation": struct.pack("hh", 0x409, 1252), } is_dll = options.dll if is_dll is None: is_dll = os.path.splitext(pathname)[1].lower() in ".dll...
Python
1
Entity { //! Known(KnownEntity), //! Unknown(Value), //! } //! #[derive(Deserialize, Debug)] //! #[serde(tag = "id")] //! enum KnownEntity { //! #[serde(rename = "minecraft:bat")] //! Bat { //! #[serde(rename = "BatFlags")] //! bat_flags: i8, //! }, //! #[serde(rename = "minec...
Rust
0
__author__ = 'Sergey Tomin' from ocelot.gui.accelerator import * from ocelot import * Q1 = Quadrupole(l= 0.4, k1=-1.3, eid= "Q1") Q2 = Quadrupole(l= 0.8, k1=1.4, eid= "Q2") Q3 = Quadrupole(l= 0.4, k1=-1.7, eid= "Q3") Q4 = Quadrupole(l= 0.5, k1=1.4 , eid= "Q4") B = Bend(l=2.7, k1=-.06, angle=2*pi/16., e1=pi/16., e2=...
Python
1
marks.pop() marks.push(last1) elif last1 == SHADDA: # is the element is a Shadda, # the previous letter must have a sukun as mark, # and the shadda take the indefinate mark marks.pop() marks.push(SUKUN) marks.push(NOT_DEF...
Python
1
y slight and false-derived cause, Yea, every idle, nice and wanton reason Shall to the king taste of this action; That, were our royal faiths martyrs in love, We shall be winnow'd with so rough a wind That even our corn shall seem as light as chaff And good from bad find no partition. ARCHBISHOP OF YORK No, no, my lord...
Python
1
ld of a `xcb_glx_create_pbuffer_request_t` struct. #[inline] pub unsafe fn xcb_glx_create_pbuffer_attribs_length( &self, r: *const xcb_glx_create_pbuffer_request_t, ) -> c_int { sym!(self, xcb_glx_create_pbuffer_attribs_length)(r) } /// Returns `true` iff the symbol `xcb_glx...
Rust
0
0, 'a'.to_idx()); assert_eq!(25, 'z'.to_idx()); } #[test] fn part1_example1() { let input = read_str_to_lines(EXAMPLE); let instructions = parse_instructions(input); let mut computer = Computer::new(instructions); computer.run(); assert_eq!(2, computer.regist...
Rust
0
globals, $a, p as _, assign_glue, (skip_base as integer + $globals.cur_val) as _ ) } // mu_skip_def_code: define(p,assign_mu_glue,mu_skip_base+cur_val); else if n == mu_skip_def_code as ...
Rust
0
{ "score": None, "label": "wall", "mask": {"hash": "897fb20b7f", "white_pixels": 14506, "shape": (512, 683)}, }, { "score": None, "label": "building", "ma...
Python
1
rt(mse) r2 = r2_score(y_test, y_pred) # Store evaluation results in the dictionary evaluation_results[model_name]["MAE"].append(mae) evaluation_results[model_name]["MSE"].append(mse) evaluation_results[model_name]["RMSE"].append(rmse) evaluation_r...
Python
1
.unwrap(); let buf_expect = &v[offset as usize..(offset as usize + read_len)]; assert_eq!(buf_expect, &buf_actual[..]); } } fn get_random_data(rand: &mut Rand32, len: usize) -> Vec<u8> { let mut v = Vec::with_capacity(len); for _ in 0..len { v.push(rand.rand_range(0..256) as u8);...
Rust
0
p(min=0.01) if soft: off = grid - xyz # B,N,3,Z,Y,X # interpret radius as sigma dist_grid = torch.sum(off ** 2, dim=2, keepdim=False) # this is B x N x Z x Y x X if torch.is_tensor(radius): radius = radius.reshape(B, N, 1, 1, 1) ...
Python
1
.into(); let (bus_code, msg) = error.parse(); Ok(Response::builder().status(StatusCode::OK).header("Content-Type", "application/json; charset=utf8").body( json!({ "code": bus_code, "msg": process_err_msg(bus_code.as_str(...
Rust
0
_ => unreachable!(), }; Ok(ca) } impl<T> Add for &DataArray<T> where T: DFNumericType, T::Native: Add<Output = T::Native> + Sub<Output = T::Native> + Mul<Output = T::Native> + Div<Output = T::Native> + num::Zero, { type Output = Result<DataArray<T>>; fn ad...
Rust
0
_abi() as *const _ as *mut _, &mut out); if hr == S_OK { Ok(foundation::collections::IVectorView::wrap(out)) } else { err(hr) } }} #[inline] pub fn get_service_response(&self) -> Result<MicrosoftAccountMultiFactorServiceResponse> { unsafe { let mut out = zeroed(); let hr = (self.get_vtb...
Rust
0
path)); trace!("walking {:?}", loc.module_path); for item in items { let result = walk_item(ctx, item); if let Err(err) = result { let span = Span::new( ctx.macro_invocation.clone(), ctx.source_file.clone(), item.span(), ...
Rust
0
message )) } else { out.finish(format_args!( "{}[{}][{}] {}", chrono::Local::now().format("[%y-%m-%d][%H:%M:%S]"), record.target(), record.level(), message ...
Rust
0
::new(dir.path()); let r = dir.run_recursive(wd); r.assert_no_errors(); let expected = vec![ dir.path().to_path_buf(), dir.join("foo"), dir.join("foo").join("a"), dir.join("foo").join("b"), dir.join("foo").join("c"), dir.join("foo").join("d"), dir.joi...
Rust
0
self.pos; self.raster.next().map(|(char, raster)| { let glyph = VectorGlyph { page_idx: raster.page_idx, page_rect: raster.page_rect, screen_rect: RectF::new( pos.x + raster.metrics.bounds.xmin, -raster.metrics....
Rust
0
ssert_eq!(parameterize("über"), "uber"); assert_eq!(parameterize("\"foo\" / ~bar~"), "foo-bar"); assert_eq!(parameterize("--foo-bar--"), "foo-bar"); } } <gh_stars>1-10 use image::DynamicImage; use std::env; use std::path::Path; use std::vec::Vec; use vtf::Error; fn main() -> Result<(), Error> { ...
Rust
0
_u8, 0, 0, 0, 0]; let initial_cs = header_info.entry_point.segment + base_segment; LittleEndian::write_u16(&mut buffer[0x01..], header_info.entry_point.offset); LittleEndian::write_u16(&mut buffer[0x03..], initial_cs); buffer }; emulator .mem_write(0, &trampoline_code[..]...
Rust
0
(crate) previous_window_state: Option<Box<WindowState>>, /// Whether there is a focus field overwrite from the last callback calls. pub(crate) pending_focus_target: Option<FocusTarget>, /// What the last motion was in case a controller was used. pub(crate) last_motion: Option<(AxisId, f64)>, } impl Def...
Rust
0
""" A `tracker.management.commands.run_telegram_bot` command for running telegram bots.` """ import asyncio from django.core.management.base import BaseCommand from tracker.telegram.bot import start_tg_bot class Command(BaseCommand): """ Django management command to run the Telegram bot. This command ...
Python
1
numerate() { match (m, v) { ('1', _) => { ids = ids .iter() .map(|e| *e + 2_usize.pow(35 - i as u32)) .collect() } ('0', '1') => { ids = ids ...
Rust
0
v /= 1000; } out = format!("{}{}", v, out); out } /// Formats a list of things as human readable list with commas and "and". /// Iterator must not be empty! pub fn comma_and_list(items: impl IntoIterator<Item = impl Display>) -> String { let items = items.into_iter().map(|i| i.to_string()).collect::<V...
Rust
0
hours = int(input("Type how many hours you stayed: ")) money = 0 if 2 >= hours >= 1: money = 5 elif 6 >= hours >= 3: money = 15 elif hours > 6: money = 20 print(f"You need to pay {money} PLN")
Python
1
h3cICLoghost, "hh3cICLoghostObjects": hh3cICLoghostObjects, "hh3cICMaxLoghost": hh3cICMaxLoghost, "hh3cICLoghostSourceInterface": hh3cICLoghostSourceInterface, "hh3cICLoghostTimestampType": hh3cICLoghostTimestampType, "hh3cICLoghostTable": hh3cICLoghostTable, "hh3cICLoghostEntr...
Python
1
# /*########################################################################## # Copyright (C) 2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software w...
Python
1
form() kwargs = ArticleMixin.get_context_data(self, **kwargs) kwargs.update(FormView.get_context_data(self, **kwargs)) return kwargs class RevisionChangeView(ArticleMixin, RedirectView): permanent = False @method_decorator(get_article(can_write=True, not_locked=True)) def dispatc...
Python
1
#!/usr/bin/env python3 # Pre-generates the expected output subset files (via fonttools) for # specified subset test suite(s). import os import sys import shutil import io import re import tempfile from difflib import unified_diff from fontTools.ttLib import TTFont from subprocess import check_call from subset_test_...
Python
1
)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `PAD58_DS1`"] pub type PAD58_DS1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PAD58_DS1`"] pub struct PAD58_DS1_W<'a> { w: &'a mut W, } impl<'a> PAD58_DS1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always...
Rust
0
ibble but doesn't wrap sprites around x and y axis. /// fn drw_vx_vy_nibble_no_wrap(cpu: &mut Chip8, opcode: u16) -> CPUResult { let x = ((opcode & 0x0F00) >> 8) as usize; let y = ((opcode & 0x00F0) >> 4) as usize; let n = (opcode & 0x000F) as usize; let vx = cpu.registers[x] as usize; let vy = cpu...
Rust
0
"""Test various import and setup routines.""" import sys import mock import pytest def test_setup(): """Test that the library sets up correctly with numpy and spidev.""" sys.modules['spidev'] = mock.MagicMock() import unicornhathd unicornhathd.setup() def test_brightness(): """Test brightness AP...
Python
1
nce, &mut actual); assert_eq!(test.expected.len(), actual.len()); for (expected, actual) in test.expected.chunks(CHACHA20_BLOCK_SIZE).zip(actual.chunks(CHACHA20_BLOCK_SIZE)) { assert_eq!(expected, actual); } // Decrypt encrypted data, and check that decrypted_data == data ...
Rust
0
=> { cache.add(listing); } None => continue, } bar.inc(1); } bar.finish(); Ok(()) } <gh_stars>0 //! Implement virtual machine to run instructions. //! //! See also: //! <https://github.com/ProgVal/pythonvm-rust/blob/master/src/processor/mod.rs> #[cfg(feature = "rustpython-compiler"...
Rust
0
} } }; } mod canary; mod s3_canary; canary_module!(paginator_canary, since: "v0.4.1"); mod transcribe_canary; #[tokio::main] async fn main() -> Result<(), Error> { let subscriber = tracing_subscriber::registry() .with(EnvFilter::from_default_env()) .with(tracing_subscriber::...
Rust
0
Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pjds](index.html) mod...
Rust
0